embindgen.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. ###############################################################################
  2. #
  3. # IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
  4. #
  5. # By downloading, copying, installing or using the software you agree to this license.
  6. # If you do not agree to this license, do not download, install,
  7. # copy or use the software.
  8. #
  9. #
  10. # License Agreement
  11. # For Open Source Computer Vision Library
  12. #
  13. # Copyright (C) 2013, OpenCV Foundation, all rights reserved.
  14. # Third party copyrights are property of their respective owners.
  15. #
  16. # Redistribution and use in source and binary forms, with or without modification,
  17. # are permitted provided that the following conditions are met:
  18. #
  19. # * Redistribution's of source code must retain the above copyright notice,
  20. # this list of conditions and the following disclaimer.
  21. #
  22. # * Redistribution's in binary form must reproduce the above copyright notice,
  23. # this list of conditions and the following disclaimer in the documentation
  24. # and/or other materials provided with the distribution.
  25. #
  26. # * The name of the copyright holders may not be used to endorse or promote products
  27. # derived from this software without specific prior written permission.
  28. #
  29. # This software is provided by the copyright holders and contributors "as is" and
  30. # any express or implied warranties, including, but not limited to, the implied
  31. # warranties of merchantability and fitness for a particular purpose are disclaimed.
  32. # In no event shall the Intel Corporation or contributors be liable for any direct,
  33. # indirect, incidental, special, exemplary, or consequential damages
  34. # (including, but not limited to, procurement of substitute goods or services;
  35. # loss of use, data, or profits; or business interruption) however caused
  36. # and on any theory of liability, whether in contract, strict liability,
  37. # or tort (including negligence or otherwise) arising in any way out of
  38. # the use of this software, even if advised of the possibility of such damage.
  39. #
  40. ###############################################################################
  41. # AUTHOR: Sajjad Taheri, University of California, Irvine. sajjadt[at]uci[dot]edu
  42. #
  43. # LICENSE AGREEMENT
  44. # Copyright (c) 2015, 2015 The Regents of the University of California (Regents)
  45. #
  46. # Redistribution and use in source and binary forms, with or without
  47. # modification, are permitted provided that the following conditions are met:
  48. # 1. Redistributions of source code must retain the above copyright
  49. # notice, this list of conditions and the following disclaimer.
  50. # 2. Redistributions in binary form must reproduce the above copyright
  51. # notice, this list of conditions and the following disclaimer in the
  52. # documentation and/or other materials provided with the distribution.
  53. # 3. Neither the name of the University nor the
  54. # names of its contributors may be used to endorse or promote products
  55. # derived from this software without specific prior written permission.
  56. #
  57. # THIS SOFTWARE IS PROVIDED BY COPYRIGHT HOLDERS AND CONTRIBUTORS ''AS IS'' AND ANY
  58. # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  59. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  60. # DISCLAIMED. IN NO EVENT SHALL COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
  61. # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  62. # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  63. # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  64. # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  65. # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  66. # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  67. ###############################################################################
  68. from __future__ import print_function
  69. import sys, re, os
  70. from templates import *
  71. if sys.version_info[0] >= 3:
  72. from io import StringIO
  73. else:
  74. from cStringIO import StringIO
  75. func_table = {}
  76. # Ignore these functions due to Embind limitations for now
  77. ignore_list = ['locate', #int&
  78. 'minEnclosingCircle', #float&
  79. 'checkRange',
  80. 'minMaxLoc', #double*
  81. 'floodFill', # special case, implemented in core_bindings.cpp
  82. 'phaseCorrelate',
  83. 'randShuffle',
  84. 'calibrationMatrixValues', #double&
  85. 'undistortPoints', # global redefinition
  86. 'CamShift', #Rect&
  87. 'meanShift' #Rect&
  88. ]
  89. def makeWhiteList(module_list):
  90. wl = {}
  91. for m in module_list:
  92. for k in m.keys():
  93. if k in wl:
  94. wl[k] += m[k]
  95. else:
  96. wl[k] = m[k]
  97. return wl
  98. white_list = None
  99. namespace_prefix_override = {
  100. 'dnn' : '',
  101. 'aruco' : '',
  102. }
  103. # Features to be exported
  104. export_enums = False
  105. export_consts = True
  106. with_wrapped_functions = True
  107. with_default_params = True
  108. with_vec_from_js_array = True
  109. wrapper_namespace = "Wrappers"
  110. type_dict = {
  111. 'InputArray': 'const cv::Mat&',
  112. 'OutputArray': 'cv::Mat&',
  113. 'InputOutputArray': 'cv::Mat&',
  114. 'InputArrayOfArrays': 'const std::vector<cv::Mat>&',
  115. 'OutputArrayOfArrays': 'std::vector<cv::Mat>&',
  116. 'string': 'std::string',
  117. 'String': 'std::string',
  118. 'const String&':'const std::string&'
  119. }
  120. def normalize_class_name(name):
  121. return re.sub(r"^cv\.", "", name).replace(".", "_")
  122. class ClassProp(object):
  123. def __init__(self, decl):
  124. self.tp = decl[0].replace("*", "_ptr").strip()
  125. self.name = decl[1]
  126. self.readonly = True
  127. if "/RW" in decl[3]:
  128. self.readonly = False
  129. class ClassInfo(object):
  130. def __init__(self, name, decl=None):
  131. self.cname = name.replace(".", "::")
  132. self.name = self.wname = normalize_class_name(name)
  133. self.ismap = False
  134. self.issimple = False
  135. self.isalgorithm = False
  136. self.methods = {}
  137. self.ext_constructors = {}
  138. self.props = []
  139. self.consts = {}
  140. customname = False
  141. self.jsfuncs = {}
  142. self.constructor_arg_num = set()
  143. self.has_smart_ptr = False
  144. if decl:
  145. self.bases = decl[1].split()[1:]
  146. if len(self.bases) > 1:
  147. self.bases = [self.bases[0].strip(",")]
  148. # return sys.exit(-1)
  149. if self.bases and self.bases[0].startswith("cv::"):
  150. self.bases[0] = self.bases[0][4:]
  151. if self.bases and self.bases[0] == "Algorithm":
  152. self.isalgorithm = True
  153. for m in decl[2]:
  154. if m.startswith("="):
  155. self.wname = m[1:]
  156. customname = True
  157. elif m == "/Map":
  158. self.ismap = True
  159. elif m == "/Simple":
  160. self.issimple = True
  161. self.props = [ClassProp(p) for p in decl[3]]
  162. if not customname and self.wname.startswith("Cv"):
  163. self.wname = self.wname[2:]
  164. def handle_ptr(tp):
  165. if tp.startswith('Ptr_'):
  166. tp = 'Ptr<' + "::".join(tp.split('_')[1:]) + '>'
  167. return tp
  168. def handle_vector(tp):
  169. if tp.startswith('vector_'):
  170. tp = handle_vector(tp[tp.find('_') + 1:])
  171. tp = 'std::vector<' + "::".join(tp.split('_')) + '>'
  172. return tp
  173. class ArgInfo(object):
  174. def __init__(self, arg_tuple):
  175. self.tp = handle_ptr(arg_tuple[0]).strip()
  176. self.name = arg_tuple[1]
  177. self.defval = arg_tuple[2]
  178. self.isarray = False
  179. self.arraylen = 0
  180. self.arraycvt = None
  181. self.inputarg = True
  182. self.outputarg = False
  183. self.returnarg = False
  184. self.const = False
  185. self.reference = False
  186. for m in arg_tuple[3]:
  187. if m == "/O":
  188. self.inputarg = False
  189. self.outputarg = True
  190. self.returnarg = True
  191. elif m == "/IO":
  192. self.inputarg = True
  193. self.outputarg = True
  194. self.returnarg = True
  195. elif m.startswith("/A"):
  196. self.isarray = True
  197. self.arraylen = m[2:].strip()
  198. elif m.startswith("/CA"):
  199. self.isarray = True
  200. self.arraycvt = m[2:].strip()
  201. elif m == "/C":
  202. self.const = True
  203. elif m == "/Ref":
  204. self.reference = True
  205. if self.tp == "Mat":
  206. if self.outputarg:
  207. self.tp = "cv::Mat&"
  208. elif self.inputarg:
  209. self.tp = "const cv::Mat&"
  210. if self.tp == "vector_Mat":
  211. if self.outputarg:
  212. self.tp = "std::vector<cv::Mat>&"
  213. elif self.inputarg:
  214. self.tp = "const std::vector<cv::Mat>&"
  215. self.tp = handle_vector(self.tp).strip()
  216. if self.const:
  217. self.tp = "const " + self.tp
  218. if self.reference:
  219. self.tp = self.tp + "&"
  220. self.py_inputarg = False
  221. self.py_outputarg = False
  222. class FuncVariant(object):
  223. def __init__(self, class_name, name, decl, is_constructor, is_class_method, is_const, is_virtual, is_pure_virtual, ref_return, const_return):
  224. self.class_name = class_name
  225. self.name = self.wname = name
  226. self.is_constructor = is_constructor
  227. self.is_class_method = is_class_method
  228. self.is_const = is_const
  229. self.is_virtual = is_virtual
  230. self.is_pure_virtual = is_pure_virtual
  231. self.refret = ref_return
  232. self.constret = const_return
  233. self.rettype = handle_vector(handle_ptr(decl[1]).strip()).strip()
  234. if self.rettype == "void":
  235. self.rettype = ""
  236. self.args = []
  237. self.array_counters = {}
  238. for a in decl[3]:
  239. ainfo = ArgInfo(a)
  240. if ainfo.isarray and not ainfo.arraycvt:
  241. c = ainfo.arraylen
  242. c_arrlist = self.array_counters.get(c, [])
  243. if c_arrlist:
  244. c_arrlist.append(ainfo.name)
  245. else:
  246. self.array_counters[c] = [ainfo.name]
  247. self.args.append(ainfo)
  248. class FuncInfo(object):
  249. def __init__(self, class_name, name, cname, namespace, isconstructor):
  250. self.name_id = '_'.join([namespace] + ([class_name] if class_name else []) + [name]) # unique id for dict key
  251. self.class_name = class_name
  252. self.name = name
  253. self.cname = cname
  254. self.namespace = namespace
  255. self.variants = []
  256. self.is_constructor = isconstructor
  257. def add_variant(self, variant):
  258. self.variants.append(variant)
  259. class Namespace(object):
  260. def __init__(self):
  261. self.funcs = {}
  262. self.enums = {}
  263. self.consts = {}
  264. class JSWrapperGenerator(object):
  265. def __init__(self):
  266. self.bindings = []
  267. self.wrapper_funcs = []
  268. self.classes = {} # FIXIT 'classes' should belong to 'namespaces'
  269. self.namespaces = {}
  270. self.enums = {} # FIXIT 'enums' should belong to 'namespaces'
  271. self.parser = hdr_parser.CppHeaderParser()
  272. self.class_idx = 0
  273. def add_class(self, stype, name, decl):
  274. class_info = ClassInfo(name, decl)
  275. class_info.decl_idx = self.class_idx
  276. self.class_idx += 1
  277. if class_info.name in self.classes:
  278. print("Generator error: class %s (cpp_name=%s) already exists" \
  279. % (class_info.name, class_info.cname))
  280. sys.exit(-1)
  281. self.classes[class_info.name] = class_info
  282. if class_info.bases:
  283. chunks = class_info.bases[0].split('::')
  284. base = '_'.join(chunks)
  285. while base not in self.classes and len(chunks) > 1:
  286. del chunks[-2]
  287. base = '_'.join(chunks)
  288. if base not in self.classes:
  289. print("Generator error: unable to resolve base %s for %s"
  290. % (class_info.bases[0], class_info.name))
  291. sys.exit(-1)
  292. else:
  293. class_info.bases[0] = "::".join(chunks)
  294. class_info.isalgorithm |= self.classes[base].isalgorithm
  295. def split_decl_name(self, name):
  296. chunks = name.split('.')
  297. namespace = chunks[:-1]
  298. classes = []
  299. while namespace and '.'.join(namespace) not in self.parser.namespaces:
  300. classes.insert(0, namespace.pop())
  301. return namespace, classes, chunks[-1]
  302. def add_enum(self, decl):
  303. name = decl[0].rsplit(" ", 1)[1]
  304. namespace, classes, val = self.split_decl_name(name)
  305. namespace = '.'.join(namespace)
  306. ns = self.namespaces.setdefault(namespace, Namespace())
  307. if len(name) == 0: name = "<unnamed>"
  308. if name.endswith("<unnamed>"):
  309. i = 0
  310. while True:
  311. i += 1
  312. candidate_name = name.replace("<unnamed>", "unnamed_%u" % i)
  313. if candidate_name not in ns.enums:
  314. name = candidate_name
  315. break;
  316. cname = name.replace('.', '::')
  317. type_dict[normalize_class_name(name)] = cname
  318. if name in ns.enums:
  319. print("Generator warning: enum %s (cname=%s) already exists" \
  320. % (name, cname))
  321. # sys.exit(-1)
  322. else:
  323. ns.enums[name] = []
  324. for item in decl[3]:
  325. ns.enums[name].append(item)
  326. const_decls = decl[3]
  327. for decl in const_decls:
  328. name = decl[0]
  329. self.add_const(name.replace("const ", "").strip(), decl)
  330. def add_const(self, name, decl):
  331. cname = name.replace('.','::')
  332. namespace, classes, name = self.split_decl_name(name)
  333. namespace = '.'.join(namespace)
  334. name = '_'.join(classes+[name])
  335. ns = self.namespaces.setdefault(namespace, Namespace())
  336. if name in ns.consts:
  337. print("Generator error: constant %s (cname=%s) already exists" \
  338. % (name, cname))
  339. sys.exit(-1)
  340. ns.consts[name] = cname
  341. def add_func(self, decl):
  342. namespace, classes, barename = self.split_decl_name(decl[0])
  343. cpp_name = "::".join(namespace + classes + [barename])
  344. name = barename
  345. class_name = ''
  346. bare_class_name = ''
  347. if classes:
  348. class_name = normalize_class_name('.'.join(namespace + classes))
  349. bare_class_name = classes[-1]
  350. namespace = '.'.join(namespace)
  351. is_constructor = name == bare_class_name
  352. is_class_method = False
  353. is_const_method = False
  354. is_virtual_method = False
  355. is_pure_virtual_method = False
  356. const_return = False
  357. ref_return = False
  358. for m in decl[2]:
  359. if m == "/S":
  360. is_class_method = True
  361. elif m == "/C":
  362. is_const_method = True
  363. elif m == "/V":
  364. is_virtual_method = True
  365. elif m == "/PV":
  366. is_pure_virtual_method = True
  367. elif m == "/Ref":
  368. ref_return = True
  369. elif m == "/CRet":
  370. const_return = True
  371. elif m.startswith("="):
  372. name = m[1:]
  373. if class_name:
  374. cpp_name = barename
  375. func_map = self.classes[class_name].methods
  376. else:
  377. func_map = self.namespaces.setdefault(namespace, Namespace()).funcs
  378. fi = FuncInfo(class_name, name, cpp_name, namespace, is_constructor)
  379. func = func_map.setdefault(fi.name_id, fi)
  380. variant = FuncVariant(class_name, name, decl, is_constructor, is_class_method, is_const_method,
  381. is_virtual_method, is_pure_virtual_method, ref_return, const_return)
  382. func.add_variant(variant)
  383. def save(self, path, name, buf):
  384. f = open(path + "/" + name, "wt")
  385. f.write(buf.getvalue())
  386. f.close()
  387. def gen_function_binding_with_wrapper(self, func, ns_name, class_info):
  388. binding_text = None
  389. wrapper_func_text = None
  390. bindings = []
  391. wrappers = []
  392. for index, variant in enumerate(func.variants):
  393. factory = False
  394. if class_info and 'Ptr<' in variant.rettype:
  395. factory = True
  396. base_class_name = variant.rettype
  397. base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
  398. if base_class_name in self.classes:
  399. self.classes[base_class_name].has_smart_ptr = True
  400. else:
  401. print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead')
  402. self.classes[class_info.name].has_smart_ptr = True
  403. def_args = []
  404. has_def_param = False
  405. # Return type
  406. ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype
  407. if ret_type.startswith('Ptr'): #smart pointer
  408. ptr_type = ret_type.replace('Ptr<', '').replace('>', '')
  409. if ptr_type in type_dict:
  410. ret_type = type_dict[ptr_type]
  411. for key in type_dict:
  412. if key in ret_type:
  413. ret_type = re.sub('(^|[^\w])' + key + '($|[^\w])', type_dict[key], ret_type)
  414. arg_types = []
  415. unwrapped_arg_types = []
  416. for arg in variant.args:
  417. arg_type = None
  418. if arg.tp in type_dict:
  419. arg_type = type_dict[arg.tp]
  420. else:
  421. arg_type = arg.tp
  422. # Add default value
  423. if with_default_params and arg.defval != '':
  424. def_args.append(arg.defval);
  425. arg_types.append(arg_type)
  426. unwrapped_arg_types.append(arg_type)
  427. # Function attribute
  428. func_attribs = ''
  429. if '*' in ''.join(arg_types):
  430. func_attribs += ', allow_raw_pointers()'
  431. if variant.is_pure_virtual:
  432. func_attribs += ', pure_virtual()'
  433. # Wrapper function
  434. if ns_name != None and ns_name != "cv":
  435. ns_parts = ns_name.split(".")
  436. if ns_parts[0] == "cv":
  437. ns_parts = ns_parts[1:]
  438. ns_part = "_".join(ns_parts) + "_"
  439. ns_id = '_'.join(ns_parts)
  440. ns_prefix = namespace_prefix_override.get(ns_id, ns_id)
  441. if ns_prefix:
  442. ns_prefix = ns_prefix + '_'
  443. else:
  444. ns_prefix = ''
  445. if class_info == None:
  446. js_func_name = ns_prefix + func.name
  447. wrap_func_name = js_func_name + "_wrapper"
  448. else:
  449. wrap_func_name = ns_prefix + func.class_name + "_" + func.name + "_wrapper"
  450. js_func_name = func.name
  451. # TODO: Name functions based wrap directives or based on arguments list
  452. if index > 0:
  453. wrap_func_name += str(index)
  454. js_func_name += str(index)
  455. c_func_name = 'Wrappers::' + wrap_func_name
  456. # Binding template-
  457. raw_arg_names = ['arg' + str(i + 1) for i in range(0, len(variant.args))]
  458. arg_names = []
  459. w_signature = []
  460. casted_arg_types = []
  461. for arg_type, arg_name in zip(arg_types, raw_arg_names):
  462. casted_arg_name = arg_name
  463. if with_vec_from_js_array:
  464. # Only support const vector reference as input parameter
  465. match = re.search(r'const std::vector<(.*)>&', arg_type)
  466. if match:
  467. type_in_vect = match.group(1)
  468. if type_in_vect in ['int', 'float', 'double', 'char', 'uchar', 'String', 'std::string']:
  469. casted_arg_name = 'emscripten::vecFromJSArray<' + type_in_vect + '>(' + arg_name + ')'
  470. arg_type = re.sub(r'std::vector<(.*)>', 'emscripten::val', arg_type)
  471. w_signature.append(arg_type + ' ' + arg_name)
  472. arg_names.append(casted_arg_name)
  473. casted_arg_types.append(arg_type)
  474. arg_types = casted_arg_types
  475. # Argument list, signature
  476. arg_names_casted = [c if a == b else c + '.as<' + a + '>()' for a, b, c in
  477. zip(unwrapped_arg_types, arg_types, arg_names)]
  478. # Add self object to the parameters
  479. if class_info and not factory:
  480. arg_types = [class_info.cname + '&'] + arg_types
  481. w_signature = [class_info.cname + '& arg0 '] + w_signature
  482. for j in range(0, len(def_args) + 1):
  483. postfix = ''
  484. if j > 0:
  485. postfix = '_' + str(j);
  486. ###################################
  487. # Wrapper
  488. if factory: # TODO or static
  489. name = class_info.cname+'::' if variant.class_name else ""
  490. cpp_call_text = static_class_call_template.substitute(scope=name,
  491. func=func.cname,
  492. args=', '.join(arg_names[:len(arg_names)-j]))
  493. elif class_info:
  494. cpp_call_text = class_call_template.substitute(obj='arg0',
  495. func=func.cname,
  496. args=', '.join(arg_names[:len(arg_names)-j]))
  497. else:
  498. cpp_call_text = call_template.substitute(func=func.cname,
  499. args=', '.join(arg_names[:len(arg_names)-j]))
  500. wrapper_func_text = wrapper_function_template.substitute(ret_val=ret_type,
  501. func=wrap_func_name+postfix,
  502. signature=', '.join(w_signature[:len(w_signature)-j]),
  503. cpp_call=cpp_call_text,
  504. const='' if variant.is_const else '')
  505. ###################################
  506. # Binding
  507. if class_info:
  508. if factory:
  509. # print("Factory Function: ", c_func_name, len(variant.args) - j, class_info.name)
  510. if variant.is_pure_virtual:
  511. # FIXME: workaround for pure virtual in constructor
  512. # e.g. DescriptorMatcher_clone_wrapper
  513. continue
  514. # consider the default parameter variants
  515. args_num = len(variant.args) - j
  516. if args_num in class_info.constructor_arg_num:
  517. # FIXME: workaround for constructor overload with same args number
  518. # e.g. DescriptorMatcher
  519. continue
  520. class_info.constructor_arg_num.add(args_num)
  521. binding_text = ctr_template.substitute(const='const' if variant.is_const else '',
  522. cpp_name=c_func_name+postfix,
  523. ret=ret_type,
  524. args=','.join(arg_types[:len(arg_types)-j]),
  525. optional=func_attribs)
  526. else:
  527. binding_template = overload_class_static_function_template if variant.is_class_method else \
  528. overload_class_function_template
  529. binding_text = binding_template.substitute(js_name=js_func_name,
  530. const='' if variant.is_const else '',
  531. cpp_name=c_func_name+postfix,
  532. ret=ret_type,
  533. args=','.join(arg_types[:len(arg_types)-j]),
  534. optional=func_attribs)
  535. else:
  536. binding_text = overload_function_template.substitute(js_name=js_func_name,
  537. cpp_name=c_func_name+postfix,
  538. const='const' if variant.is_const else '',
  539. ret=ret_type,
  540. args=', '.join(arg_types[:len(arg_types)-j]),
  541. optional=func_attribs)
  542. bindings.append(binding_text)
  543. wrappers.append(wrapper_func_text)
  544. return [bindings, wrappers]
  545. def gen_function_binding(self, func, class_info):
  546. if not class_info == None :
  547. func_name = class_info.cname+'::'+func.cname
  548. else :
  549. func_name = func.cname
  550. binding_text = None
  551. binding_text_list = []
  552. for index, variant in enumerate(func.variants):
  553. factory = False
  554. #TODO if variant.is_class_method and variant.rettype == ('Ptr<' + class_info.name + '>'):
  555. if (not class_info == None) and variant.rettype == ('Ptr<' + class_info.name + '>') or (func.name.startswith("create") and variant.rettype):
  556. factory = True
  557. base_class_name = variant.rettype
  558. base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
  559. if base_class_name in self.classes:
  560. self.classes[base_class_name].has_smart_ptr = True
  561. else:
  562. print(base_class_name, ' not found in classes for registering smart pointer using ', class_info.name, 'instead')
  563. self.classes[class_info.name].has_smart_ptr = True
  564. # Return type
  565. ret_type = 'void' if variant.rettype.strip() == '' else variant.rettype
  566. ret_type = ret_type.strip()
  567. if ret_type.startswith('Ptr'): #smart pointer
  568. ptr_type = ret_type.replace('Ptr<', '').replace('>', '')
  569. if ptr_type in type_dict:
  570. ret_type = type_dict[ptr_type]
  571. for key in type_dict:
  572. if key in ret_type:
  573. # Replace types. Instead of ret_type.replace we use regular
  574. # expression to exclude false matches.
  575. # See https://github.com/opencv/opencv/issues/15514
  576. ret_type = re.sub('(^|[^\w])' + key + '($|[^\w])', type_dict[key], ret_type)
  577. if variant.constret and ret_type.startswith('const') == False:
  578. ret_type = 'const ' + ret_type
  579. if variant.refret and ret_type.endswith('&') == False:
  580. ret_type += '&'
  581. arg_types = []
  582. orig_arg_types = []
  583. def_args = []
  584. for arg in variant.args:
  585. if arg.tp in type_dict:
  586. arg_type = type_dict[arg.tp]
  587. else:
  588. arg_type = arg.tp
  589. #if arg.outputarg:
  590. # arg_type += '&'
  591. orig_arg_types.append(arg_type)
  592. if with_default_params and arg.defval != '':
  593. def_args.append(arg.defval)
  594. arg_types.append(orig_arg_types[-1])
  595. # Function attribute
  596. func_attribs = ''
  597. if '*' in ''.join(orig_arg_types):
  598. func_attribs += ', allow_raw_pointers()'
  599. if variant.is_pure_virtual:
  600. func_attribs += ', pure_virtual()'
  601. #TODO better naming
  602. #if variant.name in self.jsfunctions:
  603. #else
  604. js_func_name = variant.name
  605. c_func_name = func.cname if (factory and variant.is_class_method == False) else func_name
  606. ################################### Binding
  607. for j in range(0, len(def_args) + 1):
  608. postfix = ''
  609. if j > 0:
  610. postfix = '_' + str(j);
  611. if factory:
  612. binding_text = ctr_template.substitute(const='const' if variant.is_const else '',
  613. cpp_name=c_func_name+postfix,
  614. ret=ret_type,
  615. args=','.join(arg_types[:len(arg_types)-j]),
  616. optional=func_attribs)
  617. else:
  618. binding_template = overload_class_static_function_template if variant.is_class_method else \
  619. overload_function_template if class_info == None else overload_class_function_template
  620. binding_text = binding_template.substitute(js_name=js_func_name,
  621. const='const' if variant.is_const else '',
  622. cpp_name=c_func_name+postfix,
  623. ret=ret_type,
  624. args=','.join(arg_types[:len(arg_types)-1]),
  625. optional=func_attribs)
  626. binding_text_list.append(binding_text)
  627. return binding_text_list
  628. def print_decls(self, decls):
  629. """
  630. Prints the list of declarations, retrieived by the parse() method
  631. """
  632. for d in decls:
  633. print(d[0], d[1], ";".join(d[2]))
  634. for a in d[3]:
  635. print(" ", a[0], a[1], a[2], end="")
  636. if a[3]:
  637. print("; ".join(a[3]))
  638. else:
  639. print()
  640. def gen(self, dst_file, src_files, core_bindings):
  641. # step 1: scan the headers and extract classes, enums and functions
  642. headers = []
  643. for hdr in src_files:
  644. decls = self.parser.parse(hdr)
  645. # print(hdr);
  646. # self.print_decls(decls);
  647. if len(decls) == 0:
  648. continue
  649. headers.append(hdr[hdr.rindex('opencv2/'):])
  650. for decl in decls:
  651. name = decl[0]
  652. type = name[:name.find(" ")]
  653. if type == "struct" or type == "class": # class/structure case
  654. name = name[name.find(" ") + 1:].strip()
  655. self.add_class(type, name, decl)
  656. elif name.startswith("enum"): # enumerations
  657. self.add_enum(decl)
  658. elif name.startswith("const"):
  659. # constant
  660. self.add_const(name.replace("const ", "").strip(), decl)
  661. else: # class/global function
  662. self.add_func(decl)
  663. # step 2: generate bindings
  664. # Global functions
  665. for ns_name, ns in sorted(self.namespaces.items()):
  666. ns_parts = ns_name.split('.')
  667. if ns_parts[0] != 'cv':
  668. print('Ignore namespace: {}'.format(ns_name))
  669. continue
  670. else:
  671. ns_parts = ns_parts[1:]
  672. ns_id = '_'.join(ns_parts)
  673. ns_prefix = namespace_prefix_override.get(ns_id, ns_id)
  674. for name_id, func in sorted(ns.funcs.items()):
  675. name = func.name
  676. if ns_prefix:
  677. name = ns_prefix + '_' + name
  678. if name in ignore_list:
  679. continue
  680. if not name in white_list['']:
  681. #print('Not in whitelist: "{}" from ns={}'.format(name, ns_name))
  682. continue
  683. ext_cnst = False
  684. # Check if the method is an external constructor
  685. for variant in func.variants:
  686. if "Ptr<" in variant.rettype:
  687. # Register the smart pointer
  688. base_class_name = variant.rettype
  689. base_class_name = base_class_name.replace("Ptr<","").replace(">","").strip()
  690. self.classes[base_class_name].has_smart_ptr = True
  691. # Adds the external constructor
  692. class_name = func.name.replace("create", "")
  693. if not class_name in self.classes:
  694. self.classes[base_class_name].methods[func.cname] = func
  695. else:
  696. self.classes[class_name].methods[func.cname] = func
  697. ext_cnst = True
  698. if ext_cnst:
  699. continue
  700. if with_wrapped_functions:
  701. binding, wrapper = self.gen_function_binding_with_wrapper(func, ns_name, class_info=None)
  702. self.bindings += binding
  703. self.wrapper_funcs += wrapper
  704. else:
  705. binding = self.gen_function_binding(func, class_info=None)
  706. self.bindings+=binding
  707. # generate code for the classes and their methods
  708. for name, class_info in sorted(self.classes.items()):
  709. class_bindings = []
  710. if not name in white_list:
  711. continue
  712. # Generate bindings for methods
  713. for method_name, method in sorted(class_info.methods.items()):
  714. if method.cname in ignore_list:
  715. continue
  716. if not method.name in white_list[method.class_name]:
  717. continue
  718. if method.is_constructor:
  719. for variant in method.variants:
  720. args = []
  721. for arg in variant.args:
  722. arg_type = type_dict[arg.tp] if arg.tp in type_dict else arg.tp
  723. args.append(arg_type)
  724. # print('Constructor: ', class_info.name, len(variant.args))
  725. args_num = len(variant.args)
  726. if args_num in class_info.constructor_arg_num:
  727. continue
  728. class_info.constructor_arg_num.add(args_num)
  729. class_bindings.append(constructor_template.substitute(signature=', '.join(args)))
  730. else:
  731. if with_wrapped_functions and (len(method.variants) > 1 or len(method.variants[0].args)>0 or "String" in method.variants[0].rettype):
  732. binding, wrapper = self.gen_function_binding_with_wrapper(method, None, class_info=class_info)
  733. self.wrapper_funcs = self.wrapper_funcs + wrapper
  734. class_bindings = class_bindings + binding
  735. else:
  736. binding = self.gen_function_binding(method, class_info=class_info)
  737. class_bindings = class_bindings + binding
  738. # Regiseter Smart pointer
  739. if class_info.has_smart_ptr:
  740. class_bindings.append(smart_ptr_reg_template.substitute(cname=class_info.cname, name=class_info.name))
  741. # Attach external constructors
  742. # for method_name, method in class_info.ext_constructors.items():
  743. # print("ext constructor", method_name)
  744. #if class_info.ext_constructors:
  745. # Generate bindings for properties
  746. for property in class_info.props:
  747. _class_property = class_property_enum_template if property.tp in type_dict else class_property_template
  748. class_bindings.append(_class_property.substitute(js_name=property.name, cpp_name='::'.join(
  749. [class_info.cname, property.name])))
  750. dv = ''
  751. base = Template("""base<$base>""")
  752. assert len(class_info.bases) <= 1 , "multiple inheritance not supported"
  753. if len(class_info.bases) == 1:
  754. dv = "," + base.substitute(base=', '.join(class_info.bases))
  755. self.bindings.append(class_template.substitute(cpp_name=class_info.cname,
  756. js_name=name,
  757. class_templates=''.join(class_bindings),
  758. derivation=dv))
  759. if export_enums:
  760. # step 4: generate bindings for enums
  761. # TODO anonymous enums are ignored for now.
  762. for ns_name, ns in sorted(self.namespaces.items()):
  763. if ns_name.split('.')[0] != 'cv':
  764. continue
  765. for name, enum in sorted(ns.enums.items()):
  766. if not name.endswith('.anonymous'):
  767. name = name.replace("cv.", "")
  768. enum_values = []
  769. for enum_val in enum:
  770. value = enum_val[0][enum_val[0].rfind(".")+1:]
  771. enum_values.append(enum_item_template.substitute(val=value,
  772. cpp_val=name.replace('.', '::')+'::'+value))
  773. self.bindings.append(enum_template.substitute(cpp_name=name.replace(".", "::"),
  774. js_name=name.replace(".", "_"),
  775. enum_items=''.join(enum_values)))
  776. else:
  777. print(name)
  778. #TODO: represent anonymous enums with constants
  779. if export_consts:
  780. # step 5: generate bindings for consts
  781. for ns_name, ns in sorted(self.namespaces.items()):
  782. if ns_name.split('.')[0] != 'cv':
  783. continue
  784. for name, const in sorted(ns.consts.items()):
  785. # print("Gen consts: ", name, const)
  786. self.bindings.append(const_template.substitute(js_name=name, value=const))
  787. with open(core_bindings) as f:
  788. ret = f.read()
  789. header_includes = '\n'.join(['#include "{}"'.format(hdr) for hdr in headers])
  790. ret = ret.replace('@INCLUDES@', header_includes)
  791. defis = '\n'.join(self.wrapper_funcs)
  792. ret += wrapper_codes_template.substitute(ns=wrapper_namespace, defs=defis)
  793. ret += emscripten_binding_template.substitute(binding_name='testBinding', bindings=''.join(self.bindings))
  794. # print(ret)
  795. text_file = open(dst_file, "w")
  796. text_file.write(ret)
  797. text_file.close()
  798. if __name__ == "__main__":
  799. if len(sys.argv) < 5:
  800. print("Usage:\n", \
  801. os.path.basename(sys.argv[0]), \
  802. "<full path to hdr_parser.py> <bindings.cpp> <headers.txt> <core_bindings.cpp> <opencv_js.config.py>")
  803. print("Current args are: ", ", ".join(["'"+a+"'" for a in sys.argv]))
  804. exit(0)
  805. dstdir = "."
  806. hdr_parser_path = os.path.abspath(sys.argv[1])
  807. if hdr_parser_path.endswith(".py"):
  808. hdr_parser_path = os.path.dirname(hdr_parser_path)
  809. sys.path.append(hdr_parser_path)
  810. import hdr_parser
  811. bindingsCpp = sys.argv[2]
  812. headers = open(sys.argv[3], 'r').read().split(';')
  813. coreBindings = sys.argv[4]
  814. whiteListFile = sys.argv[5]
  815. exec(open(whiteListFile).read())
  816. assert(white_list)
  817. generator = JSWrapperGenerator()
  818. generator.gen(bindingsCpp, headers, coreBindings)