gen.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # -*- coding: utf-8 -*-
  2. #
  3. # QAPI code generation
  4. #
  5. # Copyright (c) 2018-2019 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Markus Armbruster <armbru@redhat.com>
  9. # Marc-André Lureau <marcandre.lureau@redhat.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL, version 2.
  12. # See the COPYING file in the top-level directory.
  13. from contextlib import contextmanager
  14. import errno
  15. import os
  16. import re
  17. from .common import (
  18. c_fname,
  19. gen_endif,
  20. gen_if,
  21. guardend,
  22. guardstart,
  23. mcgen,
  24. )
  25. from .schema import QAPISchemaVisitor
  26. class QAPIGen:
  27. def __init__(self, fname):
  28. self.fname = fname
  29. self._preamble = ''
  30. self._body = ''
  31. def preamble_add(self, text):
  32. self._preamble += text
  33. def add(self, text):
  34. self._body += text
  35. def get_content(self):
  36. return self._top() + self._preamble + self._body + self._bottom()
  37. def _top(self):
  38. return ''
  39. def _bottom(self):
  40. return ''
  41. def write(self, output_dir):
  42. # Include paths starting with ../ are used to reuse modules of the main
  43. # schema in specialised schemas. Don't overwrite the files that are
  44. # already generated for the main schema.
  45. if self.fname.startswith('../'):
  46. return
  47. pathname = os.path.join(output_dir, self.fname)
  48. odir = os.path.dirname(pathname)
  49. if odir:
  50. try:
  51. os.makedirs(odir)
  52. except os.error as e:
  53. if e.errno != errno.EEXIST:
  54. raise
  55. fd = os.open(pathname, os.O_RDWR | os.O_CREAT, 0o666)
  56. f = open(fd, 'r+', encoding='utf-8')
  57. text = self.get_content()
  58. oldtext = f.read(len(text) + 1)
  59. if text != oldtext:
  60. f.seek(0)
  61. f.truncate(0)
  62. f.write(text)
  63. f.close()
  64. def _wrap_ifcond(ifcond, before, after):
  65. if before == after:
  66. return after # suppress empty #if ... #endif
  67. assert after.startswith(before)
  68. out = before
  69. added = after[len(before):]
  70. if added[0] == '\n':
  71. out += '\n'
  72. added = added[1:]
  73. out += gen_if(ifcond)
  74. out += added
  75. out += gen_endif(ifcond)
  76. return out
  77. class QAPIGenCCode(QAPIGen):
  78. def __init__(self, fname):
  79. super().__init__(fname)
  80. self._start_if = None
  81. def start_if(self, ifcond):
  82. assert self._start_if is None
  83. self._start_if = (ifcond, self._body, self._preamble)
  84. def end_if(self):
  85. assert self._start_if
  86. self._wrap_ifcond()
  87. self._start_if = None
  88. def _wrap_ifcond(self):
  89. self._body = _wrap_ifcond(self._start_if[0],
  90. self._start_if[1], self._body)
  91. self._preamble = _wrap_ifcond(self._start_if[0],
  92. self._start_if[2], self._preamble)
  93. def get_content(self):
  94. assert self._start_if is None
  95. return super().get_content()
  96. class QAPIGenC(QAPIGenCCode):
  97. def __init__(self, fname, blurb, pydoc):
  98. super().__init__(fname)
  99. self._blurb = blurb
  100. self._copyright = '\n * '.join(re.findall(r'^Copyright .*', pydoc,
  101. re.MULTILINE))
  102. def _top(self):
  103. return mcgen('''
  104. /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
  105. /*
  106. %(blurb)s
  107. *
  108. * %(copyright)s
  109. *
  110. * This work is licensed under the terms of the GNU LGPL, version 2.1 or later.
  111. * See the COPYING.LIB file in the top-level directory.
  112. */
  113. ''',
  114. blurb=self._blurb, copyright=self._copyright)
  115. def _bottom(self):
  116. return mcgen('''
  117. /* Dummy declaration to prevent empty .o file */
  118. char qapi_dummy_%(name)s;
  119. ''',
  120. name=c_fname(self.fname))
  121. class QAPIGenH(QAPIGenC):
  122. def _top(self):
  123. return super()._top() + guardstart(self.fname)
  124. def _bottom(self):
  125. return guardend(self.fname)
  126. @contextmanager
  127. def ifcontext(ifcond, *args):
  128. """
  129. A with-statement context manager that wraps with `start_if()` / `end_if()`.
  130. :param ifcond: A list of conditionals, passed to `start_if()`.
  131. :param args: any number of `QAPIGenCCode`.
  132. Example::
  133. with ifcontext(ifcond, self._genh, self._genc):
  134. modify self._genh and self._genc ...
  135. Is equivalent to calling::
  136. self._genh.start_if(ifcond)
  137. self._genc.start_if(ifcond)
  138. modify self._genh and self._genc ...
  139. self._genh.end_if()
  140. self._genc.end_if()
  141. """
  142. for arg in args:
  143. arg.start_if(ifcond)
  144. yield
  145. for arg in args:
  146. arg.end_if()
  147. class QAPISchemaMonolithicCVisitor(QAPISchemaVisitor):
  148. def __init__(self, prefix, what, blurb, pydoc):
  149. self._prefix = prefix
  150. self._what = what
  151. self._genc = QAPIGenC(self._prefix + self._what + '.c',
  152. blurb, pydoc)
  153. self._genh = QAPIGenH(self._prefix + self._what + '.h',
  154. blurb, pydoc)
  155. def write(self, output_dir):
  156. self._genc.write(output_dir)
  157. self._genh.write(output_dir)
  158. class QAPISchemaModularCVisitor(QAPISchemaVisitor):
  159. def __init__(self, prefix, what, user_blurb, builtin_blurb, pydoc):
  160. self._prefix = prefix
  161. self._what = what
  162. self._user_blurb = user_blurb
  163. self._builtin_blurb = builtin_blurb
  164. self._pydoc = pydoc
  165. self._genc = None
  166. self._genh = None
  167. self._module = {}
  168. self._main_module = None
  169. @staticmethod
  170. def _is_user_module(name):
  171. return name and not name.startswith('./')
  172. @staticmethod
  173. def _is_builtin_module(name):
  174. return not name
  175. def _module_dirname(self, what, name):
  176. if self._is_user_module(name):
  177. return os.path.dirname(name)
  178. return ''
  179. def _module_basename(self, what, name):
  180. ret = '' if self._is_builtin_module(name) else self._prefix
  181. if self._is_user_module(name):
  182. basename = os.path.basename(name)
  183. ret += what
  184. if name != self._main_module:
  185. ret += '-' + os.path.splitext(basename)[0]
  186. else:
  187. name = name[2:] if name else 'builtin'
  188. ret += re.sub(r'-', '-' + name + '-', what)
  189. return ret
  190. def _module_filename(self, what, name):
  191. return os.path.join(self._module_dirname(what, name),
  192. self._module_basename(what, name))
  193. def _add_module(self, name, blurb):
  194. basename = self._module_filename(self._what, name)
  195. genc = QAPIGenC(basename + '.c', blurb, self._pydoc)
  196. genh = QAPIGenH(basename + '.h', blurb, self._pydoc)
  197. self._module[name] = (genc, genh)
  198. self._genc, self._genh = self._module[name]
  199. def _add_user_module(self, name, blurb):
  200. assert self._is_user_module(name)
  201. if self._main_module is None:
  202. self._main_module = name
  203. self._add_module(name, blurb)
  204. def _add_system_module(self, name, blurb):
  205. self._add_module(name and './' + name, blurb)
  206. def write(self, output_dir, opt_builtins=False):
  207. for name in self._module:
  208. if self._is_builtin_module(name) and not opt_builtins:
  209. continue
  210. (genc, genh) = self._module[name]
  211. genc.write(output_dir)
  212. genh.write(output_dir)
  213. def _begin_system_module(self, name):
  214. pass
  215. def _begin_user_module(self, name):
  216. pass
  217. def visit_module(self, name):
  218. if name is None:
  219. if self._builtin_blurb:
  220. self._add_system_module(None, self._builtin_blurb)
  221. self._begin_system_module(name)
  222. else:
  223. # The built-in module has not been created. No code may
  224. # be generated.
  225. self._genc = None
  226. self._genh = None
  227. else:
  228. self._add_user_module(name, self._user_blurb)
  229. self._begin_user_module(name)
  230. def visit_include(self, name, info):
  231. relname = os.path.relpath(self._module_filename(self._what, name),
  232. os.path.dirname(self._genh.fname))
  233. self._genh.preamble_add(mcgen('''
  234. #include "%(relname)s.h"
  235. ''',
  236. relname=relname))