doc.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. # QAPI texi generator
  2. #
  3. # This work is licensed under the terms of the GNU LGPL, version 2+.
  4. # See the COPYING file in the top-level directory.
  5. """This script produces the documentation of a qapi schema in texinfo format"""
  6. from __future__ import print_function
  7. import re
  8. from qapi.gen import QAPIGenDoc, QAPISchemaVisitor
  9. MSG_FMT = """
  10. @deftypefn {type} {{}} {name}
  11. {body}{members}{features}{sections}
  12. @end deftypefn
  13. """.format
  14. TYPE_FMT = """
  15. @deftp {{{type}}} {name}
  16. {body}{members}{features}{sections}
  17. @end deftp
  18. """.format
  19. EXAMPLE_FMT = """@example
  20. {code}
  21. @end example
  22. """.format
  23. def subst_strong(doc):
  24. """Replaces *foo* by @strong{foo}"""
  25. return re.sub(r'\*([^*\n]+)\*', r'@strong{\1}', doc)
  26. def subst_emph(doc):
  27. """Replaces _foo_ by @emph{foo}"""
  28. return re.sub(r'\b_([^_\n]+)_\b', r'@emph{\1}', doc)
  29. def subst_vars(doc):
  30. """Replaces @var by @code{var}"""
  31. return re.sub(r'@([\w-]+)', r'@code{\1}', doc)
  32. def subst_braces(doc):
  33. """Replaces {} with @{ @}"""
  34. return doc.replace('{', '@{').replace('}', '@}')
  35. def texi_example(doc):
  36. """Format @example"""
  37. # TODO: Neglects to escape @ characters.
  38. # We should probably escape them in subst_braces(), and rename the
  39. # function to subst_special() or subs_texi_special(). If we do that, we
  40. # need to delay it until after subst_vars() in texi_format().
  41. doc = subst_braces(doc).strip('\n')
  42. return EXAMPLE_FMT(code=doc)
  43. def texi_format(doc):
  44. """
  45. Format documentation
  46. Lines starting with:
  47. - |: generates an @example
  48. - =: generates @section
  49. - ==: generates @subsection
  50. - 1. or 1): generates an @enumerate @item
  51. - */-: generates an @itemize list
  52. """
  53. ret = ''
  54. doc = subst_braces(doc)
  55. doc = subst_vars(doc)
  56. doc = subst_emph(doc)
  57. doc = subst_strong(doc)
  58. inlist = ''
  59. lastempty = False
  60. for line in doc.split('\n'):
  61. empty = line == ''
  62. # FIXME: Doing this in a single if / elif chain is
  63. # problematic. For instance, a line without markup terminates
  64. # a list if it follows a blank line (reaches the final elif),
  65. # but a line with some *other* markup, such as a = title
  66. # doesn't.
  67. #
  68. # Make sure to update section "Documentation markup" in
  69. # docs/devel/qapi-code-gen.txt when fixing this.
  70. if line.startswith('| '):
  71. line = EXAMPLE_FMT(code=line[2:])
  72. elif line.startswith('= '):
  73. line = '@section ' + line[2:]
  74. elif line.startswith('== '):
  75. line = '@subsection ' + line[3:]
  76. elif re.match(r'^([0-9]*\.) ', line):
  77. if not inlist:
  78. ret += '@enumerate\n'
  79. inlist = 'enumerate'
  80. ret += '@item\n'
  81. line = line[line.find(' ')+1:]
  82. elif re.match(r'^[*-] ', line):
  83. if not inlist:
  84. ret += '@itemize %s\n' % {'*': '@bullet',
  85. '-': '@minus'}[line[0]]
  86. inlist = 'itemize'
  87. ret += '@item\n'
  88. line = line[2:]
  89. elif lastempty and inlist:
  90. ret += '@end %s\n\n' % inlist
  91. inlist = ''
  92. lastempty = empty
  93. ret += line + '\n'
  94. if inlist:
  95. ret += '@end %s\n\n' % inlist
  96. return ret
  97. def texi_body(doc):
  98. """Format the main documentation body"""
  99. return texi_format(doc.body.text)
  100. def texi_if(ifcond, prefix='\n', suffix='\n'):
  101. """Format the #if condition"""
  102. if not ifcond:
  103. return ''
  104. return '%s@b{If:} @code{%s}%s' % (prefix, ', '.join(ifcond), suffix)
  105. def texi_enum_value(value, desc, suffix):
  106. """Format a table of members item for an enumeration value"""
  107. return '@item @code{%s}\n%s%s' % (
  108. value.name, desc, texi_if(value.ifcond, prefix='@*'))
  109. def texi_member(member, desc, suffix):
  110. """Format a table of members item for an object type member"""
  111. typ = member.type.doc_type()
  112. membertype = ': ' + typ if typ else ''
  113. return '@item @code{%s%s}%s%s\n%s%s' % (
  114. member.name, membertype,
  115. ' (optional)' if member.optional else '',
  116. suffix, desc, texi_if(member.ifcond, prefix='@*'))
  117. def texi_members(doc, what, base=None, variants=None,
  118. member_func=texi_member):
  119. """Format the table of members"""
  120. items = ''
  121. for section in doc.args.values():
  122. # TODO Drop fallbacks when undocumented members are outlawed
  123. if section.text:
  124. desc = texi_format(section.text)
  125. elif (variants and variants.tag_member == section.member
  126. and not section.member.type.doc_type()):
  127. values = section.member.type.member_names()
  128. members_text = ', '.join(['@t{"%s"}' % v for v in values])
  129. desc = 'One of ' + members_text + '\n'
  130. else:
  131. desc = 'Not documented\n'
  132. items += member_func(section.member, desc, suffix='')
  133. if base:
  134. items += '@item The members of @code{%s}\n' % base.doc_type()
  135. if variants:
  136. for v in variants.variants:
  137. when = ' when @code{%s} is @t{"%s"}%s' % (
  138. variants.tag_member.name, v.name, texi_if(v.ifcond, " (", ")"))
  139. if v.type.is_implicit():
  140. assert not v.type.base and not v.type.variants
  141. for m in v.type.local_members:
  142. items += member_func(m, desc='', suffix=when)
  143. else:
  144. items += '@item The members of @code{%s}%s\n' % (
  145. v.type.doc_type(), when)
  146. if not items:
  147. return ''
  148. return '\n@b{%s:}\n@table @asis\n%s@end table\n' % (what, items)
  149. def texi_arguments(doc, boxed_arg_type):
  150. if boxed_arg_type:
  151. assert not doc.args
  152. return ('\n@b{Arguments:} the members of @code{%s}\n'
  153. % boxed_arg_type.name)
  154. return texi_members(doc, 'Arguments')
  155. def texi_features(doc):
  156. """Format the table of features"""
  157. items = ''
  158. for section in doc.features.values():
  159. desc = texi_format(section.text)
  160. items += '@item @code{%s}\n%s' % (section.name, desc)
  161. if not items:
  162. return ''
  163. return '\n@b{Features:}\n@table @asis\n%s@end table\n' % (items)
  164. def texi_sections(doc, ifcond):
  165. """Format additional sections following arguments"""
  166. body = ''
  167. for section in doc.sections:
  168. if section.name:
  169. # prefer @b over @strong, so txt doesn't translate it to *Foo:*
  170. body += '\n@b{%s:}\n' % section.name
  171. if section.name and section.name.startswith('Example'):
  172. body += texi_example(section.text)
  173. else:
  174. body += texi_format(section.text)
  175. body += texi_if(ifcond, suffix='')
  176. return body
  177. def texi_type(typ, doc, ifcond, members):
  178. return TYPE_FMT(type=typ,
  179. name=doc.symbol,
  180. body=texi_body(doc),
  181. members=members,
  182. features=texi_features(doc),
  183. sections=texi_sections(doc, ifcond))
  184. def texi_msg(typ, doc, ifcond, members):
  185. return MSG_FMT(type=typ,
  186. name=doc.symbol,
  187. body=texi_body(doc),
  188. members=members,
  189. features=texi_features(doc),
  190. sections=texi_sections(doc, ifcond))
  191. class QAPISchemaGenDocVisitor(QAPISchemaVisitor):
  192. def __init__(self, prefix):
  193. self._prefix = prefix
  194. self._gen = QAPIGenDoc(self._prefix + 'qapi-doc.texi')
  195. self.cur_doc = None
  196. def write(self, output_dir):
  197. self._gen.write(output_dir)
  198. def visit_enum_type(self, name, info, ifcond, members, prefix):
  199. doc = self.cur_doc
  200. self._gen.add(texi_type('Enum', doc, ifcond,
  201. texi_members(doc, 'Values',
  202. member_func=texi_enum_value)))
  203. def visit_object_type(self, name, info, ifcond, base, members, variants,
  204. features):
  205. doc = self.cur_doc
  206. if base and base.is_implicit():
  207. base = None
  208. self._gen.add(texi_type('Object', doc, ifcond,
  209. texi_members(doc, 'Members', base, variants)))
  210. def visit_alternate_type(self, name, info, ifcond, variants):
  211. doc = self.cur_doc
  212. self._gen.add(texi_type('Alternate', doc, ifcond,
  213. texi_members(doc, 'Members')))
  214. def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
  215. success_response, boxed, allow_oob, allow_preconfig,
  216. features):
  217. doc = self.cur_doc
  218. self._gen.add(texi_msg('Command', doc, ifcond,
  219. texi_arguments(doc,
  220. arg_type if boxed else None)))
  221. def visit_event(self, name, info, ifcond, arg_type, boxed):
  222. doc = self.cur_doc
  223. self._gen.add(texi_msg('Event', doc, ifcond,
  224. texi_arguments(doc,
  225. arg_type if boxed else None)))
  226. def symbol(self, doc, entity):
  227. if self._gen._body:
  228. self._gen.add('\n')
  229. self.cur_doc = doc
  230. entity.visit(self)
  231. self.cur_doc = None
  232. def freeform(self, doc):
  233. assert not doc.args
  234. if self._gen._body:
  235. self._gen.add('\n')
  236. self._gen.add(texi_body(doc) + texi_sections(doc, None))
  237. def gen_doc(schema, output_dir, prefix):
  238. vis = QAPISchemaGenDocVisitor(prefix)
  239. vis.visit_begin(schema)
  240. for doc in schema.docs:
  241. if doc.symbol:
  242. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  243. else:
  244. vis.freeform(doc)
  245. vis.write(output_dir)