qapidoc.py 21 KB

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