gen.py 8.0 KB

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