parser.py 29 KB

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