qapi_domain.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988
  1. """
  2. QAPI domain extension.
  3. """
  4. # The best laid plans of mice and men, ...
  5. # pylint: disable=too-many-lines
  6. from __future__ import annotations
  7. from typing import (
  8. TYPE_CHECKING,
  9. List,
  10. NamedTuple,
  11. Tuple,
  12. cast,
  13. )
  14. from docutils import nodes
  15. from docutils.parsers.rst import directives
  16. from compat import (
  17. CompatField,
  18. CompatGroupedField,
  19. CompatTypedField,
  20. KeywordNode,
  21. ParserFix,
  22. Signature,
  23. SpaceNode,
  24. )
  25. from sphinx import addnodes
  26. from sphinx.directives import ObjectDescription
  27. from sphinx.domains import (
  28. Domain,
  29. Index,
  30. IndexEntry,
  31. ObjType,
  32. )
  33. from sphinx.locale import _, __
  34. from sphinx.roles import XRefRole
  35. from sphinx.util import logging
  36. from sphinx.util.docutils import SphinxDirective
  37. from sphinx.util.nodes import make_id, make_refnode
  38. if TYPE_CHECKING:
  39. from typing import (
  40. AbstractSet,
  41. Any,
  42. Dict,
  43. Iterable,
  44. Optional,
  45. Union,
  46. )
  47. from docutils.nodes import Element, Node
  48. from sphinx.addnodes import desc_signature, pending_xref
  49. from sphinx.application import Sphinx
  50. from sphinx.builders import Builder
  51. from sphinx.environment import BuildEnvironment
  52. from sphinx.util.typing import OptionSpec
  53. logger = logging.getLogger(__name__)
  54. def _unpack_field(
  55. field: nodes.Node,
  56. ) -> Tuple[nodes.field_name, nodes.field_body]:
  57. """
  58. docutils helper: unpack a field node in a type-safe manner.
  59. """
  60. assert isinstance(field, nodes.field)
  61. assert len(field.children) == 2
  62. assert isinstance(field.children[0], nodes.field_name)
  63. assert isinstance(field.children[1], nodes.field_body)
  64. return (field.children[0], field.children[1])
  65. class ObjectEntry(NamedTuple):
  66. docname: str
  67. node_id: str
  68. objtype: str
  69. aliased: bool
  70. class QAPIXRefRole(XRefRole):
  71. def process_link(
  72. self,
  73. env: BuildEnvironment,
  74. refnode: Element,
  75. has_explicit_title: bool,
  76. title: str,
  77. target: str,
  78. ) -> tuple[str, str]:
  79. refnode["qapi:module"] = env.ref_context.get("qapi:module")
  80. # Cross-references that begin with a tilde adjust the title to
  81. # only show the reference without a leading module, even if one
  82. # was provided. This is a Sphinx-standard syntax; give it
  83. # priority over QAPI-specific type markup below.
  84. hide_module = False
  85. if target.startswith("~"):
  86. hide_module = True
  87. target = target[1:]
  88. # Type names that end with "?" are considered optional
  89. # arguments and should be documented as such, but it's not
  90. # part of the xref itself.
  91. if target.endswith("?"):
  92. refnode["qapi:optional"] = True
  93. target = target[:-1]
  94. # Type names wrapped in brackets denote lists. strip the
  95. # brackets and remember to add them back later.
  96. if target.startswith("[") and target.endswith("]"):
  97. refnode["qapi:array"] = True
  98. target = target[1:-1]
  99. if has_explicit_title:
  100. # Don't mess with the title at all if it was explicitly set.
  101. # Explicit title syntax for references is e.g.
  102. # :qapi:type:`target <explicit title>`
  103. # and this explicit title overrides everything else here.
  104. return title, target
  105. title = target
  106. if hide_module:
  107. title = target.split(".")[-1]
  108. return title, target
  109. def result_nodes(
  110. self,
  111. document: nodes.document,
  112. env: BuildEnvironment,
  113. node: Element,
  114. is_ref: bool,
  115. ) -> Tuple[List[nodes.Node], List[nodes.system_message]]:
  116. # node here is the pending_xref node (or whatever nodeclass was
  117. # configured at XRefRole class instantiation time).
  118. results: List[nodes.Node] = [node]
  119. if node.get("qapi:array"):
  120. results.insert(0, nodes.literal("[", "["))
  121. results.append(nodes.literal("]", "]"))
  122. if node.get("qapi:optional"):
  123. results.append(nodes.Text(", "))
  124. results.append(nodes.emphasis("?", "optional"))
  125. return results, []
  126. class QAPIDescription(ParserFix):
  127. """
  128. Generic QAPI description.
  129. This is meant to be an abstract class, not instantiated
  130. directly. This class handles the abstract details of indexing, the
  131. TOC, and reference targets for QAPI descriptions.
  132. """
  133. def handle_signature(self, sig: str, signode: desc_signature) -> Signature:
  134. # Do nothing. The return value here is the "name" of the entity
  135. # being documented; for QAPI, this is the same as the
  136. # "signature", which is just a name.
  137. # Normally this method must also populate signode with nodes to
  138. # render the signature; here we do nothing instead - the
  139. # subclasses will handle this.
  140. return sig
  141. def get_index_text(self, name: Signature) -> Tuple[str, str]:
  142. """Return the text for the index entry of the object."""
  143. # NB: this is used for the global index, not the QAPI index.
  144. return ("single", f"{name} (QMP {self.objtype})")
  145. def _get_context(self) -> Tuple[str, str]:
  146. namespace = self.options.get(
  147. "namespace", self.env.ref_context.get("qapi:namespace", "")
  148. )
  149. modname = self.options.get(
  150. "module", self.env.ref_context.get("qapi:module", "")
  151. )
  152. return namespace, modname
  153. def _get_fqn(self, name: Signature) -> str:
  154. namespace, modname = self._get_context()
  155. # If we're documenting a module, don't include the module as
  156. # part of the FQN; we ARE the module!
  157. if self.objtype == "module":
  158. modname = ""
  159. if modname:
  160. name = f"{modname}.{name}"
  161. if namespace:
  162. name = f"{namespace}:{name}"
  163. return name
  164. def add_target_and_index(
  165. self, name: Signature, sig: str, signode: desc_signature
  166. ) -> None:
  167. # name is the return value of handle_signature.
  168. # sig is the original, raw text argument to handle_signature.
  169. # For QAPI, these are identical, currently.
  170. assert self.objtype
  171. if not (fullname := signode.get("fullname", "")):
  172. fullname = self._get_fqn(name)
  173. node_id = make_id(
  174. self.env, self.state.document, self.objtype, fullname
  175. )
  176. signode["ids"].append(node_id)
  177. self.state.document.note_explicit_target(signode)
  178. domain = cast(QAPIDomain, self.env.get_domain("qapi"))
  179. domain.note_object(fullname, self.objtype, node_id, location=signode)
  180. if "no-index-entry" not in self.options:
  181. arity, indextext = self.get_index_text(name)
  182. assert self.indexnode is not None
  183. if indextext:
  184. self.indexnode["entries"].append(
  185. (arity, indextext, node_id, "", None)
  186. )
  187. @staticmethod
  188. def split_fqn(name: str) -> Tuple[str, str, str]:
  189. if ":" in name:
  190. ns, name = name.split(":")
  191. else:
  192. ns = ""
  193. if "." in name:
  194. module, name = name.split(".")
  195. else:
  196. module = ""
  197. return (ns, module, name)
  198. def _object_hierarchy_parts(
  199. self, sig_node: desc_signature
  200. ) -> Tuple[str, ...]:
  201. if "fullname" not in sig_node:
  202. return ()
  203. return self.split_fqn(sig_node["fullname"])
  204. def _toc_entry_name(self, sig_node: desc_signature) -> str:
  205. # This controls the name in the TOC and on the sidebar.
  206. # This is the return type of _object_hierarchy_parts().
  207. toc_parts = cast(Tuple[str, ...], sig_node.get("_toc_parts", ()))
  208. if not toc_parts:
  209. return ""
  210. config = self.env.app.config
  211. namespace, modname, name = toc_parts
  212. if config.toc_object_entries_show_parents == "domain":
  213. ret = name
  214. if modname and modname != self.env.ref_context.get(
  215. "qapi:module", ""
  216. ):
  217. ret = f"{modname}.{name}"
  218. if namespace and namespace != self.env.ref_context.get(
  219. "qapi:namespace", ""
  220. ):
  221. ret = f"{namespace}:{ret}"
  222. return ret
  223. if config.toc_object_entries_show_parents == "hide":
  224. return name
  225. if config.toc_object_entries_show_parents == "all":
  226. return sig_node.get("fullname", name)
  227. return ""
  228. class QAPIObject(QAPIDescription):
  229. """
  230. Description of a generic QAPI object.
  231. It's not used directly, but is instead subclassed by specific directives.
  232. """
  233. # Inherit some standard options from Sphinx's ObjectDescription
  234. option_spec: OptionSpec = ( # type:ignore[misc]
  235. ObjectDescription.option_spec.copy()
  236. )
  237. option_spec.update(
  238. {
  239. # Context overrides:
  240. "namespace": directives.unchanged,
  241. "module": directives.unchanged,
  242. # These are QAPI originals:
  243. "since": directives.unchanged,
  244. "ifcond": directives.unchanged,
  245. "deprecated": directives.flag,
  246. "unstable": directives.flag,
  247. }
  248. )
  249. doc_field_types = [
  250. # :feat name: descr
  251. CompatGroupedField(
  252. "feature",
  253. label=_("Features"),
  254. names=("feat",),
  255. can_collapse=False,
  256. ),
  257. ]
  258. def get_signature_prefix(self) -> List[nodes.Node]:
  259. """Return a prefix to put before the object name in the signature."""
  260. assert self.objtype
  261. return [
  262. KeywordNode("", self.objtype.title()),
  263. SpaceNode(" "),
  264. ]
  265. def get_signature_suffix(self) -> List[nodes.Node]:
  266. """Return a suffix to put after the object name in the signature."""
  267. ret: List[nodes.Node] = []
  268. if "since" in self.options:
  269. ret += [
  270. SpaceNode(" "),
  271. addnodes.desc_sig_element(
  272. "", f"(Since: {self.options['since']})"
  273. ),
  274. ]
  275. return ret
  276. def handle_signature(self, sig: str, signode: desc_signature) -> Signature:
  277. """
  278. Transform a QAPI definition name into RST nodes.
  279. This method was originally intended for handling function
  280. signatures. In the QAPI domain, however, we only pass the
  281. definition name as the directive argument and handle everything
  282. else in the content body with field lists.
  283. As such, the only argument here is "sig", which is just the QAPI
  284. definition name.
  285. """
  286. # No module or domain info allowed in the signature!
  287. assert ":" not in sig
  288. assert "." not in sig
  289. namespace, modname = self._get_context()
  290. signode["fullname"] = self._get_fqn(sig)
  291. signode["namespace"] = namespace
  292. signode["module"] = modname
  293. sig_prefix = self.get_signature_prefix()
  294. if sig_prefix:
  295. signode += addnodes.desc_annotation(
  296. str(sig_prefix), "", *sig_prefix
  297. )
  298. signode += addnodes.desc_name(sig, sig)
  299. signode += self.get_signature_suffix()
  300. return sig
  301. def _add_infopips(self, contentnode: addnodes.desc_content) -> None:
  302. # Add various eye-catches and things that go below the signature
  303. # bar, but precede the user-defined content.
  304. infopips = nodes.container()
  305. infopips.attributes["classes"].append("qapi-infopips")
  306. def _add_pip(
  307. source: str, content: Union[str, List[nodes.Node]], classname: str
  308. ) -> None:
  309. node = nodes.container(source)
  310. if isinstance(content, str):
  311. node.append(nodes.Text(content))
  312. else:
  313. node.extend(content)
  314. node.attributes["classes"].extend(["qapi-infopip", classname])
  315. infopips.append(node)
  316. if "deprecated" in self.options:
  317. _add_pip(
  318. ":deprecated:",
  319. f"This {self.objtype} is deprecated.",
  320. "qapi-deprecated",
  321. )
  322. if "unstable" in self.options:
  323. _add_pip(
  324. ":unstable:",
  325. f"This {self.objtype} is unstable/experimental.",
  326. "qapi-unstable",
  327. )
  328. if self.options.get("ifcond", ""):
  329. ifcond = self.options["ifcond"]
  330. _add_pip(
  331. f":ifcond: {ifcond}",
  332. [
  333. nodes.emphasis("", "Availability"),
  334. nodes.Text(": "),
  335. nodes.literal(ifcond, ifcond),
  336. ],
  337. "qapi-ifcond",
  338. )
  339. if infopips.children:
  340. contentnode.insert(0, infopips)
  341. def _validate_field(self, field: nodes.field) -> None:
  342. """Validate field lists in this QAPI Object Description."""
  343. name, _ = _unpack_field(field)
  344. allowed_fields = set(self.env.app.config.qapi_allowed_fields)
  345. field_label = name.astext()
  346. if field_label in allowed_fields:
  347. # Explicitly allowed field list name, OK.
  348. return
  349. try:
  350. # split into field type and argument (if provided)
  351. # e.g. `:arg type name: descr` is
  352. # field_type = "arg", field_arg = "type name".
  353. field_type, field_arg = field_label.split(None, 1)
  354. except ValueError:
  355. # No arguments provided
  356. field_type = field_label
  357. field_arg = ""
  358. typemap = self.get_field_type_map()
  359. if field_type in typemap:
  360. # This is a special docfield, yet-to-be-processed. Catch
  361. # correct names, but incorrect arguments. This mismatch WILL
  362. # cause Sphinx to render this field incorrectly (without a
  363. # warning), which is never what we want.
  364. typedesc = typemap[field_type][0]
  365. if typedesc.has_arg != bool(field_arg):
  366. msg = f"docfield field list type {field_type!r} "
  367. if typedesc.has_arg:
  368. msg += "requires an argument."
  369. else:
  370. msg += "takes no arguments."
  371. logger.warning(msg, location=field)
  372. else:
  373. # This is unrecognized entirely. It's valid rST to use
  374. # arbitrary fields, but let's ensure the documentation
  375. # writer has done this intentionally.
  376. valid = ", ".join(sorted(set(typemap) | allowed_fields))
  377. msg = (
  378. f"Unrecognized field list name {field_label!r}.\n"
  379. f"Valid fields for qapi:{self.objtype} are: {valid}\n"
  380. "\n"
  381. "If this usage is intentional, please add it to "
  382. "'qapi_allowed_fields' in docs/conf.py."
  383. )
  384. logger.warning(msg, location=field)
  385. def transform_content(self, content_node: addnodes.desc_content) -> None:
  386. # This hook runs after before_content and the nested parse, but
  387. # before the DocFieldTransformer is executed.
  388. super().transform_content(content_node)
  389. self._add_infopips(content_node)
  390. # Validate field lists.
  391. for child in content_node:
  392. if isinstance(child, nodes.field_list):
  393. for field in child.children:
  394. assert isinstance(field, nodes.field)
  395. self._validate_field(field)
  396. class SpecialTypedField(CompatTypedField):
  397. def make_field(self, *args: Any, **kwargs: Any) -> nodes.field:
  398. ret = super().make_field(*args, **kwargs)
  399. # Look for the characteristic " -- " text node that Sphinx
  400. # inserts for each TypedField entry ...
  401. for node in ret.traverse(lambda n: str(n) == " -- "):
  402. par = node.parent
  403. if par.children[0].astext() != "q_dummy":
  404. continue
  405. # If the first node's text is q_dummy, this is a dummy
  406. # field we want to strip down to just its contents.
  407. del par.children[:-1]
  408. return ret
  409. class QAPICommand(QAPIObject):
  410. """Description of a QAPI Command."""
  411. doc_field_types = QAPIObject.doc_field_types.copy()
  412. doc_field_types.extend(
  413. [
  414. # :arg TypeName ArgName: descr
  415. SpecialTypedField(
  416. "argument",
  417. label=_("Arguments"),
  418. names=("arg",),
  419. typerolename="type",
  420. can_collapse=False,
  421. ),
  422. # :error: descr
  423. CompatField(
  424. "error",
  425. label=_("Errors"),
  426. names=("error", "errors"),
  427. has_arg=False,
  428. ),
  429. # :return TypeName: descr
  430. CompatGroupedField(
  431. "returnvalue",
  432. label=_("Return"),
  433. rolename="type",
  434. names=("return",),
  435. can_collapse=True,
  436. ),
  437. ]
  438. )
  439. class QAPIEnum(QAPIObject):
  440. """Description of a QAPI Enum."""
  441. doc_field_types = QAPIObject.doc_field_types.copy()
  442. doc_field_types.extend(
  443. [
  444. # :value name: descr
  445. CompatGroupedField(
  446. "value",
  447. label=_("Values"),
  448. names=("value",),
  449. can_collapse=False,
  450. )
  451. ]
  452. )
  453. class QAPIAlternate(QAPIObject):
  454. """Description of a QAPI Alternate."""
  455. doc_field_types = QAPIObject.doc_field_types.copy()
  456. doc_field_types.extend(
  457. [
  458. # :alt type name: descr
  459. CompatTypedField(
  460. "alternative",
  461. label=_("Alternatives"),
  462. names=("alt",),
  463. typerolename="type",
  464. can_collapse=False,
  465. ),
  466. ]
  467. )
  468. class QAPIObjectWithMembers(QAPIObject):
  469. """Base class for Events/Structs/Unions"""
  470. doc_field_types = QAPIObject.doc_field_types.copy()
  471. doc_field_types.extend(
  472. [
  473. # :member type name: descr
  474. SpecialTypedField(
  475. "member",
  476. label=_("Members"),
  477. names=("memb",),
  478. typerolename="type",
  479. can_collapse=False,
  480. ),
  481. ]
  482. )
  483. class QAPIEvent(QAPIObjectWithMembers):
  484. # pylint: disable=too-many-ancestors
  485. """Description of a QAPI Event."""
  486. class QAPIJSONObject(QAPIObjectWithMembers):
  487. # pylint: disable=too-many-ancestors
  488. """Description of a QAPI Object: structs and unions."""
  489. class QAPIModule(QAPIDescription):
  490. """
  491. Directive to mark description of a new module.
  492. This directive doesn't generate any special formatting, and is just
  493. a pass-through for the content body. Named section titles are
  494. allowed in the content body.
  495. Use this directive to create entries for the QAPI module in the
  496. global index and the QAPI index; as well as to associate subsequent
  497. definitions with the module they are defined in for purposes of
  498. search and QAPI index organization.
  499. :arg: The name of the module.
  500. :opt no-index: Don't add cross-reference targets or index entries.
  501. :opt no-typesetting: Don't render the content body (but preserve any
  502. cross-reference target IDs in the squelched output.)
  503. Example::
  504. .. qapi:module:: block-core
  505. :no-index:
  506. :no-typesetting:
  507. Lorem ipsum, dolor sit amet ...
  508. """
  509. def run(self) -> List[Node]:
  510. modname = self.arguments[0].strip()
  511. self.env.ref_context["qapi:module"] = modname
  512. ret = super().run()
  513. # ObjectDescription always creates a visible signature bar. We
  514. # want module items to be "invisible", however.
  515. # Extract the content body of the directive:
  516. assert isinstance(ret[-1], addnodes.desc)
  517. desc_node = ret.pop(-1)
  518. assert isinstance(desc_node.children[1], addnodes.desc_content)
  519. ret.extend(desc_node.children[1].children)
  520. # Re-home node_ids so anchor refs still work:
  521. node_ids: List[str]
  522. if node_ids := [
  523. node_id
  524. for el in desc_node.children[0].traverse(nodes.Element)
  525. for node_id in cast(List[str], el.get("ids", ()))
  526. ]:
  527. target_node = nodes.target(ids=node_ids)
  528. ret.insert(1, target_node)
  529. return ret
  530. class QAPINamespace(SphinxDirective):
  531. has_content = False
  532. required_arguments = 1
  533. def run(self) -> List[Node]:
  534. namespace = self.arguments[0].strip()
  535. self.env.ref_context["qapi:namespace"] = namespace
  536. return []
  537. class QAPIIndex(Index):
  538. """
  539. Index subclass to provide the QAPI definition index.
  540. """
  541. # pylint: disable=too-few-public-methods
  542. name = "index"
  543. localname = _("QAPI Index")
  544. shortname = _("QAPI Index")
  545. def generate(
  546. self,
  547. docnames: Optional[Iterable[str]] = None,
  548. ) -> Tuple[List[Tuple[str, List[IndexEntry]]], bool]:
  549. assert isinstance(self.domain, QAPIDomain)
  550. content: Dict[str, List[IndexEntry]] = {}
  551. collapse = False
  552. # list of all object (name, ObjectEntry) pairs, sorted by name
  553. # (ignoring the module)
  554. objects = sorted(
  555. self.domain.objects.items(),
  556. key=lambda x: x[0].split(".")[-1].lower(),
  557. )
  558. for objname, obj in objects:
  559. if docnames and obj.docname not in docnames:
  560. continue
  561. # Strip the module name out:
  562. objname = objname.split(".")[-1]
  563. # Add an alphabetical entry:
  564. entries = content.setdefault(objname[0].upper(), [])
  565. entries.append(
  566. IndexEntry(
  567. objname, 0, obj.docname, obj.node_id, obj.objtype, "", ""
  568. )
  569. )
  570. # Add a categorical entry:
  571. category = obj.objtype.title() + "s"
  572. entries = content.setdefault(category, [])
  573. entries.append(
  574. IndexEntry(objname, 0, obj.docname, obj.node_id, "", "", "")
  575. )
  576. # alphabetically sort categories; type names first, ABC entries last.
  577. sorted_content = sorted(
  578. content.items(),
  579. key=lambda x: (len(x[0]) == 1, x[0]),
  580. )
  581. return sorted_content, collapse
  582. class QAPIDomain(Domain):
  583. """QAPI language domain."""
  584. name = "qapi"
  585. label = "QAPI"
  586. # This table associates cross-reference object types (key) with an
  587. # ObjType instance, which defines the valid cross-reference roles
  588. # for each object type.
  589. #
  590. # e.g., the :qapi:type: cross-reference role can refer to enum,
  591. # struct, union, or alternate objects; but :qapi:obj: can refer to
  592. # anything. Each object also gets its own targeted cross-reference role.
  593. object_types: Dict[str, ObjType] = {
  594. "module": ObjType(_("module"), "mod", "any"),
  595. "command": ObjType(_("command"), "cmd", "any"),
  596. "event": ObjType(_("event"), "event", "any"),
  597. "enum": ObjType(_("enum"), "enum", "type", "any"),
  598. "object": ObjType(_("object"), "obj", "type", "any"),
  599. "alternate": ObjType(_("alternate"), "alt", "type", "any"),
  600. }
  601. # Each of these provides a rST directive,
  602. # e.g. .. qapi:module:: block-core
  603. directives = {
  604. "namespace": QAPINamespace,
  605. "module": QAPIModule,
  606. "command": QAPICommand,
  607. "event": QAPIEvent,
  608. "enum": QAPIEnum,
  609. "object": QAPIJSONObject,
  610. "alternate": QAPIAlternate,
  611. }
  612. # These are all cross-reference roles; e.g.
  613. # :qapi:cmd:`query-block`. The keys correlate to the names used in
  614. # the object_types table values above.
  615. roles = {
  616. "mod": QAPIXRefRole(),
  617. "cmd": QAPIXRefRole(),
  618. "event": QAPIXRefRole(),
  619. "enum": QAPIXRefRole(),
  620. "obj": QAPIXRefRole(), # specifically structs and unions.
  621. "alt": QAPIXRefRole(),
  622. # reference any data type (excludes modules, commands, events)
  623. "type": QAPIXRefRole(),
  624. "any": QAPIXRefRole(), # reference *any* type of QAPI object.
  625. }
  626. # Moved into the data property at runtime;
  627. # this is the internal index of reference-able objects.
  628. initial_data: Dict[str, Dict[str, Tuple[Any]]] = {
  629. "objects": {}, # fullname -> ObjectEntry
  630. }
  631. # Index pages to generate; each entry is an Index class.
  632. indices = [
  633. QAPIIndex,
  634. ]
  635. @property
  636. def objects(self) -> Dict[str, ObjectEntry]:
  637. ret = self.data.setdefault("objects", {})
  638. return ret # type: ignore[no-any-return]
  639. def note_object(
  640. self,
  641. name: str,
  642. objtype: str,
  643. node_id: str,
  644. aliased: bool = False,
  645. location: Any = None,
  646. ) -> None:
  647. """Note a QAPI object for cross reference."""
  648. if name in self.objects:
  649. other = self.objects[name]
  650. if other.aliased and aliased is False:
  651. # The original definition found. Override it!
  652. pass
  653. elif other.aliased is False and aliased:
  654. # The original definition is already registered.
  655. return
  656. else:
  657. # duplicated
  658. logger.warning(
  659. __(
  660. "duplicate object description of %s, "
  661. "other instance in %s, use :no-index: for one of them"
  662. ),
  663. name,
  664. other.docname,
  665. location=location,
  666. )
  667. self.objects[name] = ObjectEntry(
  668. self.env.docname, node_id, objtype, aliased
  669. )
  670. def clear_doc(self, docname: str) -> None:
  671. for fullname, obj in list(self.objects.items()):
  672. if obj.docname == docname:
  673. del self.objects[fullname]
  674. def merge_domaindata(
  675. self, docnames: AbstractSet[str], otherdata: Dict[str, Any]
  676. ) -> None:
  677. for fullname, obj in otherdata["objects"].items():
  678. if obj.docname in docnames:
  679. # Sphinx's own python domain doesn't appear to bother to
  680. # check for collisions. Assert they don't happen and
  681. # we'll fix it if/when the case arises.
  682. assert fullname not in self.objects, (
  683. "bug - collision on merge?"
  684. f" {fullname=} {obj=} {self.objects[fullname]=}"
  685. )
  686. self.objects[fullname] = obj
  687. def find_obj(
  688. self, modname: str, name: str, typ: Optional[str]
  689. ) -> list[tuple[str, ObjectEntry]]:
  690. """
  691. Find a QAPI object for "name", perhaps using the given module.
  692. Returns a list of (name, object entry) tuples.
  693. :param modname: The current module context (if any!)
  694. under which we are searching.
  695. :param name: The name of the x-ref to resolve;
  696. may or may not include a leading module.
  697. :param type: The role name of the x-ref we're resolving, if provided.
  698. (This is absent for "any" lookups.)
  699. """
  700. if not name:
  701. return []
  702. names: list[str] = []
  703. matches: list[tuple[str, ObjectEntry]] = []
  704. fullname = name
  705. if "." in fullname:
  706. # We're searching for a fully qualified reference;
  707. # ignore the contextual module.
  708. pass
  709. elif modname:
  710. # We're searching for something from somewhere;
  711. # try searching the current module first.
  712. # e.g. :qapi:cmd:`query-block` or `query-block` is being searched.
  713. fullname = f"{modname}.{name}"
  714. if typ is None:
  715. # type isn't specified, this is a generic xref.
  716. # search *all* qapi-specific object types.
  717. objtypes: List[str] = list(self.object_types)
  718. else:
  719. # type is specified and will be a role (e.g. obj, mod, cmd)
  720. # convert this to eligible object types (e.g. command, module)
  721. # using the QAPIDomain.object_types table.
  722. objtypes = self.objtypes_for_role(typ, [])
  723. if name in self.objects and self.objects[name].objtype in objtypes:
  724. names = [name]
  725. elif (
  726. fullname in self.objects
  727. and self.objects[fullname].objtype in objtypes
  728. ):
  729. names = [fullname]
  730. else:
  731. # exact match wasn't found; e.g. we are searching for
  732. # `query-block` from a different (or no) module.
  733. searchname = "." + name
  734. names = [
  735. oname
  736. for oname in self.objects
  737. if oname.endswith(searchname)
  738. and self.objects[oname].objtype in objtypes
  739. ]
  740. matches = [(oname, self.objects[oname]) for oname in names]
  741. if len(matches) > 1:
  742. matches = [m for m in matches if not m[1].aliased]
  743. return matches
  744. def resolve_xref(
  745. self,
  746. env: BuildEnvironment,
  747. fromdocname: str,
  748. builder: Builder,
  749. typ: str,
  750. target: str,
  751. node: pending_xref,
  752. contnode: Element,
  753. ) -> nodes.reference | None:
  754. modname = node.get("qapi:module")
  755. matches = self.find_obj(modname, target, typ)
  756. if not matches:
  757. # Normally, we could pass warn_dangling=True to QAPIXRefRole(),
  758. # but that will trigger on references to these built-in types,
  759. # which we'd like to ignore instead.
  760. # Take care of that warning here instead, so long as the
  761. # reference isn't to one of our built-in core types.
  762. if target not in (
  763. "string",
  764. "number",
  765. "int",
  766. "boolean",
  767. "null",
  768. "value",
  769. "q_empty",
  770. ):
  771. logger.warning(
  772. __("qapi:%s reference target not found: %r"),
  773. typ,
  774. target,
  775. type="ref",
  776. subtype="qapi",
  777. location=node,
  778. )
  779. return None
  780. if len(matches) > 1:
  781. logger.warning(
  782. __("more than one target found for cross-reference %r: %s"),
  783. target,
  784. ", ".join(match[0] for match in matches),
  785. type="ref",
  786. subtype="qapi",
  787. location=node,
  788. )
  789. name, obj = matches[0]
  790. return make_refnode(
  791. builder, fromdocname, obj.docname, obj.node_id, contnode, name
  792. )
  793. def resolve_any_xref(
  794. self,
  795. env: BuildEnvironment,
  796. fromdocname: str,
  797. builder: Builder,
  798. target: str,
  799. node: pending_xref,
  800. contnode: Element,
  801. ) -> List[Tuple[str, nodes.reference]]:
  802. results: List[Tuple[str, nodes.reference]] = []
  803. matches = self.find_obj(node.get("qapi:module"), target, None)
  804. for name, obj in matches:
  805. rolename = self.role_for_objtype(obj.objtype)
  806. assert rolename is not None
  807. role = f"qapi:{rolename}"
  808. refnode = make_refnode(
  809. builder, fromdocname, obj.docname, obj.node_id, contnode, name
  810. )
  811. results.append((role, refnode))
  812. return results
  813. def setup(app: Sphinx) -> Dict[str, Any]:
  814. app.setup_extension("sphinx.directives")
  815. app.add_config_value(
  816. "qapi_allowed_fields",
  817. set(),
  818. "env", # Setting impacts parsing phase
  819. types=set,
  820. )
  821. app.add_domain(QAPIDomain)
  822. return {
  823. "version": "1.0",
  824. "env_version": 1,
  825. "parallel_read_safe": True,
  826. "parallel_write_safe": True,
  827. }