-
Notifications
You must be signed in to change notification settings - Fork 6
/
apigen.py
785 lines (629 loc) · 27.2 KB
/
apigen.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
#/usr/bin/python3
"""
Script to generate Smalltalk Z3 API (FFI callouts) from Z3 C headers.
Generated code is printed to standard output in form of old chunk-format
changeset. By default, `apigen.py` output is suitable for Smalltalk/X. Use
option `--pharo` to output changeset suitable for Pharo.
Z3 APIs are defined in multiple header files (see `Z3_API_HEADER_FILES_TO_SCAN` in
Z3's top-level `CMakeLists.txt`)
z3_api.h
z3_ast_containers.h
z3_algebraic.h
z3_polynomial.h
z3_rcf.h
z3_fixedpoint.h
z3_optimization.h
z3_fpa.h
z3_spacer.h
All of them should be passed to `apigen.py`. Alternatively, you may use
`--z3-source=/path/to/z3` to point `apigen.py` to Z3 sources - it will then
scan all required headers from there.
### Workflow in a nutshell ###
1. Update / fix `apigen.py` (mostly you would need to update mapping
from Z3 types to their Smalltalk counterparts, search for
VOID = ScalarType('VOID' , 'void')
in `apigen.py` source.
2. If you're adding new type, create the class in Smalltalk and
commit.
3. Regenerate API classes (`Z3` and `LibZ3`) for both, Pharo
and Smalltalk/X:
make -C pharo Z3_SOURCE_DIR=/path/to/z3/sources update-Z3-API
make -C stx Z3_SOURCE_DIR=/path/to/z3/sources update-Z3-API
This will run `apigen.py`, load generated changeset into smalltalk
and save modification back to the disk.
4. Test changes:
make -C pharo clean test
make -C stx clean test
5. Review changes and - if happy - commit:
git diff
git add apigen.py \
MachineArithmetic-FFI-Pharo/LibZ3.class.st \
MachineArithmetic-FFI-SmalltalkX/LibZ3.class.st \
MachineArithmetic/Z3.class.st
git commit
### Using `apigen.py` manually ###
1. Update / fix `apigen.py` (mostly you would need to update mapping
from Z3 types to their Smalltalk counterparts, search for
VOID = ScalarType('VOID' , 'void')
in `apigen.py` source.
2. If you're adding new type, create the class in Smalltalk and
commit.
3. Run `apigen.py`:
python3 apigen.py --pharo --z3-source=../z3 > pharo/LibZ3-generated.st
Do not forget to use `--pharo` when working in Pharo!
3. Load generated changeset (`pharo/LibZ3-generated.st`) into smalltalk.
4. Test
5. Commit new / updated code from smalltalk IDE.
6. Repeat until happy.
"""
import sys
import io
import os.path
import argparse
import re
import enum
from itertools import chain
class BaseType:
def __init__(self, name):
self._name = name
def __str__(self):
return self._name
def is_array_type(self):
return False
def is_z3_type(self):
return False
def is_z3closure_type(self):
return False
def is_z3context_type(self):
return False
def is_z3contexted_type(self):
return False
def is_z3ast_type(self):
return False
def is_z3ast_sub_type(self):
return False
@property
def name(self):
return self._name
@property
def uffi_typename(self):
raise Exception("Subclass reponsibility")
class ScalarType(BaseType):
def __init__(self, name, uffi_typename = None, stx_typename = None):
super().__init__(name)
self._uffi_typename = uffi_typename
self._stx_typename = stx_typename if stx_typename else uffi_typename
@property
def uffi_typename(self):
if self._uffi_typename:
return self._uffi_typename
else:
raise Exception(f"Type {self._name} not (yet) supported.")
class Z3Type(BaseType):
def __init__(self, name, typename = None):
super().__init__(name)
self._typename = typename
def is_z3_type(self):
return True
def is_z3context_type(self):
return self._name == 'CONTEXT'
@property
def uffi_typename(self):
if self._typename:
return self._typename
else:
raise Exception(f"Type {self._name} not (yet) supported.")
class ArrayType(BaseType):
def __init__(self, ty, size = None):
super().__init__(ty.name)
self._type = ty
self._size = size
@property
def uffi_typename(self):
return 'FFIExternalArray'
@property
def element_type(self):
return self._type
def is_array_type(self):
return True
def __str__(self):
return f"{str(self._type)}[{str(self._size) if self._size else ''}]"
class Z3CtxdType(Z3Type):
def is_z3contexted_type(self):
return True
class Z3ASTType(Z3CtxdType):
def is_z3ast_type(self):
return True
class Z3ASTSubType(Z3CtxdType):
def is_z3ast_sub_type(self):
return True
class ArgumentType(enum.Flag):
IN = 1
OUT = 2
class Argument:
def __init__(self, ty, flags):
self._flags = flags
self._type = ty
@property
def type(self):
return self._type
@property
def flags(self):
return self._flags
def arg_name(self):
return self.name
def tmp_name(self):
return self.arg_name() + 'Ext'
def is_out_arg(self):
return ArgumentType.OUT in self._flags
def is_array_arg(self):
return self._type.is_array_type()
VOID = ScalarType('VOID' , 'void')
VOID_PTR = ScalarType('VOID_PTR' , 'void *')
INT = ScalarType('INT' , 'int')
UINT = ScalarType('UINT' , 'uint')
INT64 = ScalarType('INT64' , 'int64')
UINT64 = ScalarType('UINT64' , 'uint64')
STRING = ScalarType('STRING' , 'char *')
STRING_PTR = ScalarType('STRING_PTR' , 'char **')
BOOL = ScalarType('BOOL' , 'bool')
PRINT_MODE = ScalarType('PRINT_MODE' )
ERROR_CODE = ScalarType('ERROR_CODE' , 'uint')
DOUBLE = ScalarType('DOUBLE' , 'double')
FLOAT = ScalarType('FLOAT' , 'float')
CHAR = ScalarType('CHAR' , 'char')
CHAR_PTR = ScalarType('CHAR_PTR' , 'char *')
LBOOL = INT
SYMBOL = Z3CtxdType('SYMBOL' , 'Z3Symbol' )
CONFIG = Z3Type('CONFIG' , 'Z3Config')
CONTEXT = Z3Type('CONTEXT' , 'Z3Context')
AST = Z3ASTType('AST' , 'Z3AST')
APP = Z3ASTType('APP' , 'Z3AST')
SORT =Z3ASTSubType('SORT' , 'Z3Sort')
FUNC_DECL =Z3ASTSubType('FUNC_DECL' , 'Z3FuncDecl')
PATTERN = Z3CtxdType('PATTERN' , 'Z3Pattern')
MODEL = Z3CtxdType('MODEL' , 'Z3Model')
LITERALS = Z3Type('LITERALS' )
CONSTRUCTOR = Z3CtxdType('CONSTRUCTOR' , 'Z3Constructor')
CONSTRUCTOR_LIST = Z3CtxdType('CONSTRUCTOR_LIST' , 'Z3ConstructorList')
SOLVER = Z3CtxdType('SOLVER' , 'Z3Solver')
SOLVER_CALLBACK = Z3Type('SOLVER_CALLBACK' )
GOAL = Z3Type('GOAL' )
TACTIC = Z3Type('TACTIC' )
PARAMS = Z3CtxdType('PARAMS' , 'Z3ParameterSet')
PROBE = Z3Type('PROBE' )
STATS = Z3Type('STATS' )
AST_VECTOR = Z3CtxdType('AST_VECTOR' , 'Z3ASTVector')
AST_MAP = Z3Type('AST_MAP' )
APPLY_RESULT = Z3Type('APPLY_RESULT' )
FUNC_INTERP = Z3Type('FUNC_INTERP' )
FUNC_ENTRY = Z3Type('FUNC_ENTRY' )
FIXEDPOINT = Z3CtxdType('FIXEDPOINT' , 'Z3Fixedpoint')
OPTIMIZE = Z3Type('OPTIMIZE' )
PARAM_DESCRS = Z3CtxdType('PARAM_DESCRS' , 'Z3ParameterDescriptionSet')
RCF_NUM = Z3Type('RCF_NUM' )
PARSER_CONTEXT = Z3Type('PARSER_CONTEXT' )
SIMPLIFIER = Z3Type('SIMPLIFIER' )
#
# Z3 Closures (callbacks) introduced in Z3 3.12.0
#
class Z3ClosureType(BaseType):
def __init__(self, name, retTy = VOID, argTys = ()):
super().__init__(name)
self._retTy = retTy
self._argTys = argTys
def is_z3closure_type(self):
return True
@property
def uffi_typename(self):
raise Exception(f"Closures (callbacks) not (yet) supported.")
Z3_error_handler= Z3ClosureType('Z3_error_handler', VOID, ()) # (Z3_context c, Z3_error_code e));
Z3_push_eh = Z3ClosureType('Z3_push_eh', VOID, ()) # , (void* ctx, Z3_solver_callback cb));
Z3_pop_eh = Z3ClosureType('Z3_pop_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb, unsigned num_scopes));
Z3_fresh_eh = Z3ClosureType('Z3_fresh_eh', VOID_PTR,()) # (void* ctx, Z3_context new_context));
Z3_fixed_eh = Z3ClosureType('Z3_fixed_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb, Z3_ast t, Z3_ast value));
Z3_eq_eh = Z3ClosureType('Z3_eq_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb, Z3_ast s, Z3_ast t));
Z3_final_eh = Z3ClosureType('Z3_final_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb));
Z3_created_eh = Z3ClosureType('Z3_created_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb, Z3_ast t));
Z3_decide_eh = Z3ClosureType('Z3_decide_eh', VOID, ()) # (void* ctx, Z3_solver_callback cb, Z3_ast* t, unsigned* idx, Z3_lbool* phase));
Z3_on_clause_eh = Z3ClosureType('Z3_on_clause_eh',VOID, ()) # (void* ctx, Z3_ast proof_hint, Z3_ast_vector literals));
# For some API functions, error check makes no sense
# or it is not desirable. NO_ERROR_CHECK lists such
# functions.
NO_ERROR_CHECK = (
'Z3_del_context',
'Z3_get_error_code',
'Z3_get_error_msg',
'Z3_set_error',
)
API_MATCHER = re.compile("/\*\*\n (.*?(?=\*/))\*/\n\s+([^;/]+)", re.M | re.S)
DEF_MATCHER = re.compile("def_API\(.*\)\n", re.M | re.S)
FUN_MATCHER = re.compile("\w+\s+Z3_API\s+\w+\s*\((.*)\)", re.M | re.S)
ARG_MATCHER = re.compile("\w+(?:(?:\s+const)?(?:\s*\*)?\s+(\w+)(?:\[\])?)?,?")
def parse(header_path):
"""
Parse a Z3 header file and return an iterable on APIs found.
"""
with open(header_path) as header:
candidates = API_MATCHER.findall(header.read())
definitions = [ candidate for candidate in candidates if DEF_MATCHER.search(candidate[0]) ]
apis = [ API(definition[0], definition[1]) for definition in definitions ]
return apis
class API:
def __init__(self, comment, prototype):
self.comment = comment.replace("\"", "\'").replace("!", "!!")
self.prototype = prototype
def def_API(cname, rettype, args):
self.cname = cname
self.rettype = rettype
self.args = args
def _in(t):
return Argument(t, ArgumentType.IN)
def _in_array(s, t):
return Argument(ArrayType(t, s), ArgumentType.IN)
def _out(t):
return Argument(ArrayType(t, 1), ArgumentType.OUT)
def _out_array(s, t):
return Argument(ArrayType(t, s), ArgumentType.OUT)
def _inout_array(s, t):
return Argument(ArrayType(t, s), ArgumentType.IN|ArgumentType.OUT)
def _fnptr(t):
assert t.is_z3closure_type()
return _in(t)
eval(DEF_MATCHER.search(comment).group(0))
prototype_arguments = FUN_MATCHER.search(prototype)
if not prototype_arguments:
breakpoint()
prototype_arguments = prototype_arguments.group(1)
if prototype_arguments != 'void':
argnames = ARG_MATCHER.findall(prototype_arguments)
if len(self.args) != len(argnames):
import pdb; pdb.set_trace()
assert len(self.args) == len(argnames)
for i in range(0, len(argnames)):
argname = argnames[i]
if argname == None or argname == "":
argname = 'arg' + str(i)
self.args[i].name = argname
def header(self, argnames = None):
assert argnames == None or len(argnames) == len(self.args)
if argnames == None:
argnames = [arg.name for arg in self.args]
n = self.cname
if n.startswith('Z3_'):
n = n[3:]
if len(argnames) > 0:
n += ': ' + argnames[0]
if len(argnames) > 1:
for argname in argnames[1:]:
n += ' _: ' + argname
return n
def has_context_arg(self):
for arg in self.args:
if arg.type.is_z3context_type():
return True
return False
def context_arg_name(self):
for arg in self.args:
if arg.type.is_z3context_type():
return arg.name
raise Exception("Oops, this API does not take any Context argument")
def needs_error_check(self):
return self.has_context_arg() and self.cname not in NO_ERROR_CHECK
PUBLIC_METHOD_TEMPLATE = """
!Z3 class methodsFor: 'API'!
{public_header}
"
{comment}
AUTOMATICALLY GENERATED BY apigen.py. DO NOT EDIT!!
"
{public_body}
! !
"""
PRIVATE_METHOD_TEMPLATE = """
!LibZ3 methodsFor: 'API - private'!
{private_header}
"
PRIVATE - DO NOT USE!!
{prototype};
AUTOMATICALLY GENERATED BY apigen.py. DO NOT EDIT!!
"
{private_body}
! !
"""
class Source:
"""
Helper class to generate (Smalltalk) source code. Basically a string
to which one can add code using += operator with some helpers to
manage indentation.
To generate code indented by one level, do:
body = Source()
body += ...
with body.indented():
body += ...
body += ...
"""
def __init__(self, initial = '', indent_string = ' '):
self._output = io.StringIO(initial)
self._last_is_newline = False
self._indent_level = 0
self._indent_string = indent_string
def indent(self, how_much = 1):
self._indent_level += how_much
def undent(self, how_much = 1):
self._indent_level -= how_much
def indented(self, how_much = 1):
source = self
class SourceIndented:
def __enter__(self):
source.indent(how_much)
return self
def __exit__(self, exc_type, exc_value, exc_tb):
source.undent(how_much)
if exc_value is not None:
raise exc_value
return SourceIndented()
def __str__(self):
return self._output.getvalue()
def __iadd__(self, other):
other_string = str(other)
if len(other_string) > 0:
if self._last_is_newline and other_string != '\n':
self._output.write(self._indent_string * self._indent_level)
self._last_is_newline = other_string[-1] == '\n'
self._output.write(other_string)
return self
class Generator:
def generate(self, apis):
for api in apis:
self.generate1(api)
def generate1(self, api, public = True, private = True):
if public:
source = PUBLIC_METHOD_TEMPLATE.format(
comment = api.comment,
prototype = api.prototype,
public_header = self.public_header(api),
public_body = self.public_body(api)
)
source = self.reformat(source)
print(source)
if private:
source = PRIVATE_METHOD_TEMPLATE.format(
comment = api.comment,
prototype = api.prototype,
private_header= self.private_header(api),
private_body = self.private_body(api),
)
source = self.reformat(source)
print(source)
def reformat(self, source):
"""
Reformat the source to conform to dialect's convetion regarding
tabs/spaces and/or line ends.
"""
return source
def public_header(self, api):
return api.header()
def private_header(self, api, argnames = None):
return '_' + api.header(argnames)
def public_body(self, api):
try:
# Following is just to get an exception for
# unsupported types
self.type2ffi(api.rettype)
for arg in api.args:
self.type2ffi(arg.type)
body = Source()
body.indent()
temps = ['retval']
# Ensure all Z3 objects are valid upon entry.
for arg in api.args:
if arg.type.is_z3_type() and not self.arg_passed_as_raw_pointer(api, arg):
if arg.type.is_z3ast_sub_type():
body += f"{arg.name} ensureValidZ3ASTOfKind: {arg.type.name}_AST.\n"
elif arg.type.is_z3ast_type():
body += f"{arg.name} ensureValidZ3AST.\n"
else:
body += f"{arg.name} ensureValidZ3Object.\n"
elif arg.type.is_array_type() and arg.flags != ArgumentType.OUT and api.cname not in ['Z3_mk_constructor']:
eltype = arg.type.element_type
if eltype.is_z3ast_sub_type():
body += f"{arg.name} ensureValidZ3ASTArrayOfKind: {arg.type.name}_AST.\n"
elif eltype.is_z3ast_type():
body += f"{arg.name} ensureValidZ3ASTArray.\n"
elif eltype.is_z3_type():
body += f"{arg.name} ensureValidZ3ObjectArray.\n"
# Declare temps used for arrays and return value (if needed)
array_args = [ arg for arg in api.args if arg.is_array_arg() ]
has_array_args = len(array_args) > 0
for arg in array_args:
temps.append(arg.tmp_name())
if arg.type.element_type.is_z3_type():
body += f"{arg.tmp_name()} := self externalArrayFrom: {arg.name}.\n"
elif arg.type.element_type.name == 'UINT':
body += f"{arg.tmp_name()} := Z3Object externalU32ArrayFrom: {arg.name}.\n"
else:
raise Exception(f"arrays of type {arg.type.element_type} not (yet) supported")
# Call the API
body += f"retval := lib {self.private_header(api, [arg.tmp_name() if arg in array_args else arg.arg_name() for arg in api.args])}.\n"
# Check whether API call resulted in an error. This must be done immediately
# after making the call to Z3 (there's still a chance the error would be bogus,
# but this is best we can do with FFI).
#
# However, it is not that simple! If there are array arguments, we have to
# free them in ensure (otherwise we'd leak them). To make it more complicated,
# some arrays are out or in/out parameters, so we have to extract the value after
# errorCheck but NOT in #ensure: block in case call fails.
#
# Yet another 'complication' comes from the fact, that few Z3 API do not
# require error check (have no context) but use out and/or in/out
# parameters.
def output_extract_array_arg_values(body):
"""
Local helper to extract value from C arrays
"""
for arg in array_args:
if arg.is_out_arg():
eltype = arg.type.element_type
elval = 'v' if arg.arg_name() != 'v' else 'value'
elidx = 'i' if arg.arg_name() != 'i' else 'index'
body += f"1 to: {arg.arg_name()} size do: [ :i |\n"
with body.indented():
body += f"| {elval} |\n\n"
if eltype.is_z3contexted_type():
body += f"{elval} := {self.type2ffi(eltype)} fromExternalAddress: (Z3Object externalArray: {arg.tmp_name()} pointerAt: {elidx}) inContext: {api.context_arg_name()}.\n"
elif eltype.is_z3_type():
body += f"{elval} := {self.type2ffi(eltype)} fromExternalAddress: (Z3Object externalArray: {arg.tmp_name()} pointerAt: {elidx}).\n"
elif eltype.name == 'UINT':
body += f"{elval} := Z3Object externalArray: {arg.tmp_name()} u32At: {elidx}.\n"
else:
raise Exception(f"arrays of type {arg.type.element_type} not (yet) supported")
body += f"{arg.arg_name()} at: {elidx} put: {elval}.\n"
body += "].\n"
def output_free_array_args(body):
"""
Local helper to free all array arguments
"""
for arg in array_args:
body += f"{arg.tmp_name()} notNil ifTrue:[{arg.tmp_name()} free].\n"
if api.needs_error_check():
# This API does not need error check...
if not has_array_args:
# If there are no array args, we do not need to generate
# ensure: as there's nothing to free. So just generate
# error check and be done.
body += f"{api.context_arg_name()} errorCheck.\n"
else:
# There are array args so we need an ensure:
body += f"[\n"
with body.indented():
body += f"{api.context_arg_name()} errorCheck.\n"
# Now error has been checked. If there was one,
# we got out of here by means of raising an exception.
# So if we get here, call succeeded and we can extract
# values from out or in/out arrays.
output_extract_array_arg_values(body)
body += "] ensure: [\n"
with body.indented():
# Free all external arrays...
output_free_array_args(body)
body += "].\n"
else:
# This API does not need error check...
if has_array_args:
# ...but has out or in/out arguments:
output_extract_array_arg_values(body)
output_free_array_args(body)
if (api.rettype.is_z3contexted_type()):
# If retval is an AST, convert it to appropriate class and return...
body += f"^ {self.type2ffi(api.rettype)} fromExternalAddress: retval inContext: {api.context_arg_name()}."
else:
# ...just return
body += '^ retval'
# Declare all temps:
body = f"| {' '.join(temps)} |\n\n " + str(body)
return body
except Exception as e:
return f"^ self error: 'API not (yet) supported: {str(e)}'"
def private_body(self, api):
try:
body = f"^ self ffiCall: #( {self.type2ffi(api.rettype)} {api.cname} ("
for arg in api.args:
nm = arg.name
ty = self.type2ffi(arg.type)
if self.arg_passed_as_raw_pointer(api, arg):
# For explanation, see the comment below (we add it to the generated
# code as well as convenience to whoever's reading the generated code
# in Smalltalk)
body ="\"\n" + \
" In Pharo, one has to type parameter as raw pointer (void*) if one\n" + \
" wants to pass in (raw) handle.\n" + \
"\n" + \
" We do this in three cases (Z3_get_ast_kind(), Z3_get_sort() and Z3_get_sort_kind()) in order to\n" + \
" get kind/sort information before instantiating the the class. So, we have\n" + \
" to manually force void* for parameter type.\n" + \
"\n" + \
" See implementations of #fromExternalAddress:inContext: .\n" + \
" \"\n" + \
" " + \
body
ty = self.type2ffi(VOID_PTR)
body += f"{',' if arg != api.args[0] else ''} {ty} {nm}"
body += ' ) )'
return body
except Exception as e:
return f"^ self error: 'API not (yet) supported: {str(e)}'"
def arg_passed_as_raw_pointer(self, api, arg):
if (arg.type == AST and api.cname in ('Z3_get_ast_kind', 'Z3_get_sort')) \
or (arg.type == SORT and api.cname in ('Z3_get_sort_kind')):
return True
else:
return False
def type2ffi(self,type):
return type.uffi_typename
def spaces2tabs(line, tabwidth=4):
"""
Replaces sequence of tabwidth-spaces with tabs.
"""
nspaces = 0
while line[nspaces] == ' ':
nspaces = nspaces + 1
ntabs = nspaces // tabwidth
return ('\t' * ntabs) + line[ntabs * tabwidth:]
def squeakify(source):
source_in = io.StringIO(source)
source_out = io.StringIO()
for line in source_in.readlines():
source_out.write(spaces2tabs(line))
return source_out.getvalue()
class GeneratorForPharo(Generator):
def reformat(self, source):
return squeakify(source)
Z3_API_HEADER_FILES_TO_SCAN = (
'z3_api.h',
'z3_ast_containers.h',
'z3_algebraic.h',
'z3_polynomial.h',
'z3_rcf.h',
'z3_fixedpoint.h',
'z3_optimization.h',
'z3_fpa.h',
'z3_spacer.h'
)
def main(args):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("header",
nargs="*",
help="C header files to generate API from")
parser.add_argument("--pharo",
action='store_const',
const=True,
default=False,
help="Generate API for Pharo")
parser.add_argument("--z3-source",
default=None,
help="Path to Z3 source where to look for headers")
options = parser.parse_args(args)
headers = options.header
if len(headers) == 0:
if options.z3_source:
if not os.path.isdir(options.z3_source):
sys.stderr.write(f"Error: no such directory: {options.z3_source}\n")
return 2
headers = [os.path.join(options.z3_source, 'src', 'api', header) for header in Z3_API_HEADER_FILES_TO_SCAN]
else:
sys.stderr.write("Error: no headers specified - consider using --z3-source=... option!\n")
return 1
for header in headers:
if not os.path.isfile(header):
sys.stderr.write(f"Error: no such file: {header}\n")
return 3
apis = chain(*[parse(header) for header in headers])
if options.pharo:
generator = GeneratorForPharo()
else:
generator = Generator()
generator.generate(apis)
return 0;
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))