parser.py 21 KB

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