/
mling
executable file
·185 lines (163 loc) · 6.1 KB
/
mling
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
#!/usr/bin/env python
from __future__ import print_function
from optparse import OptionParser
import sys, os.path
from clang.cindex import Index
from clang.cindex import Config
from clang.cindex import TypeKind
from clang.cindex import CursorKind
class UnsupportedException(Exception):
def __init__(self, doc, message):
Exception.__init__(self)
self.__doc__ = doc
self.message = message
class MLtonStrategy:
ty_dict = {
"VOID": "unit",
"CHAR_S": "Int8.int",
"INT": "Int32.int",
"SHORT": "Int16.int",
"LONG": "Int64.int",
"LONGLONG": "Int64.int",
"UINT": "Word32.word",
"USHORT": "Word16.word",
"ULONG": "Word64.word",
"ULONGLONG": "Word64.word",
"DOUBLE": "Real64.real",
"BOOL": "bool",
"ENUM": "int",
"POINTER": "MLton.Pointer.t"
}
def __init__(self, options):
self.vals = []
self.prefix = options.prefix
def map_ty(self, ty):
if ty.kind == TypeKind.POINTER:
if ty.get_pointee().kind == TypeKind.CHAR_S:
return "string"
else:
return "MLton.Pointer.t"
elif ty.kind == TypeKind.TYPEDEF:
canonical = ty.get_canonical()
return self.map_ty(canonical)
elif ty.kind == TypeKind.UNEXPOSED:
raise UnsupportedException("unexposed type", ty.kind.name)
else:
return MLtonStrategy.ty_dict[ty.kind.name]
def process_decl(self, decl):
if decl.kind.name == "FUNCTION_DECL":
n = decl.spelling
if n.startswith("_"):
print("unrendered: "+n, file=sys.stderr)
return
args_ty = [a.type for a in decl.get_arguments()]
result_ty = decl.result_type
try:
if len(args_ty) == 0:
args_str = "unit"
else:
args_str = "(" + " * ".join([self.map_ty(a) for a in args_ty]) + ")"
result_str = self.map_ty(result_ty)
self.vals.append("val %s = _import \"%s\" public: %s -> %s;" % (n, n, args_str, result_str))
except Exception, e:
print("unrendered: "+n+" "+e.__doc__+" "+e.message, file=sys.stderr)
def process_tu(self, tu):
for decl in tu.get_children():
self.process_decl(decl)
def spell_out(self):
print("structure %s = struct" % self.prefix)
print(" val NULL = MLton.Pointer.null")
for val in self.vals:
print(" " + val)
print("end")
class PolyMLStrategy:
ty_dict = {
"VOID": "VOID",
"CHAR_S": "CHAR",
"INT": "INT",
"SHORT": "SHORT",
"LONG": "LONG",
"LONGLONG": "LONG",
"UINT": "INT",
"USHORT": "SHORT",
"ULONG": "LONG",
"ULONGLONG": "LONG",
"DOUBLE": "DOUBLE",
"BOOL": "BOOL",
"ENUM": "INT",
"POINTER": "POINTER"
}
def __init__(self, options):
self.vals = []
self.prefix = options.prefix
self.so = options.so
def map_ty(self, ty):
if ty.kind == TypeKind.POINTER:
if ty.get_pointee().kind == TypeKind.CHAR_S:
return "STRING"
else:
return "POINTER"
elif ty.kind == TypeKind.TYPEDEF:
canonical = ty.get_canonical()
return self.map_ty(canonical)
elif ty.kind == TypeKind.UNEXPOSED:
raise UnsupportedException("unexposed type", ty.kind.name)
else:
return PolyMLStrategy.ty_dict[ty.kind.name]
def process_decl(self, decl):
if decl.kind.name == "FUNCTION_DECL":
n = decl.spelling
if n.startswith("_"):
print("unrendered: "+n, file=sys.stderr)
return
args_ty = [a.type for a in decl.get_arguments()]
result_ty = decl.result_type
try:
if len(args_ty) == 0:
args_str = "()"
else:
args_str = "(" + ", ".join([self.map_ty(a) for a in args_ty]) + ")"
result_str = self.map_ty(result_ty)
self.vals.append("val %s = call%d (get \"%s\") %s %s" % (n, len(args_ty), n, args_str, result_str))
except Exception, e:
print("unrendered: "+n+" "+e.__doc__+" "+e.message, file=sys.stderr)
def process_tu(self, tu):
for decl in tu.get_children():
self.process_decl(decl)
def spell_out(self):
print("structure %s = struct" % self.prefix)
print(" open CInterface")
print(" val NULL = CInterface.null")
print(" val get = load_sym (load_lib \"%s\")" % self.so)
for val in self.vals:
print(" " + val)
print("end")
def make_strategy(options):
if options.sml == "mlton":
return MLtonStrategy(options)
elif options.sml == "poly":
return PolyMLStrategy(options)
else:
raise ValueError("Unknown SML implementation: %s" % options.sml)
def parse_opts():
usage = "usage: %prog [options] file [clang-options]"
parser = OptionParser(usage=usage)
parser.add_option("-p", "--prefix", dest="prefix", help="use PREFIX as the structure name")
parser.add_option("-s", "--sml", dest="sml", default="mlton", help="sml implementation [mlton|poly]")
parser.add_option("--so", dest="so", default="", help="shared object to be dlopened (for Poly/ML)")
(options, args) = parser.parse_args()
if len(args) < 1:
parser.error("incorrect number of arguments")
file = args[0]
clang_opts = args[1:]
if options.prefix == None:
basename = os.path.basename(file)
(name, _) = os.path.splitext(basename)
options.prefix = name.title()
return (file, options, args, clang_opts)
(file, options, args, clang_opts) = parse_opts()
index = Index.create()
tu = index.parse(file, args=clang_opts)
strategy = make_strategy(options)
strategy.process_tu(tu.cursor)
strategy.spell_out()