parser.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. if self.val.startswith('##'):
  280. # End of doc comment
  281. if self.val != '##':
  282. raise QAPIParseError(
  283. self,
  284. "junk after '##' at end of documentation comment")
  285. cur_doc.end_comment()
  286. docs.append(cur_doc)
  287. self.accept()
  288. return docs
  289. if self.val.startswith('# ='):
  290. if cur_doc.symbol:
  291. raise QAPIParseError(
  292. self,
  293. "unexpected '=' markup in definition documentation")
  294. if cur_doc.body.text:
  295. cur_doc.end_comment()
  296. docs.append(cur_doc)
  297. cur_doc = QAPIDoc(self, info)
  298. cur_doc.append(self.val)
  299. self.accept(False)
  300. raise QAPIParseError(self, "documentation comment must end with '##'")
  301. class QAPIDoc:
  302. """
  303. A documentation comment block, either definition or free-form
  304. Definition documentation blocks consist of
  305. * a body section: one line naming the definition, followed by an
  306. overview (any number of lines)
  307. * argument sections: a description of each argument (for commands
  308. and events) or member (for structs, unions and alternates)
  309. * features sections: a description of each feature flag
  310. * additional (non-argument) sections, possibly tagged
  311. Free-form documentation blocks consist only of a body section.
  312. """
  313. class Section:
  314. def __init__(self, parser, name=None, indent=0):
  315. # parser, for error messages about indentation
  316. self._parser = parser
  317. # optional section name (argument/member or section name)
  318. self.name = name
  319. self.text = ''
  320. # the expected indent level of the text of this section
  321. self._indent = indent
  322. def append(self, line):
  323. # Strip leading spaces corresponding to the expected indent level
  324. # Blank lines are always OK.
  325. if line:
  326. indent = re.match(r'\s*', line).end()
  327. if indent < self._indent:
  328. raise QAPIParseError(
  329. self._parser,
  330. "unexpected de-indent (expected at least %d spaces)" %
  331. self._indent)
  332. line = line[self._indent:]
  333. self.text += line.rstrip() + '\n'
  334. class ArgSection(Section):
  335. def __init__(self, parser, name, indent=0):
  336. super().__init__(parser, name, indent)
  337. self.member = None
  338. def connect(self, member):
  339. self.member = member
  340. def __init__(self, parser, info):
  341. # self._parser is used to report errors with QAPIParseError. The
  342. # resulting error position depends on the state of the parser.
  343. # It happens to be the beginning of the comment. More or less
  344. # servicable, but action at a distance.
  345. self._parser = parser
  346. self.info = info
  347. self.symbol = None
  348. self.body = QAPIDoc.Section(parser)
  349. # dict mapping parameter name to ArgSection
  350. self.args = OrderedDict()
  351. self.features = OrderedDict()
  352. # a list of Section
  353. self.sections = []
  354. # the current section
  355. self._section = self.body
  356. self._append_line = self._append_body_line
  357. def has_section(self, name):
  358. """Return True if we have a section with this name."""
  359. for i in self.sections:
  360. if i.name == name:
  361. return True
  362. return False
  363. def append(self, line):
  364. """
  365. Parse a comment line and add it to the documentation.
  366. The way that the line is dealt with depends on which part of
  367. the documentation we're parsing right now:
  368. * The body section: ._append_line is ._append_body_line
  369. * An argument section: ._append_line is ._append_args_line
  370. * A features section: ._append_line is ._append_features_line
  371. * An additional section: ._append_line is ._append_various_line
  372. """
  373. line = line[1:]
  374. if not line:
  375. self._append_freeform(line)
  376. return
  377. if line[0] != ' ':
  378. raise QAPIParseError(self._parser, "missing space after #")
  379. line = line[1:]
  380. self._append_line(line)
  381. def end_comment(self):
  382. self._end_section()
  383. @staticmethod
  384. def _is_section_tag(name):
  385. return name in ('Returns:', 'Since:',
  386. # those are often singular or plural
  387. 'Note:', 'Notes:',
  388. 'Example:', 'Examples:',
  389. 'TODO:')
  390. def _append_body_line(self, line):
  391. """
  392. Process a line of documentation text in the body section.
  393. If this a symbol line and it is the section's first line, this
  394. is a definition documentation block for that symbol.
  395. If it's a definition documentation block, another symbol line
  396. begins the argument section for the argument named by it, and
  397. a section tag begins an additional section. Start that
  398. section and append the line to it.
  399. Else, append the line to the current section.
  400. """
  401. name = line.split(' ', 1)[0]
  402. # FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
  403. # recognized, and get silently treated as ordinary text
  404. if not self.symbol and not self.body.text and line.startswith('@'):
  405. if not line.endswith(':'):
  406. raise QAPIParseError(self._parser, "line should end with ':'")
  407. self.symbol = line[1:-1]
  408. # FIXME invalid names other than the empty string aren't flagged
  409. if not self.symbol:
  410. raise QAPIParseError(self._parser, "invalid name")
  411. elif self.symbol:
  412. # This is a definition documentation block
  413. if name.startswith('@') and name.endswith(':'):
  414. self._append_line = self._append_args_line
  415. self._append_args_line(line)
  416. elif line == 'Features:':
  417. self._append_line = self._append_features_line
  418. elif self._is_section_tag(name):
  419. self._append_line = self._append_various_line
  420. self._append_various_line(line)
  421. else:
  422. self._append_freeform(line)
  423. else:
  424. # This is a free-form documentation block
  425. self._append_freeform(line)
  426. def _append_args_line(self, line):
  427. """
  428. Process a line of documentation text in an argument section.
  429. A symbol line begins the next argument section, a section tag
  430. section or a non-indented line after a blank line begins an
  431. additional section. Start that section and append the line to
  432. it.
  433. Else, append the line to the current section.
  434. """
  435. name = line.split(' ', 1)[0]
  436. if name.startswith('@') and name.endswith(':'):
  437. # If line is "@arg: first line of description", find
  438. # the index of 'f', which is the indent we expect for any
  439. # following lines. We then remove the leading "@arg:"
  440. # from line and replace it with spaces so that 'f' has the
  441. # same index as it did in the original line and can be
  442. # handled the same way we will handle following lines.
  443. indent = re.match(r'@\S*:\s*', line).end()
  444. line = line[indent:]
  445. if not line:
  446. # Line was just the "@arg:" header; following lines
  447. # are not indented
  448. indent = 0
  449. else:
  450. line = ' ' * indent + line
  451. self._start_args_section(name[1:-1], indent)
  452. elif self._is_section_tag(name):
  453. self._append_line = self._append_various_line
  454. self._append_various_line(line)
  455. return
  456. elif (self._section.text.endswith('\n\n')
  457. and line and not line[0].isspace()):
  458. if line == 'Features:':
  459. self._append_line = self._append_features_line
  460. else:
  461. self._start_section()
  462. self._append_line = self._append_various_line
  463. self._append_various_line(line)
  464. return
  465. self._append_freeform(line)
  466. def _append_features_line(self, line):
  467. name = line.split(' ', 1)[0]
  468. if name.startswith('@') and name.endswith(':'):
  469. # If line is "@arg: first line of description", find
  470. # the index of 'f', which is the indent we expect for any
  471. # following lines. We then remove the leading "@arg:"
  472. # from line and replace it with spaces so that 'f' has the
  473. # same index as it did in the original line and can be
  474. # handled the same way we will handle following lines.
  475. indent = re.match(r'@\S*:\s*', line).end()
  476. line = line[indent:]
  477. if not line:
  478. # Line was just the "@arg:" header; following lines
  479. # are not indented
  480. indent = 0
  481. else:
  482. line = ' ' * indent + line
  483. self._start_features_section(name[1:-1], indent)
  484. elif self._is_section_tag(name):
  485. self._append_line = self._append_various_line
  486. self._append_various_line(line)
  487. return
  488. elif (self._section.text.endswith('\n\n')
  489. and line and not line[0].isspace()):
  490. self._start_section()
  491. self._append_line = self._append_various_line
  492. self._append_various_line(line)
  493. return
  494. self._append_freeform(line)
  495. def _append_various_line(self, line):
  496. """
  497. Process a line of documentation text in an additional section.
  498. A symbol line is an error.
  499. A section tag begins an additional section. Start that
  500. section and append the line to it.
  501. Else, append the line to the current section.
  502. """
  503. name = line.split(' ', 1)[0]
  504. if name.startswith('@') and name.endswith(':'):
  505. raise QAPIParseError(self._parser,
  506. "'%s' can't follow '%s' section"
  507. % (name, self.sections[0].name))
  508. if self._is_section_tag(name):
  509. # If line is "Section: first line of description", find
  510. # the index of 'f', which is the indent we expect for any
  511. # following lines. We then remove the leading "Section:"
  512. # from line and replace it with spaces so that 'f' has the
  513. # same index as it did in the original line and can be
  514. # handled the same way we will handle following lines.
  515. indent = re.match(r'\S*:\s*', line).end()
  516. line = line[indent:]
  517. if not line:
  518. # Line was just the "Section:" header; following lines
  519. # are not indented
  520. indent = 0
  521. else:
  522. line = ' ' * indent + line
  523. self._start_section(name[:-1], indent)
  524. self._append_freeform(line)
  525. def _start_symbol_section(self, symbols_dict, name, indent):
  526. # FIXME invalid names other than the empty string aren't flagged
  527. if not name:
  528. raise QAPIParseError(self._parser, "invalid parameter name")
  529. if name in symbols_dict:
  530. raise QAPIParseError(self._parser,
  531. "'%s' parameter name duplicated" % name)
  532. assert not self.sections
  533. self._end_section()
  534. self._section = QAPIDoc.ArgSection(self._parser, name, indent)
  535. symbols_dict[name] = self._section
  536. def _start_args_section(self, name, indent):
  537. self._start_symbol_section(self.args, name, indent)
  538. def _start_features_section(self, name, indent):
  539. self._start_symbol_section(self.features, name, indent)
  540. def _start_section(self, name=None, indent=0):
  541. if name in ('Returns', 'Since') and self.has_section(name):
  542. raise QAPIParseError(self._parser,
  543. "duplicated '%s' section" % name)
  544. self._end_section()
  545. self._section = QAPIDoc.Section(self._parser, name, indent)
  546. self.sections.append(self._section)
  547. def _end_section(self):
  548. if self._section:
  549. text = self._section.text = self._section.text.strip()
  550. if self._section.name and (not text or text.isspace()):
  551. raise QAPIParseError(
  552. self._parser,
  553. "empty doc section '%s'" % self._section.name)
  554. self._section = None
  555. def _append_freeform(self, line):
  556. match = re.match(r'(@\S+:)', line)
  557. if match:
  558. raise QAPIParseError(self._parser,
  559. "'%s' not allowed in free-form documentation"
  560. % match.group(1))
  561. self._section.append(line)
  562. def connect_member(self, member):
  563. if member.name not in self.args:
  564. # Undocumented TODO outlaw
  565. self.args[member.name] = QAPIDoc.ArgSection(self._parser,
  566. member.name)
  567. self.args[member.name].connect(member)
  568. def connect_feature(self, feature):
  569. if feature.name not in self.features:
  570. raise QAPISemError(feature.info,
  571. "feature '%s' lacks documentation"
  572. % feature.name)
  573. self.features[feature.name].connect(feature)
  574. def check_expr(self, expr):
  575. if self.has_section('Returns') and 'command' not in expr:
  576. raise QAPISemError(self.info,
  577. "'Returns:' is only valid for commands")
  578. def check(self):
  579. def check_args_section(args, info, what):
  580. bogus = [name for name, section in args.items()
  581. if not section.member]
  582. if bogus:
  583. raise QAPISemError(
  584. self.info,
  585. "documented member%s '%s' %s not exist"
  586. % ("s" if len(bogus) > 1 else "",
  587. "', '".join(bogus),
  588. "do" if len(bogus) > 1 else "does"))
  589. check_args_section(self.args, self.info, 'members')
  590. check_args_section(self.features, self.info, 'features')