parser.py 24 KB

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