2
0

qapi_domain.py 33 KB

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