qapi_domain.py 30 KB

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