2
0

qapidoc.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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 sys
  24. import textwrap
  25. from typing import List
  26. from docutils import nodes
  27. from docutils.parsers.rst import Directive, directives
  28. from docutils.statemachine import ViewList
  29. from qapi.error import QAPIError, QAPISemError
  30. from qapi.gen import QAPISchemaVisitor
  31. from qapi.parser import QAPIDoc
  32. from qapi.schema import QAPISchema
  33. from sphinx import addnodes
  34. from sphinx.directives.code import CodeBlock
  35. from sphinx.errors import ExtensionError
  36. from sphinx.util.docutils import switch_source_input
  37. from sphinx.util.nodes import nested_parse_with_titles
  38. __version__ = "1.0"
  39. def dedent(text: str) -> str:
  40. # Adjust indentation to make description text parse as paragraph.
  41. lines = text.splitlines(True)
  42. if re.match(r"\s+", lines[0]):
  43. # First line is indented; description started on the line after
  44. # the name. dedent the whole block.
  45. return textwrap.dedent(text)
  46. # Descr started on same line. Dedent line 2+.
  47. return lines[0] + textwrap.dedent("".join(lines[1:]))
  48. # Disable black auto-formatter until re-enabled:
  49. # fmt: off
  50. class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
  51. """A QAPI schema visitor which generates docutils/Sphinx nodes
  52. This class builds up a tree of docutils/Sphinx nodes corresponding
  53. to documentation for the various QAPI objects. To use it, first
  54. create a QAPISchemaGenRSTVisitor object, and call its
  55. visit_begin() method. Then you can call one of the two methods
  56. 'freeform' (to add documentation for a freeform documentation
  57. chunk) or 'symbol' (to add documentation for a QAPI symbol). These
  58. will cause the visitor to build up the tree of document
  59. nodes. Once you've added all the documentation via 'freeform' and
  60. 'symbol' method calls, you can call 'get_document_nodes' to get
  61. the final list of document nodes (in a form suitable for returning
  62. from a Sphinx directive's 'run' method).
  63. """
  64. def __init__(self, sphinx_directive):
  65. self._cur_doc = None
  66. self._sphinx_directive = sphinx_directive
  67. self._top_node = nodes.section()
  68. self._active_headings = [self._top_node]
  69. def _make_dlitem(self, term, defn):
  70. """Return a dlitem node with the specified term and definition.
  71. term should be a list of Text and literal nodes.
  72. defn should be one of:
  73. - a string, which will be handed to _parse_text_into_node
  74. - a list of Text and literal nodes, which will be put into
  75. a paragraph node
  76. """
  77. dlitem = nodes.definition_list_item()
  78. dlterm = nodes.term('', '', *term)
  79. dlitem += dlterm
  80. if defn:
  81. dldef = nodes.definition()
  82. if isinstance(defn, list):
  83. dldef += nodes.paragraph('', '', *defn)
  84. else:
  85. self._parse_text_into_node(defn, dldef)
  86. dlitem += dldef
  87. return dlitem
  88. def _make_section(self, title):
  89. """Return a section node with optional title"""
  90. section = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  91. if title:
  92. section += nodes.title(title, title)
  93. return section
  94. def _nodes_for_ifcond(self, ifcond, with_if=True):
  95. """Return list of Text, literal nodes for the ifcond
  96. Return a list which gives text like ' (If: condition)'.
  97. If with_if is False, we don't return the "(If: " and ")".
  98. """
  99. doc = ifcond.docgen()
  100. if not doc:
  101. return []
  102. doc = nodes.literal('', doc)
  103. if not with_if:
  104. return [doc]
  105. nodelist = [nodes.Text(' ('), nodes.strong('', 'If: ')]
  106. nodelist.append(doc)
  107. nodelist.append(nodes.Text(')'))
  108. return nodelist
  109. def _nodes_for_one_member(self, member):
  110. """Return list of Text, literal nodes for this member
  111. Return a list of doctree nodes which give text like
  112. 'name: type (optional) (If: ...)' suitable for use as the
  113. 'term' part of a definition list item.
  114. """
  115. term = [nodes.literal('', member.name)]
  116. if member.type.doc_type():
  117. term.append(nodes.Text(': '))
  118. term.append(nodes.literal('', member.type.doc_type()))
  119. if member.optional:
  120. term.append(nodes.Text(' (optional)'))
  121. if member.ifcond.is_present():
  122. term.extend(self._nodes_for_ifcond(member.ifcond))
  123. return term
  124. def _nodes_for_variant_when(self, branches, variant):
  125. """Return list of Text, literal nodes for variant 'when' clause
  126. Return a list of doctree nodes which give text like
  127. 'when tagname is variant (If: ...)' suitable for use in
  128. the 'branches' part of a definition list.
  129. """
  130. term = [nodes.Text(' when '),
  131. nodes.literal('', branches.tag_member.name),
  132. nodes.Text(' is '),
  133. nodes.literal('', '"%s"' % variant.name)]
  134. if variant.ifcond.is_present():
  135. term.extend(self._nodes_for_ifcond(variant.ifcond))
  136. return term
  137. def _nodes_for_members(self, doc, what, base=None, branches=None):
  138. """Return list of doctree nodes for the table of members"""
  139. dlnode = nodes.definition_list()
  140. for section in doc.args.values():
  141. term = self._nodes_for_one_member(section.member)
  142. # TODO drop fallbacks when undocumented members are outlawed
  143. if section.text:
  144. defn = dedent(section.text)
  145. else:
  146. defn = [nodes.Text('Not documented')]
  147. dlnode += self._make_dlitem(term, defn)
  148. if base:
  149. dlnode += self._make_dlitem([nodes.Text('The members of '),
  150. nodes.literal('', base.doc_type())],
  151. None)
  152. if branches:
  153. for v in branches.variants:
  154. if v.type.name == 'q_empty':
  155. continue
  156. assert not v.type.is_implicit()
  157. term = [nodes.Text('The members of '),
  158. nodes.literal('', v.type.doc_type())]
  159. term.extend(self._nodes_for_variant_when(branches, v))
  160. dlnode += self._make_dlitem(term, None)
  161. if not dlnode.children:
  162. return []
  163. section = self._make_section(what)
  164. section += dlnode
  165. return [section]
  166. def _nodes_for_enum_values(self, doc):
  167. """Return list of doctree nodes for the table of enum values"""
  168. seen_item = False
  169. dlnode = nodes.definition_list()
  170. for section in doc.args.values():
  171. termtext = [nodes.literal('', section.member.name)]
  172. if section.member.ifcond.is_present():
  173. termtext.extend(self._nodes_for_ifcond(section.member.ifcond))
  174. # TODO drop fallbacks when undocumented members are outlawed
  175. if section.text:
  176. defn = dedent(section.text)
  177. else:
  178. defn = [nodes.Text('Not documented')]
  179. dlnode += self._make_dlitem(termtext, defn)
  180. seen_item = True
  181. if not seen_item:
  182. return []
  183. section = self._make_section('Values')
  184. section += dlnode
  185. return [section]
  186. def _nodes_for_arguments(self, doc, arg_type):
  187. """Return list of doctree nodes for the arguments section"""
  188. if arg_type and not arg_type.is_implicit():
  189. assert not doc.args
  190. section = self._make_section('Arguments')
  191. dlnode = nodes.definition_list()
  192. dlnode += self._make_dlitem(
  193. [nodes.Text('The members of '),
  194. nodes.literal('', arg_type.name)],
  195. None)
  196. section += dlnode
  197. return [section]
  198. return self._nodes_for_members(doc, 'Arguments')
  199. def _nodes_for_features(self, doc):
  200. """Return list of doctree nodes for the table of features"""
  201. seen_item = False
  202. dlnode = nodes.definition_list()
  203. for section in doc.features.values():
  204. dlnode += self._make_dlitem(
  205. [nodes.literal('', section.member.name)], dedent(section.text))
  206. seen_item = True
  207. if not seen_item:
  208. return []
  209. section = self._make_section('Features')
  210. section += dlnode
  211. return [section]
  212. def _nodes_for_sections(self, doc):
  213. """Return list of doctree nodes for additional sections"""
  214. nodelist = []
  215. for section in doc.sections:
  216. if section.kind == QAPIDoc.Kind.TODO:
  217. # Hide TODO: sections
  218. continue
  219. if section.kind == QAPIDoc.Kind.PLAIN:
  220. # Sphinx cannot handle sectionless titles;
  221. # Instead, just append the results to the prior section.
  222. container = nodes.container()
  223. self._parse_text_into_node(section.text, container)
  224. nodelist += container.children
  225. continue
  226. snode = self._make_section(section.kind.name.title())
  227. self._parse_text_into_node(dedent(section.text), snode)
  228. nodelist.append(snode)
  229. return nodelist
  230. def _nodes_for_if_section(self, ifcond):
  231. """Return list of doctree nodes for the "If" section"""
  232. nodelist = []
  233. if ifcond.is_present():
  234. snode = self._make_section('If')
  235. snode += nodes.paragraph(
  236. '', '', *self._nodes_for_ifcond(ifcond, with_if=False)
  237. )
  238. nodelist.append(snode)
  239. return nodelist
  240. def _add_doc(self, typ, sections):
  241. """Add documentation for a command/object/enum...
  242. We assume we're documenting the thing defined in self._cur_doc.
  243. typ is the type of thing being added ("Command", "Object", etc)
  244. sections is a list of nodes for sections to add to the definition.
  245. """
  246. doc = self._cur_doc
  247. snode = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  248. snode += nodes.title('', '', *[nodes.literal(doc.symbol, doc.symbol),
  249. nodes.Text(' (' + typ + ')')])
  250. self._parse_text_into_node(doc.body.text, snode)
  251. for s in sections:
  252. if s is not None:
  253. snode += s
  254. self._add_node_to_current_heading(snode)
  255. def visit_enum_type(self, name, info, ifcond, features, members, prefix):
  256. doc = self._cur_doc
  257. self._add_doc('Enum',
  258. self._nodes_for_enum_values(doc)
  259. + self._nodes_for_features(doc)
  260. + self._nodes_for_sections(doc)
  261. + self._nodes_for_if_section(ifcond))
  262. def visit_object_type(self, name, info, ifcond, features,
  263. base, members, branches):
  264. doc = self._cur_doc
  265. if base and base.is_implicit():
  266. base = None
  267. self._add_doc('Object',
  268. self._nodes_for_members(doc, 'Members', base, branches)
  269. + self._nodes_for_features(doc)
  270. + self._nodes_for_sections(doc)
  271. + self._nodes_for_if_section(ifcond))
  272. def visit_alternate_type(self, name, info, ifcond, features,
  273. alternatives):
  274. doc = self._cur_doc
  275. self._add_doc('Alternate',
  276. self._nodes_for_members(doc, 'Members')
  277. + self._nodes_for_features(doc)
  278. + self._nodes_for_sections(doc)
  279. + self._nodes_for_if_section(ifcond))
  280. def visit_command(self, name, info, ifcond, features, arg_type,
  281. ret_type, gen, success_response, boxed, allow_oob,
  282. allow_preconfig, coroutine):
  283. doc = self._cur_doc
  284. self._add_doc('Command',
  285. self._nodes_for_arguments(doc, arg_type)
  286. + self._nodes_for_features(doc)
  287. + self._nodes_for_sections(doc)
  288. + self._nodes_for_if_section(ifcond))
  289. def visit_event(self, name, info, ifcond, features, arg_type, boxed):
  290. doc = self._cur_doc
  291. self._add_doc('Event',
  292. self._nodes_for_arguments(doc, arg_type)
  293. + self._nodes_for_features(doc)
  294. + self._nodes_for_sections(doc)
  295. + self._nodes_for_if_section(ifcond))
  296. def symbol(self, doc, entity):
  297. """Add documentation for one symbol to the document tree
  298. This is the main entry point which causes us to add documentation
  299. nodes for a symbol (which could be a 'command', 'object', 'event',
  300. etc). We do this by calling 'visit' on the schema entity, which
  301. will then call back into one of our visit_* methods, depending
  302. on what kind of thing this symbol is.
  303. """
  304. self._cur_doc = doc
  305. entity.visit(self)
  306. self._cur_doc = None
  307. def _start_new_heading(self, heading, level):
  308. """Start a new heading at the specified heading level
  309. Create a new section whose title is 'heading' and which is placed
  310. in the docutils node tree as a child of the most recent level-1
  311. heading. Subsequent document sections (commands, freeform doc chunks,
  312. etc) will be placed as children of this new heading section.
  313. """
  314. if len(self._active_headings) < level:
  315. raise QAPISemError(self._cur_doc.info,
  316. 'Level %d subheading found outside a '
  317. 'level %d heading'
  318. % (level, level - 1))
  319. snode = self._make_section(heading)
  320. self._active_headings[level - 1] += snode
  321. self._active_headings = self._active_headings[:level]
  322. self._active_headings.append(snode)
  323. return 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. node = self._start_new_heading(heading, len(leader))
  348. if text == '':
  349. return
  350. else:
  351. node = nodes.container()
  352. self._parse_text_into_node(text, 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 NestedDirective(Directive):
  401. def run(self):
  402. raise NotImplementedError
  403. def do_parse(self, rstlist, node):
  404. """
  405. Parse rST source lines and add them to the specified node
  406. Take the list of rST source lines rstlist, parse them as
  407. rST, and add the resulting docutils nodes as children of node.
  408. The nodes are parsed in a way that allows them to include
  409. subheadings (titles) without confusing the rendering of
  410. anything else.
  411. """
  412. with switch_source_input(self.state, rstlist):
  413. nested_parse_with_titles(self.state, rstlist, node)
  414. class QAPIDocDirective(NestedDirective):
  415. """Extract documentation from the specified QAPI .json file"""
  416. required_argument = 1
  417. optional_arguments = 1
  418. option_spec = {"qapifile": directives.unchanged_required}
  419. has_content = False
  420. def new_serialno(self):
  421. """Return a unique new ID string suitable for use as a node's ID"""
  422. env = self.state.document.settings.env
  423. return "qapidoc-%d" % env.new_serialno("qapidoc")
  424. def run(self):
  425. env = self.state.document.settings.env
  426. qapifile = env.config.qapidoc_srctree + "/" + self.arguments[0]
  427. qapidir = os.path.dirname(qapifile)
  428. try:
  429. schema = QAPISchema(qapifile)
  430. # First tell Sphinx about all the schema files that the
  431. # output documentation depends on (including 'qapifile' itself)
  432. schema.visit(QAPISchemaGenDepVisitor(env, qapidir))
  433. vis = QAPISchemaGenRSTVisitor(self)
  434. vis.visit_begin(schema)
  435. for doc in schema.docs:
  436. if doc.symbol:
  437. vis.symbol(doc, schema.lookup_entity(doc.symbol))
  438. else:
  439. vis.freeform(doc)
  440. return vis.get_document_nodes()
  441. except QAPIError as err:
  442. # Launder QAPI parse errors into Sphinx extension errors
  443. # so they are displayed nicely to the user
  444. raise ExtensionError(str(err)) from err
  445. class QMPExample(CodeBlock, NestedDirective):
  446. """
  447. Custom admonition for QMP code examples.
  448. When the :annotated: option is present, the body of this directive
  449. is parsed as normal rST, but with any '::' code blocks set to use
  450. the QMP lexer. Code blocks must be explicitly written by the user,
  451. but this allows for intermingling explanatory paragraphs with
  452. arbitrary rST syntax and code blocks for more involved examples.
  453. When :annotated: is absent, the directive body is treated as a
  454. simple standalone QMP code block literal.
  455. """
  456. required_argument = 0
  457. optional_arguments = 0
  458. has_content = True
  459. option_spec = {
  460. "annotated": directives.flag,
  461. "title": directives.unchanged,
  462. }
  463. def _highlightlang(self) -> addnodes.highlightlang:
  464. """Return the current highlightlang setting for the document"""
  465. node = None
  466. doc = self.state.document
  467. if hasattr(doc, "findall"):
  468. # docutils >= 0.18.1
  469. for node in doc.findall(addnodes.highlightlang):
  470. pass
  471. else:
  472. for elem in doc.traverse():
  473. if isinstance(elem, addnodes.highlightlang):
  474. node = elem
  475. if node:
  476. return node
  477. # No explicit directive found, use defaults
  478. node = addnodes.highlightlang(
  479. lang=self.env.config.highlight_language,
  480. force=False,
  481. # Yes, Sphinx uses this value to effectively disable line
  482. # numbers and not 0 or None or -1 or something. ¯\_(ツ)_/¯
  483. linenothreshold=sys.maxsize,
  484. )
  485. return node
  486. def admonition_wrap(self, *content) -> List[nodes.Node]:
  487. title = "Example:"
  488. if "title" in self.options:
  489. title = f"{title} {self.options['title']}"
  490. admon = nodes.admonition(
  491. "",
  492. nodes.title("", title),
  493. *content,
  494. classes=["admonition", "admonition-example"],
  495. )
  496. return [admon]
  497. def run_annotated(self) -> List[nodes.Node]:
  498. lang_node = self._highlightlang()
  499. content_node: nodes.Element = nodes.section()
  500. # Configure QMP highlighting for "::" blocks, if needed
  501. if lang_node["lang"] != "QMP":
  502. content_node += addnodes.highlightlang(
  503. lang="QMP",
  504. force=False, # "True" ignores lexing errors
  505. linenothreshold=lang_node["linenothreshold"],
  506. )
  507. self.do_parse(self.content, content_node)
  508. # Restore prior language highlighting, if needed
  509. if lang_node["lang"] != "QMP":
  510. content_node += addnodes.highlightlang(**lang_node.attributes)
  511. return content_node.children
  512. def run(self) -> List[nodes.Node]:
  513. annotated = "annotated" in self.options
  514. if annotated:
  515. content_nodes = self.run_annotated()
  516. else:
  517. self.arguments = ["QMP"]
  518. content_nodes = super().run()
  519. return self.admonition_wrap(*content_nodes)
  520. def setup(app):
  521. """Register qapi-doc directive with Sphinx"""
  522. app.add_config_value("qapidoc_srctree", None, "env")
  523. app.add_directive("qapi-doc", QAPIDocDirective)
  524. app.add_directive("qmp-example", QMPExample)
  525. return {
  526. "version": __version__,
  527. "parallel_read_safe": True,
  528. "parallel_write_safe": True,
  529. }