-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathgen_wrap.py
1612 lines (1279 loc) · 50.1 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
__copyright__ = "Copyright (C) 2011-20 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 os
import re
import sys
from dataclasses import dataclass
from os.path import join
from typing import ClassVar, List, Mapping, Sequence
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 = [f"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()
class Retry(RuntimeError): # noqa: N818
pass
class BadArg(ValueError): # noqa: N818
pass
class Undocumented(ValueError): # noqa: N818
pass
class SignatureNotSupported(ValueError): # noqa: N818
pass
def to_py_class(cls):
if cls.startswith("isl_"):
cls = cls[4:]
if cls == "ctx":
return "Context"
upper_next = True
result = ""
for c in cls:
if c == "_":
upper_next = True
else:
if upper_next:
result += c.upper()
upper_next = False
else:
result += c
result = result.replace("Qpoly", "QPoly")
return result
# {{{ data model
@dataclass
class Argument:
is_const: bool
name: str
semantics: str
base_type: str
ptr: str
@dataclass
class CallbackArgument:
name: str
return_semantics: str
return_decl_words: List[str]
return_base_type: str
return_ptr: str
args: Sequence[Argument]
@dataclass
class Method:
cls: str
name: str
c_name: str
return_semantics: str
return_base_type: str
return_ptr: str
args: Sequence[Argument]
is_exported: bool
is_constructor: bool
mutator_veto: bool = False
def __post_init__(self):
assert self.name
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(f"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 f"<method {self.c_name}>"
# }}}
# {{{ PART_TO_CLASSES
PART_TO_CLASSES = {
# If you change this, change:
# - islpy/__init__.py
# - src/wrapper/wrap_isl.hpp to add WRAP_CLASS(...)
# - src/wrapper/wrap_isl_partN.hpp to add MAKE_WRAP(...)
# - doc/reference.rst
"part1": [
# lists
"id_list", "val_list",
"basic_set_list", "basic_map_list", "set_list", "map_list",
"constraint_list",
"aff_list", "pw_aff_list", "pw_multi_aff_list",
"ast_expr_list", "ast_node_list",
"qpolynomial_list",
"pw_qpolynomial_list",
"pw_qpolynomial_fold_list",
"union_pw_aff_list",
"union_pw_multi_aff_list",
"union_set_list",
"union_map_list",
# maps
"id_to_ast_expr",
# others
"ctx",
"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",
"multi_union_pw_aff",
"id", "multi_id",
"constraint", "space", "local_space",
],
"part2": [
"basic_set", "basic_map",
"set", "map",
"union_map", "union_set",
"point", "vertex", "cell", "vertices",
"stride_info",
],
"part3": [
"qpolynomial", "pw_qpolynomial",
"qpolynomial_fold", "pw_qpolynomial_fold",
"union_pw_qpolynomial_fold",
"union_pw_qpolynomial",
"term",
"schedule", "schedule_constraints",
"schedule_node",
"access_info", "flow", "restriction",
"union_access_info", "union_flow",
"ast_expr", "ast_node", "ast_print_options",
"ast_build",
]
}
CLASSES = []
for cls_list in PART_TO_CLASSES.values():
CLASSES.extend(cls_list)
CLASS_MAP = {
"equality": "constraint",
"inequality": "constraint",
"options": "ctx",
}
# }}}
# {{{ enums
ENUMS = {
# ctx.h
"isl_error",
"isl_stat",
"isl_bool",
# space.h
"isl_dim_type",
# schedule_type.h
"isl_schedule_node_type",
# ast_type.h
"isl_ast_expr_op_type",
"isl_ast_expr_type",
"isl_ast_node_type",
"isl_ast_loop_type",
# polynomial_type.h
"isl_fold",
}
TYPEDEFD_ENUMS = ["isl_stat", "isl_bool"]
MACRO_ENUMS = [
"isl_format", "isl_yaml_style",
"isl_bound", "isl_on_error", "isl_schedule_algorithm",
]
# }}}
SAFE_TYPES = [*list(ENUMS), "int", "unsigned", "uint32_t", "size_t", "double", "long",
"unsigned long", "isl_size"]
SAFE_IN_TYPES = [*SAFE_TYPES, "const char *", "char *"]
# {{{ parser helpers
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+)?([a-z_A-Z0-9]+)\s*;")
ARG_RE = re.compile(r"^((?:const\s+)?(?:\w+\s+)+)(\**)\s*(\w+)$")
INLINE_SEMICOLON_RE = re.compile(r"\;[ \t]*(?=\w)")
SUBCLASS_RE = re.compile(
r"__isl_subclass\s*"
r"\(\s*"
r"[0-9a-zA-Z_]+"
r"\s*\)")
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]
def parse_arg(arg):
if "(*" in arg:
arg_match = FUNC_PTR_RE.match(arg)
assert arg_match is not None, f"fptr: {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)
words = [w for w in words if w not in ["struct", "enum"]]
is_const = False
if words[0] == "const":
is_const = True
del words[0]
rebuilt_arg = " ".join(words)
arg_match = ARG_RE.match(rebuilt_arg)
assert arg_match is not None, rebuilt_arg
return Argument(
is_const=is_const,
name=arg_match.group(3),
semantics=semantics,
base_type=arg_match.group(1).strip(),
ptr=arg_match.group(2).strip())
def preprocess_with_macros(macro_header_contents, code):
try:
from pcpp.preprocessor import (
Action,
OutputDirective,
Preprocessor as PreprocessorBase,
)
except ImportError as err:
raise RuntimeError("pcpp was not found. Please install pcpp before "
"installing islpy. 'pip install pcpp' should do the job.") from err
class MacroExpandingCPreprocessor(PreprocessorBase):
def on_directive_handle(self, directive, toks, ifpassthru, precedingtoks):
if directive.value == "include":
raise OutputDirective(action=Action.IgnoreAndPassThrough)
elif directive.value == "define":
assert toks
macro_name = toks[0].value
if macro_name in ISL_SEM_TO_SEM:
raise OutputDirective(action=Action.IgnoreAndRemove)
return super().on_directive_handle(
directive, toks, ifpassthru, precedingtoks)
cpp = MacroExpandingCPreprocessor()
from io import StringIO
# read macro definitions, but don't output resulting code
for macro_header in macro_header_contents:
cpp.parse(macro_header)
cpp.write(StringIO())
sio_output = StringIO()
cpp.parse(code)
cpp.write(sio_output)
return sio_output.getvalue()
# }}}
# {{{ FunctionData (includes parser)
class FunctionData:
INVALID_PY_IDENTIFIER_RENAMING_MAP: ClassVar[Mapping[str, str]] = {
"2exp": "two_exp"
}
def __init__(self, include_dirs):
self.classes_to_methods = {}
self.include_dirs = include_dirs
self.seen_c_names = set()
def get_header_contents(self, fname):
from os.path import join
success = False
for inc_dir in self.include_dirs:
try:
inf = open(join(inc_dir, fname))
except OSError:
pass
else:
success = True
break
if not success:
raise RuntimeError(f"header '{fname}' not found")
try:
return inf.read()
finally:
inf.close()
def get_header_hashes(self, fnames):
import hashlib
h = hashlib.sha256()
h.update(b"v1-")
for fname in fnames:
h.update(self.get_header_contents(fname).encode())
return h.hexdigest()
preprocessed_dir = "preproc-headers"
macro_headers: ClassVar[Sequence[str]] = ["isl/multi.h", "isl/list.h"]
def get_preprocessed_header(self, fname):
header_hash = self.get_header_hashes(
[*self.macro_headers, fname])
# cache preprocessed headers to avoid install-time
# dependency on pcpp
import errno
try:
os.mkdir(self.preprocessed_dir)
except OSError as err:
if err.errno == errno.EEXIST:
pass
else:
raise
prepro_fname = join(self.preprocessed_dir, header_hash)
try:
with open(prepro_fname) as inf:
return inf.read()
except OSError:
pass
print(f"preprocessing {fname}...")
macro_header_contents = [
self.get_header_contents(mh)
for mh in self.macro_headers]
prepro_header = preprocess_with_macros(
macro_header_contents, self.get_header_contents(fname))
with open(prepro_fname, "w") as outf:
outf.write(prepro_header)
return prepro_header
# {{{ read_header
def read_header(self, fname):
lines = self.get_preprocessed_header(fname).split("\n")
# heed continuations, split at semicolons
new_lines = []
i = 0
while i < len(lines):
my_line = lines[i].strip()
i += 1
my_line, _ = SUBCLASS_RE.subn("", my_line)
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):
line = lines[i].strip()
if (not line
or line.startswith("extern")
or STRUCT_DECL_RE.search(line)
or line.startswith("typedef")
or line == "}"):
i += 1
elif "/*" in line:
while True:
if "*/" in line:
i += 1
break
i += 1
line = lines[i].strip()
elif line.endswith("{"):
while True:
if "}" in line:
i += 1
break
i += 1
line = lines[i].strip()
elif not line:
i += 1
else:
decl = ""
while True:
decl = decl + line
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
line = lines[i].strip()
if not STRUCT_DECL_RE.search(decl):
self.parse_decl(decl)
# }}}
# {{{ parse_decl
def parse_decl(self, decl):
decl_match = DECL_RE.match(decl)
if decl_match is None:
print(f"WARNING: func decl regexp not matched: {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_DECLARE_EXPORTED_LIST_FN",
"ISL_DECLARE_MULTI_IDENTITY",
"ISL_DECLARE_MULTI_ARITH",
"ISL_DECLARE_MULTI_ZERO",
"ISL_DECLARE_MULTI_NAN",
"ISL_DECLARE_MULTI_DIM_ID",
"ISL_DECLARE_MULTI_TUPLE_ID",
"ISL_DECLARE_MULTI_BIND_DOMAIN",
"ISL_DECLARE_MULTI_PARAM",
"ISL_DECLARE_MULTI_DROP_DIMS",
"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:]
# find longest class name match
class_name = None
for it_cls_name in CLASSES:
if (name.startswith(it_cls_name)
and (class_name is None
or len(class_name) < len(it_cls_name))):
class_name = it_cls_name
# 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 class_name is not None:
name = name[len(class_name)+1:]
else:
if name.startswith("bool_"):
return
if name.startswith("options_"):
class_name = "ctx"
name = name[len("options_"):]
elif name.startswith("equality_") or name.startswith("inequality_"):
class_name = "constraint"
elif name == "ast_op_type_set_print_name":
class_name = "printer"
name = "ast_op_type_set_print_name"
assert class_name is not None
if class_name == "ctx":
if name in ["alloc", "ref", "deref"]:
return
if "last_error" in name:
return
if name in ["set_error", "reset_error"]:
return
if name in ["free", "cow", "ref", "deref"]:
return
try:
args = [parse_arg(arg) for arg in args]
except BadArg:
print(f"SKIP: {class_name} {name}")
return
if name in PYTHON_RESERVED_WORDS:
name = name + "_"
name = self.INVALID_PY_IDENTIFIER_RENAMING_MAP.get(name, name)
if name[0].isdigit():
print(f"SKIP: {class_name} {name} "
"(unhandled invalid python identifier)")
return
if class_name == "options":
assert name.startswith("set_") or name.startswith("get_"), (name, c_name)
name = f"{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)
words = [w for w in words if w not in ["struct", "enum"]]
return_base_type = " ".join(words)
cls_meth_list = self.classes_to_methods.setdefault(class_name, [])
if c_name in self.seen_c_names:
return
cls_meth_list.append(Method(
class_name, name, c_name,
return_semantics, return_base_type, return_ptr,
args, is_exported=is_exported, is_constructor=is_constructor))
self.seen_c_names.add(c_name)
# }}}
# }}}
# {{{ get_callback
def get_callback(cb_name, cb):
pre_call = []
passed_args = []
post_call = []
assert cb.args[-1].name == "user"
for arg in cb.args[:-1]:
if arg.base_type.startswith("isl_"):
if arg.ptr != "*":
raise SignatureNotSupported(
f"unsupported callback arg: {arg.base_type} {arg.ptr}")
arg_cls = arg.base_type[4:]
passed_args.append(f"arg_{arg.name}")
pre_call.append(f"""
{arg_cls} *wrapped_arg_{arg.name}(new {arg_cls}(c_arg_{arg.name}));
py::object arg_{arg.name}(
handle_from_new_ptr(wrapped_arg_{arg.name}));
""")
if arg.semantics is SEM_TAKE:
# We (the callback) are supposed to free the object, so
# just let the unique_ptr get rid of it.
pass
elif arg.semantics is SEM_KEEP:
# The caller wants to keep this object, so we simply tell our
# wrapper to stop managing it after the call completes.
post_call.append(f"""
wrapped_arg_{arg.name}->invalidate();
""")
else:
raise SignatureNotSupported("unsupported callback arg semantics")
else:
raise SignatureNotSupported(
"unsupported callback arg: {arg.base_type} {arg.ptr}")
if cb.return_base_type in SAFE_IN_TYPES and not cb.return_ptr:
ret_type = f"{cb.return_base_type} {cb.return_ptr}"
if cb.return_base_type == "isl_stat":
post_call.append("""
if (retval.ptr() == Py_None)
{
return isl_stat_ok;
}
""")
else:
post_call.append("""
if (retval.ptr() == Py_None)
{
throw isl::error("callback returned None");
}
""")
if cb.return_base_type == "isl_bool":
post_call.append("""
else
return static_cast<isl_bool>(py::cast<bool>(retval));
""")
else:
post_call.append(f"""
else
return py::cast<{ret_type}>(retval);
""")
if cb.return_base_type == "isl_bool":
error_return = "isl_bool_error"
else:
error_return = "isl_stat_error"
elif cb.return_base_type.startswith("isl_") and cb.return_ptr == "*":
if cb.return_semantics is None:
raise SignatureNotSupported("callback return with unspecified semantics")
elif cb.return_semantics is not SEM_GIVE:
raise SignatureNotSupported("callback return with non-GIVE semantics")
ret_type = f"{cb.return_base_type} {cb.return_ptr}"
post_call.append("""
if (retval.ptr() == Py_None)
{
return nullptr;
}
else
{
isl::%(ret_type_name)s *wrapper_retval =
py::cast<isl::%(ret_type_name)s *>(retval);
isl_%(ret_type_name)s *unwrapped_retval =
wrapper_retval->m_data;
wrapper_retval->invalidate();
return unwrapped_retval;
}
""" % {"ret_type_name": cb.return_base_type[4:]})
error_return = "nullptr"
else:
raise SignatureNotSupported("non-int callback")
return """
static %(ret_type)s %(cb_name)s(%(input_args)s)
{
py::object py_cb = py::borrow<py::object>(
(PyObject *) c_arg_user);
try
{
%(pre_call)s
py::object retval = py_cb(%(passed_args)s);
%(post_call)s
}
catch (py::python_error &err)
{
std::cout << "[islpy warning] A Python exception occurred in "
"a call back function, ignoring:" << std::endl;
err.restore();
PyErr_Print();
PyErr_Clear();
return %(error_return)s;
}
catch (std::exception &e)
{
std::cerr << "[islpy] An exception occurred in "
"a Python callback query:" << std::endl
<< e.what() << std::endl;
std::cout << "[islpy] Aborting now." << std::endl;
return %(error_return)s;
}
}
""" % {
"ret_type": ret_type,
"cb_name": cb_name,
"input_args": (
", ".join(f"{arg.base_type} {arg.ptr}c_arg_{arg.name}"
for arg in cb.args)),
"pre_call": "\n".join(pre_call),
"passed_args": ", ".join(passed_args),
"post_call": "\n".join(post_call),
"error_return": error_return,
}
# }}}
# {{{ wrapper generator
def write_wrapper(outf, meth):
body = []
checks = []
docs = []
passed_args = []
input_args = []
post_call = []
extra_ret_vals = []
extra_ret_descrs = []
preamble = []
arg_names = []
checks.append("isl_ctx *islpy_ctx = nullptr;")
arg_idx = 0
while arg_idx < len(meth.args):
arg = meth.args[arg_idx]
arg_names.append(arg.name)
if isinstance(arg, CallbackArgument):
has_userptr = (
arg_idx + 1 < len(meth.args)
and meth.args[arg_idx+1].name.endswith("user"))
if not has_userptr:
raise SignatureNotSupported(
"callback signature without user pointer")
else:
arg_idx += 1
if meth.args[arg_idx].name != "user":
raise SignatureNotSupported("unexpected callback signature")
cb_name = f"cb_{meth.cls}_{meth.name}_{arg.name}"
if (meth.cls in ["ast_build", "ast_print_options"]
and meth.name.startswith("set_")):
extra_ret_vals.append(f"py_{arg.name}")
extra_ret_descrs.append("(opaque handle to "
"manage callback lifetime)")
input_args.append(f"py::object py_{arg.name}")
passed_args.append(cb_name)
passed_args.append(f"py_{arg.name}.ptr()")
preamble.append(get_callback(cb_name, arg))
docs.append(":param {name}: callback({args})".format(
name=arg.name,
args=", ".join(
sub_arg.name for sub_arg in arg.args
if sub_arg.name != "user")
))
elif arg.base_type in SAFE_IN_TYPES and not arg.ptr:
assert not arg.is_const
passed_args.append(f"arg_{arg.name}")
input_args.append(f"{arg.base_type} arg_{arg.name}")
doc_cls = arg.base_type
if doc_cls.startswith("isl_"):
doc_cls = doc_cls[4:]
if doc_cls == "unsigned long":
doc_cls = "int"
docs.append(f":param {arg.name}: :class:`{doc_cls}`")
elif arg.base_type in ["char", "const char"] and arg.ptr == "*":
if arg.semantics is SEM_KEEP:
passed_args.append(f"strdup({arg.name})")
else:
passed_args.append(arg.name)
def _arg_to_const_str(arg: Argument) -> str:
if arg.is_const:
return "const "
return ""
input_args.append(f"{_arg_to_const_str(arg)}{arg.base_type} *{arg.name}")
docs.append(f":param {arg.name}: string")
elif arg.base_type in ["int", "isl_bool"] and arg.ptr == "*":
if arg.name in ["exact", "tight"]:
body.append(f"{arg.base_type} arg_{arg.name};")
passed_args.append(f"&arg_{arg.name}")
if arg.base_type == "isl_bool":
extra_ret_vals.append(f"(bool) arg_{arg.name}")
else:
extra_ret_vals.append(f"arg_{arg.name}")
extra_ret_descrs.append(
f"{arg.name} ({to_py_class(arg.base_type)})")
arg_names.pop()
else:
raise SignatureNotSupported("int *")
elif arg.base_type == "isl_val" and arg.ptr == "*" and arg_idx > 0:
# {{{ val input argument
arg_descr = f":param {arg.name}: :class:`Val`"
input_args.append(f"py::object py_{arg.name}")
checks.append("""
std::unique_ptr<val> unique_arg_%(name)s;
try
{
val *arg_%(name)s = py::cast<val *>(py_%(name)s);
isl_val *tmp_ptr = isl_val_copy(arg_%(name)s->m_data);
if (!tmp_ptr)
throw isl::error("failed to copy arg %(name)s");
unique_arg_%(name)s = std::unique_ptr<val>(new val(tmp_ptr));
}
catch (py::cast_error &err)
{
// fall through to next case
}
try
{
if (!unique_arg_%(name)s.get())
{
isl_val *tmp_ptr = isl_val_int_from_si(islpy_ctx,
py::cast<long>(py_%(name)s));
if (!tmp_ptr)
throw isl::error("failed to create arg "
"%(name)s from integer");
unique_arg_%(name)s = std::unique_ptr<val>(new val(tmp_ptr));
}
}