qapidoc.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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. from docutils import nodes
  24. from docutils.statemachine import ViewList
  25. from docutils.parsers.rst import directives, Directive
  26. from sphinx.errors import ExtensionError
  27. from sphinx.util.nodes import nested_parse_with_titles
  28. import sphinx
  29. from qapi.gen import QAPISchemaVisitor
  30. from qapi.schema import QAPIError, QAPISemError, QAPISchema
  31. # Sphinx up to 1.6 uses AutodocReporter; 1.7 and later
  32. # use switch_source_input. Check borrowed from kerneldoc.py.
  33. Use_SSI = sphinx.__version__[:3] >= '1.7'
  34. if Use_SSI:
  35. from sphinx.util.docutils import switch_source_input
  36. else:
  37. from sphinx.ext.autodoc import AutodocReporter
  38. __version__ = '1.0'
  39. # Function borrowed from pydash, which is under the MIT license
  40. def intersperse(iterable, separator):
  41. """Yield the members of *iterable* interspersed with *separator*."""
  42. iterable = iter(iterable)
  43. yield next(iterable)
  44. for item in iterable:
  45. yield separator
  46. yield item
  47. class QAPISchemaGenRSTVisitor(QAPISchemaVisitor):
  48. """A QAPI schema visitor which generates docutils/Sphinx nodes
  49. This class builds up a tree of docutils/Sphinx nodes corresponding
  50. to documentation for the various QAPI objects. To use it, first
  51. create a QAPISchemaGenRSTVisitor object, and call its
  52. visit_begin() method. Then you can call one of the two methods
  53. 'freeform' (to add documentation for a freeform documentation
  54. chunk) or 'symbol' (to add documentation for a QAPI symbol). These
  55. will cause the visitor to build up the tree of document
  56. nodes. Once you've added all the documentation via 'freeform' and
  57. 'symbol' method calls, you can call 'get_document_nodes' to get
  58. the final list of document nodes (in a form suitable for returning
  59. from a Sphinx directive's 'run' method).
  60. """
  61. def __init__(self, sphinx_directive):
  62. self._cur_doc = None
  63. self._sphinx_directive = sphinx_directive
  64. self._top_node = nodes.section()
  65. self._active_headings = [self._top_node]
  66. def _make_dlitem(self, term, defn):
  67. """Return a dlitem node with the specified term and definition.
  68. term should be a list of Text and literal nodes.
  69. defn should be one of:
  70. - a string, which will be handed to _parse_text_into_node
  71. - a list of Text and literal nodes, which will be put into
  72. a paragraph node
  73. """
  74. dlitem = nodes.definition_list_item()
  75. dlterm = nodes.term('', '', *term)
  76. dlitem += dlterm
  77. if defn:
  78. dldef = nodes.definition()
  79. if isinstance(defn, list):
  80. dldef += nodes.paragraph('', '', *defn)
  81. else:
  82. self._parse_text_into_node(defn, dldef)
  83. dlitem += dldef
  84. return dlitem
  85. def _make_section(self, title):
  86. """Return a section node with optional title"""
  87. section = nodes.section(ids=[self._sphinx_directive.new_serialno()])
  88. if title:
  89. section += nodes.title(title, title)
  90. return section
  91. def _nodes_for_ifcond(self, ifcond, with_if=True):
  92. """Return list of Text, literal nodes for the ifcond
  93. Return a list which gives text like ' (If: cond1, cond2, cond3)', where
  94. the conditions are in literal-text and the commas are not.
  95. If with_if is False, we don't return the "(If: " and ")".
  96. """
  97. condlist = intersperse([nodes.literal('', c) for c in ifcond],
  98. nodes.Text(', '))
  99. if not with_if:
  100. return condlist
  101. nodelist = [nodes.Text(' ('), nodes.strong('', 'If: ')]
  102. nodelist.extend(condlist)
  103. nodelist.append(nodes.Text(')'))
  104. return nodelist
  105. def _nodes_for_one_member(self, member):
  106. """Return list of Text, literal nodes for this member
  107. Return a list of doctree nodes which give text like
  108. 'name: type (optional) (If: ...)' suitable for use as the
  109. 'term' part of a definition list item.
  110. """
  111. term = [nodes.literal('', member.name)]
  112. if member.type.doc_type():
  113. term.append(nodes.Text(': '))
  114. term.append(nodes.literal('', member.type.doc_type()))
  115. if member.optional:
  116. term.append(nodes.Text(' (optional)'))
  117. if member.ifcond:
  118. term.extend(self._nodes_for_ifcond(member.ifcond))
  119. return term
  120. def _nodes_for_variant_when(self, variants, variant):
  121. """Return list of Text, literal nodes for variant 'when' clause
  122. Return a list of doctree nodes which give text like
  123. 'when tagname is variant (If: ...)' suitable for use in
  124. the 'variants' part of a definition list.
  125. """
  126. term = [nodes.Text(' when '),
  127. nodes.literal('', variants.tag_member.name),
  128. nodes.Text(' is '),
  129. nodes.literal('', '"%s"' % variant.name)]
  130. if variant.ifcond:
  131. term.extend(self._nodes_for_ifcond(variant.ifcond))
  132. return term
  133. def _nodes_for_members(self, doc, what, base=None, variants=None):
  134. """Return list of doctree nodes for the table of members"""
  135. dlnode = nodes.definition_list()
  136. for section in doc.args.values():
  137. term = self._nodes_for_one_member(section.member)
  138. # TODO drop fallbacks when undocumented members are outlawed
  139. if section.text:
  140. defn = section.text
  141. elif (variants and variants.tag_member == section.member
  142. and not section.member.type.doc_type()):
  143. values = section.member.type.member_names()
  144. defn = [nodes.Text('One of ')]
  145. defn.extend(intersperse([nodes.literal('', v) for v in values],
  146. nodes.Text(', ')))
  147. else:
  148. defn = [nodes.Text('Not documented')]
  149. dlnode += self._make_dlitem(term, defn)
  150. if base:
  151. dlnode += self._make_dlitem([nodes.Text('The members of '),
  152. nodes.literal('', base.doc_type())],
  153. None)
  154. if variants:
  155. for v in variants.variants:
  156. if v.type.is_implicit():
  157. assert not v.type.base and not v.type.variants
  158. for m in v.type.local_members:
  159. term = self._nodes_for_one_member(m)
  160. term.extend(self._nodes_for_variant_when(variants, v))
  161. dlnode += self._make_dlitem(term, None)
  162. else:
  163. term = [nodes.Text('The members of '),
  164. nodes.literal('', v.type.doc_type())]
  165. term.extend(self._nodes_for_variant_when(variants, v))
  166. dlnode += self._make_dlitem(term, None)
  167. if not dlnode.children:
  168. return []
  169. section = self._make_section(what)
  170. section += dlnode
  171. return [section]
  172. def _nodes_for_enum_values(self, doc):
  173. """Return list of doctree nodes for the table of enum values"""
  174. seen_item = False
  175. dlnode = nodes.definition_list()
  176. for section in doc.args.values():
  177. termtext = [nodes.literal('', section.member.name)]
  178. if section.member.ifcond:
  179. termtext.extend(self._nodes_for_ifcond(section.member.ifcond))
  180. # TODO drop fallbacks when undocumented members are outlawed
  181. if section.text:
  182. defn = section.text
  183. else:
  184. defn = [nodes.Text('Not documented')]
  185. dlnode += self._make_dlitem(termtext, defn)
  186. seen_item = True
  187. if not seen_item:
  188. return []
  189. section = self._make_section('Values')
  190. section += dlnode
  191. return [section]
  192. def _nodes_for_arguments(self, doc, boxed_arg_type):
  193. """Return list of doctree nodes for the arguments section"""
  194. if boxed_arg_type:
  195. assert not doc.args
  196. section = self._make_section('Arguments')
  197. dlnode = nodes.definition_list()
  198. dlnode += self._make_dlitem(
  199. [nodes.Text('The members of '),
  200. nodes.literal('', boxed_arg_type.name)],
  201. None)
  202. section += dlnode
  203. return [section]
  204. return self._nodes_for_members(doc, 'Arguments')
  205. def _nodes_for_features(self, doc):
  206. """Return list of doctree nodes for the table of features"""
  207. seen_item = False
  208. dlnode = nodes.definition_list()
  209. for section in doc.features.values():
  210. dlnode += self._make_dlitem([nodes.literal('', section.name)],
  211. section.text)
  212. seen_item = True
  213. if not seen_item:
  214. return []
  215. section = self._make_section('Features')
  216. section += dlnode
  217. return [section]
  218. def _nodes_for_example(self, exampletext):
  219. """Return list of doctree nodes for a code example snippet"""
  220. return [nodes.literal_block(exampletext, exampletext)]
  221. def _nodes_for_sections(self, doc):
  222. """Return list of doctree nodes for additional sections"""
  223. nodelist = []
  224. for section in doc.sections:
  225. snode = self._make_section(section.name)
  226. if section.name and section.name.startswith('Example'):
  227. snode += self._nodes_for_example(section.text)
  228. else:
  229. self._parse_text_into_node(section.text, snode)
  230. nodelist.append(snode)
  231. return nodelist
  232. def _nodes_for_if_section(self, ifcond):
  233. """Return list of doctree nodes for the "If" section"""
  234. nodelist = []
  235. if ifcond:
  236. snode = self._make_section('If')
  237. snode += self._nodes_for_ifcond(ifcond, with_if=False)
  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, variants):
  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, variants)
  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, variants):
  273. doc = self._cur_doc
  274. self._add_doc('Alternate',
  275. self._nodes_for_members(doc, 'Members')
  276. + self._nodes_for_features(doc)
  277. + self._nodes_for_sections(doc)
  278. + self._nodes_for_if_section(ifcond))
  279. def visit_command(self, name, info, ifcond, features, arg_type,
  280. ret_type, gen, success_response, boxed, allow_oob,
  281. allow_preconfig, coroutine):
  282. doc = self._cur_doc
  283. self._add_doc('Command',
  284. self._nodes_for_arguments(doc,
  285. arg_type if boxed else None)
  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,
  293. arg_type if boxed else None)
  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. class QAPISchemaGenDepVisitor(QAPISchemaVisitor):
  385. """A QAPI schema visitor which adds Sphinx dependencies each module
  386. This class calls the Sphinx note_dependency() function to tell Sphinx
  387. that the generated documentation output depends on the input
  388. schema file associated with each module in the QAPI input.
  389. """
  390. def __init__(self, env, qapidir):
  391. self._env = env
  392. self._qapidir = qapidir
  393. def visit_module(self, name):
  394. if name != "./builtin":
  395. qapifile = self._qapidir + '/' + name
  396. self._env.note_dependency(os.path.abspath(qapifile))
  397. super().visit_module(name)
  398. class QAPIDocDirective(Directive):
  399. """Extract documentation from the specified QAPI .json file"""
  400. required_argument = 1
  401. optional_arguments = 1
  402. option_spec = {
  403. 'qapifile': directives.unchanged_required
  404. }
  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))
  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. # This is from kerneldoc.py -- it works around an API change in
  440. # Sphinx between 1.6 and 1.7. Unlike kerneldoc.py, we use
  441. # sphinx.util.nodes.nested_parse_with_titles() rather than the
  442. # plain self.state.nested_parse(), and so we can drop the saving
  443. # of title_styles and section_level that kerneldoc.py does,
  444. # because nested_parse_with_titles() does that for us.
  445. if Use_SSI:
  446. with switch_source_input(self.state, rstlist):
  447. nested_parse_with_titles(self.state, rstlist, node)
  448. else:
  449. save = self.state.memo.reporter
  450. self.state.memo.reporter = AutodocReporter(
  451. rstlist, self.state.memo.reporter)
  452. try:
  453. nested_parse_with_titles(self.state, rstlist, node)
  454. finally:
  455. self.state.memo.reporter = save
  456. def setup(app):
  457. """ Register qapi-doc directive with Sphinx"""
  458. app.add_config_value('qapidoc_srctree', None, 'env')
  459. app.add_directive('qapi-doc', QAPIDocDirective)
  460. return dict(
  461. version=__version__,
  462. parallel_read_safe=True,
  463. parallel_write_safe=True
  464. )