qapi.py 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  1. #
  2. # QAPI helper library
  3. #
  4. # Copyright IBM, Corp. 2011
  5. # Copyright (c) 2013-2016 Red Hat Inc.
  6. #
  7. # Authors:
  8. # Anthony Liguori <aliguori@us.ibm.com>
  9. # Markus Armbruster <armbru@redhat.com>
  10. #
  11. # This work is licensed under the terms of the GNU GPL, version 2.
  12. # See the COPYING file in the top-level directory.
  13. import re
  14. from ordereddict import OrderedDict
  15. import errno
  16. import getopt
  17. import os
  18. import sys
  19. import string
  20. builtin_types = {
  21. 'str': 'QTYPE_QSTRING',
  22. 'int': 'QTYPE_QINT',
  23. 'number': 'QTYPE_QFLOAT',
  24. 'bool': 'QTYPE_QBOOL',
  25. 'int8': 'QTYPE_QINT',
  26. 'int16': 'QTYPE_QINT',
  27. 'int32': 'QTYPE_QINT',
  28. 'int64': 'QTYPE_QINT',
  29. 'uint8': 'QTYPE_QINT',
  30. 'uint16': 'QTYPE_QINT',
  31. 'uint32': 'QTYPE_QINT',
  32. 'uint64': 'QTYPE_QINT',
  33. 'size': 'QTYPE_QINT',
  34. 'any': None, # any QType possible, actually
  35. 'QType': 'QTYPE_QSTRING',
  36. }
  37. # Are documentation comments required?
  38. doc_required = False
  39. # Whitelist of commands allowed to return a non-dictionary
  40. returns_whitelist = [
  41. # From QMP:
  42. 'human-monitor-command',
  43. 'qom-get',
  44. 'query-migrate-cache-size',
  45. 'query-tpm-models',
  46. 'query-tpm-types',
  47. 'ringbuf-read',
  48. # From QGA:
  49. 'guest-file-open',
  50. 'guest-fsfreeze-freeze',
  51. 'guest-fsfreeze-freeze-list',
  52. 'guest-fsfreeze-status',
  53. 'guest-fsfreeze-thaw',
  54. 'guest-get-time',
  55. 'guest-set-vcpus',
  56. 'guest-sync',
  57. 'guest-sync-delimited',
  58. ]
  59. # Whitelist of entities allowed to violate case conventions
  60. case_whitelist = [
  61. # From QMP:
  62. 'ACPISlotType', # DIMM, visible through query-acpi-ospm-status
  63. 'CpuInfoMIPS', # PC, visible through query-cpu
  64. 'CpuInfoTricore', # PC, visible through query-cpu
  65. 'QapiErrorClass', # all members, visible through errors
  66. 'UuidInfo', # UUID, visible through query-uuid
  67. 'X86CPURegister32', # all members, visible indirectly through qom-get
  68. 'q_obj_CpuInfo-base', # CPU, visible through query-cpu
  69. ]
  70. enum_types = []
  71. struct_types = []
  72. union_types = []
  73. events = []
  74. all_names = {}
  75. #
  76. # Parsing the schema into expressions
  77. #
  78. def error_path(parent):
  79. res = ""
  80. while parent:
  81. res = ("In file included from %s:%d:\n" % (parent['file'],
  82. parent['line'])) + res
  83. parent = parent['parent']
  84. return res
  85. class QAPIError(Exception):
  86. def __init__(self, fname, line, col, incl_info, msg):
  87. Exception.__init__(self)
  88. self.fname = fname
  89. self.line = line
  90. self.col = col
  91. self.info = incl_info
  92. self.msg = msg
  93. def __str__(self):
  94. loc = "%s:%d" % (self.fname, self.line)
  95. if self.col is not None:
  96. loc += ":%s" % self.col
  97. return error_path(self.info) + "%s: %s" % (loc, self.msg)
  98. class QAPIParseError(QAPIError):
  99. def __init__(self, parser, msg):
  100. col = 1
  101. for ch in parser.src[parser.line_pos:parser.pos]:
  102. if ch == '\t':
  103. col = (col + 7) % 8 + 1
  104. else:
  105. col += 1
  106. QAPIError.__init__(self, parser.fname, parser.line, col,
  107. parser.incl_info, msg)
  108. class QAPISemError(QAPIError):
  109. def __init__(self, info, msg):
  110. QAPIError.__init__(self, info['file'], info['line'], None,
  111. info['parent'], msg)
  112. class QAPIDoc(object):
  113. class Section(object):
  114. def __init__(self, name=None):
  115. # optional section name (argument/member or section name)
  116. self.name = name
  117. # the list of lines for this section
  118. self.content = []
  119. def append(self, line):
  120. self.content.append(line)
  121. def __repr__(self):
  122. return "\n".join(self.content).strip()
  123. class ArgSection(Section):
  124. pass
  125. def __init__(self, parser, info):
  126. # self.parser is used to report errors with QAPIParseError. The
  127. # resulting error position depends on the state of the parser.
  128. # It happens to be the beginning of the comment. More or less
  129. # servicable, but action at a distance.
  130. self.parser = parser
  131. self.info = info
  132. self.symbol = None
  133. self.body = QAPIDoc.Section()
  134. # dict mapping parameter name to ArgSection
  135. self.args = OrderedDict()
  136. # a list of Section
  137. self.sections = []
  138. # the current section
  139. self.section = self.body
  140. # associated expression (to be set by expression parser)
  141. self.expr = None
  142. def has_section(self, name):
  143. """Return True if we have a section with this name."""
  144. for i in self.sections:
  145. if i.name == name:
  146. return True
  147. return False
  148. def append(self, line):
  149. """Parse a comment line and add it to the documentation."""
  150. line = line[1:]
  151. if not line:
  152. self._append_freeform(line)
  153. return
  154. if line[0] != ' ':
  155. raise QAPIParseError(self.parser, "Missing space after #")
  156. line = line[1:]
  157. # FIXME not nice: things like '# @foo:' and '# @foo: ' aren't
  158. # recognized, and get silently treated as ordinary text
  159. if self.symbol:
  160. self._append_symbol_line(line)
  161. elif not self.body.content and line.startswith("@"):
  162. if not line.endswith(":"):
  163. raise QAPIParseError(self.parser, "Line should end with :")
  164. self.symbol = line[1:-1]
  165. # FIXME invalid names other than the empty string aren't flagged
  166. if not self.symbol:
  167. raise QAPIParseError(self.parser, "Invalid name")
  168. else:
  169. self._append_freeform(line)
  170. def _append_symbol_line(self, line):
  171. name = line.split(' ', 1)[0]
  172. if name.startswith("@") and name.endswith(":"):
  173. line = line[len(name)+1:]
  174. self._start_args_section(name[1:-1])
  175. elif name in ("Returns:", "Since:",
  176. # those are often singular or plural
  177. "Note:", "Notes:",
  178. "Example:", "Examples:",
  179. "TODO:"):
  180. line = line[len(name)+1:]
  181. self._start_section(name[:-1])
  182. self._append_freeform(line)
  183. def _start_args_section(self, name):
  184. # FIXME invalid names other than the empty string aren't flagged
  185. if not name:
  186. raise QAPIParseError(self.parser, "Invalid parameter name")
  187. if name in self.args:
  188. raise QAPIParseError(self.parser,
  189. "'%s' parameter name duplicated" % name)
  190. if self.sections:
  191. raise QAPIParseError(self.parser,
  192. "'@%s:' can't follow '%s' section"
  193. % (name, self.sections[0].name))
  194. self.section = QAPIDoc.ArgSection(name)
  195. self.args[name] = self.section
  196. def _start_section(self, name=""):
  197. if name in ("Returns", "Since") and self.has_section(name):
  198. raise QAPIParseError(self.parser,
  199. "Duplicated '%s' section" % name)
  200. self.section = QAPIDoc.Section(name)
  201. self.sections.append(self.section)
  202. def _append_freeform(self, line):
  203. in_arg = isinstance(self.section, QAPIDoc.ArgSection)
  204. if (in_arg and self.section.content
  205. and not self.section.content[-1]
  206. and line and not line[0].isspace()):
  207. self._start_section()
  208. if (in_arg or not self.section.name
  209. or not self.section.name.startswith("Example")):
  210. line = line.strip()
  211. self.section.append(line)
  212. class QAPISchemaParser(object):
  213. def __init__(self, fp, previously_included=[], incl_info=None):
  214. abs_fname = os.path.abspath(fp.name)
  215. fname = fp.name
  216. self.fname = fname
  217. previously_included.append(abs_fname)
  218. self.incl_info = incl_info
  219. self.src = fp.read()
  220. if self.src == '' or self.src[-1] != '\n':
  221. self.src += '\n'
  222. self.cursor = 0
  223. self.line = 1
  224. self.line_pos = 0
  225. self.exprs = []
  226. self.docs = []
  227. self.accept()
  228. while self.tok is not None:
  229. info = {'file': fname, 'line': self.line,
  230. 'parent': self.incl_info}
  231. if self.tok == '#':
  232. doc = self.get_doc(info)
  233. self.docs.append(doc)
  234. continue
  235. expr = self.get_expr(False)
  236. if 'include' in expr:
  237. if len(expr) != 1:
  238. raise QAPISemError(info, "Invalid 'include' directive")
  239. include = expr["include"]
  240. if not isinstance(include, str):
  241. raise QAPISemError(info,
  242. "Value of 'include' must be a string")
  243. self._include(include, info, os.path.dirname(abs_fname),
  244. previously_included)
  245. elif "pragma" in expr:
  246. if len(expr) != 1:
  247. raise QAPISemError(info, "Invalid 'pragma' directive")
  248. pragma = expr['pragma']
  249. if not isinstance(pragma, dict):
  250. raise QAPISemError(
  251. info, "Value of 'pragma' must be a dictionary")
  252. for name, value in pragma.iteritems():
  253. self._pragma(name, value, info)
  254. else:
  255. expr_elem = {'expr': expr,
  256. 'info': info}
  257. if (self.docs
  258. and self.docs[-1].info['file'] == fname
  259. and not self.docs[-1].expr):
  260. self.docs[-1].expr = expr
  261. expr_elem['doc'] = self.docs[-1]
  262. self.exprs.append(expr_elem)
  263. def _include(self, include, info, base_dir, previously_included):
  264. incl_abs_fname = os.path.join(base_dir, include)
  265. # catch inclusion cycle
  266. inf = info
  267. while inf:
  268. if incl_abs_fname == os.path.abspath(inf['file']):
  269. raise QAPISemError(info, "Inclusion loop for %s" % include)
  270. inf = inf['parent']
  271. # skip multiple include of the same file
  272. if incl_abs_fname in previously_included:
  273. return
  274. try:
  275. fobj = open(incl_abs_fname, 'r')
  276. except IOError as e:
  277. raise QAPISemError(info, '%s: %s' % (e.strerror, include))
  278. exprs_include = QAPISchemaParser(fobj, previously_included, info)
  279. self.exprs.extend(exprs_include.exprs)
  280. self.docs.extend(exprs_include.docs)
  281. def _pragma(self, name, value, info):
  282. global doc_required
  283. if name == 'doc-required':
  284. if not isinstance(value, bool):
  285. raise QAPISemError(info,
  286. "Pragma 'doc-required' must be boolean")
  287. doc_required = value
  288. else:
  289. raise QAPISemError(info, "Unknown pragma '%s'" % name)
  290. def accept(self, skip_comment=True):
  291. while True:
  292. self.tok = self.src[self.cursor]
  293. self.pos = self.cursor
  294. self.cursor += 1
  295. self.val = None
  296. if self.tok == '#':
  297. if self.src[self.cursor] == '#':
  298. # Start of doc comment
  299. skip_comment = False
  300. self.cursor = self.src.find('\n', self.cursor)
  301. if not skip_comment:
  302. self.val = self.src[self.pos:self.cursor]
  303. return
  304. elif self.tok in "{}:,[]":
  305. return
  306. elif self.tok == "'":
  307. string = ''
  308. esc = False
  309. while True:
  310. ch = self.src[self.cursor]
  311. self.cursor += 1
  312. if ch == '\n':
  313. raise QAPIParseError(self, 'Missing terminating "\'"')
  314. if esc:
  315. if ch == 'b':
  316. string += '\b'
  317. elif ch == 'f':
  318. string += '\f'
  319. elif ch == 'n':
  320. string += '\n'
  321. elif ch == 'r':
  322. string += '\r'
  323. elif ch == 't':
  324. string += '\t'
  325. elif ch == 'u':
  326. value = 0
  327. for _ in range(0, 4):
  328. ch = self.src[self.cursor]
  329. self.cursor += 1
  330. if ch not in "0123456789abcdefABCDEF":
  331. raise QAPIParseError(self,
  332. '\\u escape needs 4 '
  333. 'hex digits')
  334. value = (value << 4) + int(ch, 16)
  335. # If Python 2 and 3 didn't disagree so much on
  336. # how to handle Unicode, then we could allow
  337. # Unicode string defaults. But most of QAPI is
  338. # ASCII-only, so we aren't losing much for now.
  339. if not value or value > 0x7f:
  340. raise QAPIParseError(self,
  341. 'For now, \\u escape '
  342. 'only supports non-zero '
  343. 'values up to \\u007f')
  344. string += chr(value)
  345. elif ch in "\\/'\"":
  346. string += ch
  347. else:
  348. raise QAPIParseError(self,
  349. "Unknown escape \\%s" % ch)
  350. esc = False
  351. elif ch == "\\":
  352. esc = True
  353. elif ch == "'":
  354. self.val = string
  355. return
  356. else:
  357. string += ch
  358. elif self.src.startswith("true", self.pos):
  359. self.val = True
  360. self.cursor += 3
  361. return
  362. elif self.src.startswith("false", self.pos):
  363. self.val = False
  364. self.cursor += 4
  365. return
  366. elif self.src.startswith("null", self.pos):
  367. self.val = None
  368. self.cursor += 3
  369. return
  370. elif self.tok == '\n':
  371. if self.cursor == len(self.src):
  372. self.tok = None
  373. return
  374. self.line += 1
  375. self.line_pos = self.cursor
  376. elif not self.tok.isspace():
  377. raise QAPIParseError(self, 'Stray "%s"' % self.tok)
  378. def get_members(self):
  379. expr = OrderedDict()
  380. if self.tok == '}':
  381. self.accept()
  382. return expr
  383. if self.tok != "'":
  384. raise QAPIParseError(self, 'Expected string or "}"')
  385. while True:
  386. key = self.val
  387. self.accept()
  388. if self.tok != ':':
  389. raise QAPIParseError(self, 'Expected ":"')
  390. self.accept()
  391. if key in expr:
  392. raise QAPIParseError(self, 'Duplicate key "%s"' % key)
  393. expr[key] = self.get_expr(True)
  394. if self.tok == '}':
  395. self.accept()
  396. return expr
  397. if self.tok != ',':
  398. raise QAPIParseError(self, 'Expected "," or "}"')
  399. self.accept()
  400. if self.tok != "'":
  401. raise QAPIParseError(self, 'Expected string')
  402. def get_values(self):
  403. expr = []
  404. if self.tok == ']':
  405. self.accept()
  406. return expr
  407. if self.tok not in "{['tfn":
  408. raise QAPIParseError(self, 'Expected "{", "[", "]", string, '
  409. 'boolean or "null"')
  410. while True:
  411. expr.append(self.get_expr(True))
  412. if self.tok == ']':
  413. self.accept()
  414. return expr
  415. if self.tok != ',':
  416. raise QAPIParseError(self, 'Expected "," or "]"')
  417. self.accept()
  418. def get_expr(self, nested):
  419. if self.tok != '{' and not nested:
  420. raise QAPIParseError(self, 'Expected "{"')
  421. if self.tok == '{':
  422. self.accept()
  423. expr = self.get_members()
  424. elif self.tok == '[':
  425. self.accept()
  426. expr = self.get_values()
  427. elif self.tok in "'tfn":
  428. expr = self.val
  429. self.accept()
  430. else:
  431. raise QAPIParseError(self, 'Expected "{", "[" or string')
  432. return expr
  433. def get_doc(self, info):
  434. if self.val != '##':
  435. raise QAPIParseError(self, "Junk after '##' at start of "
  436. "documentation comment")
  437. doc = QAPIDoc(self, info)
  438. self.accept(False)
  439. while self.tok == '#':
  440. if self.val.startswith('##'):
  441. # End of doc comment
  442. if self.val != '##':
  443. raise QAPIParseError(self, "Junk after '##' at end of "
  444. "documentation comment")
  445. self.accept()
  446. return doc
  447. else:
  448. doc.append(self.val)
  449. self.accept(False)
  450. raise QAPIParseError(self, "Documentation comment must end with '##'")
  451. #
  452. # Semantic analysis of schema expressions
  453. # TODO fold into QAPISchema
  454. # TODO catching name collisions in generated code would be nice
  455. #
  456. def find_base_members(base):
  457. if isinstance(base, dict):
  458. return base
  459. base_struct_define = find_struct(base)
  460. if not base_struct_define:
  461. return None
  462. return base_struct_define['data']
  463. # Return the qtype of an alternate branch, or None on error.
  464. def find_alternate_member_qtype(qapi_type):
  465. if qapi_type in builtin_types:
  466. return builtin_types[qapi_type]
  467. elif find_struct(qapi_type):
  468. return "QTYPE_QDICT"
  469. elif find_enum(qapi_type):
  470. return "QTYPE_QSTRING"
  471. elif find_union(qapi_type):
  472. return "QTYPE_QDICT"
  473. return None
  474. # Return the discriminator enum define if discriminator is specified as an
  475. # enum type, otherwise return None.
  476. def discriminator_find_enum_define(expr):
  477. base = expr.get('base')
  478. discriminator = expr.get('discriminator')
  479. if not (discriminator and base):
  480. return None
  481. base_members = find_base_members(base)
  482. if not base_members:
  483. return None
  484. discriminator_type = base_members.get(discriminator)
  485. if not discriminator_type:
  486. return None
  487. return find_enum(discriminator_type)
  488. # Names must be letters, numbers, -, and _. They must start with letter,
  489. # except for downstream extensions which must start with __RFQDN_.
  490. # Dots are only valid in the downstream extension prefix.
  491. valid_name = re.compile('^(__[a-zA-Z0-9.-]+_)?'
  492. '[a-zA-Z][a-zA-Z0-9_-]*$')
  493. def check_name(info, source, name, allow_optional=False,
  494. enum_member=False):
  495. global valid_name
  496. membername = name
  497. if not isinstance(name, str):
  498. raise QAPISemError(info, "%s requires a string name" % source)
  499. if name.startswith('*'):
  500. membername = name[1:]
  501. if not allow_optional:
  502. raise QAPISemError(info, "%s does not allow optional name '%s'"
  503. % (source, name))
  504. # Enum members can start with a digit, because the generated C
  505. # code always prefixes it with the enum name
  506. if enum_member and membername[0].isdigit():
  507. membername = 'D' + membername
  508. # Reserve the entire 'q_' namespace for c_name(), and for 'q_empty'
  509. # and 'q_obj_*' implicit type names.
  510. if not valid_name.match(membername) or \
  511. c_name(membername, False).startswith('q_'):
  512. raise QAPISemError(info, "%s uses invalid name '%s'" % (source, name))
  513. def add_name(name, info, meta, implicit=False):
  514. global all_names
  515. check_name(info, "'%s'" % meta, name)
  516. # FIXME should reject names that differ only in '_' vs. '.'
  517. # vs. '-', because they're liable to clash in generated C.
  518. if name in all_names:
  519. raise QAPISemError(info, "%s '%s' is already defined"
  520. % (all_names[name], name))
  521. if not implicit and (name.endswith('Kind') or name.endswith('List')):
  522. raise QAPISemError(info, "%s '%s' should not end in '%s'"
  523. % (meta, name, name[-4:]))
  524. all_names[name] = meta
  525. def add_struct(definition, info):
  526. global struct_types
  527. name = definition['struct']
  528. add_name(name, info, 'struct')
  529. struct_types.append(definition)
  530. def find_struct(name):
  531. global struct_types
  532. for struct in struct_types:
  533. if struct['struct'] == name:
  534. return struct
  535. return None
  536. def add_union(definition, info):
  537. global union_types
  538. name = definition['union']
  539. add_name(name, info, 'union')
  540. union_types.append(definition)
  541. def find_union(name):
  542. global union_types
  543. for union in union_types:
  544. if union['union'] == name:
  545. return union
  546. return None
  547. def add_enum(name, info, enum_values=None, implicit=False):
  548. global enum_types
  549. add_name(name, info, 'enum', implicit)
  550. enum_types.append({"enum_name": name, "enum_values": enum_values})
  551. def find_enum(name):
  552. global enum_types
  553. for enum in enum_types:
  554. if enum['enum_name'] == name:
  555. return enum
  556. return None
  557. def is_enum(name):
  558. return find_enum(name) is not None
  559. def check_type(info, source, value, allow_array=False,
  560. allow_dict=False, allow_optional=False,
  561. allow_metas=[]):
  562. global all_names
  563. if value is None:
  564. return
  565. # Check if array type for value is okay
  566. if isinstance(value, list):
  567. if not allow_array:
  568. raise QAPISemError(info, "%s cannot be an array" % source)
  569. if len(value) != 1 or not isinstance(value[0], str):
  570. raise QAPISemError(info,
  571. "%s: array type must contain single type name" %
  572. source)
  573. value = value[0]
  574. # Check if type name for value is okay
  575. if isinstance(value, str):
  576. if value not in all_names:
  577. raise QAPISemError(info, "%s uses unknown type '%s'"
  578. % (source, value))
  579. if not all_names[value] in allow_metas:
  580. raise QAPISemError(info, "%s cannot use %s type '%s'" %
  581. (source, all_names[value], value))
  582. return
  583. if not allow_dict:
  584. raise QAPISemError(info, "%s should be a type name" % source)
  585. if not isinstance(value, OrderedDict):
  586. raise QAPISemError(info,
  587. "%s should be a dictionary or type name" % source)
  588. # value is a dictionary, check that each member is okay
  589. for (key, arg) in value.items():
  590. check_name(info, "Member of %s" % source, key,
  591. allow_optional=allow_optional)
  592. if c_name(key, False) == 'u' or c_name(key, False).startswith('has_'):
  593. raise QAPISemError(info, "Member of %s uses reserved name '%s'"
  594. % (source, key))
  595. # Todo: allow dictionaries to represent default values of
  596. # an optional argument.
  597. check_type(info, "Member '%s' of %s" % (key, source), arg,
  598. allow_array=True,
  599. allow_metas=['built-in', 'union', 'alternate', 'struct',
  600. 'enum'])
  601. def check_command(expr, info):
  602. name = expr['command']
  603. boxed = expr.get('boxed', False)
  604. args_meta = ['struct']
  605. if boxed:
  606. args_meta += ['union', 'alternate']
  607. check_type(info, "'data' for command '%s'" % name,
  608. expr.get('data'), allow_dict=not boxed, allow_optional=True,
  609. allow_metas=args_meta)
  610. returns_meta = ['union', 'struct']
  611. if name in returns_whitelist:
  612. returns_meta += ['built-in', 'alternate', 'enum']
  613. check_type(info, "'returns' for command '%s'" % name,
  614. expr.get('returns'), allow_array=True,
  615. allow_optional=True, allow_metas=returns_meta)
  616. def check_event(expr, info):
  617. global events
  618. name = expr['event']
  619. boxed = expr.get('boxed', False)
  620. meta = ['struct']
  621. if boxed:
  622. meta += ['union', 'alternate']
  623. events.append(name)
  624. check_type(info, "'data' for event '%s'" % name,
  625. expr.get('data'), allow_dict=not boxed, allow_optional=True,
  626. allow_metas=meta)
  627. def check_union(expr, info):
  628. name = expr['union']
  629. base = expr.get('base')
  630. discriminator = expr.get('discriminator')
  631. members = expr['data']
  632. # Two types of unions, determined by discriminator.
  633. # With no discriminator it is a simple union.
  634. if discriminator is None:
  635. enum_define = None
  636. allow_metas = ['built-in', 'union', 'alternate', 'struct', 'enum']
  637. if base is not None:
  638. raise QAPISemError(info, "Simple union '%s' must not have a base" %
  639. name)
  640. # Else, it's a flat union.
  641. else:
  642. # The object must have a string or dictionary 'base'.
  643. check_type(info, "'base' for union '%s'" % name,
  644. base, allow_dict=True, allow_optional=True,
  645. allow_metas=['struct'])
  646. if not base:
  647. raise QAPISemError(info, "Flat union '%s' must have a base"
  648. % name)
  649. base_members = find_base_members(base)
  650. assert base_members
  651. # The value of member 'discriminator' must name a non-optional
  652. # member of the base struct.
  653. check_name(info, "Discriminator of flat union '%s'" % name,
  654. discriminator)
  655. discriminator_type = base_members.get(discriminator)
  656. if not discriminator_type:
  657. raise QAPISemError(info,
  658. "Discriminator '%s' is not a member of base "
  659. "struct '%s'"
  660. % (discriminator, base))
  661. enum_define = find_enum(discriminator_type)
  662. allow_metas = ['struct']
  663. # Do not allow string discriminator
  664. if not enum_define:
  665. raise QAPISemError(info,
  666. "Discriminator '%s' must be of enumeration "
  667. "type" % discriminator)
  668. # Check every branch; don't allow an empty union
  669. if len(members) == 0:
  670. raise QAPISemError(info, "Union '%s' cannot have empty 'data'" % name)
  671. for (key, value) in members.items():
  672. check_name(info, "Member of union '%s'" % name, key)
  673. # Each value must name a known type
  674. check_type(info, "Member '%s' of union '%s'" % (key, name),
  675. value, allow_array=not base, allow_metas=allow_metas)
  676. # If the discriminator names an enum type, then all members
  677. # of 'data' must also be members of the enum type.
  678. if enum_define:
  679. if key not in enum_define['enum_values']:
  680. raise QAPISemError(info,
  681. "Discriminator value '%s' is not found in "
  682. "enum '%s'"
  683. % (key, enum_define["enum_name"]))
  684. # If discriminator is user-defined, ensure all values are covered
  685. if enum_define:
  686. for value in enum_define['enum_values']:
  687. if value not in members.keys():
  688. raise QAPISemError(info, "Union '%s' data missing '%s' branch"
  689. % (name, value))
  690. def check_alternate(expr, info):
  691. name = expr['alternate']
  692. members = expr['data']
  693. types_seen = {}
  694. # Check every branch; require at least two branches
  695. if len(members) < 2:
  696. raise QAPISemError(info,
  697. "Alternate '%s' should have at least two branches "
  698. "in 'data'" % name)
  699. for (key, value) in members.items():
  700. check_name(info, "Member of alternate '%s'" % name, key)
  701. # Ensure alternates have no type conflicts.
  702. check_type(info, "Member '%s' of alternate '%s'" % (key, name),
  703. value,
  704. allow_metas=['built-in', 'union', 'struct', 'enum'])
  705. qtype = find_alternate_member_qtype(value)
  706. if not qtype:
  707. raise QAPISemError(info, "Alternate '%s' member '%s' cannot use "
  708. "type '%s'" % (name, key, value))
  709. if qtype in types_seen:
  710. raise QAPISemError(info, "Alternate '%s' member '%s' can't "
  711. "be distinguished from member '%s'"
  712. % (name, key, types_seen[qtype]))
  713. types_seen[qtype] = key
  714. def check_enum(expr, info):
  715. name = expr['enum']
  716. members = expr.get('data')
  717. prefix = expr.get('prefix')
  718. if not isinstance(members, list):
  719. raise QAPISemError(info,
  720. "Enum '%s' requires an array for 'data'" % name)
  721. if prefix is not None and not isinstance(prefix, str):
  722. raise QAPISemError(info,
  723. "Enum '%s' requires a string for 'prefix'" % name)
  724. for member in members:
  725. check_name(info, "Member of enum '%s'" % name, member,
  726. enum_member=True)
  727. def check_struct(expr, info):
  728. name = expr['struct']
  729. members = expr['data']
  730. check_type(info, "'data' for struct '%s'" % name, members,
  731. allow_dict=True, allow_optional=True)
  732. check_type(info, "'base' for struct '%s'" % name, expr.get('base'),
  733. allow_metas=['struct'])
  734. def check_keys(expr_elem, meta, required, optional=[]):
  735. expr = expr_elem['expr']
  736. info = expr_elem['info']
  737. name = expr[meta]
  738. if not isinstance(name, str):
  739. raise QAPISemError(info, "'%s' key must have a string value" % meta)
  740. required = required + [meta]
  741. for (key, value) in expr.items():
  742. if key not in required and key not in optional:
  743. raise QAPISemError(info, "Unknown key '%s' in %s '%s'"
  744. % (key, meta, name))
  745. if (key == 'gen' or key == 'success-response') and value is not False:
  746. raise QAPISemError(info,
  747. "'%s' of %s '%s' should only use false value"
  748. % (key, meta, name))
  749. if key == 'boxed' and value is not True:
  750. raise QAPISemError(info,
  751. "'%s' of %s '%s' should only use true value"
  752. % (key, meta, name))
  753. for key in required:
  754. if key not in expr:
  755. raise QAPISemError(info, "Key '%s' is missing from %s '%s'"
  756. % (key, meta, name))
  757. def check_exprs(exprs):
  758. global all_names
  759. # Learn the types and check for valid expression keys
  760. for builtin in builtin_types.keys():
  761. all_names[builtin] = 'built-in'
  762. for expr_elem in exprs:
  763. expr = expr_elem['expr']
  764. info = expr_elem['info']
  765. if 'doc' not in expr_elem and doc_required:
  766. raise QAPISemError(info,
  767. "Expression missing documentation comment")
  768. if 'enum' in expr:
  769. check_keys(expr_elem, 'enum', ['data'], ['prefix'])
  770. add_enum(expr['enum'], info, expr['data'])
  771. elif 'union' in expr:
  772. check_keys(expr_elem, 'union', ['data'],
  773. ['base', 'discriminator'])
  774. add_union(expr, info)
  775. elif 'alternate' in expr:
  776. check_keys(expr_elem, 'alternate', ['data'])
  777. add_name(expr['alternate'], info, 'alternate')
  778. elif 'struct' in expr:
  779. check_keys(expr_elem, 'struct', ['data'], ['base'])
  780. add_struct(expr, info)
  781. elif 'command' in expr:
  782. check_keys(expr_elem, 'command', [],
  783. ['data', 'returns', 'gen', 'success-response', 'boxed'])
  784. add_name(expr['command'], info, 'command')
  785. elif 'event' in expr:
  786. check_keys(expr_elem, 'event', [], ['data', 'boxed'])
  787. add_name(expr['event'], info, 'event')
  788. else:
  789. raise QAPISemError(expr_elem['info'],
  790. "Expression is missing metatype")
  791. # Try again for hidden UnionKind enum
  792. for expr_elem in exprs:
  793. expr = expr_elem['expr']
  794. if 'union' in expr:
  795. if not discriminator_find_enum_define(expr):
  796. add_enum('%sKind' % expr['union'], expr_elem['info'],
  797. implicit=True)
  798. elif 'alternate' in expr:
  799. add_enum('%sKind' % expr['alternate'], expr_elem['info'],
  800. implicit=True)
  801. # Validate that exprs make sense
  802. for expr_elem in exprs:
  803. expr = expr_elem['expr']
  804. info = expr_elem['info']
  805. if 'enum' in expr:
  806. check_enum(expr, info)
  807. elif 'union' in expr:
  808. check_union(expr, info)
  809. elif 'alternate' in expr:
  810. check_alternate(expr, info)
  811. elif 'struct' in expr:
  812. check_struct(expr, info)
  813. elif 'command' in expr:
  814. check_command(expr, info)
  815. elif 'event' in expr:
  816. check_event(expr, info)
  817. else:
  818. assert False, 'unexpected meta type'
  819. return exprs
  820. def check_freeform_doc(doc):
  821. if doc.symbol:
  822. raise QAPISemError(doc.info,
  823. "Documention for '%s' is not followed"
  824. " by the definition" % doc.symbol)
  825. body = str(doc.body)
  826. if re.search(r'@\S+:', body, re.MULTILINE):
  827. raise QAPISemError(doc.info,
  828. "Free-form documentation block must not contain"
  829. " @NAME: sections")
  830. def check_definition_doc(doc, expr, info):
  831. for i in ('enum', 'union', 'alternate', 'struct', 'command', 'event'):
  832. if i in expr:
  833. meta = i
  834. break
  835. name = expr[meta]
  836. if doc.symbol != name:
  837. raise QAPISemError(info, "Definition of '%s' follows documentation"
  838. " for '%s'" % (name, doc.symbol))
  839. if doc.has_section('Returns') and 'command' not in expr:
  840. raise QAPISemError(info, "'Returns:' is only valid for commands")
  841. if meta == 'union':
  842. args = expr.get('base', [])
  843. else:
  844. args = expr.get('data', [])
  845. if isinstance(args, str):
  846. return
  847. if isinstance(args, dict):
  848. args = args.keys()
  849. assert isinstance(args, list)
  850. if (meta == 'alternate'
  851. or (meta == 'union' and not expr.get('discriminator'))):
  852. args.append('type')
  853. for arg in args:
  854. if arg[0] == '*':
  855. opt = True
  856. desc = doc.args.get(arg[1:])
  857. else:
  858. opt = False
  859. desc = doc.args.get(arg)
  860. if not desc:
  861. continue
  862. desc_opt = "#optional" in str(desc)
  863. if desc_opt and not opt:
  864. raise QAPISemError(info, "Description has #optional, "
  865. "but the declaration doesn't")
  866. if not desc_opt and opt:
  867. # silently fix the doc
  868. # TODO either fix the schema and make this an error,
  869. # or drop #optional entirely
  870. desc.append("#optional")
  871. doc_args = set(doc.args.keys())
  872. args = set([name.strip('*') for name in args])
  873. if not doc_args.issubset(args):
  874. raise QAPISemError(info, "The following documented members are not in "
  875. "the declaration: %s" % ", ".join(doc_args - args))
  876. def check_docs(docs):
  877. for doc in docs:
  878. for section in doc.args.values() + doc.sections:
  879. content = str(section)
  880. if not content or content.isspace():
  881. raise QAPISemError(doc.info,
  882. "Empty doc section '%s'" % section.name)
  883. if not doc.expr:
  884. check_freeform_doc(doc)
  885. else:
  886. check_definition_doc(doc, doc.expr, doc.info)
  887. return docs
  888. #
  889. # Schema compiler frontend
  890. #
  891. class QAPISchemaEntity(object):
  892. def __init__(self, name, info):
  893. assert isinstance(name, str)
  894. self.name = name
  895. # For explicitly defined entities, info points to the (explicit)
  896. # definition. For builtins (and their arrays), info is None.
  897. # For implicitly defined entities, info points to a place that
  898. # triggered the implicit definition (there may be more than one
  899. # such place).
  900. self.info = info
  901. def c_name(self):
  902. return c_name(self.name)
  903. def check(self, schema):
  904. pass
  905. def is_implicit(self):
  906. return not self.info
  907. def visit(self, visitor):
  908. pass
  909. class QAPISchemaVisitor(object):
  910. def visit_begin(self, schema):
  911. pass
  912. def visit_end(self):
  913. pass
  914. def visit_needed(self, entity):
  915. # Default to visiting everything
  916. return True
  917. def visit_builtin_type(self, name, info, json_type):
  918. pass
  919. def visit_enum_type(self, name, info, values, prefix):
  920. pass
  921. def visit_array_type(self, name, info, element_type):
  922. pass
  923. def visit_object_type(self, name, info, base, members, variants):
  924. pass
  925. def visit_object_type_flat(self, name, info, members, variants):
  926. pass
  927. def visit_alternate_type(self, name, info, variants):
  928. pass
  929. def visit_command(self, name, info, arg_type, ret_type,
  930. gen, success_response, boxed):
  931. pass
  932. def visit_event(self, name, info, arg_type, boxed):
  933. pass
  934. class QAPISchemaType(QAPISchemaEntity):
  935. # Return the C type for common use.
  936. # For the types we commonly box, this is a pointer type.
  937. def c_type(self):
  938. pass
  939. # Return the C type to be used in a parameter list.
  940. def c_param_type(self):
  941. return self.c_type()
  942. # Return the C type to be used where we suppress boxing.
  943. def c_unboxed_type(self):
  944. return self.c_type()
  945. def json_type(self):
  946. pass
  947. def alternate_qtype(self):
  948. json2qtype = {
  949. 'string': 'QTYPE_QSTRING',
  950. 'number': 'QTYPE_QFLOAT',
  951. 'int': 'QTYPE_QINT',
  952. 'boolean': 'QTYPE_QBOOL',
  953. 'object': 'QTYPE_QDICT'
  954. }
  955. return json2qtype.get(self.json_type())
  956. class QAPISchemaBuiltinType(QAPISchemaType):
  957. def __init__(self, name, json_type, c_type):
  958. QAPISchemaType.__init__(self, name, None)
  959. assert not c_type or isinstance(c_type, str)
  960. assert json_type in ('string', 'number', 'int', 'boolean', 'null',
  961. 'value')
  962. self._json_type_name = json_type
  963. self._c_type_name = c_type
  964. def c_name(self):
  965. return self.name
  966. def c_type(self):
  967. return self._c_type_name
  968. def c_param_type(self):
  969. if self.name == 'str':
  970. return 'const ' + self._c_type_name
  971. return self._c_type_name
  972. def json_type(self):
  973. return self._json_type_name
  974. def visit(self, visitor):
  975. visitor.visit_builtin_type(self.name, self.info, self.json_type())
  976. class QAPISchemaEnumType(QAPISchemaType):
  977. def __init__(self, name, info, values, prefix):
  978. QAPISchemaType.__init__(self, name, info)
  979. for v in values:
  980. assert isinstance(v, QAPISchemaMember)
  981. v.set_owner(name)
  982. assert prefix is None or isinstance(prefix, str)
  983. self.values = values
  984. self.prefix = prefix
  985. def check(self, schema):
  986. seen = {}
  987. for v in self.values:
  988. v.check_clash(self.info, seen)
  989. def is_implicit(self):
  990. # See QAPISchema._make_implicit_enum_type()
  991. return self.name.endswith('Kind')
  992. def c_type(self):
  993. return c_name(self.name)
  994. def member_names(self):
  995. return [v.name for v in self.values]
  996. def json_type(self):
  997. return 'string'
  998. def visit(self, visitor):
  999. visitor.visit_enum_type(self.name, self.info,
  1000. self.member_names(), self.prefix)
  1001. class QAPISchemaArrayType(QAPISchemaType):
  1002. def __init__(self, name, info, element_type):
  1003. QAPISchemaType.__init__(self, name, info)
  1004. assert isinstance(element_type, str)
  1005. self._element_type_name = element_type
  1006. self.element_type = None
  1007. def check(self, schema):
  1008. self.element_type = schema.lookup_type(self._element_type_name)
  1009. assert self.element_type
  1010. def is_implicit(self):
  1011. return True
  1012. def c_type(self):
  1013. return c_name(self.name) + pointer_suffix
  1014. def json_type(self):
  1015. return 'array'
  1016. def visit(self, visitor):
  1017. visitor.visit_array_type(self.name, self.info, self.element_type)
  1018. class QAPISchemaObjectType(QAPISchemaType):
  1019. def __init__(self, name, info, base, local_members, variants):
  1020. # struct has local_members, optional base, and no variants
  1021. # flat union has base, variants, and no local_members
  1022. # simple union has local_members, variants, and no base
  1023. QAPISchemaType.__init__(self, name, info)
  1024. assert base is None or isinstance(base, str)
  1025. for m in local_members:
  1026. assert isinstance(m, QAPISchemaObjectTypeMember)
  1027. m.set_owner(name)
  1028. if variants is not None:
  1029. assert isinstance(variants, QAPISchemaObjectTypeVariants)
  1030. variants.set_owner(name)
  1031. self._base_name = base
  1032. self.base = None
  1033. self.local_members = local_members
  1034. self.variants = variants
  1035. self.members = None
  1036. def check(self, schema):
  1037. if self.members is False: # check for cycles
  1038. raise QAPISemError(self.info,
  1039. "Object %s contains itself" % self.name)
  1040. if self.members:
  1041. return
  1042. self.members = False # mark as being checked
  1043. seen = OrderedDict()
  1044. if self._base_name:
  1045. self.base = schema.lookup_type(self._base_name)
  1046. assert isinstance(self.base, QAPISchemaObjectType)
  1047. self.base.check(schema)
  1048. self.base.check_clash(schema, self.info, seen)
  1049. for m in self.local_members:
  1050. m.check(schema)
  1051. m.check_clash(self.info, seen)
  1052. self.members = seen.values()
  1053. if self.variants:
  1054. self.variants.check(schema, seen)
  1055. assert self.variants.tag_member in self.members
  1056. self.variants.check_clash(schema, self.info, seen)
  1057. # Check that the members of this type do not cause duplicate JSON members,
  1058. # and update seen to track the members seen so far. Report any errors
  1059. # on behalf of info, which is not necessarily self.info
  1060. def check_clash(self, schema, info, seen):
  1061. assert not self.variants # not implemented
  1062. for m in self.members:
  1063. m.check_clash(info, seen)
  1064. def is_implicit(self):
  1065. # See QAPISchema._make_implicit_object_type(), as well as
  1066. # _def_predefineds()
  1067. return self.name.startswith('q_')
  1068. def is_empty(self):
  1069. assert self.members is not None
  1070. return not self.members and not self.variants
  1071. def c_name(self):
  1072. assert self.name != 'q_empty'
  1073. return QAPISchemaType.c_name(self)
  1074. def c_type(self):
  1075. assert not self.is_implicit()
  1076. return c_name(self.name) + pointer_suffix
  1077. def c_unboxed_type(self):
  1078. return c_name(self.name)
  1079. def json_type(self):
  1080. return 'object'
  1081. def visit(self, visitor):
  1082. visitor.visit_object_type(self.name, self.info,
  1083. self.base, self.local_members, self.variants)
  1084. visitor.visit_object_type_flat(self.name, self.info,
  1085. self.members, self.variants)
  1086. class QAPISchemaMember(object):
  1087. role = 'member'
  1088. def __init__(self, name):
  1089. assert isinstance(name, str)
  1090. self.name = name
  1091. self.owner = None
  1092. def set_owner(self, name):
  1093. assert not self.owner
  1094. self.owner = name
  1095. def check_clash(self, info, seen):
  1096. cname = c_name(self.name)
  1097. if cname.lower() != cname and self.owner not in case_whitelist:
  1098. raise QAPISemError(info,
  1099. "%s should not use uppercase" % self.describe())
  1100. if cname in seen:
  1101. raise QAPISemError(info, "%s collides with %s" %
  1102. (self.describe(), seen[cname].describe()))
  1103. seen[cname] = self
  1104. def _pretty_owner(self):
  1105. owner = self.owner
  1106. if owner.startswith('q_obj_'):
  1107. # See QAPISchema._make_implicit_object_type() - reverse the
  1108. # mapping there to create a nice human-readable description
  1109. owner = owner[6:]
  1110. if owner.endswith('-arg'):
  1111. return '(parameter of %s)' % owner[:-4]
  1112. elif owner.endswith('-base'):
  1113. return '(base of %s)' % owner[:-5]
  1114. else:
  1115. assert owner.endswith('-wrapper')
  1116. # Unreachable and not implemented
  1117. assert False
  1118. if owner.endswith('Kind'):
  1119. # See QAPISchema._make_implicit_enum_type()
  1120. return '(branch of %s)' % owner[:-4]
  1121. return '(%s of %s)' % (self.role, owner)
  1122. def describe(self):
  1123. return "'%s' %s" % (self.name, self._pretty_owner())
  1124. class QAPISchemaObjectTypeMember(QAPISchemaMember):
  1125. def __init__(self, name, typ, optional):
  1126. QAPISchemaMember.__init__(self, name)
  1127. assert isinstance(typ, str)
  1128. assert isinstance(optional, bool)
  1129. self._type_name = typ
  1130. self.type = None
  1131. self.optional = optional
  1132. def check(self, schema):
  1133. assert self.owner
  1134. self.type = schema.lookup_type(self._type_name)
  1135. assert self.type
  1136. class QAPISchemaObjectTypeVariants(object):
  1137. def __init__(self, tag_name, tag_member, variants):
  1138. # Flat unions pass tag_name but not tag_member.
  1139. # Simple unions and alternates pass tag_member but not tag_name.
  1140. # After check(), tag_member is always set, and tag_name remains
  1141. # a reliable witness of being used by a flat union.
  1142. assert bool(tag_member) != bool(tag_name)
  1143. assert (isinstance(tag_name, str) or
  1144. isinstance(tag_member, QAPISchemaObjectTypeMember))
  1145. assert len(variants) > 0
  1146. for v in variants:
  1147. assert isinstance(v, QAPISchemaObjectTypeVariant)
  1148. self._tag_name = tag_name
  1149. self.tag_member = tag_member
  1150. self.variants = variants
  1151. def set_owner(self, name):
  1152. for v in self.variants:
  1153. v.set_owner(name)
  1154. def check(self, schema, seen):
  1155. if not self.tag_member: # flat union
  1156. self.tag_member = seen[c_name(self._tag_name)]
  1157. assert self._tag_name == self.tag_member.name
  1158. assert isinstance(self.tag_member.type, QAPISchemaEnumType)
  1159. for v in self.variants:
  1160. v.check(schema)
  1161. # Union names must match enum values; alternate names are
  1162. # checked separately. Use 'seen' to tell the two apart.
  1163. if seen:
  1164. assert v.name in self.tag_member.type.member_names()
  1165. assert isinstance(v.type, QAPISchemaObjectType)
  1166. v.type.check(schema)
  1167. def check_clash(self, schema, info, seen):
  1168. for v in self.variants:
  1169. # Reset seen map for each variant, since qapi names from one
  1170. # branch do not affect another branch
  1171. assert isinstance(v.type, QAPISchemaObjectType)
  1172. v.type.check_clash(schema, info, dict(seen))
  1173. class QAPISchemaObjectTypeVariant(QAPISchemaObjectTypeMember):
  1174. role = 'branch'
  1175. def __init__(self, name, typ):
  1176. QAPISchemaObjectTypeMember.__init__(self, name, typ, False)
  1177. class QAPISchemaAlternateType(QAPISchemaType):
  1178. def __init__(self, name, info, variants):
  1179. QAPISchemaType.__init__(self, name, info)
  1180. assert isinstance(variants, QAPISchemaObjectTypeVariants)
  1181. assert variants.tag_member
  1182. variants.set_owner(name)
  1183. variants.tag_member.set_owner(self.name)
  1184. self.variants = variants
  1185. def check(self, schema):
  1186. self.variants.tag_member.check(schema)
  1187. # Not calling self.variants.check_clash(), because there's nothing
  1188. # to clash with
  1189. self.variants.check(schema, {})
  1190. # Alternate branch names have no relation to the tag enum values;
  1191. # so we have to check for potential name collisions ourselves.
  1192. seen = {}
  1193. for v in self.variants.variants:
  1194. v.check_clash(self.info, seen)
  1195. def c_type(self):
  1196. return c_name(self.name) + pointer_suffix
  1197. def json_type(self):
  1198. return 'value'
  1199. def visit(self, visitor):
  1200. visitor.visit_alternate_type(self.name, self.info, self.variants)
  1201. def is_empty(self):
  1202. return False
  1203. class QAPISchemaCommand(QAPISchemaEntity):
  1204. def __init__(self, name, info, arg_type, ret_type, gen, success_response,
  1205. boxed):
  1206. QAPISchemaEntity.__init__(self, name, info)
  1207. assert not arg_type or isinstance(arg_type, str)
  1208. assert not ret_type or isinstance(ret_type, str)
  1209. self._arg_type_name = arg_type
  1210. self.arg_type = None
  1211. self._ret_type_name = ret_type
  1212. self.ret_type = None
  1213. self.gen = gen
  1214. self.success_response = success_response
  1215. self.boxed = boxed
  1216. def check(self, schema):
  1217. if self._arg_type_name:
  1218. self.arg_type = schema.lookup_type(self._arg_type_name)
  1219. assert (isinstance(self.arg_type, QAPISchemaObjectType) or
  1220. isinstance(self.arg_type, QAPISchemaAlternateType))
  1221. self.arg_type.check(schema)
  1222. if self.boxed:
  1223. if self.arg_type.is_empty():
  1224. raise QAPISemError(self.info,
  1225. "Cannot use 'boxed' with empty type")
  1226. else:
  1227. assert not isinstance(self.arg_type, QAPISchemaAlternateType)
  1228. assert not self.arg_type.variants
  1229. elif self.boxed:
  1230. raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
  1231. if self._ret_type_name:
  1232. self.ret_type = schema.lookup_type(self._ret_type_name)
  1233. assert isinstance(self.ret_type, QAPISchemaType)
  1234. def visit(self, visitor):
  1235. visitor.visit_command(self.name, self.info,
  1236. self.arg_type, self.ret_type,
  1237. self.gen, self.success_response, self.boxed)
  1238. class QAPISchemaEvent(QAPISchemaEntity):
  1239. def __init__(self, name, info, arg_type, boxed):
  1240. QAPISchemaEntity.__init__(self, name, info)
  1241. assert not arg_type or isinstance(arg_type, str)
  1242. self._arg_type_name = arg_type
  1243. self.arg_type = None
  1244. self.boxed = boxed
  1245. def check(self, schema):
  1246. if self._arg_type_name:
  1247. self.arg_type = schema.lookup_type(self._arg_type_name)
  1248. assert (isinstance(self.arg_type, QAPISchemaObjectType) or
  1249. isinstance(self.arg_type, QAPISchemaAlternateType))
  1250. self.arg_type.check(schema)
  1251. if self.boxed:
  1252. if self.arg_type.is_empty():
  1253. raise QAPISemError(self.info,
  1254. "Cannot use 'boxed' with empty type")
  1255. else:
  1256. assert not isinstance(self.arg_type, QAPISchemaAlternateType)
  1257. assert not self.arg_type.variants
  1258. elif self.boxed:
  1259. raise QAPISemError(self.info, "Use of 'boxed' requires 'data'")
  1260. def visit(self, visitor):
  1261. visitor.visit_event(self.name, self.info, self.arg_type, self.boxed)
  1262. class QAPISchema(object):
  1263. def __init__(self, fname):
  1264. try:
  1265. parser = QAPISchemaParser(open(fname, "r"))
  1266. self.exprs = check_exprs(parser.exprs)
  1267. self.docs = check_docs(parser.docs)
  1268. self._entity_dict = {}
  1269. self._predefining = True
  1270. self._def_predefineds()
  1271. self._predefining = False
  1272. self._def_exprs()
  1273. self.check()
  1274. except QAPIError as err:
  1275. print >>sys.stderr, err
  1276. exit(1)
  1277. def _def_entity(self, ent):
  1278. # Only the predefined types are allowed to not have info
  1279. assert ent.info or self._predefining
  1280. assert ent.name not in self._entity_dict
  1281. self._entity_dict[ent.name] = ent
  1282. def lookup_entity(self, name, typ=None):
  1283. ent = self._entity_dict.get(name)
  1284. if typ and not isinstance(ent, typ):
  1285. return None
  1286. return ent
  1287. def lookup_type(self, name):
  1288. return self.lookup_entity(name, QAPISchemaType)
  1289. def _def_builtin_type(self, name, json_type, c_type):
  1290. self._def_entity(QAPISchemaBuiltinType(name, json_type, c_type))
  1291. # TODO As long as we have QAPI_TYPES_BUILTIN to share multiple
  1292. # qapi-types.h from a single .c, all arrays of builtins must be
  1293. # declared in the first file whether or not they are used. Nicer
  1294. # would be to use lazy instantiation, while figuring out how to
  1295. # avoid compilation issues with multiple qapi-types.h.
  1296. self._make_array_type(name, None)
  1297. def _def_predefineds(self):
  1298. for t in [('str', 'string', 'char' + pointer_suffix),
  1299. ('number', 'number', 'double'),
  1300. ('int', 'int', 'int64_t'),
  1301. ('int8', 'int', 'int8_t'),
  1302. ('int16', 'int', 'int16_t'),
  1303. ('int32', 'int', 'int32_t'),
  1304. ('int64', 'int', 'int64_t'),
  1305. ('uint8', 'int', 'uint8_t'),
  1306. ('uint16', 'int', 'uint16_t'),
  1307. ('uint32', 'int', 'uint32_t'),
  1308. ('uint64', 'int', 'uint64_t'),
  1309. ('size', 'int', 'uint64_t'),
  1310. ('bool', 'boolean', 'bool'),
  1311. ('any', 'value', 'QObject' + pointer_suffix)]:
  1312. self._def_builtin_type(*t)
  1313. self.the_empty_object_type = QAPISchemaObjectType('q_empty', None,
  1314. None, [], None)
  1315. self._def_entity(self.the_empty_object_type)
  1316. qtype_values = self._make_enum_members(['none', 'qnull', 'qint',
  1317. 'qstring', 'qdict', 'qlist',
  1318. 'qfloat', 'qbool'])
  1319. self._def_entity(QAPISchemaEnumType('QType', None, qtype_values,
  1320. 'QTYPE'))
  1321. def _make_enum_members(self, values):
  1322. return [QAPISchemaMember(v) for v in values]
  1323. def _make_implicit_enum_type(self, name, info, values):
  1324. # See also QAPISchemaObjectTypeMember._pretty_owner()
  1325. name = name + 'Kind' # Use namespace reserved by add_name()
  1326. self._def_entity(QAPISchemaEnumType(
  1327. name, info, self._make_enum_members(values), None))
  1328. return name
  1329. def _make_array_type(self, element_type, info):
  1330. name = element_type + 'List' # Use namespace reserved by add_name()
  1331. if not self.lookup_type(name):
  1332. self._def_entity(QAPISchemaArrayType(name, info, element_type))
  1333. return name
  1334. def _make_implicit_object_type(self, name, info, role, members):
  1335. if not members:
  1336. return None
  1337. # See also QAPISchemaObjectTypeMember._pretty_owner()
  1338. name = 'q_obj_%s-%s' % (name, role)
  1339. if not self.lookup_entity(name, QAPISchemaObjectType):
  1340. self._def_entity(QAPISchemaObjectType(name, info, None,
  1341. members, None))
  1342. return name
  1343. def _def_enum_type(self, expr, info):
  1344. name = expr['enum']
  1345. data = expr['data']
  1346. prefix = expr.get('prefix')
  1347. self._def_entity(QAPISchemaEnumType(
  1348. name, info, self._make_enum_members(data), prefix))
  1349. def _make_member(self, name, typ, info):
  1350. optional = False
  1351. if name.startswith('*'):
  1352. name = name[1:]
  1353. optional = True
  1354. if isinstance(typ, list):
  1355. assert len(typ) == 1
  1356. typ = self._make_array_type(typ[0], info)
  1357. return QAPISchemaObjectTypeMember(name, typ, optional)
  1358. def _make_members(self, data, info):
  1359. return [self._make_member(key, value, info)
  1360. for (key, value) in data.iteritems()]
  1361. def _def_struct_type(self, expr, info):
  1362. name = expr['struct']
  1363. base = expr.get('base')
  1364. data = expr['data']
  1365. self._def_entity(QAPISchemaObjectType(name, info, base,
  1366. self._make_members(data, info),
  1367. None))
  1368. def _make_variant(self, case, typ):
  1369. return QAPISchemaObjectTypeVariant(case, typ)
  1370. def _make_simple_variant(self, case, typ, info):
  1371. if isinstance(typ, list):
  1372. assert len(typ) == 1
  1373. typ = self._make_array_type(typ[0], info)
  1374. typ = self._make_implicit_object_type(
  1375. typ, info, 'wrapper', [self._make_member('data', typ, info)])
  1376. return QAPISchemaObjectTypeVariant(case, typ)
  1377. def _def_union_type(self, expr, info):
  1378. name = expr['union']
  1379. data = expr['data']
  1380. base = expr.get('base')
  1381. tag_name = expr.get('discriminator')
  1382. tag_member = None
  1383. if isinstance(base, dict):
  1384. base = (self._make_implicit_object_type(
  1385. name, info, 'base', self._make_members(base, info)))
  1386. if tag_name:
  1387. variants = [self._make_variant(key, value)
  1388. for (key, value) in data.iteritems()]
  1389. members = []
  1390. else:
  1391. variants = [self._make_simple_variant(key, value, info)
  1392. for (key, value) in data.iteritems()]
  1393. typ = self._make_implicit_enum_type(name, info,
  1394. [v.name for v in variants])
  1395. tag_member = QAPISchemaObjectTypeMember('type', typ, False)
  1396. members = [tag_member]
  1397. self._def_entity(
  1398. QAPISchemaObjectType(name, info, base, members,
  1399. QAPISchemaObjectTypeVariants(tag_name,
  1400. tag_member,
  1401. variants)))
  1402. def _def_alternate_type(self, expr, info):
  1403. name = expr['alternate']
  1404. data = expr['data']
  1405. variants = [self._make_variant(key, value)
  1406. for (key, value) in data.iteritems()]
  1407. tag_member = QAPISchemaObjectTypeMember('type', 'QType', False)
  1408. self._def_entity(
  1409. QAPISchemaAlternateType(name, info,
  1410. QAPISchemaObjectTypeVariants(None,
  1411. tag_member,
  1412. variants)))
  1413. def _def_command(self, expr, info):
  1414. name = expr['command']
  1415. data = expr.get('data')
  1416. rets = expr.get('returns')
  1417. gen = expr.get('gen', True)
  1418. success_response = expr.get('success-response', True)
  1419. boxed = expr.get('boxed', False)
  1420. if isinstance(data, OrderedDict):
  1421. data = self._make_implicit_object_type(
  1422. name, info, 'arg', self._make_members(data, info))
  1423. if isinstance(rets, list):
  1424. assert len(rets) == 1
  1425. rets = self._make_array_type(rets[0], info)
  1426. self._def_entity(QAPISchemaCommand(name, info, data, rets, gen,
  1427. success_response, boxed))
  1428. def _def_event(self, expr, info):
  1429. name = expr['event']
  1430. data = expr.get('data')
  1431. boxed = expr.get('boxed', False)
  1432. if isinstance(data, OrderedDict):
  1433. data = self._make_implicit_object_type(
  1434. name, info, 'arg', self._make_members(data, info))
  1435. self._def_entity(QAPISchemaEvent(name, info, data, boxed))
  1436. def _def_exprs(self):
  1437. for expr_elem in self.exprs:
  1438. expr = expr_elem['expr']
  1439. info = expr_elem['info']
  1440. if 'enum' in expr:
  1441. self._def_enum_type(expr, info)
  1442. elif 'struct' in expr:
  1443. self._def_struct_type(expr, info)
  1444. elif 'union' in expr:
  1445. self._def_union_type(expr, info)
  1446. elif 'alternate' in expr:
  1447. self._def_alternate_type(expr, info)
  1448. elif 'command' in expr:
  1449. self._def_command(expr, info)
  1450. elif 'event' in expr:
  1451. self._def_event(expr, info)
  1452. else:
  1453. assert False
  1454. def check(self):
  1455. for ent in self._entity_dict.values():
  1456. ent.check(self)
  1457. def visit(self, visitor):
  1458. visitor.visit_begin(self)
  1459. for (name, entity) in sorted(self._entity_dict.items()):
  1460. if visitor.visit_needed(entity):
  1461. entity.visit(visitor)
  1462. visitor.visit_end()
  1463. #
  1464. # Code generation helpers
  1465. #
  1466. def camel_case(name):
  1467. new_name = ''
  1468. first = True
  1469. for ch in name:
  1470. if ch in ['_', '-']:
  1471. first = True
  1472. elif first:
  1473. new_name += ch.upper()
  1474. first = False
  1475. else:
  1476. new_name += ch.lower()
  1477. return new_name
  1478. # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
  1479. # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
  1480. # ENUM24_Name -> ENUM24_NAME
  1481. def camel_to_upper(value):
  1482. c_fun_str = c_name(value, False)
  1483. if value.isupper():
  1484. return c_fun_str
  1485. new_name = ''
  1486. l = len(c_fun_str)
  1487. for i in range(l):
  1488. c = c_fun_str[i]
  1489. # When c is upper and no "_" appears before, do more checks
  1490. if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
  1491. if i < l - 1 and c_fun_str[i + 1].islower():
  1492. new_name += '_'
  1493. elif c_fun_str[i - 1].isdigit():
  1494. new_name += '_'
  1495. new_name += c
  1496. return new_name.lstrip('_').upper()
  1497. def c_enum_const(type_name, const_name, prefix=None):
  1498. if prefix is not None:
  1499. type_name = prefix
  1500. return camel_to_upper(type_name) + '_' + c_name(const_name, False).upper()
  1501. c_name_trans = string.maketrans('.-', '__')
  1502. # Map @name to a valid C identifier.
  1503. # If @protect, avoid returning certain ticklish identifiers (like
  1504. # C keywords) by prepending "q_".
  1505. #
  1506. # Used for converting 'name' from a 'name':'type' qapi definition
  1507. # into a generated struct member, as well as converting type names
  1508. # into substrings of a generated C function name.
  1509. # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
  1510. # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
  1511. def c_name(name, protect=True):
  1512. # ANSI X3J11/88-090, 3.1.1
  1513. c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
  1514. 'default', 'do', 'double', 'else', 'enum', 'extern',
  1515. 'float', 'for', 'goto', 'if', 'int', 'long', 'register',
  1516. 'return', 'short', 'signed', 'sizeof', 'static',
  1517. 'struct', 'switch', 'typedef', 'union', 'unsigned',
  1518. 'void', 'volatile', 'while'])
  1519. # ISO/IEC 9899:1999, 6.4.1
  1520. c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
  1521. # ISO/IEC 9899:2011, 6.4.1
  1522. c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic',
  1523. '_Noreturn', '_Static_assert', '_Thread_local'])
  1524. # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
  1525. # excluding _.*
  1526. gcc_words = set(['asm', 'typeof'])
  1527. # C++ ISO/IEC 14882:2003 2.11
  1528. cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
  1529. 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
  1530. 'namespace', 'new', 'operator', 'private', 'protected',
  1531. 'public', 'reinterpret_cast', 'static_cast', 'template',
  1532. 'this', 'throw', 'true', 'try', 'typeid', 'typename',
  1533. 'using', 'virtual', 'wchar_t',
  1534. # alternative representations
  1535. 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
  1536. 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
  1537. # namespace pollution:
  1538. polluted_words = set(['unix', 'errno', 'mips', 'sparc'])
  1539. name = name.translate(c_name_trans)
  1540. if protect and (name in c89_words | c99_words | c11_words | gcc_words
  1541. | cpp_words | polluted_words):
  1542. return "q_" + name
  1543. return name
  1544. eatspace = '\033EATSPACE.'
  1545. pointer_suffix = ' *' + eatspace
  1546. def genindent(count):
  1547. ret = ""
  1548. for _ in range(count):
  1549. ret += " "
  1550. return ret
  1551. indent_level = 0
  1552. def push_indent(indent_amount=4):
  1553. global indent_level
  1554. indent_level += indent_amount
  1555. def pop_indent(indent_amount=4):
  1556. global indent_level
  1557. indent_level -= indent_amount
  1558. # Generate @code with @kwds interpolated.
  1559. # Obey indent_level, and strip eatspace.
  1560. def cgen(code, **kwds):
  1561. raw = code % kwds
  1562. if indent_level:
  1563. indent = genindent(indent_level)
  1564. # re.subn() lacks flags support before Python 2.7, use re.compile()
  1565. raw = re.subn(re.compile("^.", re.MULTILINE),
  1566. indent + r'\g<0>', raw)
  1567. raw = raw[0]
  1568. return re.sub(re.escape(eatspace) + ' *', '', raw)
  1569. def mcgen(code, **kwds):
  1570. if code[0] == '\n':
  1571. code = code[1:]
  1572. return cgen(code, **kwds)
  1573. def guardname(filename):
  1574. return c_name(filename, protect=False).upper()
  1575. def guardstart(name):
  1576. return mcgen('''
  1577. #ifndef %(name)s
  1578. #define %(name)s
  1579. ''',
  1580. name=guardname(name))
  1581. def guardend(name):
  1582. return mcgen('''
  1583. #endif /* %(name)s */
  1584. ''',
  1585. name=guardname(name))
  1586. def gen_enum_lookup(name, values, prefix=None):
  1587. ret = mcgen('''
  1588. const char *const %(c_name)s_lookup[] = {
  1589. ''',
  1590. c_name=c_name(name))
  1591. for value in values:
  1592. index = c_enum_const(name, value, prefix)
  1593. ret += mcgen('''
  1594. [%(index)s] = "%(value)s",
  1595. ''',
  1596. index=index, value=value)
  1597. max_index = c_enum_const(name, '_MAX', prefix)
  1598. ret += mcgen('''
  1599. [%(max_index)s] = NULL,
  1600. };
  1601. ''',
  1602. max_index=max_index)
  1603. return ret
  1604. def gen_enum(name, values, prefix=None):
  1605. # append automatically generated _MAX value
  1606. enum_values = values + ['_MAX']
  1607. ret = mcgen('''
  1608. typedef enum %(c_name)s {
  1609. ''',
  1610. c_name=c_name(name))
  1611. i = 0
  1612. for value in enum_values:
  1613. ret += mcgen('''
  1614. %(c_enum)s = %(i)d,
  1615. ''',
  1616. c_enum=c_enum_const(name, value, prefix),
  1617. i=i)
  1618. i += 1
  1619. ret += mcgen('''
  1620. } %(c_name)s;
  1621. ''',
  1622. c_name=c_name(name))
  1623. ret += mcgen('''
  1624. extern const char *const %(c_name)s_lookup[];
  1625. ''',
  1626. c_name=c_name(name))
  1627. return ret
  1628. def gen_params(arg_type, boxed, extra):
  1629. if not arg_type:
  1630. assert not boxed
  1631. return extra
  1632. ret = ''
  1633. sep = ''
  1634. if boxed:
  1635. ret += '%s arg' % arg_type.c_param_type()
  1636. sep = ', '
  1637. else:
  1638. assert not arg_type.variants
  1639. for memb in arg_type.members:
  1640. ret += sep
  1641. sep = ', '
  1642. if memb.optional:
  1643. ret += 'bool has_%s, ' % c_name(memb.name)
  1644. ret += '%s %s' % (memb.type.c_param_type(),
  1645. c_name(memb.name))
  1646. if extra:
  1647. ret += sep + extra
  1648. return ret
  1649. #
  1650. # Common command line parsing
  1651. #
  1652. def parse_command_line(extra_options="", extra_long_options=[]):
  1653. try:
  1654. opts, args = getopt.gnu_getopt(sys.argv[1:],
  1655. "chp:o:" + extra_options,
  1656. ["source", "header", "prefix=",
  1657. "output-dir="] + extra_long_options)
  1658. except getopt.GetoptError as err:
  1659. print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
  1660. sys.exit(1)
  1661. output_dir = ""
  1662. prefix = ""
  1663. do_c = False
  1664. do_h = False
  1665. extra_opts = []
  1666. for oa in opts:
  1667. o, a = oa
  1668. if o in ("-p", "--prefix"):
  1669. match = re.match('([A-Za-z_.-][A-Za-z0-9_.-]*)?', a)
  1670. if match.end() != len(a):
  1671. print >>sys.stderr, \
  1672. "%s: 'funny character '%s' in argument of --prefix" \
  1673. % (sys.argv[0], a[match.end()])
  1674. sys.exit(1)
  1675. prefix = a
  1676. elif o in ("-o", "--output-dir"):
  1677. output_dir = a + "/"
  1678. elif o in ("-c", "--source"):
  1679. do_c = True
  1680. elif o in ("-h", "--header"):
  1681. do_h = True
  1682. else:
  1683. extra_opts.append(oa)
  1684. if not do_c and not do_h:
  1685. do_c = True
  1686. do_h = True
  1687. if len(args) != 1:
  1688. print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
  1689. sys.exit(1)
  1690. fname = args[0]
  1691. return (fname, output_dir, do_c, do_h, prefix, extra_opts)
  1692. #
  1693. # Generate output files with boilerplate
  1694. #
  1695. def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
  1696. c_comment, h_comment):
  1697. guard = guardname(prefix + h_file)
  1698. c_file = output_dir + prefix + c_file
  1699. h_file = output_dir + prefix + h_file
  1700. if output_dir:
  1701. try:
  1702. os.makedirs(output_dir)
  1703. except os.error as e:
  1704. if e.errno != errno.EEXIST:
  1705. raise
  1706. def maybe_open(really, name, opt):
  1707. if really:
  1708. return open(name, opt)
  1709. else:
  1710. import StringIO
  1711. return StringIO.StringIO()
  1712. fdef = maybe_open(do_c, c_file, 'w')
  1713. fdecl = maybe_open(do_h, h_file, 'w')
  1714. fdef.write(mcgen('''
  1715. /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
  1716. %(comment)s
  1717. ''',
  1718. comment=c_comment))
  1719. fdecl.write(mcgen('''
  1720. /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
  1721. %(comment)s
  1722. #ifndef %(guard)s
  1723. #define %(guard)s
  1724. ''',
  1725. comment=h_comment, guard=guard))
  1726. return (fdef, fdecl)
  1727. def close_output(fdef, fdecl):
  1728. fdecl.write('''
  1729. #endif
  1730. ''')
  1731. fdecl.close()
  1732. fdef.close()