-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtype_manager.py
548 lines (396 loc) · 15.2 KB
/
type_manager.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
class Conv(str):
def __new__(self, conv, *args, **kwargs):
return super(Conv, self).__new__(self, conv)
def __init__(self, conv, post=None):
self.post = post
class Type():
def get_cpp_type(self):
"""The type used in the original OpenCV C++ header.
"""
raise Exception('Unimplemented')
def get_c_type(self):
"""The type used in the generated C file.
"""
raise Exception('Unimplemented')
def get_ctypes_type(self):
"""The type used in OCaml ctypes types.
"""
raise Exception('Unimplemented')
def get_ctypes_value(self):
"""The value used in OCaml ctypes type expressions.
"""
raise Exception('Unimplemented')
def get_ocaml_type(self):
"""The type used in OCaml.
"""
raise Exception('Unimplemented')
def get_ocaml_param_type(self):
"""The type used in OCaml parameters.
"""
return self.get_ocaml_type()
def cpp_to_c(self, val):
return Conv(val)
def c_to_cpp(self, val):
return Conv(val)
def ctypes_to_ocaml(self, val):
return Conv(val)
def ocaml_to_ctypes(self, val):
return Conv(val)
def must_pass_pointer(self):
"""False iff this value can be passed on the stack.
(True iff it must be passed on the heap insead.)
"""
return False
def is_pointer(self):
"""True iff this type is a pointer.
"""
return False
def has_default_value(self):
return self.get_default_value() != None
def get_default_value(self):
"""An OCaml string default value for arguments of this type
iff it is optional, otherwise None.
"""
return None
def return_value(self, val):
"""The return transformation applied to val if values of this type should
be returned. None if values of this type should not be returned.
"""
return None
def is_cloneable(self):
"""True iff parameters of this type should be optionally cloned
before being returned (making pure functions out of impure functions).
"""
return False
def is_draw_function(self):
"""True iff parameters of this type indicate that the function is
a drawing function.
"""
return False
class BaseType(Type):
def __init__(self, cpp_type, c_type, ctypes_type, ctypes_value, ocaml_type):
self.cpp_type = cpp_type
self.c_type = c_type
self.ctypes_type = ctypes_type
self.ctypes_value = ctypes_value
self.ocaml_type = ocaml_type
def get_cpp_type(self):
return self.cpp_type
def get_c_type(self):
return self.c_type
def get_ctypes_type(self):
return self.ctypes_type
def get_ctypes_value(self):
return self.ctypes_value
def get_ocaml_type(self):
return self.ocaml_type
class String(BaseType):
def __init__(self):
super().__init__('cv::String', 'const char *', 'string', 'string', 'string')
def cpp_to_c(self, val):
return Conv('({}).c_str()'.format(val))
def c_to_cpp(self, val):
return Conv('cv::String({})'.format(val))
class WrapperType(Type):
def __init__(self, inner):
self.inner = inner
def get_cpp_type(self):
return self.inner.get_cpp_type()
def get_c_type(self):
return self.inner.get_c_type()
def get_ctypes_type(self):
return self.inner.get_ctypes_type()
def get_ctypes_value(self):
return self.inner.get_ctypes_value()
def get_ocaml_type(self):
return self.inner.get_ocaml_type()
def cpp_to_c(self, val):
return self.inner.cpp_to_c(val)
def c_to_cpp(self, val):
return self.inner.c_to_cpp(val)
def ctypes_to_ocaml(self, val):
return self.inner.ctypes_to_ocaml(val)
def ocaml_to_ctypes(self, val):
return self.inner.ocaml_to_ctypes(val)
class Const(WrapperType):
def __init__(self, inner):
super().__init__(inner)
def get_cpp_type(self):
# don't double const
return 'const {}'.format(self.inner.get_cpp_type().replace('const ', ''))
def get_c_type(self):
# don't double const
return 'const {}'.format(self.inner.get_c_type().replace('const ', ''))
class GenericPointer(WrapperType):
def __init__(self, inner, pointer_char):
super().__init__(inner)
self.pointer_char = pointer_char
def get_cpp_type(self):
return '{}{}'.format(self.inner.get_cpp_type(), self.pointer_char)
def get_c_type(self):
return '{}{}'.format(self.inner.get_c_type(), self.pointer_char)
def get_ctypes_type(self):
return '({}) ptr'.format(self.inner.get_ctypes_type())
def get_ctypes_value(self):
return 'ptr ({})'.format(self.inner.get_ctypes_value())
def get_ocaml_type(self):
return self.inner.get_ocaml_type()
def ctypes_to_ocaml(self, val):
return Conv(self.inner.ctypes_to_ocaml('(!@ ({}))'.format(val)))
def ocaml_to_ctypes(self, val):
return Conv('(allocate ({}) ({}))'.format(self.inner.get_ctypes_value(),
self.inner.ocaml_to_ctypes(val)))
def is_pointer(self):
return True
class Pointer(GenericPointer):
def __init__(self, inner):
super().__init__(inner, '*')
class Reference(GenericPointer):
def __init__(self, inner):
super().__init__(inner, '&')
class Array(WrapperType):
def __init__(self, inner, dimension=None):
super().__init__(inner)
self.dimension = dimension
def get_dimension_str(self):
return '' if self.dimension is None else str(self.dimension)
def get_cpp_type(self):
return '{}[{}]'.format(self.inner.get_cpp_type(),
self.get_dimension_str())
def get_c_type(self):
return '{}[{}]'.format(self.inner.get_c_type(),
self.get_dimension_str())
def get_ctypes_type(self):
return '({}) ptr'.format(self.get_ctypes_type())
def get_ctypes_value(self):
return 'ptr ({})'.format(self.get_ctypes_value())
def get_ocaml_type(self):
# TODO currently no fancy processing to extract array values
return '({}) ptr'.format(self.inner.get_ctypes_type())
class Vector(WrapperType):
def __init__(self, inner):
super().__init__(inner)
def get_cpp_type(self):
return 'std::vector<{}>'.format(self.inner.get_cpp_type())
def get_c_type(self):
return 'std::vector<{}>'.format(self.inner.get_c_type())
def get_ctypes_type(self):
return '({}) ptr'.format(self.inner.get_ctypes_type())
def get_ctypes_value(self):
return 'ptr ({})'.format(self.inner.get_ctypes_value())
def get_ocaml_type(self):
return '({}) list'.format(self.inner.get_ocaml_type())
def ctypes_to_ocaml(self, val):
return Conv('list_of_vector ({}) ({}) |> List.map (fun x -> {})'
.format(self.inner.get_ctypes_value(), val,
self.inner.ctypes_to_ocaml('x')))
def ocaml_to_ctypes(self, val):
# TODO what if the std::vector is also an output?
# i.e. do we need to do the same kind of backpatching that we do for Mat?
return Conv('Vector.vector_of_list ({}) ({} |> List.map (fun x -> {})) |> from_voidp ({})'
.format(self.inner.get_ctypes_value(), val,
self.inner.ocaml_to_ctypes('x'),
self.inner.get_ctypes_value()))
def must_pass_pointer(self):
return True
class CustomType(BaseType):
def __init__(self, cpp_type, c_type, ctypes_type, ctypes_value, ocaml_type,
cpp2c='{}', c2cpp='{}', ctypes2ocaml='{}', ocaml2ctypes='{}', post=None,
must_pointerize=False):
super().__init__(cpp_type, c_type, ctypes_type, ctypes_value, ocaml_type)
self.cpp2c = cpp2c
self.c2cpp = c2cpp
self.ctypes2ocaml = ctypes2ocaml
self.ocaml2ctypes = ocaml2ctypes
self.post = post
self.must_pointerize = must_pointerize
def cpp_to_c(self, val):
return Conv(self.cpp2c.format(val))
def c_to_cpp(self, val):
return Conv(self.c2cpp.format(val))
def ctypes_to_ocaml(self, val):
return Conv(self.ctypes2ocaml.format(val))
def ocaml_to_ctypes(self, val):
post = None if self.post is None else self.post.format(val)
return Conv(self.ocaml2ctypes.format(val), post=post)
def must_pass_pointer(self):
return self.must_pointerize
class Mat(Type):
def get_cpp_type(self):
return 'cv::Mat'
def get_c_type(self):
return 'cv::Mat'
def get_ctypes_type(self):
return 'unit ptr'
def get_ctypes_value(self):
return 'ptr void'
def get_ocaml_type(self):
return 'Mat.t'
def ctypes_to_ocaml(self, val):
return Conv('(Mat.bigarray_of_cmat ({}))'.format(val))
def _post(self, original, converted):
return 'Mat.copy_cmat_bigarray {} {}'.format(original, converted)
def ocaml_to_ctypes(self, val):
return Conv('(Mat.cmat_of_bigarray ({}))'.format(val), post=self._post)
def must_pass_pointer(self):
return True
class Cvdata(Type):
def __init__(self, cpp_type, optional=False, ret=False, cloneable=False,
is_draw=False):
self.cpp_type = cpp_type
self.optional = optional
self.ret = ret
self.cloneable = cloneable
self.is_draw = is_draw
def get_cpp_type(self):
return 'cv::{}'.format(self.cpp_type)
def get_c_type(self):
return 'cv::{}'.format(self.cpp_type)
def get_ctypes_type(self):
return 'unit ptr'
def get_ctypes_value(self):
return 'ptr void'
def get_ocaml_type(self):
return 'Cvdata.t'
def ctypes_to_ocaml(self, val):
return Conv('(Cvdata.extract_cvdata ({}))'.format(val))
def _post(self, original, converted):
return 'Cvdata.pack_cvdata_post {} {}'.format(original, converted)
def ocaml_to_ctypes(self, val):
return Conv('(Cvdata.pack_cvdata ({}))'.format(val), post=self._post)
def get_default_value(self):
return '(Cvdata.Mat (Mat.create ()))' if self.optional else None
def return_value(self, val):
return val if self.ret else None
def is_cloneable(self):
return self.cloneable
def is_draw_function(self):
return self.is_draw
class CvdataArray(Cvdata):
def __init__(self, *args, mutable=False, **kwargs):
super().__init__(*args, **kwargs)
self.mutable = mutable
def get_ocaml_type(self):
return '(Cvdata.t list)'
def get_ocaml_param_type(self):
if self.mutable:
return '(Cvdata.t list ref)'
else:
return self.get_ocaml_type()
def ctypes_to_ocaml(self, val):
return Conv('(Cvdata.extract_cvdata_array ({}))'.format(val))
def _post(self, original, converted):
return 'Cvdata.pack_cvdata_array_post {} {}'.format(original, converted)
def ocaml_to_ctypes(self, val):
if self.mutable:
return Conv('(Cvdata.pack_cvdata_array (!({})))'.format(val), post=self._post)
else:
return Conv('(Cvdata.pack_cvdata_array ({}))'.format(val))
def get_default_value(self):
if self.optional:
if self.mutable:
return '(ref [])'
else:
return '[]'
else:
return None
def return_value(self, val):
if self.ret:
if self.mutable:
return '(!({}))'.format(val)
else:
return val
else:
return None
class Scalar(Type):
def get_cpp_type(self):
return 'cv::Scalar'
def get_c_type(self):
return 'cv::Scalar *'
def get_ctypes_type(self):
return 'unit ptr'
def get_ctypes_value(self):
return 'ptr void'
def get_ocaml_type(self):
return 'Scalar.t'
def c_to_cpp(self, val):
return Conv('*({})'.format(val))
def ctypes_to_ocaml(self, val):
return Conv('(Scalar.ctypes_to_ocaml ({}))'.format(val))
def ocaml_to_ctypes(self, val):
return Conv('(Scalar.ocaml_to_ctypes ({}))'.format(val))
def must_pass_pointer(self):
return True
class RecycleFlag(BaseType):
def __init__(self):
super().__init__('__recycle_flag', 'bool', 'bool', 'bool', 'bool')
def get_default_value(self):
return 'false'
CONST = 'const'
STD_VECTOR = 'std::vector<'
CV_NAMESPACE = 'cv::'
type_map = {}
def add_type(new_type, silent_on_exists=False):
if new_type.get_cpp_type() in type_map:
if not silent_on_exists:
raise Exception('Trying to add previously added type: {}'
.format(new_type.get_cpp_type()))
else:
type_map[new_type.get_cpp_type()] = new_type
def wrap_type(cls, inner, *args):
return None if inner is None else cls(inner, *args)
def get_type(cpp_name):
"""Returns the type associated with the given C++ name.
Returns None if no type could be found.
"""
cpp_name = cpp_name.strip()
if cpp_name in type_map:
return type_map[cpp_name]
if (CV_NAMESPACE + cpp_name) in type_map:
return type_map[CV_NAMESPACE + cpp_name]
if cpp_name.startswith(CONST):
return wrap_type(Const, get_type(cpp_name[len(CONST):]))
if cpp_name.endswith('*'):
return wrap_type(Pointer, get_type(cpp_name[:-1]))
if cpp_name.endswith('&'):
return wrap_type(Reference, get_type(cpp_name[:-1]))
if cpp_name.endswith(']'):
try:
left = cpp_name.rindex('[')
return wrap_type(Array, get_type(cpp_name[:left]), cpp_name[left+1:-1])
except ValueError:
pass
if cpp_name.startswith(STD_VECTOR):
try:
right = cpp_name.rindex('>')
return wrap_type(Vector, get_type(cpp_name[len(STD_VECTOR):right]))
except ValueError:
pass
print('Could not find type for cpp_name: {}'.format(cpp_name))
return None
def has_type(cpp_name):
return get_type(cpp_name) is not None
def add_type_alias(type_name, alias):
existing_type = get_type(type_name)
assert existing_type is not None
assert alias not in type_map
type_map[alias] = existing_type
def add_types():
add_type(BaseType('void', 'void', 'unit', 'void', 'unit'))
add_type(BaseType('int', 'int', 'int', 'int', 'int'))
add_type(BaseType('double', 'double', 'float', 'double', 'float'))
add_type(BaseType('float', 'float', 'float', 'float', 'float'))
add_type(BaseType('bool', 'bool', 'bool', 'bool', 'bool'))
add_type(BaseType('char', 'char', 'char', 'char', 'char'))
add_type(String())
add_type(Mat())
add_type(Scalar())
add_type(Cvdata('InputArray'))
add_type(Cvdata('OutputArray', optional=True, ret=True))
add_type(Cvdata('InputOutputArray', is_draw=True))
add_type(CvdataArray('InputArrayOfArrays'))
add_type(CvdataArray('OutputArrayOfArrays',
optional=True, ret=True, mutable=True))
add_type(CvdataArray('InputOutputArrayOfArrays', mutable=True))
add_type(RecycleFlag())
add_types()