parser.py 25 KB

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