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. 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. for cur_doc in self.get_doc(info):
  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(self, info: QAPISourceInfo) -> List['QAPIDoc']:
  362. if self.val != '##':
  363. raise QAPIParseError(
  364. self, "junk after '##' at start of documentation comment")
  365. docs = []
  366. cur_doc = QAPIDoc(self, info)
  367. self.accept(False)
  368. while self.tok == '#':
  369. assert isinstance(self.val, str)
  370. if self.val.startswith('##'):
  371. # End of doc comment
  372. if self.val != '##':
  373. raise QAPIParseError(
  374. self,
  375. "junk after '##' at end of documentation comment")
  376. cur_doc.end_comment()
  377. docs.append(cur_doc)
  378. self.accept()
  379. return docs
  380. if self.val.startswith('# ='):
  381. if cur_doc.symbol:
  382. raise QAPIParseError(
  383. self,
  384. "unexpected '=' markup in definition documentation")
  385. if cur_doc.body.text:
  386. raise QAPIParseError(
  387. self,
  388. "'=' heading must come first in a comment block")
  389. cur_doc.append(self.val)
  390. self.accept(False)
  391. raise QAPIParseError(self, "documentation comment must end with '##'")
  392. class QAPIDoc:
  393. """
  394. A documentation comment block, either definition or free-form
  395. Definition documentation blocks consist of
  396. * a body section: one line naming the definition, followed by an
  397. overview (any number of lines)
  398. * argument sections: a description of each argument (for commands
  399. and events) or member (for structs, unions and alternates)
  400. * features sections: a description of each feature flag
  401. * additional (non-argument) sections, possibly tagged
  402. Free-form documentation blocks consist only of a body section.
  403. """
  404. class Section:
  405. # pylint: disable=too-few-public-methods
  406. def __init__(self, parser: QAPISchemaParser,
  407. tag: Optional[str] = None):
  408. # section source info, i.e. where it begins
  409. self.info = parser.info
  410. # parser, for error messages about indentation
  411. self._parser = parser
  412. # section tag, if any ('Returns', '@name', ...)
  413. self.tag = tag
  414. # section text without tag
  415. self.text = ''
  416. # indentation to strip (None means indeterminate)
  417. self._indent = None if self.tag else 0
  418. def append(self, line: str) -> None:
  419. line = line.rstrip()
  420. if line:
  421. indent = must_match(r'\s*', line).end()
  422. if self._indent is None:
  423. # indeterminate indentation
  424. if self.text != '':
  425. # non-blank, non-first line determines indentation
  426. if indent == 0:
  427. raise QAPIParseError(
  428. self._parser, "line needs to be indented")
  429. self._indent = indent
  430. elif indent < self._indent:
  431. raise QAPIParseError(
  432. self._parser,
  433. "unexpected de-indent (expected at least %d spaces)" %
  434. self._indent)
  435. line = line[self._indent:]
  436. self.text += line + '\n'
  437. class ArgSection(Section):
  438. def __init__(self, parser: QAPISchemaParser,
  439. tag: str):
  440. super().__init__(parser, tag)
  441. self.member: Optional['QAPISchemaMember'] = None
  442. def connect(self, member: 'QAPISchemaMember') -> None:
  443. self.member = member
  444. class NullSection(Section):
  445. """
  446. Immutable dummy section for use at the end of a doc block.
  447. """
  448. # pylint: disable=too-few-public-methods
  449. def append(self, line: str) -> None:
  450. assert False, "Text appended after end_comment() called."
  451. def __init__(self, parser: QAPISchemaParser, info: QAPISourceInfo):
  452. # self._parser is used to report errors with QAPIParseError. The
  453. # resulting error position depends on the state of the parser.
  454. # It happens to be the beginning of the comment. More or less
  455. # servicable, but action at a distance.
  456. self._parser = parser
  457. self.info = info
  458. self.symbol: Optional[str] = None
  459. self.body = QAPIDoc.Section(parser)
  460. # dicts mapping parameter/feature names to their ArgSection
  461. self.args: Dict[str, QAPIDoc.ArgSection] = OrderedDict()
  462. self.features: Dict[str, QAPIDoc.ArgSection] = OrderedDict()
  463. self.sections: List[QAPIDoc.Section] = []
  464. # the current section
  465. self._section = self.body
  466. self._append_line = self._append_body_line
  467. def has_section(self, tag: str) -> bool:
  468. """Return True if we have a section with this tag."""
  469. for i in self.sections:
  470. if i.tag == tag:
  471. return True
  472. return False
  473. def append(self, line: str) -> None:
  474. """
  475. Parse a comment line and add it to the documentation.
  476. The way that the line is dealt with depends on which part of
  477. the documentation we're parsing right now:
  478. * The body section: ._append_line is ._append_body_line
  479. * An argument section: ._append_line is ._append_args_line
  480. * A features section: ._append_line is ._append_features_line
  481. * An additional section: ._append_line is ._append_various_line
  482. """
  483. line = line[1:]
  484. if not line:
  485. self._append_freeform(line)
  486. return
  487. if line[0] != ' ':
  488. raise QAPIParseError(self._parser, "missing space after #")
  489. line = line[1:]
  490. self._append_line(line)
  491. def end_comment(self) -> None:
  492. self._switch_section(QAPIDoc.NullSection(self._parser))
  493. @staticmethod
  494. def _match_at_name_colon(string: str) -> Optional[Match[str]]:
  495. return re.match(r'@([^:]*): *', string)
  496. @staticmethod
  497. def _match_section_tag(string: str) -> Optional[Match[str]]:
  498. return re.match(r'(Returns|Since|Notes?|Examples?|TODO): *', string)
  499. def _append_body_line(self, line: str) -> None:
  500. """
  501. Process a line of documentation text in the body section.
  502. If this a symbol line and it is the section's first line, this
  503. is a definition documentation block for that symbol.
  504. If it's a definition documentation block, another symbol line
  505. begins the argument section for the argument named by it, and
  506. a section tag begins an additional section. Start that
  507. section and append the line to it.
  508. Else, append the line to the current section.
  509. """
  510. # FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
  511. # recognized, and get silently treated as ordinary text
  512. if not self.symbol and not self.body.text and line.startswith('@'):
  513. if not line.endswith(':'):
  514. raise QAPIParseError(self._parser, "line should end with ':'")
  515. self.symbol = line[1:-1]
  516. # Invalid names are not checked here, but the name provided MUST
  517. # match the following definition, which *is* validated in expr.py.
  518. if not self.symbol:
  519. raise QAPIParseError(
  520. self._parser, "name required after '@'")
  521. elif self.symbol:
  522. # This is a definition documentation block
  523. if self._match_at_name_colon(line):
  524. self._append_line = self._append_args_line
  525. self._append_args_line(line)
  526. elif line == 'Features:':
  527. self._append_line = self._append_features_line
  528. elif self._match_section_tag(line):
  529. self._append_line = self._append_various_line
  530. self._append_various_line(line)
  531. else:
  532. self._append_freeform(line)
  533. else:
  534. # This is a free-form documentation block
  535. self._append_freeform(line)
  536. def _append_args_line(self, line: str) -> None:
  537. """
  538. Process a line of documentation text in an argument section.
  539. A symbol line begins the next argument section, a section tag
  540. section or a non-indented line after a blank line begins an
  541. additional section. Start that section and append the line to
  542. it.
  543. Else, append the line to the current section.
  544. """
  545. match = self._match_at_name_colon(line)
  546. if match:
  547. line = line[match.end():]
  548. self._start_args_section(match.group(1))
  549. elif self._match_section_tag(line):
  550. self._append_line = self._append_various_line
  551. self._append_various_line(line)
  552. return
  553. elif (self._section.text.endswith('\n\n')
  554. and line and not line[0].isspace()):
  555. if line == 'Features:':
  556. self._append_line = self._append_features_line
  557. else:
  558. self._start_section()
  559. self._append_line = self._append_various_line
  560. self._append_various_line(line)
  561. return
  562. self._append_freeform(line)
  563. def _append_features_line(self, line: str) -> None:
  564. match = self._match_at_name_colon(line)
  565. if match:
  566. line = line[match.end():]
  567. self._start_features_section(match.group(1))
  568. elif self._match_section_tag(line):
  569. self._append_line = self._append_various_line
  570. self._append_various_line(line)
  571. return
  572. elif (self._section.text.endswith('\n\n')
  573. and line and not line[0].isspace()):
  574. self._start_section()
  575. self._append_line = self._append_various_line
  576. self._append_various_line(line)
  577. return
  578. self._append_freeform(line)
  579. def _append_various_line(self, line: str) -> None:
  580. """
  581. Process a line of documentation text in an additional section.
  582. A symbol line is an error.
  583. A section tag begins an additional section. Start that
  584. section and append the line to it.
  585. Else, append the line to the current section.
  586. """
  587. match = self._match_at_name_colon(line)
  588. if match:
  589. raise QAPIParseError(self._parser,
  590. "description of '@%s:' follows a section"
  591. % match.group(1))
  592. match = self._match_section_tag(line)
  593. if match:
  594. line = line[match.end():]
  595. self._start_section(match.group(1))
  596. self._append_freeform(line)
  597. def _start_symbol_section(
  598. self,
  599. symbols_dict: Dict[str, 'QAPIDoc.ArgSection'],
  600. name: str) -> None:
  601. # FIXME invalid names other than the empty string aren't flagged
  602. if not name:
  603. raise QAPIParseError(self._parser, "invalid parameter name")
  604. if name in symbols_dict:
  605. raise QAPIParseError(self._parser,
  606. "'%s' parameter name duplicated" % name)
  607. assert not self.sections
  608. new_section = QAPIDoc.ArgSection(self._parser, '@' + name)
  609. self._switch_section(new_section)
  610. symbols_dict[name] = new_section
  611. def _start_args_section(self, name: str) -> None:
  612. self._start_symbol_section(self.args, name)
  613. def _start_features_section(self, name: str) -> None:
  614. self._start_symbol_section(self.features, name)
  615. def _start_section(self, tag: Optional[str] = None) -> None:
  616. if tag in ('Returns', 'Since') and self.has_section(tag):
  617. raise QAPIParseError(self._parser,
  618. "duplicated '%s' section" % tag)
  619. new_section = QAPIDoc.Section(self._parser, tag)
  620. self._switch_section(new_section)
  621. self.sections.append(new_section)
  622. def _switch_section(self, new_section: 'QAPIDoc.Section') -> None:
  623. text = self._section.text = self._section.text.strip('\n')
  624. # Only the 'body' section is allowed to have an empty body.
  625. # All other sections, including anonymous ones, must have text.
  626. if self._section != self.body and not text:
  627. # We do not create anonymous sections unless there is
  628. # something to put in them; this is a parser bug.
  629. assert self._section.tag
  630. raise QAPISemError(
  631. self._section.info,
  632. "text required after '%s:'" % self._section.tag)
  633. self._section = new_section
  634. def _append_freeform(self, line: str) -> None:
  635. match = re.match(r'(@\S+:)', line)
  636. if match:
  637. raise QAPIParseError(self._parser,
  638. "'%s' not allowed in free-form documentation"
  639. % match.group(1))
  640. self._section.append(line)
  641. def connect_member(self, member: 'QAPISchemaMember') -> None:
  642. if member.name not in self.args:
  643. if self.symbol not in member.info.pragma.documentation_exceptions:
  644. raise QAPISemError(member.info,
  645. "%s '%s' lacks documentation"
  646. % (member.role, member.name))
  647. self.args[member.name] = QAPIDoc.ArgSection(self._parser,
  648. '@' + member.name)
  649. self.args[member.name].connect(member)
  650. def connect_feature(self, feature: 'QAPISchemaFeature') -> None:
  651. if feature.name not in self.features:
  652. raise QAPISemError(feature.info,
  653. "feature '%s' lacks documentation"
  654. % feature.name)
  655. self.features[feature.name].connect(feature)
  656. def check_expr(self, expr: QAPIExpression) -> None:
  657. if 'command' not in expr:
  658. sec = next((sec for sec in self.sections
  659. if sec.tag == 'Returns'),
  660. None)
  661. if sec:
  662. raise QAPISemError(sec.info,
  663. "'Returns:' is only valid for commands")
  664. def check(self) -> None:
  665. def check_args_section(
  666. args: Dict[str, QAPIDoc.ArgSection], what: str
  667. ) -> None:
  668. bogus = [name for name, section in args.items()
  669. if not section.member]
  670. if bogus:
  671. raise QAPISemError(
  672. args[bogus[0]].info,
  673. "documented %s%s '%s' %s not exist" % (
  674. what,
  675. "s" if len(bogus) > 1 else "",
  676. "', '".join(bogus),
  677. "do" if len(bogus) > 1 else "does"
  678. ))
  679. check_args_section(self.args, 'member')
  680. check_args_section(self.features, 'feature')