PageRenderTime 55ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/bindings/python/codegen/h2def.py

https://code.google.com/p/oscats/
Python | 540 lines | 501 code | 19 blank | 20 comment | 25 complexity | bd0b2405ba9b097b5b513ab8f1d78406 MD5 | raw file
Possible License(s): GPL-3.0, GPL-2.0, LGPL-2.1
  1. #!/usr/bin/env python
  2. # -*- Mode: Python; py-indent-offset: 4 -*-
  3. # Search through a header file looking for function prototypes.
  4. # For each prototype, generate a scheme style definition.
  5. # GPL'ed
  6. # Toby D. Reeves <toby@max.rl.plh.af.mil>
  7. #
  8. # Modified by James Henstridge <james@daa.com.au> to output stuff in
  9. # Havoc's new defs format. Info on this format can be seen at:
  10. # http://mail.gnome.org/archives/gtk-devel-list/2000-January/msg00070.html
  11. # Updated to be PEP-8 compatible and refactored to use OOP
  12. import getopt
  13. import os
  14. import re
  15. import string
  16. import sys
  17. import defsparser
  18. # ------------------ Create typecodes from typenames ---------
  19. _upperstr_pat1 = re.compile(r'([^A-Z])([A-Z])')
  20. _upperstr_pat2 = re.compile(r'([A-Z][A-Z])([A-Z][0-9a-z])')
  21. _upperstr_pat3 = re.compile(r'^([A-Z])([A-Z])')
  22. def to_upper_str(name):
  23. """Converts a typename to the equivalent upercase and underscores
  24. name. This is used to form the type conversion macros and enum/flag
  25. name variables"""
  26. name = _upperstr_pat1.sub(r'\1_\2', name)
  27. name = _upperstr_pat2.sub(r'\1_\2', name)
  28. name = _upperstr_pat3.sub(r'\1_\2', name, count=1)
  29. return string.upper(name)
  30. def typecode(typename):
  31. """create a typecode (eg. GTK_TYPE_WIDGET) from a typename"""
  32. return string.replace(to_upper_str(typename), '_', '_TYPE_', 1)
  33. # ------------------ Find object definitions -----------------
  34. def strip_comments(buf):
  35. parts = []
  36. lastpos = 0
  37. while 1:
  38. pos = string.find(buf, '/*', lastpos)
  39. if pos >= 0:
  40. parts.append(buf[lastpos:pos])
  41. pos = string.find(buf, '*/', pos)
  42. if pos >= 0:
  43. lastpos = pos + 2
  44. else:
  45. break
  46. else:
  47. parts.append(buf[lastpos:])
  48. break
  49. return string.join(parts, '')
  50. obj_name_pat = "[A-Z][a-z]*[A-Z][A-Za-z0-9]*"
  51. split_prefix_pat = re.compile('([A-Z][a-z]*)([A-Za-z0-9]+)')
  52. def find_obj_defs(buf, objdefs=[]):
  53. """
  54. Try to find object definitions in header files.
  55. """
  56. # filter out comments from buffer.
  57. buf = strip_comments(buf)
  58. maybeobjdefs = [] # contains all possible objects from file
  59. # first find all structures that look like they may represent a GtkObject
  60. pat = re.compile("struct _(" + obj_name_pat + ")\s*{\s*" +
  61. "(" + obj_name_pat + ")\s+", re.MULTILINE)
  62. pos = 0
  63. while pos < len(buf):
  64. m = pat.search(buf, pos)
  65. if not m: break
  66. maybeobjdefs.append((m.group(1), m.group(2)))
  67. pos = m.end()
  68. # handle typedef struct { ... } style struct defs.
  69. pat = re.compile("typedef struct\s+[_\w]*\s*{\s*" +
  70. "(" + obj_name_pat + ")\s+[^}]*}\s*" +
  71. "(" + obj_name_pat + ")\s*;", re.MULTILINE)
  72. pos = 0
  73. while pos < len(buf):
  74. m = pat.search(buf, pos)
  75. if not m: break
  76. maybeobjdefs.append((m.group(2), m.group(1)))
  77. pos = m.end()
  78. # now find all structures that look like they might represent a class:
  79. pat = re.compile("struct _(" + obj_name_pat + ")Class\s*{\s*" +
  80. "(" + obj_name_pat + ")Class\s+", re.MULTILINE)
  81. pos = 0
  82. while pos < len(buf):
  83. m = pat.search(buf, pos)
  84. if not m: break
  85. t = (m.group(1), m.group(2))
  86. # if we find an object structure together with a corresponding
  87. # class structure, then we have probably found a GtkObject subclass.
  88. if t in maybeobjdefs:
  89. objdefs.append(t)
  90. pos = m.end()
  91. pat = re.compile("typedef struct\s+[_\w]*\s*{\s*" +
  92. "(" + obj_name_pat + ")Class\s+[^}]*}\s*" +
  93. "(" + obj_name_pat + ")Class\s*;", re.MULTILINE)
  94. pos = 0
  95. while pos < len(buf):
  96. m = pat.search(buf, pos)
  97. if not m: break
  98. t = (m.group(2), m.group(1))
  99. # if we find an object structure together with a corresponding
  100. # class structure, then we have probably found a GtkObject subclass.
  101. if t in maybeobjdefs:
  102. objdefs.append(t)
  103. pos = m.end()
  104. # now find all structures that look like they might represent
  105. # a class inherited from GTypeInterface:
  106. pat = re.compile("struct _(" + obj_name_pat + ")Class\s*{\s*" +
  107. "GTypeInterface\s+", re.MULTILINE)
  108. pos = 0
  109. while pos < len(buf):
  110. m = pat.search(buf, pos)
  111. if not m: break
  112. t = (m.group(1), '')
  113. t2 = (m.group(1)+'Class', 'GTypeInterface')
  114. # if we find an object structure together with a corresponding
  115. # class structure, then we have probably found a GtkObject subclass.
  116. if t2 in maybeobjdefs:
  117. objdefs.append(t)
  118. pos = m.end()
  119. # now find all structures that look like they might represent
  120. # an Iface inherited from GTypeInterface:
  121. pat = re.compile("struct _(" + obj_name_pat + ")Iface\s*{\s*" +
  122. "GTypeInterface\s+", re.MULTILINE)
  123. pos = 0
  124. while pos < len(buf):
  125. m = pat.search(buf, pos)
  126. if not m: break
  127. t = (m.group(1), '')
  128. t2 = (m.group(1)+'Iface', 'GTypeInterface')
  129. # if we find an object structure together with a corresponding
  130. # class structure, then we have probably found a GtkObject subclass.
  131. if t2 in maybeobjdefs:
  132. objdefs.append(t)
  133. pos = m.end()
  134. def sort_obj_defs(objdefs):
  135. objdefs.sort() # not strictly needed, but looks nice
  136. pos = 0
  137. while pos < len(objdefs):
  138. klass,parent = objdefs[pos]
  139. for i in range(pos+1, len(objdefs)):
  140. # parent below subclass ... reorder
  141. if objdefs[i][0] == parent:
  142. objdefs.insert(i+1, objdefs[pos])
  143. del objdefs[pos]
  144. break
  145. else:
  146. pos = pos + 1
  147. return objdefs
  148. # ------------------ Find enum definitions -----------------
  149. def find_enum_defs(buf, enums=[]):
  150. # strip comments
  151. # bulk comments
  152. buf = strip_comments(buf)
  153. buf = re.sub('\n', ' ', buf)
  154. enum_pat = re.compile(r'enum\s*{([^}]*)}\s*([A-Z][A-Za-z]*)(\s|;)')
  155. splitter = re.compile(r'\s*,\s', re.MULTILINE)
  156. pos = 0
  157. while pos < len(buf):
  158. m = enum_pat.search(buf, pos)
  159. if not m: break
  160. name = m.group(2)
  161. vals = m.group(1)
  162. isflags = string.find(vals, '<<') >= 0
  163. entries = []
  164. for val in splitter.split(vals):
  165. if not string.strip(val): continue
  166. entries.append(string.split(val)[0])
  167. if name != 'GdkCursorType':
  168. enums.append((name, isflags, entries))
  169. pos = m.end()
  170. # ------------------ Find function definitions -----------------
  171. def clean_func(buf):
  172. """
  173. Ideally would make buf have a single prototype on each line.
  174. Actually just cuts out a good deal of junk, but leaves lines
  175. where a regex can figure prototypes out.
  176. """
  177. # bulk comments
  178. buf = strip_comments(buf)
  179. # compact continued lines
  180. pat = re.compile(r"""\\\n""", re.MULTILINE)
  181. buf = pat.sub('', buf)
  182. # Preprocess directives
  183. pat = re.compile(r"""^[#].*?$""", re.MULTILINE)
  184. buf = pat.sub('', buf)
  185. #typedefs, stucts, and enums
  186. pat = re.compile(r"""^(typedef|struct|enum)(\s|.|\n)*?;\s*""",
  187. re.MULTILINE)
  188. buf = pat.sub('', buf)
  189. #strip DECLS macros
  190. pat = re.compile(r"""G_BEGIN_DECLS|BEGIN_LIBGTOP_DECLS""", re.MULTILINE)
  191. buf = pat.sub('', buf)
  192. #extern "C"
  193. pat = re.compile(r"""^\s*(extern)\s+\"C\"\s+{""", re.MULTILINE)
  194. buf = pat.sub('', buf)
  195. #multiple whitespace
  196. pat = re.compile(r"""\s+""", re.MULTILINE)
  197. buf = pat.sub(' ', buf)
  198. #clean up line ends
  199. pat = re.compile(r""";\s*""", re.MULTILINE)
  200. buf = pat.sub('\n', buf)
  201. buf = buf.lstrip()
  202. #associate *, &, and [] with type instead of variable
  203. #pat = re.compile(r'\s+([*|&]+)\s*(\w+)')
  204. pat = re.compile(r' \s* ([*|&]+) \s* (\w+)', re.VERBOSE)
  205. buf = pat.sub(r'\1 \2', buf)
  206. pat = re.compile(r'\s+ (\w+) \[ \s* \]', re.VERBOSE)
  207. buf = pat.sub(r'[] \1', buf)
  208. # make return types that are const work.
  209. buf = string.replace(buf, 'G_CONST_RETURN ', 'const-')
  210. buf = string.replace(buf, 'const ', 'const-')
  211. #strip GSEAL macros from the middle of function declarations:
  212. pat = re.compile(r"""GSEAL""", re.VERBOSE)
  213. buf = pat.sub('', buf)
  214. return buf
  215. proto_pat=re.compile(r"""
  216. (?P<ret>(-|\w|\&|\*)+\s*) # return type
  217. \s+ # skip whitespace
  218. (?P<func>\w+)\s*[(] # match the function name until the opening (
  219. \s*(?P<args>.*?)\s*[)] # group the function arguments
  220. """, re.IGNORECASE|re.VERBOSE)
  221. #"""
  222. arg_split_pat = re.compile("\s*,\s*")
  223. get_type_pat = re.compile(r'(const-)?([A-Za-z0-9]+)\*?\s+')
  224. pointer_pat = re.compile('.*\*$')
  225. func_new_pat = re.compile('(\w+)_new$')
  226. class DefsWriter:
  227. def __init__(self, fp=None, prefix=None, verbose=False,
  228. defsfilter=None):
  229. if not fp:
  230. fp = sys.stdout
  231. self.fp = fp
  232. self.prefix = prefix
  233. self.verbose = verbose
  234. self._enums = {}
  235. self._objects = {}
  236. self._functions = {}
  237. if defsfilter:
  238. filter = defsparser.DefsParser(defsfilter)
  239. filter.startParsing()
  240. for func in filter.functions + filter.methods.values():
  241. self._functions[func.c_name] = func
  242. for obj in filter.objects + filter.boxes + filter.interfaces:
  243. self._objects[obj.c_name] = obj
  244. for obj in filter.enums:
  245. self._enums[obj.c_name] = obj
  246. def write_def(self, deffile):
  247. buf = open(deffile).read()
  248. self.fp.write('\n;; From %s\n\n' % os.path.basename(deffile))
  249. self._define_func(buf)
  250. self.fp.write('\n')
  251. def write_enum_defs(self, enums, fp=None):
  252. if not fp:
  253. fp = self.fp
  254. fp.write(';; Enumerations and flags ...\n\n')
  255. trans = string.maketrans(string.uppercase + '_',
  256. string.lowercase + '-')
  257. filter = self._enums
  258. for cname, isflags, entries in enums:
  259. if filter:
  260. if cname in filter:
  261. continue
  262. name = cname
  263. module = None
  264. m = split_prefix_pat.match(cname)
  265. if m:
  266. module = m.group(1)
  267. name = m.group(2)
  268. if isflags:
  269. fp.write('(define-flags ' + name + '\n')
  270. else:
  271. fp.write('(define-enum ' + name + '\n')
  272. if module:
  273. fp.write(' (in-module "' + module + '")\n')
  274. fp.write(' (c-name "' + cname + '")\n')
  275. fp.write(' (gtype-id "' + typecode(cname) + '")\n')
  276. prefix = entries[0]
  277. for ent in entries:
  278. # shorten prefix til we get a match ...
  279. # and handle GDK_FONT_FONT, GDK_FONT_FONTSET case
  280. while ent[:len(prefix)] != prefix or len(prefix) >= len(ent):
  281. prefix = prefix[:-1]
  282. prefix_len = len(prefix)
  283. fp.write(' (values\n')
  284. for ent in entries:
  285. fp.write(' \'("%s" "%s")\n' %
  286. (string.translate(ent[prefix_len:], trans), ent))
  287. fp.write(' )\n')
  288. fp.write(')\n\n')
  289. def write_obj_defs(self, objdefs, fp=None):
  290. if not fp:
  291. fp = self.fp
  292. fp.write(';; -*- scheme -*-\n')
  293. fp.write('; object definitions ...\n')
  294. filter = self._objects
  295. for klass, parent in objdefs:
  296. if filter:
  297. if klass in filter:
  298. continue
  299. m = split_prefix_pat.match(klass)
  300. cmodule = None
  301. cname = klass
  302. if m:
  303. cmodule = m.group(1)
  304. cname = m.group(2)
  305. fp.write('(define-object ' + cname + '\n')
  306. if cmodule:
  307. fp.write(' (in-module "' + cmodule + '")\n')
  308. if parent:
  309. fp.write(' (parent "' + parent + '")\n')
  310. fp.write(' (c-name "' + klass + '")\n')
  311. fp.write(' (gtype-id "' + typecode(klass) + '")\n')
  312. # should do something about accessible fields
  313. fp.write(')\n\n')
  314. def _define_func(self, buf):
  315. buf = clean_func(buf)
  316. buf = string.split(buf,'\n')
  317. filter = self._functions
  318. for p in buf:
  319. if not p:
  320. continue
  321. m = proto_pat.match(p)
  322. if m == None:
  323. if self.verbose:
  324. sys.stderr.write('No match:|%s|\n' % p)
  325. continue
  326. func = m.group('func')
  327. if func[0] == '_':
  328. continue
  329. if filter:
  330. if func in filter:
  331. continue
  332. ret = m.group('ret')
  333. args = m.group('args')
  334. args = arg_split_pat.split(args)
  335. for i in range(len(args)):
  336. spaces = string.count(args[i], ' ')
  337. if spaces > 1:
  338. args[i] = string.replace(args[i], ' ', '-', spaces - 1)
  339. self._write_func(func, ret, args)
  340. def _write_func(self, name, ret, args):
  341. if len(args) >= 1:
  342. # methods must have at least one argument
  343. munged_name = name.replace('_', '')
  344. m = get_type_pat.match(args[0])
  345. if m:
  346. obj = m.group(2)
  347. if munged_name[:len(obj)] == obj.lower():
  348. self._write_method(obj, name, ret, args)
  349. return
  350. if self.prefix:
  351. l = len(self.prefix)
  352. if name[:l] == self.prefix and name[l] == '_':
  353. fname = name[l+1:]
  354. else:
  355. fname = name
  356. else:
  357. fname = name
  358. # it is either a constructor or normal function
  359. self.fp.write('(define-function ' + fname + '\n')
  360. self.fp.write(' (c-name "' + name + '")\n')
  361. # Hmmm... Let's asume that a constructor function name
  362. # ends with '_new' and it returns a pointer.
  363. m = func_new_pat.match(name)
  364. if pointer_pat.match(ret) and m:
  365. cname = ''
  366. for s in m.group(1).split ('_'):
  367. cname += s.title()
  368. if cname != '':
  369. self.fp.write(' (is-constructor-of "' + cname + '")\n')
  370. self._write_return(ret)
  371. self._write_arguments(args)
  372. def _write_method(self, obj, name, ret, args):
  373. regex = string.join(map(lambda x: x+'_?', string.lower(obj)),'')
  374. mname = re.sub(regex, '', name, 1)
  375. if self.prefix:
  376. l = len(self.prefix) + 1
  377. if mname[:l] == self.prefix and mname[l+1] == '_':
  378. mname = mname[l+1:]
  379. self.fp.write('(define-method ' + mname + '\n')
  380. self.fp.write(' (of-object "' + obj + '")\n')
  381. self.fp.write(' (c-name "' + name + '")\n')
  382. self._write_return(ret)
  383. self._write_arguments(args[1:])
  384. def _write_return(self, ret):
  385. if ret != 'void':
  386. self.fp.write(' (return-type "' + ret + '")\n')
  387. else:
  388. self.fp.write(' (return-type "none")\n')
  389. def _write_arguments(self, args):
  390. is_varargs = 0
  391. has_args = len(args) > 0
  392. for arg in args:
  393. if arg == '...':
  394. is_varargs = 1
  395. elif arg in ('void', 'void '):
  396. has_args = 0
  397. if has_args:
  398. self.fp.write(' (parameters\n')
  399. for arg in args:
  400. if arg != '...':
  401. tupleArg = tuple(string.split(arg))
  402. if len(tupleArg) == 2:
  403. self.fp.write(' \'("%s" "%s")\n' % tupleArg)
  404. self.fp.write(' )\n')
  405. if is_varargs:
  406. self.fp.write(' (varargs #t)\n')
  407. self.fp.write(')\n\n')
  408. # ------------------ Main function -----------------
  409. def main(args):
  410. verbose = False
  411. onlyenums = False
  412. onlyobjdefs = False
  413. separate = False
  414. modulename = None
  415. defsfilter = None
  416. opts, args = getopt.getopt(args[1:], 'vs:m:f:',
  417. ['onlyenums', 'onlyobjdefs',
  418. 'modulename=', 'separate=',
  419. 'defsfilter='])
  420. for o, v in opts:
  421. if o == '-v':
  422. verbose = True
  423. if o == '--onlyenums':
  424. onlyenums = True
  425. if o == '--onlyobjdefs':
  426. onlyobjdefs = True
  427. if o in ('-s', '--separate'):
  428. separate = v
  429. if o in ('-m', '--modulename'):
  430. modulename = v
  431. if o in ('-f', '--defsfilter'):
  432. defsfilter = v
  433. if not args[0:1]:
  434. print 'Must specify at least one input file name'
  435. return -1
  436. # read all the object definitions in
  437. objdefs = []
  438. enums = []
  439. for filename in args:
  440. buf = open(filename).read()
  441. find_obj_defs(buf, objdefs)
  442. find_enum_defs(buf, enums)
  443. objdefs = sort_obj_defs(objdefs)
  444. if separate:
  445. methods = file(separate + '.defs', 'w')
  446. types = file(separate + '-types.defs', 'w')
  447. dw = DefsWriter(methods, prefix=modulename, verbose=verbose,
  448. defsfilter=defsfilter)
  449. dw.write_obj_defs(objdefs, types)
  450. dw.write_enum_defs(enums, types)
  451. print "Wrote %s-types.defs" % separate
  452. for filename in args:
  453. dw.write_def(filename)
  454. print "Wrote %s.defs" % separate
  455. else:
  456. dw = DefsWriter(prefix=modulename, verbose=verbose,
  457. defsfilter=defsfilter)
  458. if onlyenums:
  459. dw.write_enum_defs(enums)
  460. elif onlyobjdefs:
  461. dw.write_obj_defs(objdefs)
  462. else:
  463. dw.write_obj_defs(objdefs)
  464. dw.write_enum_defs(enums)
  465. for filename in args:
  466. dw.write_def(filename)
  467. if __name__ == '__main__':
  468. sys.exit(main(sys.argv))