qapidoc.py 22 KB

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