qapi_domain.py 28 KB

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