blob: 2b5775d2af9e0134ac9344368f388d5900645600 [file] [log] [blame]
Michael Roth0f923be2011-07-19 14:50:39 -05001#
2# QAPI helper library
3#
4# Copyright IBM, Corp. 2011
Markus Armbrusterc7a3f252013-07-27 17:41:55 +02005# Copyright (c) 2013 Red Hat Inc.
Michael Roth0f923be2011-07-19 14:50:39 -05006#
7# Authors:
8# Anthony Liguori <aliguori@us.ibm.com>
Markus Armbrusterc7a3f252013-07-27 17:41:55 +02009# Markus Armbruster <armbru@redhat.com>
Michael Roth0f923be2011-07-19 14:50:39 -050010#
Markus Armbruster678e48a2014-03-01 08:40:34 +010011# This work is licensed under the terms of the GNU GPL, version 2.
12# See the COPYING file in the top-level directory.
Michael Roth0f923be2011-07-19 14:50:39 -050013
Lluís Vilanovaa719a272014-05-07 20:46:15 +020014import re
Michael Roth0f923be2011-07-19 14:50:39 -050015from ordereddict import OrderedDict
Lluís Vilanova33aaad52014-05-02 15:52:35 +020016import os
Markus Armbruster2caba362013-07-27 17:41:56 +020017import sys
Michael Roth0f923be2011-07-19 14:50:39 -050018
Eric Blakeb52c4b92015-05-04 09:05:00 -060019builtin_types = {
Kevin Wolf69dd62d2013-07-08 16:14:21 +020020 'str': 'QTYPE_QSTRING',
21 'int': 'QTYPE_QINT',
22 'number': 'QTYPE_QFLOAT',
23 'bool': 'QTYPE_QBOOL',
24 'int8': 'QTYPE_QINT',
25 'int16': 'QTYPE_QINT',
26 'int32': 'QTYPE_QINT',
27 'int64': 'QTYPE_QINT',
28 'uint8': 'QTYPE_QINT',
29 'uint16': 'QTYPE_QINT',
30 'uint32': 'QTYPE_QINT',
31 'uint64': 'QTYPE_QINT',
32}
33
Lluís Vilanovaa719a272014-05-07 20:46:15 +020034def error_path(parent):
35 res = ""
36 while parent:
37 res = ("In file included from %s:%d:\n" % (parent['file'],
38 parent['line'])) + res
39 parent = parent['parent']
40 return res
41
Markus Armbruster2caba362013-07-27 17:41:56 +020042class QAPISchemaError(Exception):
43 def __init__(self, schema, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020044 self.input_file = schema.input_file
Markus Armbruster2caba362013-07-27 17:41:56 +020045 self.msg = msg
Wenchao Xia515b9432014-03-04 18:44:33 -080046 self.col = 1
47 self.line = schema.line
48 for ch in schema.src[schema.line_pos:schema.pos]:
49 if ch == '\t':
Markus Armbruster2caba362013-07-27 17:41:56 +020050 self.col = (self.col + 7) % 8 + 1
51 else:
52 self.col += 1
Lluís Vilanovaa719a272014-05-07 20:46:15 +020053 self.info = schema.parent_info
Markus Armbruster2caba362013-07-27 17:41:56 +020054
55 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020056 return error_path(self.info) + \
57 "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg)
Markus Armbruster2caba362013-07-27 17:41:56 +020058
Wenchao Xiab86b05e2014-03-04 18:44:34 -080059class QAPIExprError(Exception):
60 def __init__(self, expr_info, msg):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020061 self.info = expr_info
Wenchao Xiab86b05e2014-03-04 18:44:34 -080062 self.msg = msg
63
64 def __str__(self):
Lluís Vilanovaa719a272014-05-07 20:46:15 +020065 return error_path(self.info['parent']) + \
66 "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
Wenchao Xiab86b05e2014-03-04 18:44:34 -080067
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020068class QAPISchema:
Michael Roth0f923be2011-07-19 14:50:39 -050069
Benoît Canet24fd8482014-05-16 12:51:56 +020070 def __init__(self, fp, input_relname=None, include_hist=[],
71 previously_included=[], parent_info=None):
72 """ include_hist is a stack used to detect inclusion cycles
73 previously_included is a global state used to avoid multiple
74 inclusions of the same file"""
Lluís Vilanovaa719a272014-05-07 20:46:15 +020075 input_fname = os.path.abspath(fp.name)
76 if input_relname is None:
77 input_relname = fp.name
78 self.input_dir = os.path.dirname(input_fname)
79 self.input_file = input_relname
80 self.include_hist = include_hist + [(input_relname, input_fname)]
Benoît Canet24fd8482014-05-16 12:51:56 +020081 previously_included.append(input_fname)
Lluís Vilanovaa719a272014-05-07 20:46:15 +020082 self.parent_info = parent_info
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020083 self.src = fp.read()
84 if self.src == '' or self.src[-1] != '\n':
85 self.src += '\n'
86 self.cursor = 0
Wenchao Xia515b9432014-03-04 18:44:33 -080087 self.line = 1
88 self.line_pos = 0
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020089 self.exprs = []
90 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -050091
Markus Armbrusterc7a3f252013-07-27 17:41:55 +020092 while self.tok != None:
Lluís Vilanovaa719a272014-05-07 20:46:15 +020093 expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info}
94 expr = self.get_expr(False)
95 if isinstance(expr, dict) and "include" in expr:
96 if len(expr) != 1:
97 raise QAPIExprError(expr_info, "Invalid 'include' directive")
98 include = expr["include"]
99 if not isinstance(include, str):
100 raise QAPIExprError(expr_info,
101 'Expected a file name (string), got: %s'
102 % include)
103 include_path = os.path.join(self.input_dir, include)
Stefan Hajnoczi7ac9a9d2014-08-27 12:08:51 +0100104 for elem in self.include_hist:
105 if include_path == elem[1]:
106 raise QAPIExprError(expr_info, "Inclusion loop for %s"
107 % include)
Benoît Canet24fd8482014-05-16 12:51:56 +0200108 # skip multiple include of the same file
109 if include_path in previously_included:
110 continue
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200111 try:
112 fobj = open(include_path, 'r')
Luiz Capitulino34788812014-05-20 13:50:19 -0400113 except IOError, e:
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200114 raise QAPIExprError(expr_info,
115 '%s: %s' % (e.strerror, include))
Benoît Canet24fd8482014-05-16 12:51:56 +0200116 exprs_include = QAPISchema(fobj, include, self.include_hist,
117 previously_included, expr_info)
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200118 self.exprs.extend(exprs_include.exprs)
119 else:
120 expr_elem = {'expr': expr,
121 'info': expr_info}
122 self.exprs.append(expr_elem)
Michael Roth0f923be2011-07-19 14:50:39 -0500123
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200124 def accept(self):
125 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200126 self.tok = self.src[self.cursor]
Markus Armbruster2caba362013-07-27 17:41:56 +0200127 self.pos = self.cursor
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200128 self.cursor += 1
129 self.val = None
Michael Roth0f923be2011-07-19 14:50:39 -0500130
Markus Armbrusterf1a145e2013-07-27 17:42:01 +0200131 if self.tok == '#':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200132 self.cursor = self.src.find('\n', self.cursor)
133 elif self.tok in ['{', '}', ':', ',', '[', ']']:
134 return
135 elif self.tok == "'":
136 string = ''
137 esc = False
138 while True:
139 ch = self.src[self.cursor]
140 self.cursor += 1
141 if ch == '\n':
Markus Armbruster2caba362013-07-27 17:41:56 +0200142 raise QAPISchemaError(self,
143 'Missing terminating "\'"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200144 if esc:
145 string += ch
146 esc = False
147 elif ch == "\\":
148 esc = True
149 elif ch == "'":
150 self.val = string
151 return
152 else:
153 string += ch
154 elif self.tok == '\n':
155 if self.cursor == len(self.src):
156 self.tok = None
157 return
Wenchao Xia515b9432014-03-04 18:44:33 -0800158 self.line += 1
159 self.line_pos = self.cursor
Markus Armbruster9213aa52013-07-27 17:41:57 +0200160 elif not self.tok.isspace():
161 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
Michael Roth0f923be2011-07-19 14:50:39 -0500162
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200163 def get_members(self):
164 expr = OrderedDict()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200165 if self.tok == '}':
166 self.accept()
167 return expr
168 if self.tok != "'":
169 raise QAPISchemaError(self, 'Expected string or "}"')
170 while True:
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200171 key = self.val
172 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200173 if self.tok != ':':
174 raise QAPISchemaError(self, 'Expected ":"')
175 self.accept()
Wenchao Xia4b359912014-03-04 18:44:32 -0800176 if key in expr:
177 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200178 expr[key] = self.get_expr(True)
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200179 if self.tok == '}':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200180 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200181 return expr
182 if self.tok != ',':
183 raise QAPISchemaError(self, 'Expected "," or "}"')
184 self.accept()
185 if self.tok != "'":
186 raise QAPISchemaError(self, 'Expected string')
Michael Roth0f923be2011-07-19 14:50:39 -0500187
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200188 def get_values(self):
189 expr = []
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200190 if self.tok == ']':
191 self.accept()
192 return expr
193 if not self.tok in [ '{', '[', "'" ]:
194 raise QAPISchemaError(self, 'Expected "{", "[", "]" or string')
195 while True:
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200196 expr.append(self.get_expr(True))
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200197 if self.tok == ']':
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200198 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200199 return expr
200 if self.tok != ',':
201 raise QAPISchemaError(self, 'Expected "," or "]"')
202 self.accept()
Michael Roth0f923be2011-07-19 14:50:39 -0500203
Markus Armbruster5f3cd2b2013-07-27 17:41:59 +0200204 def get_expr(self, nested):
205 if self.tok != '{' and not nested:
206 raise QAPISchemaError(self, 'Expected "{"')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200207 if self.tok == '{':
208 self.accept()
209 expr = self.get_members()
210 elif self.tok == '[':
211 self.accept()
212 expr = self.get_values()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200213 elif self.tok == "'":
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200214 expr = self.val
215 self.accept()
Markus Armbruster6974ccd2013-07-27 17:41:58 +0200216 else:
217 raise QAPISchemaError(self, 'Expected "{", "[" or string')
Markus Armbrusterc7a3f252013-07-27 17:41:55 +0200218 return expr
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200219
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800220def find_base_fields(base):
221 base_struct_define = find_struct(base)
222 if not base_struct_define:
223 return None
224 return base_struct_define['data']
225
Wenchao Xiabceae762014-03-06 17:08:56 -0800226# Return the discriminator enum define if discriminator is specified as an
227# enum type, otherwise return None.
228def discriminator_find_enum_define(expr):
229 base = expr.get('base')
230 discriminator = expr.get('discriminator')
231
232 if not (discriminator and base):
233 return None
234
235 base_fields = find_base_fields(base)
236 if not base_fields:
237 return None
238
239 discriminator_type = base_fields.get(discriminator)
240 if not discriminator_type:
241 return None
242
243 return find_enum(discriminator_type)
244
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200245def check_event(expr, expr_info):
246 params = expr.get('data')
247 if params:
248 for argname, argentry, optional, structured in parse_args(params):
249 if structured:
250 raise QAPIExprError(expr_info,
251 "Nested structure define in event is not "
Wenchao Xiad6f9c822014-06-24 16:33:59 -0700252 "supported, event '%s', argname '%s'"
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200253 % (expr['event'], argname))
254
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800255def check_union(expr, expr_info):
256 name = expr['union']
257 base = expr.get('base')
258 discriminator = expr.get('discriminator')
259 members = expr['data']
260
261 # If the object has a member 'base', its value must name a complex type.
262 if base:
263 base_fields = find_base_fields(base)
264 if not base_fields:
265 raise QAPIExprError(expr_info,
266 "Base '%s' is not a valid type"
267 % base)
268
269 # If the union object has no member 'discriminator', it's an
270 # ordinary union.
271 if not discriminator:
272 enum_define = None
273
274 # Else if the value of member 'discriminator' is {}, it's an
275 # anonymous union.
276 elif discriminator == {}:
277 enum_define = None
278
279 # Else, it's a flat union.
280 else:
281 # The object must have a member 'base'.
282 if not base:
283 raise QAPIExprError(expr_info,
284 "Flat union '%s' must have a base field"
285 % name)
286 # The value of member 'discriminator' must name a member of the
287 # base type.
288 discriminator_type = base_fields.get(discriminator)
289 if not discriminator_type:
290 raise QAPIExprError(expr_info,
291 "Discriminator '%s' is not a member of base "
292 "type '%s'"
293 % (discriminator, base))
294 enum_define = find_enum(discriminator_type)
Wenchao Xia52230702014-03-04 18:44:39 -0800295 # Do not allow string discriminator
296 if not enum_define:
297 raise QAPIExprError(expr_info,
298 "Discriminator '%s' must be of enumeration "
299 "type" % discriminator)
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800300
301 # Check every branch
302 for (key, value) in members.items():
303 # If this named member's value names an enum type, then all members
304 # of 'data' must also be members of the enum type.
305 if enum_define and not key in enum_define['enum_values']:
306 raise QAPIExprError(expr_info,
307 "Discriminator value '%s' is not found in "
308 "enum '%s'" %
309 (key, enum_define["enum_name"]))
310 # Todo: add checking for values. Key is checked as above, value can be
311 # also checked here, but we need more functions to handle array case.
312
313def check_exprs(schema):
314 for expr_elem in schema.exprs:
315 expr = expr_elem['expr']
316 if expr.has_key('union'):
317 check_union(expr, expr_elem['info'])
Wenchao Xia21cd70d2014-06-18 08:43:28 +0200318 if expr.has_key('event'):
319 check_event(expr, expr_elem['info'])
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800320
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200321def parse_schema(input_file):
Markus Armbruster2caba362013-07-27 17:41:56 +0200322 try:
Lluís Vilanova33aaad52014-05-02 15:52:35 +0200323 schema = QAPISchema(open(input_file, "r"))
Lluís Vilanovaa719a272014-05-07 20:46:15 +0200324 except (QAPISchemaError, QAPIExprError), e:
Markus Armbruster2caba362013-07-27 17:41:56 +0200325 print >>sys.stderr, e
326 exit(1)
327
Kevin Wolfbd9927f2013-07-01 16:31:50 +0200328 exprs = []
329
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800330 for expr_elem in schema.exprs:
331 expr = expr_elem['expr']
Markus Armbruster28b8bd42013-07-27 17:42:00 +0200332 if expr.has_key('enum'):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800333 add_enum(expr['enum'], expr['data'])
Markus Armbruster28b8bd42013-07-27 17:42:00 +0200334 elif expr.has_key('union'):
335 add_union(expr)
Markus Armbruster28b8bd42013-07-27 17:42:00 +0200336 elif expr.has_key('type'):
337 add_struct(expr)
338 exprs.append(expr)
Michael Roth0f923be2011-07-19 14:50:39 -0500339
Wenchao Xiabceae762014-03-06 17:08:56 -0800340 # Try again for hidden UnionKind enum
341 for expr_elem in schema.exprs:
342 expr = expr_elem['expr']
343 if expr.has_key('union'):
344 if not discriminator_find_enum_define(expr):
345 add_enum('%sKind' % expr['union'])
346
Wenchao Xiab86b05e2014-03-04 18:44:34 -0800347 try:
348 check_exprs(schema)
349 except QAPIExprError, e:
350 print >>sys.stderr, e
351 exit(1)
352
Michael Roth0f923be2011-07-19 14:50:39 -0500353 return exprs
354
355def parse_args(typeinfo):
Kevin Wolfb35284e2013-07-01 16:31:51 +0200356 if isinstance(typeinfo, basestring):
357 struct = find_struct(typeinfo)
358 assert struct != None
359 typeinfo = struct['data']
360
Michael Roth0f923be2011-07-19 14:50:39 -0500361 for member in typeinfo:
362 argname = member
363 argentry = typeinfo[member]
364 optional = False
365 structured = False
366 if member.startswith('*'):
367 argname = member[1:]
368 optional = True
369 if isinstance(argentry, OrderedDict):
370 structured = True
371 yield (argname, argentry, optional, structured)
372
373def de_camel_case(name):
374 new_name = ''
375 for ch in name:
376 if ch.isupper() and new_name:
377 new_name += '_'
378 if ch == '-':
379 new_name += '_'
380 else:
381 new_name += ch.lower()
382 return new_name
383
384def camel_case(name):
385 new_name = ''
386 first = True
387 for ch in name:
388 if ch in ['_', '-']:
389 first = True
390 elif first:
391 new_name += ch.upper()
392 first = False
393 else:
394 new_name += ch.lower()
395 return new_name
396
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200397def c_var(name, protect=True):
Blue Swirl427a1a22012-07-30 15:46:55 +0000398 # ANSI X3J11/88-090, 3.1.1
399 c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
400 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
401 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
402 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
403 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
404 # ISO/IEC 9899:1999, 6.4.1
405 c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
406 # ISO/IEC 9899:2011, 6.4.1
407 c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
408 '_Static_assert', '_Thread_local'])
409 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
410 # excluding _.*
411 gcc_words = set(['asm', 'typeof'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400412 # C++ ISO/IEC 14882:2003 2.11
413 cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
414 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
415 'namespace', 'new', 'operator', 'private', 'protected',
416 'public', 'reinterpret_cast', 'static_cast', 'template',
417 'this', 'throw', 'true', 'try', 'typeid', 'typename',
418 'using', 'virtual', 'wchar_t',
419 # alternative representations
420 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
421 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
Paolo Bonzini10577252012-09-19 16:31:07 +0200422 # namespace pollution:
Max Reitz8592a542013-12-20 19:28:18 +0100423 polluted_words = set(['unix', 'errno'])
Tomoki Sekiyama6f880092013-08-07 11:39:43 -0400424 if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
Blue Swirl427a1a22012-07-30 15:46:55 +0000425 return "q_" + name
Federico Simoncellic9da2282012-03-20 13:54:35 +0000426 return name.replace('-', '_').lstrip("*")
427
Paolo Bonzinieda50a62012-09-19 16:31:06 +0200428def c_fun(name, protect=True):
429 return c_var(name, protect).replace('.', '_')
Michael Roth0f923be2011-07-19 14:50:39 -0500430
431def c_list_type(name):
432 return '%sList' % name
433
434def type_name(name):
435 if type(name) == list:
436 return c_list_type(name[0])
437 return name
438
439enum_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200440struct_types = []
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200441union_types = []
Kevin Wolfb35284e2013-07-01 16:31:51 +0200442
443def add_struct(definition):
444 global struct_types
445 struct_types.append(definition)
446
447def find_struct(name):
448 global struct_types
449 for struct in struct_types:
450 if struct['type'] == name:
451 return struct
452 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500453
Kevin Wolfea66c6d2013-07-16 10:49:41 +0200454def add_union(definition):
455 global union_types
456 union_types.append(definition)
457
458def find_union(name):
459 global union_types
460 for union in union_types:
461 if union['union'] == name:
462 return union
463 return None
464
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800465def add_enum(name, enum_values = None):
Michael Roth0f923be2011-07-19 14:50:39 -0500466 global enum_types
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800467 enum_types.append({"enum_name": name, "enum_values": enum_values})
468
469def find_enum(name):
470 global enum_types
471 for enum in enum_types:
472 if enum['enum_name'] == name:
473 return enum
474 return None
Michael Roth0f923be2011-07-19 14:50:39 -0500475
476def is_enum(name):
Wenchao Xiadad1fca2014-03-04 18:44:31 -0800477 return find_enum(name) != None
Michael Roth0f923be2011-07-19 14:50:39 -0500478
Amos Kong05dfb262014-06-10 19:25:53 +0800479eatspace = '\033EATSPACE.'
480
481# A special suffix is added in c_type() for pointer types, and it's
482# stripped in mcgen(). So please notice this when you check the return
483# value of c_type() outside mcgen().
Amos Kong0d14eeb2014-06-10 19:25:52 +0800484def c_type(name, is_param=False):
Michael Roth0f923be2011-07-19 14:50:39 -0500485 if name == 'str':
Amos Kong0d14eeb2014-06-10 19:25:52 +0800486 if is_param:
Amos Kong05dfb262014-06-10 19:25:53 +0800487 return 'const char *' + eatspace
488 return 'char *' + eatspace
489
Michael Roth0f923be2011-07-19 14:50:39 -0500490 elif name == 'int':
491 return 'int64_t'
Laszlo Ersekc46f18c2012-07-17 16:17:06 +0200492 elif (name == 'int8' or name == 'int16' or name == 'int32' or
493 name == 'int64' or name == 'uint8' or name == 'uint16' or
494 name == 'uint32' or name == 'uint64'):
495 return name + '_t'
Laszlo Ersek092705d2012-07-17 16:17:07 +0200496 elif name == 'size':
497 return 'uint64_t'
Michael Roth0f923be2011-07-19 14:50:39 -0500498 elif name == 'bool':
499 return 'bool'
500 elif name == 'number':
501 return 'double'
502 elif type(name) == list:
Amos Kong05dfb262014-06-10 19:25:53 +0800503 return '%s *%s' % (c_list_type(name[0]), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500504 elif is_enum(name):
505 return name
506 elif name == None or len(name) == 0:
507 return 'void'
508 elif name == name.upper():
Amos Kong05dfb262014-06-10 19:25:53 +0800509 return '%sEvent *%s' % (camel_case(name), eatspace)
Michael Roth0f923be2011-07-19 14:50:39 -0500510 else:
Amos Kong05dfb262014-06-10 19:25:53 +0800511 return '%s *%s' % (name, eatspace)
512
513def is_c_ptr(name):
514 suffix = "*" + eatspace
515 return c_type(name).endswith(suffix)
Michael Roth0f923be2011-07-19 14:50:39 -0500516
517def genindent(count):
518 ret = ""
519 for i in range(count):
520 ret += " "
521 return ret
522
523indent_level = 0
524
525def push_indent(indent_amount=4):
526 global indent_level
527 indent_level += indent_amount
528
529def pop_indent(indent_amount=4):
530 global indent_level
531 indent_level -= indent_amount
532
533def cgen(code, **kwds):
534 indent = genindent(indent_level)
535 lines = code.split('\n')
536 lines = map(lambda x: indent + x, lines)
537 return '\n'.join(lines) % kwds + '\n'
538
539def mcgen(code, **kwds):
Amos Kong05dfb262014-06-10 19:25:53 +0800540 raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
541 return re.sub(re.escape(eatspace) + ' *', '', raw)
Michael Roth0f923be2011-07-19 14:50:39 -0500542
543def basename(filename):
544 return filename.split("/")[-1]
545
546def guardname(filename):
Michael Rothd8e1f212011-11-29 16:47:48 -0600547 guard = basename(filename).rsplit(".", 1)[0]
548 for substr in [".", " ", "-"]:
549 guard = guard.replace(substr, "_")
550 return guard.upper() + '_H'
Michael Rothc0afa9c2013-05-10 17:46:00 -0500551
552def guardstart(name):
553 return mcgen('''
554
555#ifndef %(name)s
556#define %(name)s
557
558''',
559 name=guardname(name))
560
561def guardend(name):
562 return mcgen('''
563
564#endif /* %(name)s */
565
566''',
567 name=guardname(name))
Wenchao Xia62996592014-03-04 18:44:35 -0800568
Wenchao Xia5d371f42014-03-04 18:44:40 -0800569# ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
570# ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
571# ENUM24_Name -> ENUM24_NAME
572def _generate_enum_string(value):
573 c_fun_str = c_fun(value, False)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800574 if value.isupper():
Wenchao Xia5d371f42014-03-04 18:44:40 -0800575 return c_fun_str
576
Wenchao Xia62996592014-03-04 18:44:35 -0800577 new_name = ''
Wenchao Xia5d371f42014-03-04 18:44:40 -0800578 l = len(c_fun_str)
579 for i in range(l):
580 c = c_fun_str[i]
581 # When c is upper and no "_" appears before, do more checks
582 if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
583 # Case 1: next string is lower
584 # Case 2: previous string is digit
585 if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
586 c_fun_str[i - 1].isdigit():
587 new_name += '_'
Wenchao Xia62996592014-03-04 18:44:35 -0800588 new_name += c
589 return new_name.lstrip('_').upper()
Wenchao Xiab0b58192014-03-04 18:44:36 -0800590
591def generate_enum_full_value(enum_name, enum_value):
Wenchao Xia5d371f42014-03-04 18:44:40 -0800592 abbrev_string = _generate_enum_string(enum_name)
593 value_string = _generate_enum_string(enum_value)
Wenchao Xiab0b58192014-03-04 18:44:36 -0800594 return "%s_%s" % (abbrev_string, value_string)