forked from inducer/islpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_wrap.py
1752 lines (1380 loc) · 51.9 KB
/
gen_wrap.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
from __future__ import print_function
__copyright__ = "Copyright (C) 2011-15 Andreas Kloeckner"
__license__ = """
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import re
import sys
from py_codegen import PythonCodeGenerator, Indentation
from distutils.sysconfig import get_config_var
SEM_TAKE = "take"
SEM_GIVE = "give"
SEM_KEEP = "keep"
SEM_NULL = "null"
ISL_SEM_TO_SEM = {
"__isl_take": SEM_TAKE,
"__isl_give": SEM_GIVE,
"__isl_keep": SEM_KEEP,
"__isl_null": SEM_NULL,
}
NON_COPYABLE = ["ctx", "printer", "access_info"]
NON_COPYABLE_WITH_ISL_PREFIX = ["isl_"+i for i in NON_COPYABLE]
PYTHON_RESERVED_WORDS = """
and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
""".split()
# {{{ data model
class Argument:
def __init__(self, name, semantics, decl_words, base_type, ptr):
self.name = name
self.semantics = semantics
assert isinstance(decl_words, list)
self.decl_words = decl_words
self.base_type = base_type
self.ptr = ptr
def c_declarator(self):
return "{decl_words} {type} {ptr}{name}".format(
decl_words=" ".join(self.decl_words),
type=self.base_type,
ptr=self.ptr,
name=self.name)
class CallbackArgument:
def __init__(self, name,
return_semantics, return_decl_words, return_base_type, return_ptr, args):
self.name = name
self.return_semantics = return_semantics
assert isinstance(return_decl_words, list)
self.return_decl_words = return_decl_words
self.return_base_type = return_base_type
self.return_ptr = return_ptr
self.args = args
def c_declarator(self):
return "{decl_words} {type} {ptr}(*{name})({args})".format(
decl_words=" ".join(self.return_decl_words),
type=self.return_base_type,
ptr=self.return_ptr,
name=self.name,
args=", ".join(arg.c_declarator() for arg in self.args))
class Method:
def __init__(self, cls, name, c_name,
return_semantics, return_decl_words, return_base_type, return_ptr,
args, is_exported, is_constructor):
self.cls = cls
self.name = name
self.c_name = c_name
self.return_semantics = return_semantics
self.return_decl_words = return_decl_words
self.return_base_type = return_base_type
self.return_ptr = return_ptr
self.args = args
self.mutator_veto = False
self.is_exported = is_exported
self.is_constructor = is_constructor
if not self.is_static:
self.args[0].name = "self"
@property
def is_static(self):
return not (self.args and self.args[0].base_type.startswith("isl_"+self.cls))
@property
def is_mutator(self):
return (not self.is_static
and self.args[0].semantics is SEM_TAKE
and self.return_ptr == "*" == self.args[0].ptr
and self.return_base_type == self.args[0].base_type
and self.return_semantics is SEM_GIVE
and not self.mutator_veto
and self.args[0].base_type in NON_COPYABLE_WITH_ISL_PREFIX)
def __repr__(self):
return "<method %s>" % self.c_name
# }}}
CLASSES = [
# /!\ Order matters, class names that are prefixes of others should go last.
"ctx",
# lists
"id_list", "val_list",
"basic_set_list", "basic_map_list", "set_list", "map_list",
"union_set_list",
"constraint_list",
"aff_list", "pw_aff_list", "pw_multi_aff_list",
"ast_expr_list", "ast_node_list",
"pw_qpolynomial_list",
"pw_qpolynomial_fold_list",
# maps
"id_to_ast_expr",
# others
"printer", "val", "multi_val", "vec", "mat", "fixed_box",
"aff", "pw_aff", "union_pw_aff",
"multi_aff", "multi_pw_aff", "pw_multi_aff", "union_pw_multi_aff",
"union_pw_aff_list",
"multi_union_pw_aff",
"id",
"constraint", "space", "local_space",
"basic_set", "basic_map",
"set", "map",
"union_map", "union_set",
"point", "vertex", "cell", "vertices",
"stride_info",
"qpolynomial_fold", "pw_qpolynomial_fold",
"union_pw_qpolynomial_fold",
"union_pw_qpolynomial",
"qpolynomial", "pw_qpolynomial",
"term",
"band", "schedule_constraints", "schedule_node", "schedule",
"access_info", "flow", "restriction",
"union_access_info", "union_flow",
"ast_expr", "ast_node", "ast_print_options",
"ast_build",
]
UNTYPEDEFD_CLASSES = ["options"]
IMPLICIT_CONVERSIONS = {
"isl_set": [("isl_basic_set", "from_basic_set")],
"isl_map": [("isl_basic_map", "from_basic_map")],
"isl_union_set": [("isl_set", "from_set")],
"isl_union_map": [("isl_map", "from_map")],
"isl_local_space": [("isl_space", "from_space")],
"isl_pw_aff": [("isl_aff", "from_aff")],
}
ENUMS = {
# ctx.h
"isl_error": """
isl_error_none,
isl_error_abort,
isl_error_alloc,
isl_error_unknown,
isl_error_internal,
isl_error_invalid,
isl_error_quota,
isl_error_unsupported,
""",
"isl_stat": """
isl_stat_error,
isl_stat_ok,
""",
"isl_bool": """
isl_bool_error,
isl_bool_false,
isl_bool_true,
""",
# space.h
"isl_dim_type": """
isl_dim_cst,
isl_dim_param,
isl_dim_in,
isl_dim_out,
isl_dim_set,
isl_dim_div,
isl_dim_all,
""",
# schedule_type.h
"isl_schedule_node_type": """
isl_schedule_node_error,
isl_schedule_node_band,
isl_schedule_node_context,
isl_schedule_node_domain,
isl_schedule_node_expansion,
isl_schedule_node_extension,
isl_schedule_node_filter,
isl_schedule_node_leaf,
isl_schedule_node_guard,
isl_schedule_node_mark,
isl_schedule_node_sequence,
isl_schedule_node_set,
""",
# ast_type.h
"isl_ast_op_type": """
isl_ast_op_error,
isl_ast_op_and,
isl_ast_op_and_then,
isl_ast_op_or,
isl_ast_op_or_else,
isl_ast_op_max,
isl_ast_op_min,
isl_ast_op_minus,
isl_ast_op_add,
isl_ast_op_sub,
isl_ast_op_mul,
isl_ast_op_div,
isl_ast_op_fdiv_q,
isl_ast_op_pdiv_q,
isl_ast_op_pdiv_r,
isl_ast_op_zdiv_r,
isl_ast_op_cond,
isl_ast_op_select,
isl_ast_op_eq,
isl_ast_op_le,
isl_ast_op_lt,
isl_ast_op_ge,
isl_ast_op_gt,
isl_ast_op_call,
isl_ast_op_access,
isl_ast_op_member,
isl_ast_op_address_of,
""",
"isl_ast_expr_type": """
isl_ast_expr_error,
isl_ast_expr_op,
isl_ast_expr_id,
isl_ast_expr_int,
""",
"isl_ast_node_type": """
isl_ast_node_error,
isl_ast_node_for,
isl_ast_node_if,
isl_ast_node_block,
isl_ast_node_mark,
isl_ast_node_user,
""",
"isl_ast_loop_type": """
isl_ast_loop_error,
isl_ast_loop_default,
isl_ast_loop_atomic,
isl_ast_loop_unroll,
isl_ast_loop_separate,
""",
# polynomial_type.h
"isl_fold": """
isl_fold_min,
isl_fold_max,
isl_fold_list,
""",
# printer.h
"isl_format": """
ISL_FORMAT_ISL,
ISL_FORMAT_POLYLIB,
ISL_FORMAT_POLYLIB_CONSTRAINTS,
ISL_FORMAT_OMEGA,
ISL_FORMAT_C,
ISL_FORMAT_LATEX,
ISL_FORMAT_EXT_POLYLIB,
""",
"isl_yaml_style": """
ISL_YAML_STYLE_BLOCK,
ISL_YAML_STYLE_FLOW,
""",
# options.h
"isl_bound": """
ISL_BOUND_BERNSTEIN,
ISL_BOUND_RANGE,
""",
"isl_on_error": """
ISL_ON_ERROR_WARN,
ISL_ON_ERROR_CONTINUE,
ISL_ON_ERROR_ABORT,
""",
"isl_schedule_algorithm": """
ISL_SCHEDULE_ALGORITHM_ISL,
ISL_SCHEDULE_ALGORITHM_FEAUTRIER,
"""
}
TYPEDEFD_ENUMS = ["isl_stat", "isl_bool"]
MACRO_ENUMS = [
"isl_format", "isl_yaml_style",
"isl_bound", "isl_on_error", "isl_schedule_algorithm",
]
HEADER_PREAMBLE = """
// flow.h
typedef int (*isl_access_level_before)(void *first, void *second);
typedef isl_restriction *(*isl_access_restrict)(
isl_map *source_map, isl_set *sink,
void *source_user, void *user);
"""
PY_PREAMBLE = """
from __future__ import print_function
import six
import sys
import logging
import threading
_PY3 = sys.version_info >= (3,)
is_win = sys.platform.startswith('win32')
from islpy._isl_cffi import ffi
if is_win:
lib = ffi.dlopen('{win_pyd}')
else:
lib = ffi.dlopen(None)
from cffi import FFI
libc_ffi = FFI()
cdef_string = '''
char *strdup(const char *s);
void free(void *ptr);
'''
if is_win:
cdef_string = cdef_string.replace('strdup', '_strdup')
libc_ffi.cdef(cdef_string)
if is_win and sys.version_info >= (3,5):
libc = libc_ffi.dlopen('ucrtbase')
else:
libc = libc_ffi.dlopen(None)
class Error(Exception):
pass
class IslTypeError(Error, TypeError):
pass
_context_use_map = {{}}
def _deref_ctx(ctx_data, ctx_iptr):
_context_use_map[ctx_iptr] -= 1
if _context_use_map[ctx_iptr] == 0:
del _context_use_map[ctx_iptr]
lib.isl_ctx_free(ctx_data)
def _get_last_error_str(ctx_data):
code = lib.isl_ctx_last_error(ctx_data)
for name in dir(error):
if name.startswith("_"):
continue
if getattr(error, name) == code:
return "isl_error_"+name
return "(unknown error)"
class _ISLObjectBase(object):
def __init__(self, _data):
self._setup(_data)
def _setup(self, data):
assert not hasattr(self, "data")
assert isinstance(data, ffi.CData)
self.data = data
self._set_ctx_data()
iptr = self._ctx_iptr
_context_use_map[iptr] = _context_use_map.get(iptr, 0) + 1
def _reset(self, data):
assert self.data is not None
assert isinstance(data, ffi.CData)
_deref_ctx(self._ctx_data, self._ctx_iptr)
self.data = data
self._set_ctx_data()
iptr = self._ctx_iptr
_context_use_map[iptr] = _context_use_map.get(iptr, 0) + 1
def _set_ctx_data(self):
self._ctx_data = self._get_ctx_data()
self._ctx_iptr = int(ffi.cast("intptr_t", self._get_ctx_data()))
def _release(self):
if self.data is None:
raise Error("cannot release already-released object")
data = self.data
if _deref_ctx is not None:
_deref_ctx(self._ctx_data, self._ctx_iptr)
else:
# This can happen if we're called super-late in cleanup.
# Since everything else is already mopped up, we really
# can't do what it takes to mop up this context.
# So we leak it (i.e. leave it for the OS to clean up.)
pass
self.data = None
return data
def __eq__(self, other):
return (type(self) == type(other) and self.data == other.data)
def __ne__(self, other):
return not self.__eq__(other)
class _EnumBase(object):
@classmethod
def find_value(cls, v):
for name in dir(cls):
if getattr(cls, name) == v:
return name
raise ValueError("Value '%s' not found in enum" % v)
class _ManagedCString(object):
def __init__(self, cdata):
if is_win:
self.data = libc._strdup(cdata)
else:
self.data = libc.strdup(cdata)
if self.data == libc_ffi.NULL:
raise Error("strdup() failed")
def release(self):
if self.data is None:
raise Error("cannot release already-released object")
data = self.data
self.data = None
return data
def __del__(self):
libc.free(self.data)
if _PY3:
class DelayedKeyboardInterrupt(object):
def __enter__(self):
self.previous_switch_interval = sys.getswitchinterval()
sys.setswitchinterval(10000000)
def __exit__(self, type, value, traceback):
sys.setswitchinterval(self.previous_switch_interval)
else:
class DelayedKeyboardInterrupt(object):
def __enter__(self):
self.previous_check_interval = sys.getcheckinterval()
sys.setcheckinterval(100000000)
def __exit__(self, type, value, traceback):
sys.setcheckinterval(self.previous_check_interval)
"""
SAFE_TYPES = list(ENUMS) + ["int", "unsigned", "uint32_t", "size_t", "double",
"long", "unsigned long"]
SAFE_IN_TYPES = SAFE_TYPES + ["const char *", "char *"]
SPECIAL_CLASS_NAME_MAP = {
"ctx": "Context"
}
def isl_class_to_py_class(cls_name):
if cls_name.startswith("isl_"):
cls_name = cls_name[4:]
try:
return SPECIAL_CLASS_NAME_MAP[cls_name]
except KeyError:
result = cls_name.title().replace("_", "")
result = result.replace("Qpoly", "QPoly")
return result
# {{{ parser
DECL_RE = re.compile(r"""
(?:__isl_overload\s*)?
((?:\w+\s+)*) (\**) \s* (?# return type)
(\w+) (?# func name)
\(
(.*) (?# args)
\)
""",
re.VERBOSE)
FUNC_PTR_RE = re.compile(r"""
((?:\w+\s+)*) (\**) \s* (?# return type)
\(\*(\w+)\) (?# func name)
\(
(.*) (?# args)
\)
""",
re.VERBOSE)
STRUCT_DECL_RE = re.compile(
r"(__isl_export\s+)?"
"struct\s+"
"(__isl_export\s+)?"
"(__isl_subclass\([a-z_ ]+\)\s+)?"
"([a-z_A-Z0-9]+)\s*;")
ARG_RE = re.compile(r"^((?:\w+)\s+)+(\**)\s*(\w+)$")
INLINE_SEMICOLON_RE = re.compile(r"\;[ \t]*(?=\w)")
def filter_semantics(words):
semantics = []
other_words = []
for w in words:
if w in ISL_SEM_TO_SEM:
semantics.append(ISL_SEM_TO_SEM[w])
else:
other_words.append(w)
if semantics:
assert len(semantics) == 1
return semantics[0], other_words
else:
return None, other_words
def split_at_unparenthesized_commas(s):
paren_level = 0
i = 0
last_start = 0
while i < len(s):
c = s[i]
if c == "(":
paren_level += 1
elif c == ")":
paren_level -= 1
elif c == "," and paren_level == 0:
yield s[last_start:i]
last_start = i+1
i += 1
yield s[last_start:i]
class BadArg(ValueError):
pass
class Retry(ValueError):
pass
class Undocumented(ValueError):
pass
class SignatureNotSupported(ValueError):
pass
def parse_arg(arg):
if "(*" in arg:
arg_match = FUNC_PTR_RE.match(arg)
assert arg_match is not None, "fptr: %s" % arg
return_semantics, ret_words = filter_semantics(
arg_match.group(1).split())
return_decl_words = ret_words[:-1]
return_base_type = ret_words[-1]
return_ptr = arg_match.group(2)
name = arg_match.group(3)
args = [parse_arg(i.strip())
for i in split_at_unparenthesized_commas(arg_match.group(4))]
return CallbackArgument(name.strip(),
return_semantics,
return_decl_words,
return_base_type,
return_ptr.strip(),
args)
words = arg.split()
semantics, words = filter_semantics(words)
decl_words = []
if words[0] in ["struct", "enum"]:
decl_words.append(words.pop(0))
rebuilt_arg = " ".join(words)
arg_match = ARG_RE.match(rebuilt_arg)
base_type = arg_match.group(1).strip()
if base_type == "isl_args":
raise BadArg("isl_args not supported")
assert arg_match is not None, rebuilt_arg
return Argument(
name=arg_match.group(3),
semantics=semantics,
decl_words=decl_words,
base_type=base_type,
ptr=arg_match.group(2).strip())
class FunctionData:
def __init__(self, include_dirs):
self.classes_to_methods = {}
self.include_dirs = include_dirs
self.seen_c_names = set()
self.headers = []
def read_header(self, fname):
self.headers.append(fname)
from os.path import join
success = False
for inc_dir in self.include_dirs:
try:
inf = open(join(inc_dir, fname), "rt")
except IOError:
pass
else:
success = True
break
if not success:
raise RuntimeError("header '%s' not found" % fname)
try:
lines = inf.readlines()
finally:
inf.close()
# heed continuations, split at semicolons
new_lines = []
i = 0
while i < len(lines):
my_line = lines[i].strip()
i += 1
while my_line.endswith("\\"):
my_line = my_line[:-1] + lines[i].strip()
i += 1
if not my_line.strip().startswith("#"):
my_line = INLINE_SEMICOLON_RE.sub(";\n", my_line)
new_lines.extend(my_line.split("\n"))
lines = new_lines
i = 0
while i < len(lines):
l = lines[i].strip()
if (not l
or l.startswith("extern")
or STRUCT_DECL_RE.search(l)
or l.startswith("typedef")
or l == "}"):
i += 1
elif "/*" in l:
while True:
if "*/" in l:
i += 1
break
i += 1
l = lines[i].strip()
elif l.endswith("{"):
while True:
if "}" in l:
i += 1
break
i += 1
l = lines[i].strip()
elif not l:
i += 1
else:
decl = ""
while True:
decl = decl + l
if decl:
decl += " "
i += 1
if STRUCT_DECL_RE.search(decl):
break
open_par_count = sum(1 for i in decl if i == "(")
close_par_count = sum(1 for i in decl if i == ")")
if open_par_count and open_par_count == close_par_count:
break
l = lines[i].strip()
if not STRUCT_DECL_RE.search(decl):
self.parse_decl(decl)
def parse_decl(self, decl):
decl_match = DECL_RE.match(decl)
if decl_match is None:
print("WARNING: func decl regexp not matched: %s" % decl)
return
return_base_type = decl_match.group(1)
return_base_type = return_base_type.replace("ISL_DEPRECATED", "").strip()
return_ptr = decl_match.group(2)
c_name = decl_match.group(3)
args = [i.strip()
for i in split_at_unparenthesized_commas(decl_match.group(4))]
if args == ["void"]:
args = []
if c_name in [
"ISL_ARG_DECL",
"ISL_DECLARE_LIST",
"ISL_DECLARE_LIST_FN",
"isl_ast_op_type_print_macro",
"ISL_DECLARE_MULTI",
"ISL_DECLARE_MULTI_CMP",
"ISL_DECLARE_MULTI_NEG",
"ISL_DECLARE_MULTI_DIMS",
"ISL_DECLARE_MULTI_WITH_DOMAIN",
"isl_malloc_or_die",
"isl_calloc_or_die",
"isl_realloc_or_die",
"isl_handle_error",
]:
return
assert c_name.startswith("isl_"), c_name
name = c_name[4:]
found_class = False
for cls in CLASSES:
if name.startswith(cls):
found_class = True
name = name[len(cls)+1:]
break
# Don't be tempted to chop off "_val"--the "_val" versions of
# some methods are incompatible with the isl_int ones.
#
# (For example, isl_aff_get_constant() returns just the constant,
# but isl_aff_get_constant_val() returns the constant divided by
# the denominator.)
#
# To avoid breaking user code in non-obvious ways, the new
# names are carried over to the Python level.
if not found_class:
if name.startswith("options_"):
found_class = True
cls = "ctx"
name = name[len("options_"):]
elif name.startswith("equality_") or name.startswith("inequality_"):
found_class = True
cls = "constraint"
elif name == "ast_op_type_set_print_name":
found_class = True
cls = "printer"
name = "ast_op_type_set_print_name"
if name.startswith("2"):
name = "two_"+name[1:]
assert found_class, name
try:
args = [parse_arg(arg) for arg in args]
except BadArg:
print("SKIP: %s %s" % (cls, name))
return
if name in PYTHON_RESERVED_WORDS:
name = name + "_"
if cls == "options":
assert name.startswith("set_") or name.startswith("get_"), (name, c_name)
name = name[:4]+"option_"+name[4:]
words = return_base_type.split()
is_exported = "__isl_export" in words
if is_exported:
words.remove("__isl_export")
is_constructor = "__isl_constructor" in words
if is_constructor:
words.remove("__isl_constructor")
return_semantics, words = filter_semantics(words)
return_decl_words = []
if words[0] in ["struct", "enum"]:
return_decl_words.append(words.pop(0))
return_base_type = " ".join(words)
cls_meth_list = self.classes_to_methods.setdefault(cls, [])
if c_name in self.seen_c_names:
return
cls_meth_list.append(Method(
cls, name, c_name,
return_semantics, return_decl_words, return_base_type, return_ptr,
args, is_exported=is_exported, is_constructor=is_constructor))
self.seen_c_names.add(c_name)
# }}}
# {{{ header writer
def write_enums_to_header(header_f):
for enum_name, value_str in ENUMS.items():
values = [v.strip() for v in value_str.split(",") if v.strip()]
if enum_name not in MACRO_ENUMS:
if enum_name in TYPEDEFD_ENUMS:
pattern = "typedef enum {{ {values}, ... }} {name};\n"
else:
pattern = "enum {name} {{ {values}, ... }};\n"
header_f.write(
pattern.format(
name=enum_name,
values=", ".join(values)))
else:
for v in values:
header_f.write("static const int {name};".format(name=v))
def write_classes_to_header(header_f):
for cls_name in CLASSES:
header_f.write("struct isl_{name};\n".format(name=cls_name))
if cls_name not in UNTYPEDEFD_CLASSES:
header_f.write(
"typedef struct isl_{name} isl_{name};\n"
.format(name=cls_name))
def write_method_header(header_f, method):
header_f.write(
"{return_decl_words} {ret_type} {ret_ptr}{name}({args});\n"
.format(
return_decl_words=" ".join(method.return_decl_words),
ret_type=method.return_base_type,
ret_ptr=method.return_ptr,
name=method.c_name,
args=", ".join(arg.c_declarator() for arg in method.args)))
# }}}
# {{{ python wrapper writer
def write_enums_to_wrapper(wrapper_f):
gen = PythonCodeGenerator()
gen("")
gen("# {{{ enums")
gen("")
for enum_name, value_str in ENUMS.items():
values = [v.strip() for v in value_str.split(",") if v.strip()]
assert enum_name.startswith("isl_")
name = enum_name[4:]
if name == "bool":
continue
from os.path import commonprefix
common_len = len(commonprefix(values))
gen("class {name}(_EnumBase):".format(name=name))
with Indentation(gen):
for val in values:
py_name = val[common_len:]
if py_name in PYTHON_RESERVED_WORDS:
py_name += "_"
gen(
"{py_name} = lib.{val}"
.format(
val=val,
py_name=py_name,
))
gen("")
gen("# }}}")
gen("")
wrapper_f.write(gen.get())
def write_classes_to_wrapper(wrapper_f):
gen = PythonCodeGenerator()
gen("# {{{ declare classes")
gen("")
for cls_name in CLASSES:
py_cls = isl_class_to_py_class(cls_name)
gen("class {cls}(_ISLObjectBase):".format(cls=py_cls))
with Indentation(gen):
gen("_base_name = "+repr(cls_name))
gen("")
if cls_name == "ctx":
gen("""
def _get_ctx_data(self):
return self.data
def __del__(self):
if self.data is not None:
self._release()
""")
gen("")
else:
gen("""
def _get_ctx_data(self):
return lib.isl_{cls}_get_ctx(self.data)
def __del__(self):
if self.data is not None:
lib.isl_{cls}_free(self.data)
_deref_ctx(self._ctx_data, self._ctx_iptr)