/
code_gen_c.py
3264 lines (2804 loc) · 144 KB
/
code_gen_c.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
# -*- coding: utf-8 -*-
"""
Adapted from the astor library for Python AST manipulation.
Copyright (c) 2018-2020 Andrea Zanelli
This module converts a Python AST into C source code.
"""
# TODO(andrea): in Python 3.8+ a constant string has type ast.Constant. In order to
# support the latest versions I might need to add checks for ast.Constant.value in order
# to determine whether a numerical value
# or a string is used
# TODO(andrea): add utility to asses AST structure
import ast
import astunparse as astu
import sys
from .op_util import get_op_symbol, get_op_precedence, Precedence
from .node_util import ExplicitNodeVisitor
from .string_repr import pretty_string
from .source_repr import pretty_source
from ..laparser.laparser import LAParser
from collections import namedtuple
# import astpretty as ap
from astpretty import pprint as np
import os
import json
from jinja2 import Template
from collections import OrderedDict
import casadi as ca
pmt_temp_functions = {\
'_Z4pmatdimsdims': 'c_pmt_create_pmat', \
'_Z4pvecdims': 'c_pmt_create_pvec', \
'_Z10pmat_printpmat': 'c_pmt_pmat_print', \
'_Z8pmt_gemmpmatpmatpmat': 'c_pmt_gemm_nn', \
'_Z8pmt_gemmpmatpmatpmatpmat': 'c_pmt_gemm_nn', \
'_Z11pmt_gemm_nnpmatpmatpmatpmat': 'c_pmt_gemm_nn', \
'_Z11pmt_gemm_nnpmatpmatpmat': 'c_pmt_gemm_nn', \
'_Z11pmt_gemm_ntpmatpmatpmatpmat': 'c_pmt_gemm_nt', \
'_Z11pmt_gemm_ntpmatpmatpmat': 'c_pmt_gemm_nt', \
'_Z11pmt_gemm_tnpmatpmatpmatpmat': 'c_pmt_gemm_tn', \
'_Z11pmt_gemm_tnpmatpmatpmat': 'c_pmt_gemm_tn', \
'_Z11pmt_gemm_ttpmatpmatpmatpmat': 'c_pmt_gemm_tt', \
'_Z11pmt_gemm_ttpmatpmatpmat': 'c_pmt_gemm_tt', \
'_Z8pmt_geadfloatpmatpmat': 'c_pmt_gead', \
'_Z9pmt_potrfpmatpmat': 'c_pmt_potrf', \
'_Z10pmt_potrsmpmatpmat': 'c_pmt_potrsm', \
'_Z9pmat_tranpmatpmat': 'c_pmt_pmat_tran', \
'_Z9pmat_copypmatpmat': 'c_pmt_pmat_copy', \
'_Z9pmat_fillpmatfloat': 'c_pmt_pmat_fill', \
'_Z9pmat_hcatpmatpmatpmat': 'c_pmt_pmat_hcat', \
'_Z9pmat_vcatpmatpmatpmat': 'c_pmt_pmat_vcat', \
'_Z10pvec_printpvec': 'c_pmt_pvec_print', \
'_Z9pvec_copypvecpvec': 'c_pmt_pvec_copy', \
'_Z5print' : 'printf'}
# 'pmt_trmm_rlnn': 'c_pmt_trmm_rlnn', \
# 'pmt_syrk_ln': 'c_pmt_syrk_ln', \
# 'pmt_getrf': 'c_pmt_getrf', \
# 'pmt_getrsm': 'c_pmt_getrsm', \
# 'pmt_getrsv': 'c_pmt_getrsv', \
# 'pmt_potrsv': 'c_pmt_potrsv', \
# 'pvec_fill': 'c_pmt_pvec_fill', \
# 'print': 'printf'}
pmt_temp_types = {\
'pmat': 'struct pmat *', \
'pvec': 'struct pvec *', \
'None': 'void', \
'NoneType': 'void', \
'ptr_int': 'int *', \
'ptr_pmat': 'struct pmat **', \
'int': 'int', \
'float': 'double', \
'dimv': 'dimv', \
'dims': 'dims'}
# arg_types = {\
# 'pmat': ['int', 'int'], \
# 'pvec': ['int'], \
# 'pmt_gemm_nn': ['pmat', 'pmat', 'pmat', 'pmat'], \
# 'pmt_gemm_tn': ['pmat', 'pmat', 'pmat', 'pmat'], \
# 'pmt_trmm_rlnn': ['pmat', 'pmat', 'pmat'], \
# 'pmt_syrk_ln': ['pmat', 'pmat', 'pmat', 'pmat'], \
# 'pmt_gead': ['float', 'pmat', 'pmat'], \
# 'pmt_getrf': ['pmat', 'pmat', 'List'], \
# 'pmt_getrsm': ['pmat', 'List', 'pmat'], \
# 'pmt_getrsv': ['pmat', 'List', 'pvec'], \
# 'pmt_potrf': ['pmat', 'pmat'], \
# 'pmt_potrsm': ['pmat', 'pmat'], \
# 'pmt_potrsv': ['pmat', 'pvec'], \
# 'pmat_fill': ['pmat', 'float'], \
# 'pmat_copy': ['pmat', 'pmat'], \
# 'pmat_tran': ['pmat', 'pmat'], \
# 'pmat_vcat': ['pmat', 'pmat', 'pmat'], \
# 'pmat_hcat': ['pmat', 'pmat', 'pmat'], \
# 'pmat_print': ['pmat'], \
# 'pvec_fill': ['pvec', 'float'], \
# 'pvec_copy': ['pvec', 'pvec', 'pmat', 'pmat'], \
# 'pvec_print': ['pmat', 'pmat', 'pmat', 'pmat'], \
# }
native_types = ['int', 'float']
legacy_classinfo = ["ast.Num", "ast.Str"]
def my_isinstance(obj, classinfo):
if classinfo in legacy_classinfo:
if classinfo == "ast.Num":
if isinstance(obj, ast.Constant):
if isinstance(obj.value, int) or isinstance(obj.value, float):
return True
else:
return False
else:
return False
if classinfo == "ast.Str":
if isinstance(obj, ast.Constant):
if isinstance(obj.value, str):
return True
else:
return False
else:
return False
else:
return isinstance(obj, classinfo)
def check_node_structure(node, struct):
if struct == {}:
return True
else:
res = True
for key in struct.keys():
if hasattr(node, key):
res = res and check_node_structure(getattr(node, key), struct[key])
else:
return False
return res
def get_slice_value(node):
if sys.version_info >= (3, 9):
slice_val = node
else:
slice_val = node.value
return slice_val
class PmtArg:
def __init__(self, name):
self.name = name
self.type = None
self.tran = None
self.view = None
class PmtCall:
def __init__(self, name):
self.name = name
self.arg_num = 0
self.args = []
self.keywords = None
def recurse_attributes(node):
if my_isinstance(node, ast.Name):
return node.id
elif my_isinstance(node, ast.Attribute):
return recurse_attributes(node.value) + '->' + node.attr
else:
raise cgenException('Invalid attribute or method {}'.format(node))
def parse_pmt_gemm_args(generator, call, node):
arg0 = call.args[0].name
arg1 = call.args[1].name
arg2 = call.args[2].name
#default keyords arg values
alpha = 1.0
beta = 0.0
# loop over keywords
for kw in call.keywords:
if kw.arg == 'alpha':
alpha = kw.value.n
if kw.arg == 'beta':
beta = kw.value.n
if len(call.args) > 3:
arg3 = call.args[3].name
else:
arg3 = call.args[2].name
if call.args[0].tran:
tranA = 't'
else:
tranA = 'n'
if call.args[1].tran:
tranB = 't'
else:
tranB = 'n'
if call.args[2].tran:
raise cgenException('Cannot transpose arg 2 of gemm call', node.lineno)
if len(call.args) > 3:
if call.args[3].tran:
raise cgenException('Cannot transpose arg 3 of gemm call', node.lineno)
blasfeo_call = \
"blasfeo_dgemm_{4}{5}({0}->bmat->m, {1}->bmat->n, {0}->bmat->n, {6}, {0}->bmat, 0, 0, {1}->bmat, 0, 0, {7}, {2}->bmat, 0, 0, {3}->bmat, 0, 0);\n".format(arg0, arg1, arg2, arg3, tranA, tranB, alpha, beta)
generator.write(blasfeo_call, dest = 'src')
return
blas_api_funs = {'pmt_gemm' : parse_pmt_gemm_args}
usr_temp_types = {}
class cgenException(Exception):
def __init__(self, message, lineno):
super().__init__(message)
self.message = message
self.lineno = lineno
def to_source(node, module_name, indent_with=' ' * 4, add_line_information=False,
pretty_string=pretty_string, pretty_source=pretty_source,
main=False, size_of_pointer=8, size_of_int=4, size_of_double=8):
"""This function can convert a node tree back into python sourcecode.
This is useful for debugging purposes, especially if you're dealing with
custom asts not generated by python itself.
It could be that the sourcecode is evaluable when the AST itself is not
compilable / evaluable. The reason for this is that the AST contains some
more data than regular sourcecode does, which is dropped during
conversion.
Each level of indentation is replaced with `indent_with`. Per default this
parameter is equal to four spaces as suggested by PEP 8, but it might be
adjusted to match the application's styleguide.
If `add_line_information` is set to `True` comments for the line numbers
of the nodes are added to the output. This can be used to spot wrong line
number information of statement nodes.
"""
generator = SourceGenerator(indent_with, size_of_pointer, \
size_of_int, size_of_double, add_line_information, pretty_string)
generator.result.source.append('#include "stdlib.h"\n')
# generator.result.source.append('#include "pmat_blasfeo_wrapper.h"\n')
# generator.result.source.append('#include "pvec_blasfeo_wrapper.h"\n')
# generator.result.source.append('#include "pmt_heap.h"\n')
generator.result.source.append('#include "%s.h"\n' %(module_name))
generator.result.source.append('void * ___c_pmt_8_heap;\n')
generator.result.source.append('void * ___c_pmt_64_heap;\n')
generator.result.source.append('void * ___c_pmt_8_heap_head;\n')
generator.result.source.append('void * ___c_pmt_64_heap_head;\n')
generator.result.header.append('#include "prometeo.h"\n')
generator.result.header.append('#include "timing.h"\n')
generator.result.header.append('#include "pmt_aux.h"\n')
generator.result.header.append('#ifdef __cplusplus\nextern "C" {\n#endif\n\n')
try:
generator.visit(node)
except:
print('\n > Exception -- prometeo code-gen: \033[1;31mparser error at {}:{}\033[0;0m\n'.format(generator.current_line, generator.current_col))
raise
generator.result.source.append('\n')
if set(generator.result.source[0]) == set('\n'):
generator.result.source[0] = ''
generator.result.header.append('#ifdef __cplusplus\n}\n#endif\n\n')
generator.result.header.append('\n')
if set(generator.result.header[0]) == set('\n'):
generator.result.header[0] = ''
# dump meta-data to JSON file
pmt_cache_dir = '__pmt_cache__'
if not os.path.exists(pmt_cache_dir):
os.mkdir(pmt_cache_dir)
os.chdir(pmt_cache_dir)
json_file = 'typed_record.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.typed_record), f, indent=4)
json_file = 'meta_info.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.meta_info), f, indent=3)
json_file = 'var_dim_record.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.var_dim_record), f, indent=4)
json_file = 'dim_record.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.dim_record), f, indent=4)
json_file = 'usr_types.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(usr_temp_types), f, indent=4)
json_file = 'heap8.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.heap8_record), f, indent=4)
json_file = 'heap64.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.heap64_record), f, indent=4)
json_file = 'constructor_record.json'
with open(json_file, 'w') as f:
json.dump(OrderedDict(generator.heap64_record), f, indent=4)
json_file = 'function_record.json'
with open(json_file, 'w') as f:
json.dump(generator.function_record, f, indent=4)
json_file = 'casadi_funs.json'
with open(json_file, 'w') as f:
json.dump(generator.casadi_funs, f, indent=4)
os.chdir('..')
return generator.result
def precedence_setter(AST=ast.AST, get_op_precedence=get_op_precedence,
my_isinstance=my_isinstance, list=list):
""" This only uses a closure for performance reasons,
to reduce the number of attribute lookups. (set_precedence
is called a lot of times.)
"""
def set_precedence(value, *nodes):
"""Set the precedence (of the parent) into the children.
"""
if my_isinstance(value, AST):
value = get_op_precedence(value)
for node in nodes:
if my_isinstance(node, AST):
node._pp = value
elif my_isinstance(node, list):
set_precedence(value, *node)
else:
assert node is None, node
return set_precedence
set_precedence = precedence_setter()
def descope(current_scope, pop):
if current_scope.endswith(pop):
return current_scope[:-len(pop)]
else:
raise Exception('Attempt to descope {}, which is \
not the current scope'.format(pop))
def Num_or_Name(node):
"""
Return node.n if, if node is of type Num, node.id if node is of type Name
and -node.n if node is of type UnaryOp and node.op is of type USub
"""
if my_isinstance(node, "ast.Num"):
return node.n
elif my_isinstance(node, ast.Name):
return node.id
elif my_isinstance(node, ast.UnaryOp):
if my_isinstance(node.op, ast.USub):
return -Num_or_Name(node.operand)
else:
raise cgenException('node.op is not of type ast.USub.\n', node.lineno)
else:
raise cgenException('node is not of type ast.Num nor ast.Name.\n', node.lineno)
def check_expression(node, binops, unops, usr_types, ast_types, record):
"""
Return True if node is an expression that uses the operations in binops and unops and
whose operations are of the types contained in the tuples usr_types and ast_types
"""
if my_isinstance(node, ast_types):
return True
elif my_isinstance(node, ast.Name):
if node.id in record:
return True
else:
if my_isinstance(node, ast.BinOp):
if my_isinstance(node.op, binops):
return check_expression(node.left, binops, unops, usr_types, ast_types, record) \
and check_expression(node.right, binops, unops, usr_types, ast_types, record)
else:
raise cgenException('unsopported BinOp {}\n'.format(astu.unparse(node)), node.lineno)
elif my_isinstance(node, ast.UnaryOp):
if my_isinstance(node.op, unops):
return check_expression(node.operand, binops, unops, usr_types, ast_types, record)
else:
raise cgenException('unsopported UnaryOp {}\n'.format(astu.unparse(node)), node.lineno)
else:
raise cgenException('could not resolve expression {}\n'.format(astu.unparse(node)), node.lineno)
# def process_annotation(ann_node):
# if my_isinstance(ann_node, ast.Name):
# return ann_node.id
# elif my_isinstance(ann_node, ast.Subscript):
# return ann_node.value.id + '[' + Num_or_Name(ann_node.slice.value.elts[0]) + \
# ',' + Num_or_Name(ann_node.slice.value.elts[0]) + ']'
# def get_pmt_type_value(node, record):
# """
# Return prometeo-type of node.value
# """
# # simple value
# if hasattr(node, 'value'):
# if my_isinstance(node.value, ast.Name):
# var_name = Num_or_Name(node)
# if var_name in record:
# return record[var_name]
# # try to infer basic types
# if my_isinstance(node.value, ast.Num):
# import pdb; pdb.set_trace()
# if my_isinstance(node.ast.Num, int):
# return 'int'
# elif my_isinstance(node.ast.Num, float):
# return 'float'
# else:
# raise cgenException('Could not determine type of node.value', self.lineno)
class Delimit(object):
"""A context manager that can add enclosing
delimiters around the output of a
SourceGenerator method. By default, the
parentheses are added, but the enclosed code
may set discard=True to get rid of them.
"""
discard = False
def __init__(self, tree, *args):
""" use write instead of using result.source directly
for initial data, because it may flush
preceding data into result.source.
"""
delimiters = '()'
node = None
op = None
for arg in args:
if my_isinstance(arg, ast.AST):
if node is None:
node = arg
else:
op = arg
else:
delimiters = arg
tree.write(delimiters[0], dest = 'src')
result = self.result = tree.result
result.source = self.result.source = tree.result.source
self.index = len(result.source)
self.closing = delimiters[1]
if node is not None:
self.p = p = get_op_precedence(op or node)
self.pp = pp = tree.get__pp(node)
self.discard = p >= pp
def __enter__(self):
return self
def __exit__(self, *exc_info):
result = self.result
result.source = self.result.source
start = self.index - 1
if self.discard:
result.source[start] = ''
else:
result.source.append(self.closing)
class SourceGenerator(ExplicitNodeVisitor):
"""This visitor is able to transform a well formed syntax tree into C
source code.
For more details have a look at the docstring of the `node_to_source`
function.
"""
using_unicode_literals = False
def __init__(self, indent_with, size_of_pointer, size_of_int, size_of_double, \
add_line_information=False,pretty_string=pretty_string,
blasfeo_ps = 4, blasfeo_nc = 4):
self.result = namedtuple('result', 'source header')
self.result.source = []
self.result.header = []
self.indent_with = indent_with
self.add_line_information = add_line_information
self.indentation = 0 # Current indentation level
self.new_lines = 0 # Number of lines to insert before next code
self.colinfo = 0, 0 # index in result.source of string containing
# linefeed, and position of last linefeed in
# that string
self.pretty_string = pretty_string
AST = ast.AST
visit = self.visit
newline = self.newline
result = self.result
result.source = self.result.source
result.header = self.result.header
append_src = result.source.append
append_hdr = result.header.append
self.size_of_pointer = size_of_pointer
self.size_of_int = size_of_int
self.size_of_double = size_of_double
self.blasfeo_ps = blasfeo_ps
self.blasfeo_nc = blasfeo_nc
self.typed_record = {'global': dict()}
self.meta_info = {'global': {'methods' : dict(), 'attributes' : dict()}}
# self.heap8_record = {'global': dict()}
self.heap8_record = {'global': "0"}
# self.heap64_record = {'global': dict()}
self.heap64_record = {'global': "0"}
self.scope = 'global'
self.call_scope = 'global'
self.casadi_funs = []
self.var_dim_record = {'global': dict()}
self.dim_record = dict()
self.constructor_record = []
self.function_record = {
'global': {
'_Z4pmatdimsdims' : {
'arg_types' : ["dims", "dims"],
'ret_type': "pmat"
},
'_Z4pvecdims' : {
'arg_types' : ["dims"],
'ret_type': "pvec"
},
'_Z10pmat_printpmat' : {
'arg_types' : ["pmat"],
'ret_type': "None"
},
'_Z8pmt_gemmpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z8pmt_gemmpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_nnpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_nnpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_ntpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_ntpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_tnpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_tnpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_ttpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z11pmt_gemm_ttpmatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z8pmt_geadfloatpmatpmat' : {
'arg_types' : ["float", "pmat", "pmat"],
'ret_type': "None"
},
'_Z9pmt_potrfpmatpmat' : {
'arg_types' : ["pmat", "pmat"],
'ret_type': "None"
},
'_Z10pmt_potrsmpmatpmat' : {
'arg_types' : ["pmat", "pmat"],
'ret_type': "None"
},
'_Z9pmat_tranpmatpmat' : {
'arg_types' : ["pmat", "pmat"],
'ret_type': "None"
},
'_Z9pmat_copypmatpmat' : {
'arg_types' : ["pmat", "pmat"],
'ret_type': "None"
},
'_Z9pmat_fillpmatfloat' : {
'arg_types' : ["pmat", "float"],
'ret_type': "None"
},
'_Z9pmat_hcatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z9pmat_vcatpmatpmatpmat' : {
'arg_types' : ["pmat", "pmat", "pmat"],
'ret_type': "None"
},
'_Z10pvec_printpvec' : {
'arg_types' : ["pvec"],
'ret_type': "None"
},
'_Z9pvec_copypvecpvec' : {
'arg_types' : ["pvec", "pvec"],
'ret_type': "None"
}
}
}
self.in_main = False
self.current_line = 1
self.current_col = 1
def write(*params, dest):
""" self.write is a closure for performance (to reduce the number
of attribute lookups).
"""
for item in params:
if my_isinstance(item, AST):
visit(item)
elif callable(item):
item()
elif item == '\n':
newline()
else:
if dest == 'src':
if self.new_lines:
append_src('\n' * self.new_lines)
self.colinfo = len(result.source), 0
append_src(self.indent_with * self.indentation)
self.new_lines = 0
if item:
append_src(item)
if dest == 'hdr':
if self.new_lines:
append_hdr('\n' * self.new_lines)
self.colinfo = len(result.header), 0
append_hdr(self.indent_with * self.indentation)
self.new_lines = 0
if item:
append_hdr(item)
self.write = write
def __getattr__(self, name, defaults=dict(keywords=(),
_pp=Precedence.highest).get):
""" Get an attribute of the node.
like dict.get (returns None if doesn't exist)
"""
if not name.startswith('get_'):
raise AttributeError
geta = getattr
shortname = name[4:]
default = defaults(shortname)
def getter(node):
return geta(node, shortname, default)
setattr(self, name, getter)
return getter
def delimit(self, *args):
return Delimit(self, *args)
def conditional_write(self, *stuff, dest):
if stuff[-1] is not None:
self.write(*stuff, dest = dest)
# Inform the caller that we wrote
return True
def newline(self, node=None, extra=0):
self.new_lines = max(self.new_lines, 1 + extra)
if node is not None and self.add_line_information:
self.write('# line: %s' % node.lineno, dest = 'src')
self.new_lines = 1
def get_type_of_node(self, node, scope):
"""
Get type of AST node.
Parameters
----------
node
node whose type we want to determine
scope
current scope
Returns
-------
type_val : str
type of expression
arg_types : dict
type of arguments (if a Call node is being analyzed, None otherwise)
"""
if my_isinstance(node, ast.Name):
if node.id in self.typed_record[scope]:
type_val = self.typed_record[scope][node.id]
elif node.id in self.dim_record:
type_val = 'dims'
else:
raise cgenException('Undefined variable {}'.format(node.id), node.lineno)
return type_val, None
elif my_isinstance(node, "ast.Num"):
type_val = type(node.n).__name__
return type_val, None
elif my_isinstance(node, "ast.Str"):
type_val = type(node.value).__name__
return type_val, None
elif my_isinstance(node, ast.NameConstant):
if node.value == None:
type_val = None
return type_val, None
else:
raise cgenException('Undefined type {}'.format(node.value), node.lineno)
elif my_isinstance(node, ast.BinOp):
type_l, s = self.get_type_of_node(node.left, scope)
type_r, s = self.get_type_of_node(node.right, scope)
if type_l != type_r:
raise cgenException("Type mismatch in BinOp: left = {}, \
right = {}".format(type_l,type_r), node.lineno)
return type_l, None
elif my_isinstance(node, ast.UnaryOp):
type_val, s = self.get_type_of_node(node.operand, scope)
return type_val, None
elif my_isinstance(node, ast.Subscript):
if my_isinstance(node.value, ast.Name):
if node.value.id not in self.typed_record[scope]:
raise cgenException('Undefined variable {}'.format(node.id), node.lineno)
elif self.typed_record[scope][node.value.id] == 'pmat' or \
self.typed_record[scope][node.value.id] == 'pvec':
return 'float', None
elif 'List' in self.typed_record[scope][node.value.id]:
raise Exception("Not implemented")
elif my_isinstance(node.value, ast.Attribute):
type_val, s = self.get_type_of_node(node.value, scope)
# the type of a subscripted List is given by the type of
# its elements
return type_val.split('[')[1].split(',')[0], None
else:
raise cgenException("Invalid node type {}".format(node.value), node.lineno)
elif my_isinstance(node, ast.Attribute):
# check if first attr is 'self'
attr_chain = recurse_attributes(node.value)
attr_list = attr_chain.split('->')
if attr_list[0] == 'self':
class_scope = '@'.join(scope.split('@')[:-1])
type_val = self.get_type_of_node_rec(node.value, class_scope)
else:
type_val = self.get_type_of_node_rec(node.value, scope)
if node.attr not in self.meta_info[type_val]['attr']:
raise cgenException('Undefined variable or attribute {}'.format(node.attr), node.lineno)
if self.meta_info[type_val]['attr'][node.attr] in native_types:
type_val = self.meta_info[type_val]['attr'][node.attr]
else:
type_val = 'global@' + self.meta_info[type_val]['attr'][node.attr]
return type_val, None
elif my_isinstance(node, ast.Call):
if my_isinstance(node.func, ast.Name):
fun_name = node.func.id
pre_mangl = '_Z' + str(len(fun_name))
post_mangl = self.build_arg_mangling(node.args, is_call = True)
fun_name_m = pre_mangl + fun_name + post_mangl
# TODO(andrea): add check for casadi functions
if fun_name_m in self.function_record['global']:
type_val = self.function_record['global'][fun_name_m]['ret_type']
return type_val, self.function_record['global'][fun_name_m]['arg_types']
elif fun_name not in self.casadi_functions:
return 'pmat'
else:
raise cgenException('Undefined method {}'.format(fun_name_m), node.lineno)
elif my_isinstance(node.func, ast.Attribute):
type_val = self.get_type_of_node_rec(node.func.value, scope)
fun_name = node.func.attr
pre_mangl = '_Z' + str(len(fun_name))
post_mangl = self.build_arg_mangling(node.args, is_call = True)
fun_name_m = pre_mangl + fun_name + post_mangl
if fun_name_m not in self.meta_info[type_val]['methods']:
raise cgenException('Undefined method {}'.format(fun_name_m), node.lineno)
arg_types = self.meta_info[type_val]['methods'][fun_name_m]['args']
type_val = self.meta_info[type_val]['methods'][fun_name_m]['return_type']
return type_val, arg_types
else:
raise cgenException('Parse error.', node.lineno)
def get_type_of_node_rec(self, node, scope):
if my_isinstance(node, ast.Name):
if node.id == 'self':
type_val = scope
return type_val
if node.id not in self.typed_record[scope]:
raise cgenException('Undefined variable or attribute {}'.format(node.id), node.lineno)
if self.typed_record[scope][node.id] in native_types:
type_val = self.typed_record[scope][node.id]
else:
type_val = 'global@' + self.typed_record[scope][node.id]
return type_val
else:
if my_isinstance(node, ast.Attribute):
type_val = self.get_type_of_node_rec(node.value, scope)
if node.attr not in self.meta_info[type_val]['attr']:
raise cgenException('Undefined variable or attribute {}'.format(node.attr), node.lineno)
if self.meta_info[type_val]['attr'][node.attr] in native_types:
type_val = self.meta_info[type_val]['attr'][node.attr]
else:
type_val = 'global@' + self.meta_info[type_val]['attr'][node.attr]
return type_val
def fun_in_function_record(self, scope):
tokens = scope.split('@')
if tokens[0] in self.function_record:
return self.fun_in_function_record_rec(tokens[1:], self.function_record[tokens[0]])
else:
return False
def fun_in_function_record_rec(self, tokens, scope):
if 'ret_type' in scope:
return True
elif tokens[0] in scope:
return self.fun_in_function_record_rec(tokens[1:], scope[tokens[0]])
else:
return False
def get_ret_type_from_function_record(self, scope):
tokens = scope.split('@')
if tokens[0] in self.function_record:
return self.get_ret_type_from_function_record_rec(tokens[1:], self.function_record[tokens[0]])
else:
raise cgenException('Could not resolve scope {}'.format(scope), node.lineno)
def get_ret_type_from_function_record_rec(self, tokens, scope):
if 'ret_type' in scope:
return scope["ret_type"]
elif tokens[0] in scope:
return self.get_ret_type_from_function_record_rec(tokens[1:], scope[tokens[0]])
else:
raise cgenException('Could not resolve scope {}'.format(scope), node.lineno)
def body(self, statements):
self.indentation += 1
self.write(*statements, dest = 'src')
self.indentation -= 1
def body_class(self, statements, name):
self.indentation += 1
# class attributes (header)
self.write_class(*statements, name=name)
self.write('};', dest = 'hdr')
self.indentation -= 1
# method prototypes
self.write_class_method_prototypes(*statements, name=name)
self.write('\n', dest = 'src')
# init
self.write_class_constructor(*statements, name=name)
# methods
self.write_class_methods(*statements, name=name)
def process_list_type(self, node):
if node.value.func.id != 'plist':
raise cgenException('Cannot create Lists without using'
' plist constructor.', node.lineno)
else:
if len(node.value.args) != 2:
raise cgenException('Type annotations in List \
declaration must have the format \
List[<type>, <sizes>]', node.lineno)
# attribute is a List
ann = node.value.args[0].value
dims = Num_or_Name(node.value.args[1])
# ann = node.annotation.slice.value.elts[0].id
# dims = Num_or_Name(node.annotation.slice.value.elts[1])
if my_isinstance(dims, str):
list_type = 'List[' + ann + ', ' + dims + ']'
else:
list_type = 'List[' + ann + ', ' + str(dims) + ']'
return list_type
if my_isinstance(dims, str):
# dimension argument is a variable
self.typed_record[self.scope][node.target.attr] = \
'List[' + ann + ', ' + dims + ']'
# TODO(andrea):
# use instead 'dict({type: 'List', "attr": {"ann" : ann, "dims" : dims}})
else:
# dimension argument is an integer
self.typed_record[self.scope][node.target.attr] = \
'List[' + ann + ', ' + str(dims) + ']'
def write_instance_attributes(self, params, name):
"""
Add instance attributes to struct definition in the header.
"""
for item in params:
if my_isinstance(item, ast.AnnAssign):
# skip non-attribute declarations
if my_isinstance(item.target, ast.Name):
break
if item.target.value.id != 'self':
raise cgenException('Unrecognized attribute declaration', self.lineno)
set_precedence(item, item.target, item.annotation)
set_precedence(Precedence.Comma, item.value)
need_parens = my_isinstance(item.target, ast.Name) and not item.simple
begin = '(' if need_parens else ''
end = ')' if need_parens else ''
annotation = item.annotation
# annotation = ast.parse(item.annotation.s).body[0]
# if 'value' in annotation.value.__dict__:
type_py = annotation.id
if type_py == 'List':
list_type = self.process_list_type(item)
self.meta_info[self.scope]['attr'][item.target.attr] = list_type
else:
self.meta_info[self.scope]['attr'][item.target.attr] = type_py
if type_py == 'List':
list_type = self.process_list_type(item)
self.typed_record[self.scope][item.target.attr] = list_type
# check if dims is not a numerical value
# TODO(andrea): fix this for numeric values!
ann = item.value.args[0].value
if ann in pmt_temp_types:
ann = pmt_temp_types[ann]
dims = Num_or_Name(item.value.args[1])
if my_isinstance(dims, str):
dim_list = self.dim_record[dims]
if my_isinstance(dim_list, list):
array_size = len(dim_list)
else:
array_size = dim_list
# array_size = str(Num_or_Name(item.value.args[1]))
# self.statement([], ann, ' ', item.target, '[', array_size, '];')
self.write('%s' %ann, ' ', '%s' %item.target.attr, \
'[%s' %array_size, '];\n', dest = 'hdr')
else:
# not a List
ann = type_py
# check for user-defined types
if ann in usr_temp_types:
self.write('struct %s' %ann, ' ', item.target.attr, '___;\n', dest = 'hdr')
self.write('struct %s *' %ann, ' ', item.target.attr, ';\n', dest = 'hdr')
# self.statement(node, node.annotation, ' ', node.target, '= &', node.target, '___;')
else: