parser.py 30 KB

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