-
Notifications
You must be signed in to change notification settings - Fork 1
/
bindgen.py
197 lines (154 loc) · 6.5 KB
/
bindgen.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
# MIT License
#
# Copyright (c) 2020, 2021 magistermaks
#
# 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 stuff
import argparse
import os.path
import re
langs = {"java", "python"}
# parse cl args
parser = argparse.ArgumentParser( description="Sequensa Dynamic API binding generator" )
parser.add_argument( "--lang", help="select the target binding language [" + (",".join(langs)) + "]", type=str, default="" )
parser.add_argument( "--source", help="select the source file", type=str, default="./src/api/dyncapi.cpp" )
parser.add_argument( "--output", help="select the output file", type=str, default="./output.txt" )
parser.add_argument( "--verbose", help="print some garbage to console", action="store_true" )
args = parser.parse_args()
# fail if no language is set
if args.lang == "":
print( "Error: Target language not set!" )
print( " * Try setting the language using the '--lang' flag" )
exit()
# fail if an unknown language is set
if not args.lang in langs:
print( "Error: Target language not avaible!" )
print( " * Try selecting one of: " + (",".join(langs)) )
print( " * Try commiting your own language binding generator" )
exit()
# load source file
try:
ifile = open(args.source, mode='r')
except:
print( "Error: Failed to open source file at '" + args.source + "'!" )
print( " * Try changing source file location using '--source' flag" )
exit()
#load output file
try:
ofile = open(args.output, mode='w')
except:
print( "Error: Failed to open output file at '" + args.output + "'!" )
print( " * Try changing output file location using '--output' flag" )
exit()
# get contents
lines = ifile.read().split('\n')
ifile.close()
api = []
# print status
if args.verbose:
print( "Reading Source..." )
# parse file
for x in range( len(lines) ):
line = lines[x]
if line.startswith("FUNC"):
obj = { "comment": lines[x-1][4:], "function": line[5:-2] }
api.append(obj)
if args.verbose:
print( " * " + str(obj) )
# print status
if args.verbose:
print( "\nGenerating Binding..." )
output = ""
# java binding generator
if args.lang == "java":
# assume that the target is a java project
if "/main/java/" in args.output:
parts = os.path.dirname(args.output).split("/main/java/")
if len(parts) == 2:
package = parts[1].replace("/", ".")
output += "package " + package + ";\n"
print( " * Deduced package is: '" + package + "'" )
else:
print( parts )
print( " * Failed to deduce package!" )
output += "\n"
output += "import com.sun.jna.Callback;\n"
output += "import com.sun.jna.Library;\n"
output += "import com.sun.jna.Pointer;\n"
output += "\n"
output += "// Auto generated by bindgen.py \n"
output += "public interface SequensaLibrary extends Library {\n\n"
output += " interface Native extends Callback {\n"
output += " Pointer call( Pointer stream );\n"
output += " }\n\n"
output += " interface ErrorHandle extends Callback {\n"
output += " boolean call( Pointer error );\n"
output += " }\n\n"
def get_interface( func ):
str1 = func.replace("void*", "Pointer").replace("const char*", "String").replace("int*", "Pointer")
return re.sub(r"\bbool\b", "boolean", str1) + ";"
for method in api:
output += " /// " + method["comment"] + "\n"
output += " " + get_interface( method["function"] ) + "\n\n"
output += "}\n"
# python binding generator
if args.lang == "python":
# spilt function to (return type) (name) (args)
pattern = re.compile(r"(.+?(?=seq_))(\bseq_[a-z_]+\b)(.+)")
def map_type( type ):
type = ("c_" + type).replace("c_int*", "POINTER(c_int)").replace("*", "_p").replace("const ", "")
return type.replace("c_ErrorHandle", "c_void_p").replace("c_Native", "c_void_p");
def map_args( str ):
if str == "()":
return ""
else:
return ", ".join( [ map_type(x.rsplit(' ', 1)[0]) for x in str[2:-2].split(", ") ] )
def get_function( func, doc ):
result = pattern.search(func)
str = ""
if result:
res = map_type(result.group(1))
name = result.group(2)
args = result.group(3)
if re.match(r"\bc_void\b", res):
res = "None"
str += "libsq." + name + ".__doc__ = \"" + doc + "\"\n"
str += "libsq." + name + ".restype = " + res + "\n"
str += "libsq." + name + ".argtypes = [" + map_args( args ) + "]\n"
str += name + " = libsq." + name + "\n"
else:
raise Exception("Pattern failed to match!")
return str
output += "\n"
output += "from ctypes import *\n"
output += "import os\n"
output += "\n"
output += "libsq = cdll.LoadLibrary( 'C:/sequensa/libseqapi.dll' if os.name == 'nt' else os.path.expanduser('~') + '/sequensa/libseqapi.so' )\n"
output += "\n"
output += "libsq.SQNATIVE = CFUNCTYPE(c_void_p, c_void_p)\n"
output += "libsq.SQERRHANDLE = CFUNCTYPE(c_bool, c_void_p)\n"
output += "\n"
for method in api:
output += "# " + method["comment"] + "\n"
output += get_function( method["function"], method["comment"] ) + "\n"
output += "\n"
ofile.write( output )
ofile.close()
if args.verbose:
print( " * Done!" )