qapidoc.py 21 KB

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