parser.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747
  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. from collections import OrderedDict
  17. import os
  18. import re
  19. from typing import (
  20. TYPE_CHECKING,
  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, object]):
  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(OrderedDict({'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] = OrderedDict()
  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[indent:])
  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[indent:])
  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(self, 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(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(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|Since|Notes?|Examples?|TODO): *',
  486. line):
  487. # tagged section
  488. doc.new_tagged_section(match.group(1))
  489. text = line[match.end():]
  490. if text:
  491. doc.append_line(text)
  492. line = self.get_doc_indented(doc)
  493. no_more_args = True
  494. elif line.startswith('='):
  495. raise QAPIParseError(
  496. self,
  497. "unexpected '=' markup in definition documentation")
  498. else:
  499. # tag-less paragraph
  500. doc.ensure_untagged_section()
  501. doc.append_line(line)
  502. line = self.get_doc_paragraph(doc)
  503. else:
  504. # Free-form documentation
  505. doc = QAPIDoc(self, info)
  506. doc.ensure_untagged_section()
  507. first = True
  508. while line is not None:
  509. if match := self._match_at_name_colon(line):
  510. raise QAPIParseError(
  511. self,
  512. "'@%s:' not allowed in free-form documentation"
  513. % match.group(1))
  514. if line.startswith('='):
  515. if not first:
  516. raise QAPIParseError(
  517. self,
  518. "'=' heading must come first in a comment block")
  519. doc.append_line(line)
  520. self.accept(False)
  521. line = self.get_doc_line()
  522. first = False
  523. self.accept(False)
  524. doc.end()
  525. return doc
  526. class QAPIDoc:
  527. """
  528. A documentation comment block, either definition or free-form
  529. Definition documentation blocks consist of
  530. * a body section: one line naming the definition, followed by an
  531. overview (any number of lines)
  532. * argument sections: a description of each argument (for commands
  533. and events) or member (for structs, unions and alternates)
  534. * features sections: a description of each feature flag
  535. * additional (non-argument) sections, possibly tagged
  536. Free-form documentation blocks consist only of a body section.
  537. """
  538. class Section:
  539. def __init__(self, parser: QAPISchemaParser,
  540. tag: Optional[str] = None):
  541. # section source info, i.e. where it begins
  542. self.info = parser.info
  543. # parser, for error messages about indentation
  544. self._parser = parser
  545. # section tag, if any ('Returns', '@name', ...)
  546. self.tag = tag
  547. # section text without tag
  548. self.text = ''
  549. def append_line(self, line: str) -> None:
  550. self.text += line + '\n'
  551. class ArgSection(Section):
  552. def __init__(self, parser: QAPISchemaParser,
  553. tag: str):
  554. super().__init__(parser, tag)
  555. self.member: Optional['QAPISchemaMember'] = None
  556. def connect(self, member: 'QAPISchemaMember') -> None:
  557. self.member = member
  558. def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo,
  559. symbol: Optional[str] = None):
  560. # self._parser is used to report errors with QAPIParseError. The
  561. # resulting error position depends on the state of the parser.
  562. # It happens to be the beginning of the comment. More or less
  563. # servicable, but action at a distance.
  564. self._parser = parser
  565. # info points to the doc comment block's first line
  566. self.info = info
  567. # definition doc's symbol, None for free-form doc
  568. self.symbol: Optional[str] = symbol
  569. # the sections in textual order
  570. self.all_sections: List[QAPIDoc.Section] = [QAPIDoc.Section(parser)]
  571. # the body section
  572. self.body: Optional[QAPIDoc.Section] = self.all_sections[0]
  573. # dicts mapping parameter/feature names to their description
  574. self.args: Dict[str, QAPIDoc.ArgSection] = {}
  575. self.features: Dict[str, QAPIDoc.ArgSection] = {}
  576. # sections other than .body, .args, .features
  577. self.sections: List[QAPIDoc.Section] = []
  578. def end(self) -> None:
  579. for section in self.all_sections:
  580. section.text = section.text.strip('\n')
  581. if section.tag is not None and section.text == '':
  582. raise QAPISemError(
  583. section.info, "text required after '%s:'" % section.tag)
  584. def ensure_untagged_section(self) -> None:
  585. if self.all_sections and not self.all_sections[-1].tag:
  586. # extend current section
  587. self.all_sections[-1].text += '\n'
  588. return
  589. # start new section
  590. section = self.Section(self._parser)
  591. self.sections.append(section)
  592. self.all_sections.append(section)
  593. def new_tagged_section(self, tag: str) -> None:
  594. if tag in ('Returns', 'Since'):
  595. for section in self.all_sections:
  596. if isinstance(section, self.ArgSection):
  597. continue
  598. if section.tag == tag:
  599. raise QAPIParseError(
  600. self._parser, "duplicated '%s' section" % tag)
  601. section = self.Section(self._parser, tag)
  602. self.sections.append(section)
  603. self.all_sections.append(section)
  604. def _new_description(self, name: str,
  605. desc: Dict[str, ArgSection]) -> None:
  606. if not name:
  607. raise QAPIParseError(self._parser, "invalid parameter name")
  608. if name in desc:
  609. raise QAPIParseError(self._parser,
  610. "'%s' parameter name duplicated" % name)
  611. section = self.ArgSection(self._parser, '@' + name)
  612. self.all_sections.append(section)
  613. desc[name] = section
  614. def new_argument(self, name: str) -> None:
  615. self._new_description(name, self.args)
  616. def new_feature(self, name: str) -> None:
  617. self._new_description(name, self.features)
  618. def append_line(self, line: str) -> None:
  619. self.all_sections[-1].append_line(line)
  620. def connect_member(self, member: 'QAPISchemaMember') -> None:
  621. if member.name not in self.args:
  622. if self.symbol not in member.info.pragma.documentation_exceptions:
  623. raise QAPISemError(member.info,
  624. "%s '%s' lacks documentation"
  625. % (member.role, member.name))
  626. self.args[member.name] = QAPIDoc.ArgSection(
  627. self._parser, '@' + member.name)
  628. self.args[member.name].connect(member)
  629. def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
  630. if feature.name not in self.features:
  631. raise QAPISemError(feature.info,
  632. "feature '%s' lacks documentation"
  633. % feature.name)
  634. self.features[feature.name].connect(feature)
  635. def check_expr(self, expr: QAPIExpression) -> None:
  636. if 'command' not in expr:
  637. sec = next((sec for sec in self.sections
  638. if sec.tag == 'Returns'),
  639. None)
  640. if sec:
  641. raise QAPISemError(sec.info,
  642. "'Returns:' is only valid for commands")
  643. def check(self) -> None:
  644. def check_args_section(
  645. args: Dict[str, QAPIDoc.ArgSection], what: str
  646. ) -> None:
  647. bogus = [name for name, section in args.items()
  648. if not section.member]
  649. if bogus:
  650. raise QAPISemError(
  651. args[bogus[0]].info,
  652. "documented %s%s '%s' %s not exist" % (
  653. what,
  654. "s" if len(bogus) > 1 else "",
  655. "', '".join(bogus),
  656. "do" if len(bogus) > 1 else "does"
  657. ))
  658. check_args_section(self.args, 'member')
  659. check_args_section(self.features, 'feature')