parser.py 30 KB

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