parser.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772
  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. Dict,
  21. List,
  22. Optional,
  23. Set,
  24. Union,
  25. )
  26. from .common import must_match
  27. from .error import QAPISemError, QAPISourceError
  28. from .source import QAPISourceInfo
  29. # Return value alias for get_expr().
  30. _ExprValue = Union[List[object], Dict[str, object], str, bool]
  31. class QAPIParseError(QAPISourceError):
  32. """Error class for all QAPI schema parsing errors."""
  33. def __init__(self, parser: 'QAPISchemaParser', msg: str):
  34. col = 1
  35. for ch in parser.src[parser.line_pos:parser.pos]:
  36. if ch == '\t':
  37. col = (col + 7) % 8 + 1
  38. else:
  39. col += 1
  40. super().__init__(parser.info, msg, col)
  41. class QAPISchemaParser:
  42. """
  43. Parse QAPI schema source.
  44. Parse a JSON-esque schema file and process directives. See
  45. qapi-code-gen.txt section "Schema Syntax" for the exact syntax.
  46. Grammatical validation is handled later by `expr.check_exprs()`.
  47. :param fname: Source file name.
  48. :param previously_included:
  49. The absolute names of previously included source files,
  50. if being invoked from another parser.
  51. :param incl_info:
  52. `QAPISourceInfo` belonging to the parent module.
  53. ``None`` implies this is the root module.
  54. :ivar exprs: Resulting parsed expressions.
  55. :ivar docs: Resulting parsed documentation blocks.
  56. :raise OSError: For problems reading the root schema document.
  57. :raise QAPIError: For errors in the schema source.
  58. """
  59. def __init__(self,
  60. fname: str,
  61. previously_included: Optional[Set[str]] = None,
  62. incl_info: Optional[QAPISourceInfo] = None):
  63. self._fname = fname
  64. self._included = previously_included or set()
  65. self._included.add(os.path.abspath(self._fname))
  66. self.src = ''
  67. # Lexer state (see `accept` for details):
  68. self.info = QAPISourceInfo(self._fname, incl_info)
  69. self.tok: Union[None, str] = None
  70. self.pos = 0
  71. self.cursor = 0
  72. self.val: Optional[Union[bool, str]] = None
  73. self.line_pos = 0
  74. # Parser output:
  75. self.exprs: List[Dict[str, object]] = []
  76. self.docs: List[QAPIDoc] = []
  77. # Showtime!
  78. self._parse()
  79. def _parse(self) -> None:
  80. """
  81. Parse the QAPI schema document.
  82. :return: None. Results are stored in ``.exprs`` and ``.docs``.
  83. """
  84. cur_doc = None
  85. # May raise OSError; allow the caller to handle it.
  86. with open(self._fname, 'r', encoding='utf-8') as fp:
  87. self.src = fp.read()
  88. if self.src == '' or self.src[-1] != '\n':
  89. self.src += '\n'
  90. # Prime the lexer:
  91. self.accept()
  92. # Parse until done:
  93. while self.tok is not None:
  94. info = self.info
  95. if self.tok == '#':
  96. self.reject_expr_doc(cur_doc)
  97. for cur_doc in self.get_doc(info):
  98. self.docs.append(cur_doc)
  99. continue
  100. expr = self.get_expr()
  101. if not isinstance(expr, dict):
  102. raise QAPISemError(
  103. info, "top-level expression must be an object")
  104. if 'include' in expr:
  105. self.reject_expr_doc(cur_doc)
  106. if len(expr) != 1:
  107. raise QAPISemError(info, "invalid 'include' directive")
  108. include = expr['include']
  109. if not isinstance(include, str):
  110. raise QAPISemError(info,
  111. "value of 'include' must be a string")
  112. incl_fname = os.path.join(os.path.dirname(self._fname),
  113. include)
  114. self.exprs.append({'expr': {'include': incl_fname},
  115. 'info': info})
  116. exprs_include = self._include(include, info, incl_fname,
  117. self._included)
  118. if exprs_include:
  119. self.exprs.extend(exprs_include.exprs)
  120. self.docs.extend(exprs_include.docs)
  121. elif "pragma" in expr:
  122. self.reject_expr_doc(cur_doc)
  123. if len(expr) != 1:
  124. raise QAPISemError(info, "invalid 'pragma' directive")
  125. pragma = expr['pragma']
  126. if not isinstance(pragma, dict):
  127. raise QAPISemError(
  128. info, "value of 'pragma' must be an object")
  129. for name, value in pragma.items():
  130. self._pragma(name, value, info)
  131. else:
  132. expr_elem = {'expr': expr,
  133. 'info': info}
  134. if cur_doc:
  135. if not cur_doc.symbol:
  136. raise QAPISemError(
  137. cur_doc.info, "definition documentation required")
  138. expr_elem['doc'] = cur_doc
  139. self.exprs.append(expr_elem)
  140. cur_doc = None
  141. self.reject_expr_doc(cur_doc)
  142. @staticmethod
  143. def reject_expr_doc(doc: Optional['QAPIDoc']) -> None:
  144. if doc and doc.symbol:
  145. raise QAPISemError(
  146. doc.info,
  147. "documentation for '%s' is not followed by the definition"
  148. % doc.symbol)
  149. @staticmethod
  150. def _include(include: str,
  151. info: QAPISourceInfo,
  152. incl_fname: str,
  153. previously_included: Set[str]
  154. ) -> Optional['QAPISchemaParser']:
  155. incl_abs_fname = os.path.abspath(incl_fname)
  156. # catch inclusion cycle
  157. inf: Optional[QAPISourceInfo] = info
  158. while inf:
  159. if incl_abs_fname == os.path.abspath(inf.fname):
  160. raise QAPISemError(info, "inclusion loop for %s" % include)
  161. inf = inf.parent
  162. # skip multiple include of the same file
  163. if incl_abs_fname in previously_included:
  164. return None
  165. try:
  166. return QAPISchemaParser(incl_fname, previously_included, info)
  167. except OSError as err:
  168. raise QAPISemError(
  169. info,
  170. f"can't read include file '{incl_fname}': {err.strerror}"
  171. ) from err
  172. @staticmethod
  173. def _pragma(name: str, value: object, info: QAPISourceInfo) -> None:
  174. def check_list_str(name: str, value: object) -> List[str]:
  175. if (not isinstance(value, list) or
  176. any(not isinstance(elt, str) for elt in value)):
  177. raise QAPISemError(
  178. info,
  179. "pragma %s must be a list of strings" % name)
  180. return value
  181. pragma = info.pragma
  182. if name == 'doc-required':
  183. if not isinstance(value, bool):
  184. raise QAPISemError(info,
  185. "pragma 'doc-required' must be boolean")
  186. pragma.doc_required = value
  187. elif name == 'command-name-exceptions':
  188. pragma.command_name_exceptions = check_list_str(name, value)
  189. elif name == 'command-returns-exceptions':
  190. pragma.command_returns_exceptions = check_list_str(name, value)
  191. elif name == 'member-name-exceptions':
  192. pragma.member_name_exceptions = check_list_str(name, value)
  193. else:
  194. raise QAPISemError(info, "unknown pragma '%s'" % name)
  195. def accept(self, skip_comment: bool = True) -> None:
  196. """
  197. Read and store the next token.
  198. :param skip_comment:
  199. When false, return COMMENT tokens ("#").
  200. This is used when reading documentation blocks.
  201. :return:
  202. None. Several instance attributes are updated instead:
  203. - ``.tok`` represents the token type. See below for values.
  204. - ``.info`` describes the token's source location.
  205. - ``.val`` is the token's value, if any. See below.
  206. - ``.pos`` is the buffer index of the first character of
  207. the token.
  208. * Single-character tokens:
  209. These are "{", "}", ":", ",", "[", and "]".
  210. ``.tok`` holds the single character and ``.val`` is None.
  211. * Multi-character tokens:
  212. * COMMENT:
  213. This token is not normally returned by the lexer, but it can
  214. be when ``skip_comment`` is False. ``.tok`` is "#", and
  215. ``.val`` is a string including all chars until end-of-line,
  216. including the "#" itself.
  217. * STRING:
  218. ``.tok`` is "'", the single quote. ``.val`` contains the
  219. string, excluding the surrounding quotes.
  220. * TRUE and FALSE:
  221. ``.tok`` is either "t" or "f", ``.val`` will be the
  222. corresponding bool value.
  223. * EOF:
  224. ``.tok`` and ``.val`` will both be None at EOF.
  225. """
  226. while True:
  227. self.tok = self.src[self.cursor]
  228. self.pos = self.cursor
  229. self.cursor += 1
  230. self.val = None
  231. if self.tok == '#':
  232. if self.src[self.cursor] == '#':
  233. # Start of doc comment
  234. skip_comment = False
  235. self.cursor = self.src.find('\n', self.cursor)
  236. if not skip_comment:
  237. self.val = self.src[self.pos:self.cursor]
  238. return
  239. elif self.tok in '{}:,[]':
  240. return
  241. elif self.tok == "'":
  242. # Note: we accept only printable ASCII
  243. string = ''
  244. esc = False
  245. while True:
  246. ch = self.src[self.cursor]
  247. self.cursor += 1
  248. if ch == '\n':
  249. raise QAPIParseError(self, "missing terminating \"'\"")
  250. if esc:
  251. # Note: we recognize only \\ because we have
  252. # no use for funny characters in strings
  253. if ch != '\\':
  254. raise QAPIParseError(self,
  255. "unknown escape \\%s" % ch)
  256. esc = False
  257. elif ch == '\\':
  258. esc = True
  259. continue
  260. elif ch == "'":
  261. self.val = string
  262. return
  263. if ord(ch) < 32 or ord(ch) >= 127:
  264. raise QAPIParseError(
  265. self, "funny character in string")
  266. string += ch
  267. elif self.src.startswith('true', self.pos):
  268. self.val = True
  269. self.cursor += 3
  270. return
  271. elif self.src.startswith('false', self.pos):
  272. self.val = False
  273. self.cursor += 4
  274. return
  275. elif self.tok == '\n':
  276. if self.cursor == len(self.src):
  277. self.tok = None
  278. return
  279. self.info = self.info.next_line()
  280. self.line_pos = self.cursor
  281. elif not self.tok.isspace():
  282. # Show up to next structural, whitespace or quote
  283. # character
  284. match = must_match('[^[\\]{}:,\\s\'"]+',
  285. self.src[self.cursor-1:])
  286. raise QAPIParseError(self, "stray '%s'" % match.group(0))
  287. def get_members(self) -> Dict[str, object]:
  288. expr: Dict[str, object] = OrderedDict()
  289. if self.tok == '}':
  290. self.accept()
  291. return expr
  292. if self.tok != "'":
  293. raise QAPIParseError(self, "expected string or '}'")
  294. while True:
  295. key = self.val
  296. assert isinstance(key, str) # Guaranteed by tok == "'"
  297. self.accept()
  298. if self.tok != ':':
  299. raise QAPIParseError(self, "expected ':'")
  300. self.accept()
  301. if key in expr:
  302. raise QAPIParseError(self, "duplicate key '%s'" % key)
  303. expr[key] = self.get_expr()
  304. if self.tok == '}':
  305. self.accept()
  306. return expr
  307. if self.tok != ',':
  308. raise QAPIParseError(self, "expected ',' or '}'")
  309. self.accept()
  310. if self.tok != "'":
  311. raise QAPIParseError(self, "expected string")
  312. def get_values(self) -> List[object]:
  313. expr: List[object] = []
  314. if self.tok == ']':
  315. self.accept()
  316. return expr
  317. if self.tok not in tuple("{['tf"):
  318. raise QAPIParseError(
  319. self, "expected '{', '[', ']', string, or boolean")
  320. while True:
  321. expr.append(self.get_expr())
  322. if self.tok == ']':
  323. self.accept()
  324. return expr
  325. if self.tok != ',':
  326. raise QAPIParseError(self, "expected ',' or ']'")
  327. self.accept()
  328. def get_expr(self) -> _ExprValue:
  329. expr: _ExprValue
  330. if self.tok == '{':
  331. self.accept()
  332. expr = self.get_members()
  333. elif self.tok == '[':
  334. self.accept()
  335. expr = self.get_values()
  336. elif self.tok in tuple("'tf"):
  337. assert isinstance(self.val, (str, bool))
  338. expr = self.val
  339. self.accept()
  340. else:
  341. raise QAPIParseError(
  342. self, "expected '{', '[', string, or boolean")
  343. return expr
  344. def get_doc(self, info: QAPISourceInfo) -> List['QAPIDoc']:
  345. if self.val != '##':
  346. raise QAPIParseError(
  347. self, "junk after '##' at start of documentation comment")
  348. docs = []
  349. cur_doc = QAPIDoc(self, info)
  350. self.accept(False)
  351. while self.tok == '#':
  352. assert isinstance(self.val, str)
  353. if self.val.startswith('##'):
  354. # End of doc comment
  355. if self.val != '##':
  356. raise QAPIParseError(
  357. self,
  358. "junk after '##' at end of documentation comment")
  359. cur_doc.end_comment()
  360. docs.append(cur_doc)
  361. self.accept()
  362. return docs
  363. if self.val.startswith('# ='):
  364. if cur_doc.symbol:
  365. raise QAPIParseError(
  366. self,
  367. "unexpected '=' markup in definition documentation")
  368. if cur_doc.body.text:
  369. cur_doc.end_comment()
  370. docs.append(cur_doc)
  371. cur_doc = QAPIDoc(self, info)
  372. cur_doc.append(self.val)
  373. self.accept(False)
  374. raise QAPIParseError(self, "documentation comment must end with '##'")
  375. class QAPIDoc:
  376. """
  377. A documentation comment block, either definition or free-form
  378. Definition documentation blocks consist of
  379. * a body section: one line naming the definition, followed by an
  380. overview (any number of lines)
  381. * argument sections: a description of each argument (for commands
  382. and events) or member (for structs, unions and alternates)
  383. * features sections: a description of each feature flag
  384. * additional (non-argument) sections, possibly tagged
  385. Free-form documentation blocks consist only of a body section.
  386. """
  387. class Section:
  388. def __init__(self, parser, name=None, indent=0):
  389. # parser, for error messages about indentation
  390. self._parser = parser
  391. # optional section name (argument/member or section name)
  392. self.name = name
  393. self.text = ''
  394. # the expected indent level of the text of this section
  395. self._indent = indent
  396. def append(self, line):
  397. # Strip leading spaces corresponding to the expected indent level
  398. # Blank lines are always OK.
  399. if line:
  400. indent = must_match(r'\s*', line).end()
  401. if indent < self._indent:
  402. raise QAPIParseError(
  403. self._parser,
  404. "unexpected de-indent (expected at least %d spaces)" %
  405. self._indent)
  406. line = line[self._indent:]
  407. self.text += line.rstrip() + '\n'
  408. class ArgSection(Section):
  409. def __init__(self, parser, name, indent=0):
  410. super().__init__(parser, name, indent)
  411. self.member = None
  412. def connect(self, member):
  413. self.member = member
  414. def __init__(self, parser, info):
  415. # self._parser is used to report errors with QAPIParseError. The
  416. # resulting error position depends on the state of the parser.
  417. # It happens to be the beginning of the comment. More or less
  418. # servicable, but action at a distance.
  419. self._parser = parser
  420. self.info = info
  421. self.symbol = None
  422. self.body = QAPIDoc.Section(parser)
  423. # dict mapping parameter name to ArgSection
  424. self.args = OrderedDict()
  425. self.features = OrderedDict()
  426. # a list of Section
  427. self.sections = []
  428. # the current section
  429. self._section = self.body
  430. self._append_line = self._append_body_line
  431. def has_section(self, name):
  432. """Return True if we have a section with this name."""
  433. for i in self.sections:
  434. if i.name == name:
  435. return True
  436. return False
  437. def append(self, line):
  438. """
  439. Parse a comment line and add it to the documentation.
  440. The way that the line is dealt with depends on which part of
  441. the documentation we're parsing right now:
  442. * The body section: ._append_line is ._append_body_line
  443. * An argument section: ._append_line is ._append_args_line
  444. * A features section: ._append_line is ._append_features_line
  445. * An additional section: ._append_line is ._append_various_line
  446. """
  447. line = line[1:]
  448. if not line:
  449. self._append_freeform(line)
  450. return
  451. if line[0] != ' ':
  452. raise QAPIParseError(self._parser, "missing space after #")
  453. line = line[1:]
  454. self._append_line(line)
  455. def end_comment(self):
  456. self._end_section()
  457. @staticmethod
  458. def _is_section_tag(name):
  459. return name in ('Returns:', 'Since:',
  460. # those are often singular or plural
  461. 'Note:', 'Notes:',
  462. 'Example:', 'Examples:',
  463. 'TODO:')
  464. def _append_body_line(self, line):
  465. """
  466. Process a line of documentation text in the body section.
  467. If this a symbol line and it is the section's first line, this
  468. is a definition documentation block for that symbol.
  469. If it's a definition documentation block, another symbol line
  470. begins the argument section for the argument named by it, and
  471. a section tag begins an additional section. Start that
  472. section and append the line to it.
  473. Else, append the line to the current section.
  474. """
  475. name = line.split(' ', 1)[0]
  476. # FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
  477. # recognized, and get silently treated as ordinary text
  478. if not self.symbol and not self.body.text and line.startswith('@'):
  479. if not line.endswith(':'):
  480. raise QAPIParseError(self._parser, "line should end with ':'")
  481. self.symbol = line[1:-1]
  482. # Invalid names are not checked here, but the name provided MUST
  483. # match the following definition, which *is* validated in expr.py.
  484. if not self.symbol:
  485. raise QAPIParseError(
  486. self._parser, "name required after '@'")
  487. elif self.symbol:
  488. # This is a definition documentation block
  489. if name.startswith('@') and name.endswith(':'):
  490. self._append_line = self._append_args_line
  491. self._append_args_line(line)
  492. elif line == 'Features:':
  493. self._append_line = self._append_features_line
  494. elif self._is_section_tag(name):
  495. self._append_line = self._append_various_line
  496. self._append_various_line(line)
  497. else:
  498. self._append_freeform(line)
  499. else:
  500. # This is a free-form documentation block
  501. self._append_freeform(line)
  502. def _append_args_line(self, line):
  503. """
  504. Process a line of documentation text in an argument section.
  505. A symbol line begins the next argument section, a section tag
  506. section or a non-indented line after a blank line begins an
  507. additional section. Start that section and append the line to
  508. it.
  509. Else, append the line to the current section.
  510. """
  511. name = line.split(' ', 1)[0]
  512. if name.startswith('@') and name.endswith(':'):
  513. # If line is "@arg: first line of description", find
  514. # the index of 'f', which is the indent we expect for any
  515. # following lines. We then remove the leading "@arg:"
  516. # from line and replace it with spaces so that 'f' has the
  517. # same index as it did in the original line and can be
  518. # handled the same way we will handle following lines.
  519. indent = must_match(r'@\S*:\s*', line).end()
  520. line = line[indent:]
  521. if not line:
  522. # Line was just the "@arg:" header; following lines
  523. # are not indented
  524. indent = 0
  525. else:
  526. line = ' ' * indent + line
  527. self._start_args_section(name[1:-1], indent)
  528. elif self._is_section_tag(name):
  529. self._append_line = self._append_various_line
  530. self._append_various_line(line)
  531. return
  532. elif (self._section.text.endswith('\n\n')
  533. and line and not line[0].isspace()):
  534. if line == 'Features:':
  535. self._append_line = self._append_features_line
  536. else:
  537. self._start_section()
  538. self._append_line = self._append_various_line
  539. self._append_various_line(line)
  540. return
  541. self._append_freeform(line)
  542. def _append_features_line(self, line):
  543. name = line.split(' ', 1)[0]
  544. if name.startswith('@') and name.endswith(':'):
  545. # If line is "@arg: first line of description", find
  546. # the index of 'f', which is the indent we expect for any
  547. # following lines. We then remove the leading "@arg:"
  548. # from line and replace it with spaces so that 'f' has the
  549. # same index as it did in the original line and can be
  550. # handled the same way we will handle following lines.
  551. indent = must_match(r'@\S*:\s*', line).end()
  552. line = line[indent:]
  553. if not line:
  554. # Line was just the "@arg:" header; following lines
  555. # are not indented
  556. indent = 0
  557. else:
  558. line = ' ' * indent + line
  559. self._start_features_section(name[1:-1], indent)
  560. elif self._is_section_tag(name):
  561. self._append_line = self._append_various_line
  562. self._append_various_line(line)
  563. return
  564. elif (self._section.text.endswith('\n\n')
  565. and line and not line[0].isspace()):
  566. self._start_section()
  567. self._append_line = self._append_various_line
  568. self._append_various_line(line)
  569. return
  570. self._append_freeform(line)
  571. def _append_various_line(self, line):
  572. """
  573. Process a line of documentation text in an additional section.
  574. A symbol line is an error.
  575. A section tag begins an additional section. Start that
  576. section and append the line to it.
  577. Else, append the line to the current section.
  578. """
  579. name = line.split(' ', 1)[0]
  580. if name.startswith('@') and name.endswith(':'):
  581. raise QAPIParseError(self._parser,
  582. "'%s' can't follow '%s' section"
  583. % (name, self.sections[0].name))
  584. if self._is_section_tag(name):
  585. # If line is "Section: first line of description", find
  586. # the index of 'f', which is the indent we expect for any
  587. # following lines. We then remove the leading "Section:"
  588. # from line and replace it with spaces so that 'f' has the
  589. # same index as it did in the original line and can be
  590. # handled the same way we will handle following lines.
  591. indent = must_match(r'\S*:\s*', line).end()
  592. line = line[indent:]
  593. if not line:
  594. # Line was just the "Section:" header; following lines
  595. # are not indented
  596. indent = 0
  597. else:
  598. line = ' ' * indent + line
  599. self._start_section(name[:-1], indent)
  600. self._append_freeform(line)
  601. def _start_symbol_section(self, symbols_dict, name, indent):
  602. # FIXME invalid names other than the empty string aren't flagged
  603. if not name:
  604. raise QAPIParseError(self._parser, "invalid parameter name")
  605. if name in symbols_dict:
  606. raise QAPIParseError(self._parser,
  607. "'%s' parameter name duplicated" % name)
  608. assert not self.sections
  609. self._end_section()
  610. self._section = QAPIDoc.ArgSection(self._parser, name, indent)
  611. symbols_dict[name] = self._section
  612. def _start_args_section(self, name, indent):
  613. self._start_symbol_section(self.args, name, indent)
  614. def _start_features_section(self, name, indent):
  615. self._start_symbol_section(self.features, name, indent)
  616. def _start_section(self, name=None, indent=0):
  617. if name in ('Returns', 'Since') and self.has_section(name):
  618. raise QAPIParseError(self._parser,
  619. "duplicated '%s' section" % name)
  620. self._end_section()
  621. self._section = QAPIDoc.Section(self._parser, name, indent)
  622. self.sections.append(self._section)
  623. def _end_section(self):
  624. if self._section:
  625. text = self._section.text = self._section.text.strip()
  626. if self._section.name and (not text or text.isspace()):
  627. raise QAPIParseError(
  628. self._parser,
  629. "empty doc section '%s'" % self._section.name)
  630. self._section = None
  631. def _append_freeform(self, line):
  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):
  639. if member.name not in self.args:
  640. # Undocumented TODO outlaw
  641. self.args[member.name] = QAPIDoc.ArgSection(self._parser,
  642. member.name)
  643. self.args[member.name].connect(member)
  644. def connect_feature(self, feature):
  645. if feature.name not in self.features:
  646. raise QAPISemError(feature.info,
  647. "feature '%s' lacks documentation"
  648. % feature.name)
  649. self.features[feature.name].connect(feature)
  650. def check_expr(self, expr):
  651. if self.has_section('Returns') and 'command' not in expr:
  652. raise QAPISemError(self.info,
  653. "'Returns:' is only valid for commands")
  654. def check(self):
  655. def check_args_section(args, what):
  656. bogus = [name for name, section in args.items()
  657. if not section.member]
  658. if bogus:
  659. raise QAPISemError(
  660. self.info,
  661. "documented %s%s '%s' %s not exist" % (
  662. what,
  663. "s" if len(bogus) > 1 else "",
  664. "', '".join(bogus),
  665. "do" if len(bogus) > 1 else "does"
  666. ))
  667. check_args_section(self.args, 'member')
  668. check_args_section(self.features, 'feature')