qapi_domain.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. """
  2. QAPI domain extension.
  3. """
  4. from __future__ import annotations
  5. from typing import (
  6. TYPE_CHECKING,
  7. AbstractSet,
  8. Any,
  9. Dict,
  10. Iterable,
  11. List,
  12. NamedTuple,
  13. Optional,
  14. Tuple,
  15. cast,
  16. )
  17. from docutils import nodes
  18. from docutils.parsers.rst import directives
  19. from compat import KeywordNode, SpaceNode
  20. from sphinx import addnodes
  21. from sphinx.addnodes import desc_signature, pending_xref
  22. from sphinx.directives import ObjectDescription
  23. from sphinx.domains import (
  24. Domain,
  25. Index,
  26. IndexEntry,
  27. ObjType,
  28. )
  29. from sphinx.locale import _, __
  30. from sphinx.roles import XRefRole
  31. from sphinx.util import logging
  32. from sphinx.util.docfields import GroupedField, TypedField
  33. from sphinx.util.nodes import make_id, make_refnode
  34. if TYPE_CHECKING:
  35. from docutils.nodes import Element, Node
  36. from sphinx.application import Sphinx
  37. from sphinx.builders import Builder
  38. from sphinx.environment import BuildEnvironment
  39. from sphinx.util.typing import OptionSpec
  40. logger = logging.getLogger(__name__)
  41. class ObjectEntry(NamedTuple):
  42. docname: str
  43. node_id: str
  44. objtype: str
  45. aliased: bool
  46. class QAPIXRefRole(XRefRole):
  47. def process_link(
  48. self,
  49. env: BuildEnvironment,
  50. refnode: Element,
  51. has_explicit_title: bool,
  52. title: str,
  53. target: str,
  54. ) -> tuple[str, str]:
  55. refnode["qapi:module"] = env.ref_context.get("qapi:module")
  56. # Cross-references that begin with a tilde adjust the title to
  57. # only show the reference without a leading module, even if one
  58. # was provided. This is a Sphinx-standard syntax; give it
  59. # priority over QAPI-specific type markup below.
  60. hide_module = False
  61. if target.startswith("~"):
  62. hide_module = True
  63. target = target[1:]
  64. # Type names that end with "?" are considered optional
  65. # arguments and should be documented as such, but it's not
  66. # part of the xref itself.
  67. if target.endswith("?"):
  68. refnode["qapi:optional"] = True
  69. target = target[:-1]
  70. # Type names wrapped in brackets denote lists. strip the
  71. # brackets and remember to add them back later.
  72. if target.startswith("[") and target.endswith("]"):
  73. refnode["qapi:array"] = True
  74. target = target[1:-1]
  75. if has_explicit_title:
  76. # Don't mess with the title at all if it was explicitly set.
  77. # Explicit title syntax for references is e.g.
  78. # :qapi:type:`target <explicit title>`
  79. # and this explicit title overrides everything else here.
  80. return title, target
  81. title = target
  82. if hide_module:
  83. title = target.split(".")[-1]
  84. return title, target
  85. # Alias for the return of handle_signature(), which is used in several places.
  86. # (In the Python domain, this is Tuple[str, str] instead.)
  87. Signature = str
  88. class QAPIDescription(ObjectDescription[Signature]):
  89. """
  90. Generic QAPI description.
  91. This is meant to be an abstract class, not instantiated
  92. directly. This class handles the abstract details of indexing, the
  93. TOC, and reference targets for QAPI descriptions.
  94. """
  95. def handle_signature(self, sig: str, signode: desc_signature) -> Signature:
  96. # Do nothing. The return value here is the "name" of the entity
  97. # being documented; for QAPI, this is the same as the
  98. # "signature", which is just a name.
  99. # Normally this method must also populate signode with nodes to
  100. # render the signature; here we do nothing instead - the
  101. # subclasses will handle this.
  102. return sig
  103. def get_index_text(self, name: Signature) -> Tuple[str, str]:
  104. """Return the text for the index entry of the object."""
  105. # NB: this is used for the global index, not the QAPI index.
  106. return ("single", f"{name} (QMP {self.objtype})")
  107. def add_target_and_index(
  108. self, name: Signature, sig: str, signode: desc_signature
  109. ) -> None:
  110. # name is the return value of handle_signature.
  111. # sig is the original, raw text argument to handle_signature.
  112. # For QAPI, these are identical, currently.
  113. assert self.objtype
  114. # If we're documenting a module, don't include the module as
  115. # part of the FQN.
  116. modname = ""
  117. if self.objtype != "module":
  118. modname = self.options.get(
  119. "module", self.env.ref_context.get("qapi:module")
  120. )
  121. fullname = (modname + "." if modname else "") + name
  122. node_id = make_id(
  123. self.env, self.state.document, self.objtype, fullname
  124. )
  125. signode["ids"].append(node_id)
  126. self.state.document.note_explicit_target(signode)
  127. domain = cast(QAPIDomain, self.env.get_domain("qapi"))
  128. domain.note_object(fullname, self.objtype, node_id, location=signode)
  129. if "no-index-entry" not in self.options:
  130. arity, indextext = self.get_index_text(name)
  131. assert self.indexnode is not None
  132. if indextext:
  133. self.indexnode["entries"].append(
  134. (arity, indextext, node_id, "", None)
  135. )
  136. def _object_hierarchy_parts(
  137. self, sig_node: desc_signature
  138. ) -> Tuple[str, ...]:
  139. if "fullname" not in sig_node:
  140. return ()
  141. modname = sig_node.get("module")
  142. fullname = sig_node["fullname"]
  143. if modname:
  144. return (modname, *fullname.split("."))
  145. return tuple(fullname.split("."))
  146. def _toc_entry_name(self, sig_node: desc_signature) -> str:
  147. # This controls the name in the TOC and on the sidebar.
  148. # This is the return type of _object_hierarchy_parts().
  149. toc_parts = cast(Tuple[str, ...], sig_node.get("_toc_parts", ()))
  150. if not toc_parts:
  151. return ""
  152. config = self.env.app.config
  153. *parents, name = toc_parts
  154. if config.toc_object_entries_show_parents == "domain":
  155. return sig_node.get("fullname", name)
  156. if config.toc_object_entries_show_parents == "hide":
  157. return name
  158. if config.toc_object_entries_show_parents == "all":
  159. return ".".join(parents + [name])
  160. return ""
  161. class QAPIObject(QAPIDescription):
  162. """
  163. Description of a generic QAPI object.
  164. It's not used directly, but is instead subclassed by specific directives.
  165. """
  166. # Inherit some standard options from Sphinx's ObjectDescription
  167. option_spec: OptionSpec = ( # type:ignore[misc]
  168. ObjectDescription.option_spec.copy()
  169. )
  170. option_spec.update(
  171. {
  172. # Borrowed from the Python domain:
  173. "module": directives.unchanged, # Override contextual module name
  174. # These are QAPI originals:
  175. "since": directives.unchanged,
  176. }
  177. )
  178. doc_field_types = [
  179. # :feat name: descr
  180. GroupedField(
  181. "feature",
  182. label=_("Features"),
  183. names=("feat",),
  184. can_collapse=False,
  185. ),
  186. ]
  187. def get_signature_prefix(self) -> List[nodes.Node]:
  188. """Return a prefix to put before the object name in the signature."""
  189. assert self.objtype
  190. return [
  191. KeywordNode("", self.objtype.title()),
  192. SpaceNode(" "),
  193. ]
  194. def get_signature_suffix(self) -> List[nodes.Node]:
  195. """Return a suffix to put after the object name in the signature."""
  196. ret: List[nodes.Node] = []
  197. if "since" in self.options:
  198. ret += [
  199. SpaceNode(" "),
  200. addnodes.desc_sig_element(
  201. "", f"(Since: {self.options['since']})"
  202. ),
  203. ]
  204. return ret
  205. def handle_signature(self, sig: str, signode: desc_signature) -> Signature:
  206. """
  207. Transform a QAPI definition name into RST nodes.
  208. This method was originally intended for handling function
  209. signatures. In the QAPI domain, however, we only pass the
  210. definition name as the directive argument and handle everything
  211. else in the content body with field lists.
  212. As such, the only argument here is "sig", which is just the QAPI
  213. definition name.
  214. """
  215. modname = self.options.get(
  216. "module", self.env.ref_context.get("qapi:module")
  217. )
  218. signode["fullname"] = sig
  219. signode["module"] = modname
  220. sig_prefix = self.get_signature_prefix()
  221. if sig_prefix:
  222. signode += addnodes.desc_annotation(
  223. str(sig_prefix), "", *sig_prefix
  224. )
  225. signode += addnodes.desc_name(sig, sig)
  226. signode += self.get_signature_suffix()
  227. return sig
  228. class QAPICommand(QAPIObject):
  229. """Description of a QAPI Command."""
  230. doc_field_types = QAPIObject.doc_field_types.copy()
  231. doc_field_types.extend(
  232. [
  233. # :arg TypeName ArgName: descr
  234. TypedField(
  235. "argument",
  236. label=_("Arguments"),
  237. names=("arg",),
  238. can_collapse=False,
  239. ),
  240. ]
  241. )
  242. class QAPIModule(QAPIDescription):
  243. """
  244. Directive to mark description of a new module.
  245. This directive doesn't generate any special formatting, and is just
  246. a pass-through for the content body. Named section titles are
  247. allowed in the content body.
  248. Use this directive to create entries for the QAPI module in the
  249. global index and the QAPI index; as well as to associate subsequent
  250. definitions with the module they are defined in for purposes of
  251. search and QAPI index organization.
  252. :arg: The name of the module.
  253. :opt no-index: Don't add cross-reference targets or index entries.
  254. :opt no-typesetting: Don't render the content body (but preserve any
  255. cross-reference target IDs in the squelched output.)
  256. Example::
  257. .. qapi:module:: block-core
  258. :no-index:
  259. :no-typesetting:
  260. Lorem ipsum, dolor sit amet ...
  261. """
  262. def run(self) -> List[Node]:
  263. modname = self.arguments[0].strip()
  264. self.env.ref_context["qapi:module"] = modname
  265. ret = super().run()
  266. # ObjectDescription always creates a visible signature bar. We
  267. # want module items to be "invisible", however.
  268. # Extract the content body of the directive:
  269. assert isinstance(ret[-1], addnodes.desc)
  270. desc_node = ret.pop(-1)
  271. assert isinstance(desc_node.children[1], addnodes.desc_content)
  272. ret.extend(desc_node.children[1].children)
  273. # Re-home node_ids so anchor refs still work:
  274. node_ids: List[str]
  275. if node_ids := [
  276. node_id
  277. for el in desc_node.children[0].traverse(nodes.Element)
  278. for node_id in cast(List[str], el.get("ids", ()))
  279. ]:
  280. target_node = nodes.target(ids=node_ids)
  281. ret.insert(1, target_node)
  282. return ret
  283. class QAPIIndex(Index):
  284. """
  285. Index subclass to provide the QAPI definition index.
  286. """
  287. # pylint: disable=too-few-public-methods
  288. name = "index"
  289. localname = _("QAPI Index")
  290. shortname = _("QAPI Index")
  291. def generate(
  292. self,
  293. docnames: Optional[Iterable[str]] = None,
  294. ) -> Tuple[List[Tuple[str, List[IndexEntry]]], bool]:
  295. assert isinstance(self.domain, QAPIDomain)
  296. content: Dict[str, List[IndexEntry]] = {}
  297. collapse = False
  298. # list of all object (name, ObjectEntry) pairs, sorted by name
  299. # (ignoring the module)
  300. objects = sorted(
  301. self.domain.objects.items(),
  302. key=lambda x: x[0].split(".")[-1].lower(),
  303. )
  304. for objname, obj in objects:
  305. if docnames and obj.docname not in docnames:
  306. continue
  307. # Strip the module name out:
  308. objname = objname.split(".")[-1]
  309. # Add an alphabetical entry:
  310. entries = content.setdefault(objname[0].upper(), [])
  311. entries.append(
  312. IndexEntry(
  313. objname, 0, obj.docname, obj.node_id, obj.objtype, "", ""
  314. )
  315. )
  316. # Add a categorical entry:
  317. category = obj.objtype.title() + "s"
  318. entries = content.setdefault(category, [])
  319. entries.append(
  320. IndexEntry(objname, 0, obj.docname, obj.node_id, "", "", "")
  321. )
  322. # alphabetically sort categories; type names first, ABC entries last.
  323. sorted_content = sorted(
  324. content.items(),
  325. key=lambda x: (len(x[0]) == 1, x[0]),
  326. )
  327. return sorted_content, collapse
  328. class QAPIDomain(Domain):
  329. """QAPI language domain."""
  330. name = "qapi"
  331. label = "QAPI"
  332. # This table associates cross-reference object types (key) with an
  333. # ObjType instance, which defines the valid cross-reference roles
  334. # for each object type.
  335. object_types: Dict[str, ObjType] = {
  336. "module": ObjType(_("module"), "mod", "any"),
  337. "command": ObjType(_("command"), "cmd", "any"),
  338. }
  339. # Each of these provides a rST directive,
  340. # e.g. .. qapi:module:: block-core
  341. directives = {
  342. "module": QAPIModule,
  343. "command": QAPICommand,
  344. }
  345. # These are all cross-reference roles; e.g.
  346. # :qapi:cmd:`query-block`. The keys correlate to the names used in
  347. # the object_types table values above.
  348. roles = {
  349. "mod": QAPIXRefRole(),
  350. "cmd": QAPIXRefRole(),
  351. "any": QAPIXRefRole(), # reference *any* type of QAPI object.
  352. }
  353. # Moved into the data property at runtime;
  354. # this is the internal index of reference-able objects.
  355. initial_data: Dict[str, Dict[str, Tuple[Any]]] = {
  356. "objects": {}, # fullname -> ObjectEntry
  357. }
  358. # Index pages to generate; each entry is an Index class.
  359. indices = [
  360. QAPIIndex,
  361. ]
  362. @property
  363. def objects(self) -> Dict[str, ObjectEntry]:
  364. ret = self.data.setdefault("objects", {})
  365. return ret # type: ignore[no-any-return]
  366. def note_object(
  367. self,
  368. name: str,
  369. objtype: str,
  370. node_id: str,
  371. aliased: bool = False,
  372. location: Any = None,
  373. ) -> None:
  374. """Note a QAPI object for cross reference."""
  375. if name in self.objects:
  376. other = self.objects[name]
  377. if other.aliased and aliased is False:
  378. # The original definition found. Override it!
  379. pass
  380. elif other.aliased is False and aliased:
  381. # The original definition is already registered.
  382. return
  383. else:
  384. # duplicated
  385. logger.warning(
  386. __(
  387. "duplicate object description of %s, "
  388. "other instance in %s, use :no-index: for one of them"
  389. ),
  390. name,
  391. other.docname,
  392. location=location,
  393. )
  394. self.objects[name] = ObjectEntry(
  395. self.env.docname, node_id, objtype, aliased
  396. )
  397. def clear_doc(self, docname: str) -> None:
  398. for fullname, obj in list(self.objects.items()):
  399. if obj.docname == docname:
  400. del self.objects[fullname]
  401. def merge_domaindata(
  402. self, docnames: AbstractSet[str], otherdata: Dict[str, Any]
  403. ) -> None:
  404. for fullname, obj in otherdata["objects"].items():
  405. if obj.docname in docnames:
  406. # Sphinx's own python domain doesn't appear to bother to
  407. # check for collisions. Assert they don't happen and
  408. # we'll fix it if/when the case arises.
  409. assert fullname not in self.objects, (
  410. "bug - collision on merge?"
  411. f" {fullname=} {obj=} {self.objects[fullname]=}"
  412. )
  413. self.objects[fullname] = obj
  414. def find_obj(
  415. self, modname: str, name: str, typ: Optional[str]
  416. ) -> list[tuple[str, ObjectEntry]]:
  417. """
  418. Find a QAPI object for "name", perhaps using the given module.
  419. Returns a list of (name, object entry) tuples.
  420. :param modname: The current module context (if any!)
  421. under which we are searching.
  422. :param name: The name of the x-ref to resolve;
  423. may or may not include a leading module.
  424. :param type: The role name of the x-ref we're resolving, if provided.
  425. (This is absent for "any" lookups.)
  426. """
  427. if not name:
  428. return []
  429. names: list[str] = []
  430. matches: list[tuple[str, ObjectEntry]] = []
  431. fullname = name
  432. if "." in fullname:
  433. # We're searching for a fully qualified reference;
  434. # ignore the contextual module.
  435. pass
  436. elif modname:
  437. # We're searching for something from somewhere;
  438. # try searching the current module first.
  439. # e.g. :qapi:cmd:`query-block` or `query-block` is being searched.
  440. fullname = f"{modname}.{name}"
  441. if typ is None:
  442. # type isn't specified, this is a generic xref.
  443. # search *all* qapi-specific object types.
  444. objtypes: List[str] = list(self.object_types)
  445. else:
  446. # type is specified and will be a role (e.g. obj, mod, cmd)
  447. # convert this to eligible object types (e.g. command, module)
  448. # using the QAPIDomain.object_types table.
  449. objtypes = self.objtypes_for_role(typ, [])
  450. if name in self.objects and self.objects[name].objtype in objtypes:
  451. names = [name]
  452. elif (
  453. fullname in self.objects
  454. and self.objects[fullname].objtype in objtypes
  455. ):
  456. names = [fullname]
  457. else:
  458. # exact match wasn't found; e.g. we are searching for
  459. # `query-block` from a different (or no) module.
  460. searchname = "." + name
  461. names = [
  462. oname
  463. for oname in self.objects
  464. if oname.endswith(searchname)
  465. and self.objects[oname].objtype in objtypes
  466. ]
  467. matches = [(oname, self.objects[oname]) for oname in names]
  468. if len(matches) > 1:
  469. matches = [m for m in matches if not m[1].aliased]
  470. return matches
  471. def resolve_xref(
  472. self,
  473. env: BuildEnvironment,
  474. fromdocname: str,
  475. builder: Builder,
  476. typ: str,
  477. target: str,
  478. node: pending_xref,
  479. contnode: Element,
  480. ) -> nodes.reference | None:
  481. modname = node.get("qapi:module")
  482. matches = self.find_obj(modname, target, typ)
  483. if not matches:
  484. return None
  485. if len(matches) > 1:
  486. logger.warning(
  487. __("more than one target found for cross-reference %r: %s"),
  488. target,
  489. ", ".join(match[0] for match in matches),
  490. type="ref",
  491. subtype="qapi",
  492. location=node,
  493. )
  494. name, obj = matches[0]
  495. return make_refnode(
  496. builder, fromdocname, obj.docname, obj.node_id, contnode, name
  497. )
  498. def resolve_any_xref(
  499. self,
  500. env: BuildEnvironment,
  501. fromdocname: str,
  502. builder: Builder,
  503. target: str,
  504. node: pending_xref,
  505. contnode: Element,
  506. ) -> List[Tuple[str, nodes.reference]]:
  507. results: List[Tuple[str, nodes.reference]] = []
  508. matches = self.find_obj(node.get("qapi:module"), target, None)
  509. for name, obj in matches:
  510. rolename = self.role_for_objtype(obj.objtype)
  511. assert rolename is not None
  512. role = f"qapi:{rolename}"
  513. refnode = make_refnode(
  514. builder, fromdocname, obj.docname, obj.node_id, contnode, name
  515. )
  516. results.append((role, refnode))
  517. return results
  518. def setup(app: Sphinx) -> Dict[str, Any]:
  519. app.setup_extension("sphinx.directives")
  520. app.add_domain(QAPIDomain)
  521. return {
  522. "version": "1.0",
  523. "env_version": 1,
  524. "parallel_read_safe": True,
  525. "parallel_write_safe": True,
  526. }