qapi_domain.py 28 KB

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