parser.py 25 KB

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