qapidoc_legacy.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. # coding=utf-8
  2. # type: ignore
  3. #
  4. # QEMU qapidoc QAPI file parsing extension
  5. #
  6. # Copyright (c) 2020 Linaro
  7. #
  8. # This work is licensed under the terms of the GNU GPLv2 or later.
  9. # See the COPYING file in the top-level directory.
  10. """
  11. qapidoc is a Sphinx extension that implements the qapi-doc directive
  12. The purpose of this extension is to read the documentation comments
  13. in QAPI schema files, and insert them all into the current document.
  14. It implements one new rST directive, "qapi-doc::".
  15. Each qapi-doc:: directive takes one argument, which is the
  16. pathname of the schema file to process, relative to the source tree.
  17. The docs/conf.py file must set the qapidoc_srctree config value to
  18. the root of the QEMU source tree.
  19. The Sphinx documentation on writing extensions is at:
  20. https://www.sphinx-doc.org/en/master/development/index.html
  21. """
  22. import re
  23. import textwrap
  24. from docutils import nodes
  25. from docutils.statemachine import ViewList
  26. from qapi.error import QAPISemError
  27. from qapi.gen import QAPISchemaVisitor
  28. from qapi.parser import QAPIDoc
  29. def dedent(text: str) -> str:
  30. # Adjust indentation to make description text parse as paragraph.
  31. lines = text.splitlines(True)
  32. if re.match(r"\s+", lines[0]):
  33. # First line is indented; description started on the line after
  34. # the name. dedent the whole block.
  35. return textwrap.dedent(text)
  36. # Descr started on same line. Dedent line 2+.
  37. return lines[0] + textwrap.dedent("".join(lines[1:]))
  38. class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
  39. """A QAPI schema visitor which generates docutils/Sphinx nodes
  40. This class builds up a tree of docutils/Sphinx nodes corresponding
  41. to documentation for the various QAPI objects. To use it, first
  42. create a QAPISchemaGenRSTVisitor object, and call its
  43. visit_begin() method. Then you can call one of the two methods
  44. 'freeform' (to add documentation for a freeform documentation
  45. chunk) or 'symbol' (to add documentation for a QAPI symbol). These
  46. will cause the visitor to build up the tree of document
  47. nodes. Once you've added all the documentation via 'freeform' and
  48. 'symbol' method calls, you can call 'get_document_nodes' to get
  49. the final list of document nodes (in a form suitable for returning
  50. from a Sphinx directive's 'run' method).
  51. """
  52. def __init__(self, sphinx_directive):
  53. self._cur_doc = None
  54. self._sphinx_directive = sphinx_directive
  55. self._top_node = nodes.section()
  56. self._active_headings = [self._top_node]
  57. def _make_dlitem(self, term, defn):
  58. """Return a dlitem node with the specified term and definition.
  59. term should be a list of Text and literal nodes.
  60. defn should be one of:
  61. - a string, which will be handed to _parse_text_into_node
  62. - a list of Text and literal nodes, which will be put into
  63. a paragraph node
  64. """
  65. dlitem = nodes.definition_list_item()
  66. dlterm = nodes.term('', '', *term)
  67. dlitem += dlterm
  68. if defn:
  69. dldef = nodes.definition()
  70. if isinstance(defn, list):
  71. dldef += nodes.paragraph('', '', *defn)
  72. else:
  73. self._parse_text_into_node(defn, dldef)
  74. dlitem += dldef
  75. return dlitem
  76. def _make_section(self, title):
  77. """Return a section node with optional title"""
  78. section = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  79. if title:
  80. section += nodes.title(title, title)
  81. return section
  82. def _nodes_for_ifcond(self, ifcond, with_if=True):
  83. """Return list of Text, literal nodes for the ifcond
  84. Return a list which gives text like ' (If: condition)'.
  85. If with_if is False, we don't return the "(If: " and ")".
  86. """
  87. doc = ifcond.docgen()
  88. if not doc:
  89. return []
  90. doc = nodes.literal('', doc)
  91. if not with_if:
  92. return [doc]
  93. nodelist = [nodes.Text(' ('), nodes.strong('', 'If: ')]
  94. nodelist.append(doc)
  95. nodelist.append(nodes.Text(')'))
  96. return nodelist
  97. def _nodes_for_one_member(self, member):
  98. """Return list of Text, literal nodes for this member
  99. Return a list of doctree nodes which give text like
  100. 'name: type (optional) (If: ...)' suitable for use as the
  101. 'term' part of a definition list item.
  102. """
  103. term = [nodes.literal('', member.name)]
  104. if member.type.doc_type():
  105. term.append(nodes.Text(': '))
  106. term.append(nodes.literal('', member.type.doc_type()))
  107. if member.optional:
  108. term.append(nodes.Text(' (optional)'))
  109. if member.ifcond.is_present():
  110. term.extend(self._nodes_for_ifcond(member.ifcond))
  111. return term
  112. def _nodes_for_variant_when(self, branches, variant):
  113. """Return list of Text, literal nodes for variant 'when' clause
  114. Return a list of doctree nodes which give text like
  115. 'when tagname is variant (If: ...)' suitable for use in
  116. the 'branches' part of a definition list.
  117. """
  118. term = [nodes.Text(' when '),
  119. nodes.literal('', branches.tag_member.name),
  120. nodes.Text(' is '),
  121. nodes.literal('', '"%s"' % variant.name)]
  122. if variant.ifcond.is_present():
  123. term.extend(self._nodes_for_ifcond(variant.ifcond))
  124. return term
  125. def _nodes_for_members(self, doc, what, base=None, branches=None):
  126. """Return list of doctree nodes for the table of members"""
  127. dlnode = nodes.definition_list()
  128. for section in doc.args.values():
  129. term = self._nodes_for_one_member(section.member)
  130. # TODO drop fallbacks when undocumented members are outlawed
  131. if section.text:
  132. defn = dedent(section.text)
  133. else:
  134. defn = [nodes.Text('Not documented')]
  135. dlnode += self._make_dlitem(term, defn)
  136. if base:
  137. dlnode += self._make_dlitem([nodes.Text('The members of '),
  138. nodes.literal('', base.doc_type())],
  139. None)
  140. if branches:
  141. for v in branches.variants:
  142. if v.type.name == 'q_empty':
  143. continue
  144. assert not v.type.is_implicit()
  145. term = [nodes.Text('The members of '),
  146. nodes.literal('', v.type.doc_type())]
  147. term.extend(self._nodes_for_variant_when(branches, v))
  148. dlnode += self._make_dlitem(term, None)
  149. if not dlnode.children:
  150. return []
  151. section = self._make_section(what)
  152. section += dlnode
  153. return [section]
  154. def _nodes_for_enum_values(self, doc):
  155. """Return list of doctree nodes for the table of enum values"""
  156. seen_item = False
  157. dlnode = nodes.definition_list()
  158. for section in doc.args.values():
  159. termtext = [nodes.literal('', section.member.name)]
  160. if section.member.ifcond.is_present():
  161. termtext.extend(self._nodes_for_ifcond(section.member.ifcond))
  162. # TODO drop fallbacks when undocumented members are outlawed
  163. if section.text:
  164. defn = dedent(section.text)
  165. else:
  166. defn = [nodes.Text('Not documented')]
  167. dlnode += self._make_dlitem(termtext, defn)
  168. seen_item = True
  169. if not seen_item:
  170. return []
  171. section = self._make_section('Values')
  172. section += dlnode
  173. return [section]
  174. def _nodes_for_arguments(self, doc, arg_type):
  175. """Return list of doctree nodes for the arguments section"""
  176. if arg_type and not arg_type.is_implicit():
  177. assert not doc.args
  178. section = self._make_section('Arguments')
  179. dlnode = nodes.definition_list()
  180. dlnode += self._make_dlitem(
  181. [nodes.Text('The members of '),
  182. nodes.literal('', arg_type.name)],
  183. None)
  184. section += dlnode
  185. return [section]
  186. return self._nodes_for_members(doc, 'Arguments')
  187. def _nodes_for_features(self, doc):
  188. """Return list of doctree nodes for the table of features"""
  189. seen_item = False
  190. dlnode = nodes.definition_list()
  191. for section in doc.features.values():
  192. dlnode += self._make_dlitem(
  193. [nodes.literal('', section.member.name)], dedent(section.text))
  194. seen_item = True
  195. if not seen_item:
  196. return []
  197. section = self._make_section('Features')
  198. section += dlnode
  199. return [section]
  200. def _nodes_for_sections(self, doc):
  201. """Return list of doctree nodes for additional sections"""
  202. nodelist = []
  203. for section in doc.sections:
  204. if section.kind == QAPIDoc.Kind.TODO:
  205. # Hide TODO: sections
  206. continue
  207. if section.kind == QAPIDoc.Kind.PLAIN:
  208. # Sphinx cannot handle sectionless titles;
  209. # Instead, just append the results to the prior section.
  210. container = nodes.container()
  211. self._parse_text_into_node(section.text, container)
  212. nodelist += container.children
  213. continue
  214. snode = self._make_section(section.kind.name.title())
  215. self._parse_text_into_node(dedent(section.text), snode)
  216. nodelist.append(snode)
  217. return nodelist
  218. def _nodes_for_if_section(self, ifcond):
  219. """Return list of doctree nodes for the "If" section"""
  220. nodelist = []
  221. if ifcond.is_present():
  222. snode = self._make_section('If')
  223. snode += nodes.paragraph(
  224. '', '', *self._nodes_for_ifcond(ifcond, with_if=False)
  225. )
  226. nodelist.append(snode)
  227. return nodelist
  228. def _add_doc(self, typ, sections):
  229. """Add documentation for a command/object/enum...
  230. We assume we're documenting the thing defined in self._cur_doc.
  231. typ is the type of thing being added ("Command", "Object", etc)
  232. sections is a list of nodes for sections to add to the definition.
  233. """
  234. doc = self._cur_doc
  235. snode = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  236. snode += nodes.title('', '', *[nodes.literal(doc.symbol, doc.symbol),
  237. nodes.Text(' (' + typ + ')')])
  238. self._parse_text_into_node(doc.body.text, snode)
  239. for s in sections:
  240. if s is not None:
  241. snode += s
  242. self._add_node_to_current_heading(snode)
  243. def visit_enum_type(self, name, info, ifcond, features, members, prefix):
  244. doc = self._cur_doc
  245. self._add_doc('Enum',
  246. self._nodes_for_enum_values(doc)
  247. + self._nodes_for_features(doc)
  248. + self._nodes_for_sections(doc)
  249. + self._nodes_for_if_section(ifcond))
  250. def visit_object_type(self, name, info, ifcond, features,
  251. base, members, branches):
  252. doc = self._cur_doc
  253. if base and base.is_implicit():
  254. base = None
  255. self._add_doc('Object',
  256. self._nodes_for_members(doc, 'Members', base, branches)
  257. + self._nodes_for_features(doc)
  258. + self._nodes_for_sections(doc)
  259. + self._nodes_for_if_section(ifcond))
  260. def visit_alternate_type(self, name, info, ifcond, features,
  261. alternatives):
  262. doc = self._cur_doc
  263. self._add_doc('Alternate',
  264. self._nodes_for_members(doc, 'Members')
  265. + self._nodes_for_features(doc)
  266. + self._nodes_for_sections(doc)
  267. + self._nodes_for_if_section(ifcond))
  268. def visit_command(self, name, info, ifcond, features, arg_type,
  269. ret_type, gen, success_response, boxed, allow_oob,
  270. allow_preconfig, coroutine):
  271. doc = self._cur_doc
  272. self._add_doc('Command',
  273. self._nodes_for_arguments(doc, arg_type)
  274. + self._nodes_for_features(doc)
  275. + self._nodes_for_sections(doc)
  276. + self._nodes_for_if_section(ifcond))
  277. def visit_event(self, name, info, ifcond, features, arg_type, boxed):
  278. doc = self._cur_doc
  279. self._add_doc('Event',
  280. self._nodes_for_arguments(doc, arg_type)
  281. + self._nodes_for_features(doc)
  282. + self._nodes_for_sections(doc)
  283. + self._nodes_for_if_section(ifcond))
  284. def symbol(self, doc, entity):
  285. """Add documentation for one symbol to the document tree
  286. This is the main entry point which causes us to add documentation
  287. nodes for a symbol (which could be a 'command', 'object', 'event',
  288. etc). We do this by calling 'visit' on the schema entity, which
  289. will then call back into one of our visit_* methods, depending
  290. on what kind of thing this symbol is.
  291. """
  292. self._cur_doc = doc
  293. entity.visit(self)
  294. self._cur_doc = None
  295. def _start_new_heading(self, heading, level):
  296. """Start a new heading at the specified heading level
  297. Create a new section whose title is 'heading' and which is placed
  298. in the docutils node tree as a child of the most recent level-1
  299. heading. Subsequent document sections (commands, freeform doc chunks,
  300. etc) will be placed as children of this new heading section.
  301. """
  302. if len(self._active_headings) < level:
  303. raise QAPISemError(self._cur_doc.info,
  304. 'Level %d subheading found outside a '
  305. 'level %d heading'
  306. % (level, level - 1))
  307. snode = self._make_section(heading)
  308. self._active_headings[level - 1] += snode
  309. self._active_headings = self._active_headings[:level]
  310. self._active_headings.append(snode)
  311. return snode
  312. def _add_node_to_current_heading(self, node):
  313. """Add the node to whatever the current active heading is"""
  314. self._active_headings[-1] += node
  315. def freeform(self, doc):
  316. """Add a piece of 'freeform' documentation to the document tree
  317. A 'freeform' document chunk doesn't relate to any particular
  318. symbol (for instance, it could be an introduction).
  319. If the freeform document starts with a line of the form
  320. '= Heading text', this is a section or subsection heading, with
  321. the heading level indicated by the number of '=' signs.
  322. """
  323. # QAPIDoc documentation says free-form documentation blocks
  324. # must have only a body section, nothing else.
  325. assert not doc.sections
  326. assert not doc.args
  327. assert not doc.features
  328. self._cur_doc = doc
  329. text = doc.body.text
  330. if re.match(r'=+ ', text):
  331. # Section/subsection heading (if present, will always be
  332. # the first line of the block)
  333. (heading, _, text) = text.partition('\n')
  334. (leader, _, heading) = heading.partition(' ')
  335. node = self._start_new_heading(heading, len(leader))
  336. if text == '':
  337. return
  338. else:
  339. node = nodes.container()
  340. self._parse_text_into_node(text, node)
  341. self._cur_doc = None
  342. def _parse_text_into_node(self, doctext, node):
  343. """Parse a chunk of QAPI-doc-format text into the node
  344. The doc comment can contain most inline rST markup, including
  345. bulleted and enumerated lists.
  346. As an extra permitted piece of markup, @var will be turned
  347. into ``var``.
  348. """
  349. # Handle the "@var means ``var`` case
  350. doctext = re.sub(r'@([\w-]+)', r'``\1``', doctext)
  351. rstlist = ViewList()
  352. for line in doctext.splitlines():
  353. # The reported line number will always be that of the start line
  354. # of the doc comment, rather than the actual location of the error.
  355. # Being more precise would require overhaul of the QAPIDoc class
  356. # to track lines more exactly within all the sub-parts of the doc
  357. # comment, as well as counting lines here.
  358. rstlist.append(line, self._cur_doc.info.fname,
  359. self._cur_doc.info.line)
  360. # Append a blank line -- in some cases rST syntax errors get
  361. # attributed to the line after one with actual text, and if there
  362. # isn't anything in the ViewList corresponding to that then Sphinx
  363. # 1.6's AutodocReporter will then misidentify the source/line location
  364. # in the error message (usually attributing it to the top-level
  365. # .rst file rather than the offending .json file). The extra blank
  366. # line won't affect the rendered output.
  367. rstlist.append("", self._cur_doc.info.fname, self._cur_doc.info.line)
  368. self._sphinx_directive.do_parse(rstlist, node)
  369. def get_document_node(self):
  370. """Return the root docutils node which makes up the document"""
  371. return self._top_node