parser.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  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. cur_doc = 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. doc = QAPIDoc(self, info)
  253. self.accept(False)
  254. while self.tok == '#':
  255. if self.val.startswith('##'):
  256. # End of doc comment
  257. if self.val != '##':
  258. raise QAPIParseError(
  259. self,
  260. "junk after '##' at end of documentation comment")
  261. doc.end_comment()
  262. self.accept()
  263. return doc
  264. doc.append(self.val)
  265. self.accept(False)
  266. raise QAPIParseError(self, "documentation comment must end with '##'")
  267. class QAPIDoc:
  268. """
  269. A documentation comment block, either definition or free-form
  270. Definition documentation blocks consist of
  271. * a body section: one line naming the definition, followed by an
  272. overview (any number of lines)
  273. * argument sections: a description of each argument (for commands
  274. and events) or member (for structs, unions and alternates)
  275. * features sections: a description of each feature flag
  276. * additional (non-argument) sections, possibly tagged
  277. Free-form documentation blocks consist only of a body section.
  278. """
  279. class Section:
  280. def __init__(self, name=None):
  281. # optional section name (argument/member or section name)
  282. self.name = name
  283. # the list of lines for this section
  284. self.text = ''
  285. def append(self, line):
  286. self.text += line.rstrip() + '\n'
  287. class ArgSection(Section):
  288. def __init__(self, name):
  289. super().__init__(name)
  290. self.member = None
  291. def connect(self, member):
  292. self.member = member
  293. def __init__(self, parser, info):
  294. # self._parser is used to report errors with QAPIParseError. The
  295. # resulting error position depends on the state of the parser.
  296. # It happens to be the beginning of the comment. More or less
  297. # servicable, but action at a distance.
  298. self._parser = parser
  299. self.info = info
  300. self.symbol = None
  301. self.body = QAPIDoc.Section()
  302. # dict mapping parameter name to ArgSection
  303. self.args = OrderedDict()
  304. self.features = OrderedDict()
  305. # a list of Section
  306. self.sections = []
  307. # the current section
  308. self._section = self.body
  309. self._append_line = self._append_body_line
  310. def has_section(self, name):
  311. """Return True if we have a section with this name."""
  312. for i in self.sections:
  313. if i.name == name:
  314. return True
  315. return False
  316. def append(self, line):
  317. """
  318. Parse a comment line and add it to the documentation.
  319. The way that the line is dealt with depends on which part of
  320. the documentation we're parsing right now:
  321. * The body section: ._append_line is ._append_body_line
  322. * An argument section: ._append_line is ._append_args_line
  323. * A features section: ._append_line is ._append_features_line
  324. * An additional section: ._append_line is ._append_various_line
  325. """
  326. line = line[1:]
  327. if not line:
  328. self._append_freeform(line)
  329. return
  330. if line[0] != ' ':
  331. raise QAPIParseError(self._parser, "missing space after #")
  332. line = line[1:]
  333. self._append_line(line)
  334. def end_comment(self):
  335. self._end_section()
  336. @staticmethod
  337. def _is_section_tag(name):
  338. return name in ('Returns:', 'Since:',
  339. # those are often singular or plural
  340. 'Note:', 'Notes:',
  341. 'Example:', 'Examples:',
  342. 'TODO:')
  343. def _append_body_line(self, line):
  344. """
  345. Process a line of documentation text in the body section.
  346. If this a symbol line and it is the section's first line, this
  347. is a definition documentation block for that symbol.
  348. If it's a definition documentation block, another symbol line
  349. begins the argument section for the argument named by it, and
  350. a section tag begins an additional section. Start that
  351. section and append the line to it.
  352. Else, append the line to the current section.
  353. """
  354. name = line.split(' ', 1)[0]
  355. # FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
  356. # recognized, and get silently treated as ordinary text
  357. if not self.symbol and not self.body.text and line.startswith('@'):
  358. if not line.endswith(':'):
  359. raise QAPIParseError(self._parser, "line should end with ':'")
  360. self.symbol = line[1:-1]
  361. # FIXME invalid names other than the empty string aren't flagged
  362. if not self.symbol:
  363. raise QAPIParseError(self._parser, "invalid name")
  364. elif self.symbol:
  365. # This is a definition documentation block
  366. if name.startswith('@') and name.endswith(':'):
  367. self._append_line = self._append_args_line
  368. self._append_args_line(line)
  369. elif line == 'Features:':
  370. self._append_line = self._append_features_line
  371. elif self._is_section_tag(name):
  372. self._append_line = self._append_various_line
  373. self._append_various_line(line)
  374. else:
  375. self._append_freeform(line.strip())
  376. else:
  377. # This is a free-form documentation block
  378. self._append_freeform(line.strip())
  379. def _append_args_line(self, line):
  380. """
  381. Process a line of documentation text in an argument section.
  382. A symbol line begins the next argument section, a section tag
  383. section or a non-indented line after a blank line begins an
  384. additional section. Start that section and append the line to
  385. it.
  386. Else, append the line to the current section.
  387. """
  388. name = line.split(' ', 1)[0]
  389. if name.startswith('@') and name.endswith(':'):
  390. line = line[len(name)+1:]
  391. self._start_args_section(name[1:-1])
  392. elif self._is_section_tag(name):
  393. self._append_line = self._append_various_line
  394. self._append_various_line(line)
  395. return
  396. elif (self._section.text.endswith('\n\n')
  397. and line and not line[0].isspace()):
  398. if line == 'Features:':
  399. self._append_line = self._append_features_line
  400. else:
  401. self._start_section()
  402. self._append_line = self._append_various_line
  403. self._append_various_line(line)
  404. return
  405. self._append_freeform(line.strip())
  406. def _append_features_line(self, line):
  407. name = line.split(' ', 1)[0]
  408. if name.startswith('@') and name.endswith(':'):
  409. line = line[len(name)+1:]
  410. self._start_features_section(name[1:-1])
  411. elif self._is_section_tag(name):
  412. self._append_line = self._append_various_line
  413. self._append_various_line(line)
  414. return
  415. elif (self._section.text.endswith('\n\n')
  416. and line and not line[0].isspace()):
  417. self._start_section()
  418. self._append_line = self._append_various_line
  419. self._append_various_line(line)
  420. return
  421. self._append_freeform(line.strip())
  422. def _append_various_line(self, line):
  423. """
  424. Process a line of documentation text in an additional section.
  425. A symbol line is an error.
  426. A section tag begins an additional section. Start that
  427. section and append the line to it.
  428. Else, append the line to the current section.
  429. """
  430. name = line.split(' ', 1)[0]
  431. if name.startswith('@') and name.endswith(':'):
  432. raise QAPIParseError(self._parser,
  433. "'%s' can't follow '%s' section"
  434. % (name, self.sections[0].name))
  435. if self._is_section_tag(name):
  436. line = line[len(name)+1:]
  437. self._start_section(name[:-1])
  438. if (not self._section.name or
  439. not self._section.name.startswith('Example')):
  440. line = line.strip()
  441. self._append_freeform(line)
  442. def _start_symbol_section(self, symbols_dict, name):
  443. # FIXME invalid names other than the empty string aren't flagged
  444. if not name:
  445. raise QAPIParseError(self._parser, "invalid parameter name")
  446. if name in symbols_dict:
  447. raise QAPIParseError(self._parser,
  448. "'%s' parameter name duplicated" % name)
  449. assert not self.sections
  450. self._end_section()
  451. self._section = QAPIDoc.ArgSection(name)
  452. symbols_dict[name] = self._section
  453. def _start_args_section(self, name):
  454. self._start_symbol_section(self.args, name)
  455. def _start_features_section(self, name):
  456. self._start_symbol_section(self.features, name)
  457. def _start_section(self, name=None):
  458. if name in ('Returns', 'Since') and self.has_section(name):
  459. raise QAPIParseError(self._parser,
  460. "duplicated '%s' section" % name)
  461. self._end_section()
  462. self._section = QAPIDoc.Section(name)
  463. self.sections.append(self._section)
  464. def _end_section(self):
  465. if self._section:
  466. text = self._section.text = self._section.text.strip()
  467. if self._section.name and (not text or text.isspace()):
  468. raise QAPIParseError(
  469. self._parser,
  470. "empty doc section '%s'" % self._section.name)
  471. self._section = None
  472. def _append_freeform(self, line):
  473. match = re.match(r'(@\S+:)', line)
  474. if match:
  475. raise QAPIParseError(self._parser,
  476. "'%s' not allowed in free-form documentation"
  477. % match.group(1))
  478. self._section.append(line)
  479. def connect_member(self, member):
  480. if member.name not in self.args:
  481. # Undocumented TODO outlaw
  482. self.args[member.name] = QAPIDoc.ArgSection(member.name)
  483. self.args[member.name].connect(member)
  484. def connect_feature(self, feature):
  485. if feature.name not in self.features:
  486. raise QAPISemError(feature.info,
  487. "feature '%s' lacks documentation"
  488. % feature.name)
  489. self.features[feature.name].connect(feature)
  490. def check_expr(self, expr):
  491. if self.has_section('Returns') and 'command' not in expr:
  492. raise QAPISemError(self.info,
  493. "'Returns:' is only valid for commands")
  494. def check(self):
  495. def check_args_section(args, info, what):
  496. bogus = [name for name, section in args.items()
  497. if not section.member]
  498. if bogus:
  499. raise QAPISemError(
  500. self.info,
  501. "documented member%s '%s' %s not exist"
  502. % ("s" if len(bogus) > 1 else "",
  503. "', '".join(bogus),
  504. "do" if len(bogus) > 1 else "does"))
  505. check_args_section(self.args, self.info, 'members')
  506. check_args_section(self.features, self.info, 'features')