parser.py 25 KB

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