parser.py 21 KB

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