doc.py 9.5 KB

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