parser.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. # -*- coding: utf-8 -*-
  2. #
  3. # QAPI schema parser
  4. #
  5. # Copyright IBM, Corp. 2011
  6. # Copyright (c) 2013-2019 Red Hat Inc.
  7. #
  8. # Authors:
  9. # Anthony Liguori <aliguori@us.ibm.com>
  10. # Markus Armbruster <armbru@redhat.com>
  11. # Marc-André Lureau <marcandre.lureau@redhat.com>
  12. # Kevin Wolf <kwolf@redhat.com>
  13. #
  14. # This work is licensed under the terms of the GNU GPL, version 2.
  15. # See the COPYING file in the top-level directory.
  16. import os
  17. import re
  18. from typing import (
  19. TYPE_CHECKING,
  20. Any,
  21. Dict,
  22. List,
  23. Mapping,
  24. Match,
  25. Optional,
  26. Set,
  27. Union,
  28. )
  29. from .common import must_match
  30. from .error import QAPISemError, QAPISourceError
  31. from .source import QAPISourceInfo
  32. if TYPE_CHECKING:
  33. # pylint: disable=cyclic-import
  34. # TODO: Remove cycle. [schema -> expr -> parser -> schema]
  35. from .schema import QAPISchemaFeature, QAPISchemaMember
  36. # Return value alias for get_expr().
  37. _ExprValue = Union[List[object], Dict[str, object], str, bool]
  38. class QAPIExpression(Dict[str, Any]):
  39. # pylint: disable=too-few-public-methods
  40. def __init__(self,
  41. data: Mapping[str, object],
  42. info: QAPISourceInfo,
  43. doc: Optional['QAPIDoc'] = None):
  44. super().__init__(data)
  45. self.info = info
  46. self.doc: Optional['QAPIDoc'] = doc
  47. class QAPIParseError(QAPISourceError):
  48. """Error class for all QAPI schema parsing errors."""
  49. def __init__(self, parser: 'QAPISchemaParser', msg: str):
  50. col = 1
  51. for ch in parser.src[parser.line_pos:parser.pos]:
  52. if ch == '\t':
  53. col = (col + 7) % 8 + 1
  54. else:
  55. col += 1
  56. super().__init__(parser.info, msg, col)
  57. class QAPISchemaParser:
  58. """
  59. Parse QAPI schema source.
  60. Parse a JSON-esque schema file and process directives. See
  61. qapi-code-gen.rst section "Schema Syntax" for the exact syntax.
  62. Grammatical validation is handled later by `expr.check_exprs()`.
  63. :param fname: Source file name.
  64. :param previously_included:
  65. The absolute names of previously included source files,
  66. if being invoked from another parser.
  67. :param incl_info:
  68. `QAPISourceInfo` belonging to the parent module.
  69. ``None`` implies this is the root module.
  70. :ivar exprs: Resulting parsed expressions.
  71. :ivar docs: Resulting parsed documentation blocks.
  72. :raise OSError: For problems reading the root schema document.
  73. :raise QAPIError: For errors in the schema source.
  74. """
  75. def __init__(self,
  76. fname: str,
  77. previously_included: Optional[Set[str]] = None,
  78. incl_info: Optional[QAPISourceInfo] = None):
  79. self._fname = fname
  80. self._included = previously_included or set()
  81. self._included.add(os.path.abspath(self._fname))
  82. self.src = ''
  83. # Lexer state (see `accept` for details):
  84. self.info = QAPISourceInfo(self._fname, incl_info)
  85. self.tok: Union[None, str] = None
  86. self.pos = 0
  87. self.cursor = 0
  88. self.val: Optional[Union[bool, str]] = None
  89. self.line_pos = 0
  90. # Parser output:
  91. self.exprs: List[QAPIExpression] = []
  92. self.docs: List[QAPIDoc] = []
  93. # Showtime!
  94. self._parse()
  95. def _parse(self) -> None:
  96. """
  97. Parse the QAPI schema document.
  98. :return: None. Results are stored in ``.exprs`` and ``.docs``.
  99. """
  100. cur_doc = None
  101. # May raise OSError; allow the caller to handle it.
  102. with open(self._fname, 'r', encoding='utf-8') as fp:
  103. self.src = fp.read()
  104. if self.src == '' or self.src[-1] != '\n':
  105. self.src += '\n'
  106. # Prime the lexer:
  107. self.accept()
  108. # Parse until done:
  109. while self.tok is not None:
  110. info = self.info
  111. if self.tok == '#':
  112. self.reject_expr_doc(cur_doc)
  113. cur_doc = self.get_doc()
  114. self.docs.append(cur_doc)
  115. continue
  116. expr = self.get_expr()
  117. if not isinstance(expr, dict):
  118. raise QAPISemError(
  119. info, "top-level expression must be an object")
  120. if 'include' in expr:
  121. self.reject_expr_doc(cur_doc)
  122. if len(expr) != 1:
  123. raise QAPISemError(info, "invalid 'include' directive")
  124. include = expr['include']
  125. if not isinstance(include, str):
  126. raise QAPISemError(info,
  127. "value of 'include' must be a string")
  128. incl_fname = os.path.join(os.path.dirname(self._fname),
  129. include)
  130. self._add_expr({'include': incl_fname}, info)
  131. exprs_include = self._include(include, info, incl_fname,
  132. self._included)
  133. if exprs_include:
  134. self.exprs.extend(exprs_include.exprs)
  135. self.docs.extend(exprs_include.docs)
  136. elif "pragma" in expr:
  137. self.reject_expr_doc(cur_doc)
  138. if len(expr) != 1:
  139. raise QAPISemError(info, "invalid 'pragma' directive")
  140. pragma = expr['pragma']
  141. if not isinstance(pragma, dict):
  142. raise QAPISemError(
  143. info, "value of 'pragma' must be an object")
  144. for name, value in pragma.items():
  145. self._pragma(name, value, info)
  146. else:
  147. if cur_doc and not cur_doc.symbol:
  148. raise QAPISemError(
  149. cur_doc.info, "definition documentation required")
  150. self._add_expr(expr, info, cur_doc)
  151. cur_doc = None
  152. self.reject_expr_doc(cur_doc)
  153. def _add_expr(self, expr: Mapping[str, object],
  154. info: QAPISourceInfo,
  155. doc: Optional['QAPIDoc'] = None) -> None:
  156. self.exprs.append(QAPIExpression(expr, info, doc))
  157. @staticmethod
  158. def reject_expr_doc(doc: Optional['QAPIDoc']) -> None:
  159. if doc and doc.symbol:
  160. raise QAPISemError(
  161. doc.info,
  162. "documentation for '%s' is not followed by the definition"
  163. % doc.symbol)
  164. @staticmethod
  165. def _include(include: str,
  166. info: QAPISourceInfo,
  167. incl_fname: str,
  168. previously_included: Set[str]
  169. ) -> Optional['QAPISchemaParser']:
  170. incl_abs_fname = os.path.abspath(incl_fname)
  171. # catch inclusion cycle
  172. inf: Optional[QAPISourceInfo] = info
  173. while inf:
  174. if incl_abs_fname == os.path.abspath(inf.fname):
  175. raise QAPISemError(info, "inclusion loop for %s" % include)
  176. inf = inf.parent
  177. # skip multiple include of the same file
  178. if incl_abs_fname in previously_included:
  179. return None
  180. try:
  181. return QAPISchemaParser(incl_fname, previously_included, info)
  182. except OSError as err:
  183. raise QAPISemError(
  184. info,
  185. f"can't read include file '{incl_fname}': {err.strerror}"
  186. ) from err
  187. @staticmethod
  188. def _pragma(name: str, value: object, info: QAPISourceInfo) -> None:
  189. def check_list_str(name: str, value: object) -> List[str]:
  190. if (not isinstance(value, list) or
  191. any(not isinstance(elt, str) for elt in value)):
  192. raise QAPISemError(
  193. info,
  194. "pragma %s must be a list of strings" % name)
  195. return value
  196. pragma = info.pragma
  197. if name == 'doc-required':
  198. if not isinstance(value, bool):
  199. raise QAPISemError(info,
  200. "pragma 'doc-required' must be boolean")
  201. pragma.doc_required = value
  202. elif name == 'command-name-exceptions':
  203. pragma.command_name_exceptions = check_list_str(name, value)
  204. elif name == 'command-returns-exceptions':
  205. pragma.command_returns_exceptions = check_list_str(name, value)
  206. elif name == 'documentation-exceptions':
  207. pragma.documentation_exceptions = check_list_str(name, value)
  208. elif name == 'member-name-exceptions':
  209. pragma.member_name_exceptions = check_list_str(name, value)
  210. else:
  211. raise QAPISemError(info, "unknown pragma '%s'" % name)
  212. def accept(self, skip_comment: bool = True) -> None:
  213. """
  214. Read and store the next token.
  215. :param skip_comment:
  216. When false, return COMMENT tokens ("#").
  217. This is used when reading documentation blocks.
  218. :return:
  219. None. Several instance attributes are updated instead:
  220. - ``.tok`` represents the token type. See below for values.
  221. - ``.info`` describes the token's source location.
  222. - ``.val`` is the token's value, if any. See below.
  223. - ``.pos`` is the buffer index of the first character of
  224. the token.
  225. * Single-character tokens:
  226. These are "{", "}", ":", ",", "[", and "]".
  227. ``.tok`` holds the single character and ``.val`` is None.
  228. * Multi-character tokens:
  229. * COMMENT:
  230. This token is not normally returned by the lexer, but it can
  231. be when ``skip_comment`` is False. ``.tok`` is "#", and
  232. ``.val`` is a string including all chars until end-of-line,
  233. including the "#" itself.
  234. * STRING:
  235. ``.tok`` is "'", the single quote. ``.val`` contains the
  236. string, excluding the surrounding quotes.
  237. * TRUE and FALSE:
  238. ``.tok`` is either "t" or "f", ``.val`` will be the
  239. corresponding bool value.
  240. * EOF:
  241. ``.tok`` and ``.val`` will both be None at EOF.
  242. """
  243. while True:
  244. self.tok = self.src[self.cursor]
  245. self.pos = self.cursor
  246. self.cursor += 1
  247. self.val = None
  248. if self.tok == '#':
  249. if self.src[self.cursor] == '#':
  250. # Start of doc comment
  251. skip_comment = False
  252. self.cursor = self.src.find('\n', self.cursor)
  253. if not skip_comment:
  254. self.val = self.src[self.pos:self.cursor]
  255. return
  256. elif self.tok in '{}:,[]':
  257. return
  258. elif self.tok == "'":
  259. # Note: we accept only printable ASCII
  260. string = ''
  261. esc = False
  262. while True:
  263. ch = self.src[self.cursor]
  264. self.cursor += 1
  265. if ch == '\n':
  266. raise QAPIParseError(self, "missing terminating \"'\"")
  267. if esc:
  268. # Note: we recognize only \\ because we have
  269. # no use for funny characters in strings
  270. if ch != '\\':
  271. raise QAPIParseError(self,
  272. "unknown escape \\%s" % ch)
  273. esc = False
  274. elif ch == '\\':
  275. esc = True
  276. continue
  277. elif ch == "'":
  278. self.val = string
  279. return
  280. if ord(ch) < 32 or ord(ch) >= 127:
  281. raise QAPIParseError(
  282. self, "funny character in string")
  283. string += ch
  284. elif self.src.startswith('true', self.pos):
  285. self.val = True
  286. self.cursor += 3
  287. return
  288. elif self.src.startswith('false', self.pos):
  289. self.val = False
  290. self.cursor += 4
  291. return
  292. elif self.tok == '\n':
  293. if self.cursor == len(self.src):
  294. self.tok = None
  295. return
  296. self.info = self.info.next_line()
  297. self.line_pos = self.cursor
  298. elif not self.tok.isspace():
  299. # Show up to next structural, whitespace or quote
  300. # character
  301. match = must_match('[^[\\]{}:,\\s\']+',
  302. self.src[self.cursor-1:])
  303. raise QAPIParseError(self, "stray '%s'" % match.group(0))
  304. def get_members(self) -> Dict[str, object]:
  305. expr: Dict[str, object] = {}
  306. if self.tok == '}':
  307. self.accept()
  308. return expr
  309. if self.tok != "'":
  310. raise QAPIParseError(self, "expected string or '}'")
  311. while True:
  312. key = self.val
  313. assert isinstance(key, str) # Guaranteed by tok == "'"
  314. self.accept()
  315. if self.tok != ':':
  316. raise QAPIParseError(self, "expected ':'")
  317. self.accept()
  318. if key in expr:
  319. raise QAPIParseError(self, "duplicate key '%s'" % key)
  320. expr[key] = self.get_expr()
  321. if self.tok == '}':
  322. self.accept()
  323. return expr
  324. if self.tok != ',':
  325. raise QAPIParseError(self, "expected ',' or '}'")
  326. self.accept()
  327. if self.tok != "'":
  328. raise QAPIParseError(self, "expected string")
  329. def get_values(self) -> List[object]:
  330. expr: List[object] = []
  331. if self.tok == ']':
  332. self.accept()
  333. return expr
  334. if self.tok not in tuple("{['tf"):
  335. raise QAPIParseError(
  336. self, "expected '{', '[', ']', string, or boolean")
  337. while True:
  338. expr.append(self.get_expr())
  339. if self.tok == ']':
  340. self.accept()
  341. return expr
  342. if self.tok != ',':
  343. raise QAPIParseError(self, "expected ',' or ']'")
  344. self.accept()
  345. def get_expr(self) -> _ExprValue:
  346. expr: _ExprValue
  347. if self.tok == '{':
  348. self.accept()
  349. expr = self.get_members()
  350. elif self.tok == '[':
  351. self.accept()
  352. expr = self.get_values()
  353. elif self.tok in tuple("'tf"):
  354. assert isinstance(self.val, (str, bool))
  355. expr = self.val
  356. self.accept()
  357. else:
  358. raise QAPIParseError(
  359. self, "expected '{', '[', string, or boolean")
  360. return expr
  361. def get_doc_line(self) -> Optional[str]:
  362. if self.tok != '#':
  363. raise QAPIParseError(
  364. self, "documentation comment must end with '##'")
  365. assert isinstance(self.val, str)
  366. if self.val.startswith('##'):
  367. # End of doc comment
  368. if self.val != '##':
  369. raise QAPIParseError(
  370. self, "junk after '##' at end of documentation comment")
  371. return None
  372. if self.val == '#':
  373. return ''
  374. if self.val[1] != ' ':
  375. raise QAPIParseError(self, "missing space after #")
  376. return self.val[2:].rstrip()
  377. @staticmethod
  378. def _match_at_name_colon(string: str) -> Optional[Match[str]]:
  379. return re.match(r'@([^:]*): *', string)
  380. def get_doc_indented(self, doc: 'QAPIDoc') -> Optional[str]:
  381. self.accept(False)
  382. line = self.get_doc_line()
  383. while line == '':
  384. doc.append_line(line)
  385. self.accept(False)
  386. line = self.get_doc_line()
  387. if line is None:
  388. return line
  389. indent = must_match(r'\s*', line).end()
  390. if not indent:
  391. return line
  392. doc.append_line(line)
  393. prev_line_blank = False
  394. while True:
  395. self.accept(False)
  396. line = self.get_doc_line()
  397. if line is None:
  398. return line
  399. if self._match_at_name_colon(line):
  400. return line
  401. cur_indent = must_match(r'\s*', line).end()
  402. if line != '' and cur_indent < indent:
  403. if prev_line_blank:
  404. return line
  405. raise QAPIParseError(
  406. self,
  407. "unexpected de-indent (expected at least %d spaces)" %
  408. indent)
  409. doc.append_line(line)
  410. prev_line_blank = True
  411. def get_doc_paragraph(self, doc: 'QAPIDoc') -> Optional[str]:
  412. while True:
  413. self.accept(False)
  414. line = self.get_doc_line()
  415. if line is None:
  416. return line
  417. if line == '':
  418. return line
  419. doc.append_line(line)
  420. def get_doc(self) -> 'QAPIDoc':
  421. if self.val != '##':
  422. raise QAPIParseError(
  423. self, "junk after '##' at start of documentation comment")
  424. info = self.info
  425. self.accept(False)
  426. line = self.get_doc_line()
  427. if line is not None and line.startswith('@'):
  428. # Definition documentation
  429. if not line.endswith(':'):
  430. raise QAPIParseError(self, "line should end with ':'")
  431. # Invalid names are not checked here, but the name
  432. # provided *must* match the following definition,
  433. # which *is* validated in expr.py.
  434. symbol = line[1:-1]
  435. if not symbol:
  436. raise QAPIParseError(self, "name required after '@'")
  437. doc = QAPIDoc(info, symbol)
  438. self.accept(False)
  439. line = self.get_doc_line()
  440. no_more_args = False
  441. while line is not None:
  442. # Blank lines
  443. while line == '':
  444. self.accept(False)
  445. line = self.get_doc_line()
  446. if line is None:
  447. break
  448. # Non-blank line, first of a section
  449. if line == 'Features:':
  450. if doc.features:
  451. raise QAPIParseError(
  452. self, "duplicated 'Features:' line")
  453. self.accept(False)
  454. line = self.get_doc_line()
  455. while line == '':
  456. self.accept(False)
  457. line = self.get_doc_line()
  458. while (line is not None
  459. and (match := self._match_at_name_colon(line))):
  460. doc.new_feature(self.info, match.group(1))
  461. text = line[match.end():]
  462. if text:
  463. doc.append_line(text)
  464. line = self.get_doc_indented(doc)
  465. if not doc.features:
  466. raise QAPIParseError(
  467. self, 'feature descriptions expected')
  468. no_more_args = True
  469. elif match := self._match_at_name_colon(line):
  470. # description
  471. if no_more_args:
  472. raise QAPIParseError(
  473. self,
  474. "description of '@%s:' follows a section"
  475. % match.group(1))
  476. while (line is not None
  477. and (match := self._match_at_name_colon(line))):
  478. doc.new_argument(self.info, match.group(1))
  479. text = line[match.end():]
  480. if text:
  481. doc.append_line(text)
  482. line = self.get_doc_indented(doc)
  483. no_more_args = True
  484. elif match := re.match(
  485. r'(Returns|Errors|Since|Notes?|Examples?|TODO)'
  486. r'(?!::): *',
  487. line,
  488. ):
  489. # tagged section
  490. # Note: "sections" with two colons are left alone as
  491. # rST markup and not interpreted as a section heading.
  492. # TODO: Remove these errors sometime in 2025 or so
  493. # after we've fully transitioned to the new qapidoc
  494. # generator.
  495. # See commit message for more markup suggestions O:-)
  496. if 'Note' in match.group(1):
  497. emsg = (
  498. f"The '{match.group(1)}' section is no longer "
  499. "supported. Please use rST's '.. note::' or "
  500. "'.. admonition:: notes' directives, or another "
  501. "suitable admonition instead."
  502. )
  503. raise QAPIParseError(self, emsg)
  504. if 'Example' in match.group(1):
  505. emsg = (
  506. f"The '{match.group(1)}' section is no longer "
  507. "supported. Please use the '.. qmp-example::' "
  508. "directive, or other suitable markup instead."
  509. )
  510. raise QAPIParseError(self, emsg)
  511. doc.new_tagged_section(self.info, match.group(1))
  512. text = line[match.end():]
  513. if text:
  514. doc.append_line(text)
  515. line = self.get_doc_indented(doc)
  516. no_more_args = True
  517. elif line.startswith('='):
  518. raise QAPIParseError(
  519. self,
  520. "unexpected '=' markup in definition documentation")
  521. else:
  522. # tag-less paragraph
  523. doc.ensure_untagged_section(self.info)
  524. doc.append_line(line)
  525. line = self.get_doc_paragraph(doc)
  526. else:
  527. # Free-form documentation
  528. doc = QAPIDoc(info)
  529. doc.ensure_untagged_section(self.info)
  530. first = True
  531. while line is not None:
  532. if match := self._match_at_name_colon(line):
  533. raise QAPIParseError(
  534. self,
  535. "'@%s:' not allowed in free-form documentation"
  536. % match.group(1))
  537. if line.startswith('='):
  538. if not first:
  539. raise QAPIParseError(
  540. self,
  541. "'=' heading must come first in a comment block")
  542. doc.append_line(line)
  543. self.accept(False)
  544. line = self.get_doc_line()
  545. first = False
  546. self.accept()
  547. doc.end()
  548. return doc
  549. class QAPIDoc:
  550. """
  551. A documentation comment block, either definition or free-form
  552. Definition documentation blocks consist of
  553. * a body section: one line naming the definition, followed by an
  554. overview (any number of lines)
  555. * argument sections: a description of each argument (for commands
  556. and events) or member (for structs, unions and alternates)
  557. * features sections: a description of each feature flag
  558. * additional (non-argument) sections, possibly tagged
  559. Free-form documentation blocks consist only of a body section.
  560. """
  561. class Section:
  562. # pylint: disable=too-few-public-methods
  563. def __init__(self, info: QAPISourceInfo,
  564. tag: Optional[str] = None):
  565. # section source info, i.e. where it begins
  566. self.info = info
  567. # section tag, if any ('Returns', '@name', ...)
  568. self.tag = tag
  569. # section text without tag
  570. self.text = ''
  571. def append_line(self, line: str) -> None:
  572. self.text += line + '\n'
  573. class ArgSection(Section):
  574. def __init__(self, info: QAPISourceInfo, tag: str):
  575. super().__init__(info, tag)
  576. self.member: Optional['QAPISchemaMember'] = None
  577. def connect(self, member: 'QAPISchemaMember') -> None:
  578. self.member = member
  579. def __init__(self, info: QAPISourceInfo, symbol: Optional[str] = None):
  580. # info points to the doc comment block's first line
  581. self.info = info
  582. # definition doc's symbol, None for free-form doc
  583. self.symbol: Optional[str] = symbol
  584. # the sections in textual order
  585. self.all_sections: List[QAPIDoc.Section] = [QAPIDoc.Section(info)]
  586. # the body section
  587. self.body: Optional[QAPIDoc.Section] = self.all_sections[0]
  588. # dicts mapping parameter/feature names to their description
  589. self.args: Dict[str, QAPIDoc.ArgSection] = {}
  590. self.features: Dict[str, QAPIDoc.ArgSection] = {}
  591. # a command's "Returns" and "Errors" section
  592. self.returns: Optional[QAPIDoc.Section] = None
  593. self.errors: Optional[QAPIDoc.Section] = None
  594. # "Since" section
  595. self.since: Optional[QAPIDoc.Section] = None
  596. # sections other than .body, .args, .features
  597. self.sections: List[QAPIDoc.Section] = []
  598. def end(self) -> None:
  599. for section in self.all_sections:
  600. section.text = section.text.strip('\n')
  601. if section.tag is not None and section.text == '':
  602. raise QAPISemError(
  603. section.info, "text required after '%s:'" % section.tag)
  604. def ensure_untagged_section(self, info: QAPISourceInfo) -> None:
  605. if self.all_sections and not self.all_sections[-1].tag:
  606. # extend current section
  607. section = self.all_sections[-1]
  608. if not section.text:
  609. # Section is empty so far; update info to start *here*.
  610. section.info = info
  611. section.text += '\n'
  612. return
  613. # start new section
  614. section = self.Section(info)
  615. self.sections.append(section)
  616. self.all_sections.append(section)
  617. def new_tagged_section(self, info: QAPISourceInfo, tag: str) -> None:
  618. section = self.Section(info, tag)
  619. if tag == 'Returns':
  620. if self.returns:
  621. raise QAPISemError(
  622. info, "duplicated '%s' section" % tag)
  623. self.returns = section
  624. elif tag == 'Errors':
  625. if self.errors:
  626. raise QAPISemError(
  627. info, "duplicated '%s' section" % tag)
  628. self.errors = section
  629. elif tag == 'Since':
  630. if self.since:
  631. raise QAPISemError(
  632. info, "duplicated '%s' section" % tag)
  633. self.since = section
  634. self.sections.append(section)
  635. self.all_sections.append(section)
  636. def _new_description(self, info: QAPISourceInfo, name: str,
  637. desc: Dict[str, ArgSection]) -> None:
  638. if not name:
  639. raise QAPISemError(info, "invalid parameter name")
  640. if name in desc:
  641. raise QAPISemError(info, "'%s' parameter name duplicated" % name)
  642. section = self.ArgSection(info, '@' + name)
  643. self.all_sections.append(section)
  644. desc[name] = section
  645. def new_argument(self, info: QAPISourceInfo, name: str) -> None:
  646. self._new_description(info, name, self.args)
  647. def new_feature(self, info: QAPISourceInfo, name: str) -> None:
  648. self._new_description(info, name, self.features)
  649. def append_line(self, line: str) -> None:
  650. self.all_sections[-1].append_line(line)
  651. def connect_member(self, member: 'QAPISchemaMember') -> None:
  652. if member.name not in self.args:
  653. assert member.info
  654. if self.symbol not in member.info.pragma.documentation_exceptions:
  655. raise QAPISemError(member.info,
  656. "%s '%s' lacks documentation"
  657. % (member.role, member.name))
  658. self.args[member.name] = QAPIDoc.ArgSection(
  659. self.info, '@' + member.name)
  660. self.args[member.name].connect(member)
  661. def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
  662. if feature.name not in self.features:
  663. raise QAPISemError(feature.info,
  664. "feature '%s' lacks documentation"
  665. % feature.name)
  666. self.features[feature.name].connect(feature)
  667. def check_expr(self, expr: QAPIExpression) -> None:
  668. if 'command' in expr:
  669. if self.returns and 'returns' not in expr:
  670. raise QAPISemError(
  671. self.returns.info,
  672. "'Returns' section, but command doesn't return anything")
  673. else:
  674. if self.returns:
  675. raise QAPISemError(
  676. self.returns.info,
  677. "'Returns' section is only valid for commands")
  678. if self.errors:
  679. raise QAPISemError(
  680. self.errors.info,
  681. "'Errors' section is only valid for commands")
  682. def check(self) -> None:
  683. def check_args_section(
  684. args: Dict[str, QAPIDoc.ArgSection], what: str
  685. ) -> None:
  686. bogus = [name for name, section in args.items()
  687. if not section.member]
  688. if bogus:
  689. raise QAPISemError(
  690. args[bogus[0]].info,
  691. "documented %s%s '%s' %s not exist" % (
  692. what,
  693. "s" if len(bogus) > 1 else "",
  694. "', '".join(bogus),
  695. "do" if len(bogus) > 1 else "does"
  696. ))
  697. check_args_section(self.args, 'member')
  698. check_args_section(self.features, 'feature')