parser.py 24 KB

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