]>
Commit | Line | Data |
---|---|---|
0f923be2 MR |
1 | # |
2 | # QAPI helper library | |
3 | # | |
4 | # Copyright IBM, Corp. 2011 | |
fe2a9303 | 5 | # Copyright (c) 2013-2015 Red Hat Inc. |
0f923be2 MR |
6 | # |
7 | # Authors: | |
8 | # Anthony Liguori <[email protected]> | |
c7a3f252 | 9 | # Markus Armbruster <[email protected]> |
0f923be2 | 10 | # |
678e48a2 MA |
11 | # This work is licensed under the terms of the GNU GPL, version 2. |
12 | # See the COPYING file in the top-level directory. | |
0f923be2 | 13 | |
a719a27c | 14 | import re |
0f923be2 | 15 | from ordereddict import OrderedDict |
33aaad52 | 16 | import os |
2caba36c | 17 | import sys |
0f923be2 | 18 | |
b52c4b9c | 19 | builtin_types = { |
69dd62df KW |
20 | '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', | |
cb17f79e | 32 | 'size': 'QTYPE_QINT', |
69dd62df KW |
33 | } |
34 | ||
4dc2e690 EB |
35 | enum_types = [] |
36 | struct_types = [] | |
37 | union_types = [] | |
38 | events = [] | |
39 | all_names = {} | |
40 | ||
a719a27c LV |
41 | def error_path(parent): |
42 | res = "" | |
43 | while parent: | |
44 | res = ("In file included from %s:%d:\n" % (parent['file'], | |
45 | parent['line'])) + res | |
46 | parent = parent['parent'] | |
47 | return res | |
48 | ||
2caba36c MA |
49 | class QAPISchemaError(Exception): |
50 | def __init__(self, schema, msg): | |
a719a27c | 51 | self.input_file = schema.input_file |
2caba36c | 52 | self.msg = msg |
515b943a WX |
53 | self.col = 1 |
54 | self.line = schema.line | |
55 | for ch in schema.src[schema.line_pos:schema.pos]: | |
56 | if ch == '\t': | |
2caba36c MA |
57 | self.col = (self.col + 7) % 8 + 1 |
58 | else: | |
59 | self.col += 1 | |
a719a27c | 60 | self.info = schema.parent_info |
2caba36c MA |
61 | |
62 | def __str__(self): | |
a719a27c LV |
63 | return error_path(self.info) + \ |
64 | "%s:%d:%d: %s" % (self.input_file, self.line, self.col, self.msg) | |
2caba36c | 65 | |
b86b05ed WX |
66 | class QAPIExprError(Exception): |
67 | def __init__(self, expr_info, msg): | |
a719a27c | 68 | self.info = expr_info |
b86b05ed WX |
69 | self.msg = msg |
70 | ||
71 | def __str__(self): | |
a719a27c LV |
72 | return error_path(self.info['parent']) + \ |
73 | "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg) | |
b86b05ed | 74 | |
c7a3f252 MA |
75 | class QAPISchema: |
76 | ||
24fd8489 BC |
77 | def __init__(self, fp, input_relname=None, include_hist=[], |
78 | previously_included=[], parent_info=None): | |
79 | """ include_hist is a stack used to detect inclusion cycles | |
80 | previously_included is a global state used to avoid multiple | |
81 | inclusions of the same file""" | |
a719a27c LV |
82 | input_fname = os.path.abspath(fp.name) |
83 | if input_relname is None: | |
84 | input_relname = fp.name | |
85 | self.input_dir = os.path.dirname(input_fname) | |
86 | self.input_file = input_relname | |
87 | self.include_hist = include_hist + [(input_relname, input_fname)] | |
24fd8489 | 88 | previously_included.append(input_fname) |
a719a27c | 89 | self.parent_info = parent_info |
c7a3f252 MA |
90 | self.src = fp.read() |
91 | if self.src == '' or self.src[-1] != '\n': | |
92 | self.src += '\n' | |
93 | self.cursor = 0 | |
515b943a WX |
94 | self.line = 1 |
95 | self.line_pos = 0 | |
c7a3f252 MA |
96 | self.exprs = [] |
97 | self.accept() | |
98 | ||
99 | while self.tok != None: | |
a719a27c LV |
100 | expr_info = {'file': input_relname, 'line': self.line, 'parent': self.parent_info} |
101 | expr = self.get_expr(False) | |
102 | if isinstance(expr, dict) and "include" in expr: | |
103 | if len(expr) != 1: | |
104 | raise QAPIExprError(expr_info, "Invalid 'include' directive") | |
105 | include = expr["include"] | |
106 | if not isinstance(include, str): | |
107 | raise QAPIExprError(expr_info, | |
108 | 'Expected a file name (string), got: %s' | |
109 | % include) | |
110 | include_path = os.path.join(self.input_dir, include) | |
7ac9a9d6 SH |
111 | for elem in self.include_hist: |
112 | if include_path == elem[1]: | |
113 | raise QAPIExprError(expr_info, "Inclusion loop for %s" | |
114 | % include) | |
24fd8489 BC |
115 | # skip multiple include of the same file |
116 | if include_path in previously_included: | |
117 | continue | |
a719a27c LV |
118 | try: |
119 | fobj = open(include_path, 'r') | |
34788811 | 120 | except IOError, e: |
a719a27c LV |
121 | raise QAPIExprError(expr_info, |
122 | '%s: %s' % (e.strerror, include)) | |
24fd8489 BC |
123 | exprs_include = QAPISchema(fobj, include, self.include_hist, |
124 | previously_included, expr_info) | |
a719a27c LV |
125 | self.exprs.extend(exprs_include.exprs) |
126 | else: | |
127 | expr_elem = {'expr': expr, | |
128 | 'info': expr_info} | |
129 | self.exprs.append(expr_elem) | |
c7a3f252 MA |
130 | |
131 | def accept(self): | |
132 | while True: | |
c7a3f252 | 133 | self.tok = self.src[self.cursor] |
2caba36c | 134 | self.pos = self.cursor |
c7a3f252 MA |
135 | self.cursor += 1 |
136 | self.val = None | |
137 | ||
f1a145e1 | 138 | if self.tok == '#': |
c7a3f252 MA |
139 | self.cursor = self.src.find('\n', self.cursor) |
140 | elif self.tok in ['{', '}', ':', ',', '[', ']']: | |
141 | return | |
142 | elif self.tok == "'": | |
143 | string = '' | |
144 | esc = False | |
145 | while True: | |
146 | ch = self.src[self.cursor] | |
147 | self.cursor += 1 | |
148 | if ch == '\n': | |
2caba36c MA |
149 | raise QAPISchemaError(self, |
150 | 'Missing terminating "\'"') | |
c7a3f252 MA |
151 | if esc: |
152 | string += ch | |
153 | esc = False | |
154 | elif ch == "\\": | |
155 | esc = True | |
156 | elif ch == "'": | |
157 | self.val = string | |
158 | return | |
159 | else: | |
160 | string += ch | |
e53188ad FZ |
161 | elif self.tok in "tfn": |
162 | val = self.src[self.cursor - 1:] | |
163 | if val.startswith("true"): | |
164 | self.val = True | |
165 | self.cursor += 3 | |
166 | return | |
167 | elif val.startswith("false"): | |
168 | self.val = False | |
169 | self.cursor += 4 | |
170 | return | |
171 | elif val.startswith("null"): | |
172 | self.val = None | |
173 | self.cursor += 3 | |
174 | return | |
c7a3f252 MA |
175 | elif self.tok == '\n': |
176 | if self.cursor == len(self.src): | |
177 | self.tok = None | |
178 | return | |
515b943a WX |
179 | self.line += 1 |
180 | self.line_pos = self.cursor | |
9213aa53 MA |
181 | elif not self.tok.isspace(): |
182 | raise QAPISchemaError(self, 'Stray "%s"' % self.tok) | |
c7a3f252 MA |
183 | |
184 | def get_members(self): | |
185 | expr = OrderedDict() | |
6974ccd5 MA |
186 | if self.tok == '}': |
187 | self.accept() | |
188 | return expr | |
189 | if self.tok != "'": | |
190 | raise QAPISchemaError(self, 'Expected string or "}"') | |
191 | while True: | |
c7a3f252 MA |
192 | key = self.val |
193 | self.accept() | |
6974ccd5 MA |
194 | if self.tok != ':': |
195 | raise QAPISchemaError(self, 'Expected ":"') | |
196 | self.accept() | |
4b35991a WX |
197 | if key in expr: |
198 | raise QAPISchemaError(self, 'Duplicate key "%s"' % key) | |
5f3cd2b7 | 199 | expr[key] = self.get_expr(True) |
6974ccd5 | 200 | if self.tok == '}': |
c7a3f252 | 201 | self.accept() |
6974ccd5 MA |
202 | return expr |
203 | if self.tok != ',': | |
204 | raise QAPISchemaError(self, 'Expected "," or "}"') | |
205 | self.accept() | |
206 | if self.tok != "'": | |
207 | raise QAPISchemaError(self, 'Expected string') | |
c7a3f252 MA |
208 | |
209 | def get_values(self): | |
210 | expr = [] | |
6974ccd5 MA |
211 | if self.tok == ']': |
212 | self.accept() | |
213 | return expr | |
e53188ad FZ |
214 | if not self.tok in "{['tfn": |
215 | raise QAPISchemaError(self, 'Expected "{", "[", "]", string, ' | |
216 | 'boolean or "null"') | |
6974ccd5 | 217 | while True: |
5f3cd2b7 | 218 | expr.append(self.get_expr(True)) |
6974ccd5 | 219 | if self.tok == ']': |
c7a3f252 | 220 | self.accept() |
6974ccd5 MA |
221 | return expr |
222 | if self.tok != ',': | |
223 | raise QAPISchemaError(self, 'Expected "," or "]"') | |
224 | self.accept() | |
c7a3f252 | 225 | |
5f3cd2b7 MA |
226 | def get_expr(self, nested): |
227 | if self.tok != '{' and not nested: | |
228 | raise QAPISchemaError(self, 'Expected "{"') | |
c7a3f252 MA |
229 | if self.tok == '{': |
230 | self.accept() | |
231 | expr = self.get_members() | |
232 | elif self.tok == '[': | |
233 | self.accept() | |
234 | expr = self.get_values() | |
e53188ad | 235 | elif self.tok in "'tfn": |
c7a3f252 MA |
236 | expr = self.val |
237 | self.accept() | |
6974ccd5 MA |
238 | else: |
239 | raise QAPISchemaError(self, 'Expected "{", "[" or string') | |
c7a3f252 | 240 | return expr |
bd9927fe | 241 | |
b86b05ed WX |
242 | def find_base_fields(base): |
243 | base_struct_define = find_struct(base) | |
244 | if not base_struct_define: | |
245 | return None | |
246 | return base_struct_define['data'] | |
247 | ||
811d04fd EB |
248 | # Return the qtype of an alternate branch, or None on error. |
249 | def find_alternate_member_qtype(qapi_type): | |
44bd1276 EB |
250 | if builtin_types.has_key(qapi_type): |
251 | return builtin_types[qapi_type] | |
252 | elif find_struct(qapi_type): | |
253 | return "QTYPE_QDICT" | |
254 | elif find_enum(qapi_type): | |
255 | return "QTYPE_QSTRING" | |
811d04fd EB |
256 | elif find_union(qapi_type): |
257 | return "QTYPE_QDICT" | |
44bd1276 EB |
258 | return None |
259 | ||
bceae769 WX |
260 | # Return the discriminator enum define if discriminator is specified as an |
261 | # enum type, otherwise return None. | |
262 | def discriminator_find_enum_define(expr): | |
263 | base = expr.get('base') | |
264 | discriminator = expr.get('discriminator') | |
265 | ||
266 | if not (discriminator and base): | |
267 | return None | |
268 | ||
269 | base_fields = find_base_fields(base) | |
270 | if not base_fields: | |
271 | return None | |
272 | ||
273 | discriminator_type = base_fields.get(discriminator) | |
274 | if not discriminator_type: | |
275 | return None | |
276 | ||
277 | return find_enum(discriminator_type) | |
278 | ||
21cd70df | 279 | def check_event(expr, expr_info): |
4dc2e690 EB |
280 | global events |
281 | name = expr['event'] | |
21cd70df | 282 | params = expr.get('data') |
4dc2e690 EB |
283 | |
284 | if name.upper() == 'MAX': | |
285 | raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created") | |
286 | events.append(name) | |
287 | ||
21cd70df WX |
288 | if params: |
289 | for argname, argentry, optional, structured in parse_args(params): | |
290 | if structured: | |
291 | raise QAPIExprError(expr_info, | |
292 | "Nested structure define in event is not " | |
d6f9c82c | 293 | "supported, event '%s', argname '%s'" |
21cd70df WX |
294 | % (expr['event'], argname)) |
295 | ||
b86b05ed WX |
296 | def check_union(expr, expr_info): |
297 | name = expr['union'] | |
298 | base = expr.get('base') | |
299 | discriminator = expr.get('discriminator') | |
300 | members = expr['data'] | |
44bd1276 | 301 | values = { 'MAX': '(automatic)' } |
b86b05ed | 302 | |
a8d4a2e4 EB |
303 | # If the object has a member 'base', its value must name a complex type, |
304 | # and there must be a discriminator. | |
305 | if base is not None: | |
306 | if discriminator is None: | |
307 | raise QAPIExprError(expr_info, | |
308 | "Union '%s' requires a discriminator to go " | |
309 | "along with base" %name) | |
b86b05ed | 310 | |
811d04fd | 311 | # Two types of unions, determined by discriminator. |
811d04fd EB |
312 | |
313 | # With no discriminator it is a simple union. | |
314 | if discriminator is None: | |
b86b05ed | 315 | enum_define = None |
44bd1276 EB |
316 | if base is not None: |
317 | raise QAPIExprError(expr_info, | |
811d04fd | 318 | "Simple union '%s' must not have a base" |
44bd1276 | 319 | % name) |
b86b05ed WX |
320 | |
321 | # Else, it's a flat union. | |
322 | else: | |
44bd1276 EB |
323 | # The object must have a string member 'base'. |
324 | if not isinstance(base, str): | |
b86b05ed | 325 | raise QAPIExprError(expr_info, |
44bd1276 | 326 | "Flat union '%s' must have a string base field" |
b86b05ed | 327 | % name) |
44bd1276 EB |
328 | base_fields = find_base_fields(base) |
329 | if not base_fields: | |
330 | raise QAPIExprError(expr_info, | |
331 | "Base '%s' is not a valid type" | |
332 | % base) | |
333 | ||
b86b05ed WX |
334 | # The value of member 'discriminator' must name a member of the |
335 | # base type. | |
44bd1276 EB |
336 | if not isinstance(discriminator, str): |
337 | raise QAPIExprError(expr_info, | |
338 | "Flat union '%s' discriminator must be a string" | |
339 | % name) | |
b86b05ed WX |
340 | discriminator_type = base_fields.get(discriminator) |
341 | if not discriminator_type: | |
342 | raise QAPIExprError(expr_info, | |
343 | "Discriminator '%s' is not a member of base " | |
344 | "type '%s'" | |
345 | % (discriminator, base)) | |
346 | enum_define = find_enum(discriminator_type) | |
5223070c WX |
347 | # Do not allow string discriminator |
348 | if not enum_define: | |
349 | raise QAPIExprError(expr_info, | |
350 | "Discriminator '%s' must be of enumeration " | |
351 | "type" % discriminator) | |
b86b05ed WX |
352 | |
353 | # Check every branch | |
354 | for (key, value) in members.items(): | |
44bd1276 | 355 | # If the discriminator names an enum type, then all members |
b86b05ed | 356 | # of 'data' must also be members of the enum type. |
44bd1276 EB |
357 | if enum_define: |
358 | if not key in enum_define['enum_values']: | |
359 | raise QAPIExprError(expr_info, | |
360 | "Discriminator value '%s' is not found in " | |
361 | "enum '%s'" % | |
362 | (key, enum_define["enum_name"])) | |
363 | ||
364 | # Otherwise, check for conflicts in the generated enum | |
365 | else: | |
366 | c_key = _generate_enum_string(key) | |
367 | if c_key in values: | |
368 | raise QAPIExprError(expr_info, | |
369 | "Union '%s' member '%s' clashes with '%s'" | |
370 | % (name, key, values[c_key])) | |
371 | values[c_key] = key | |
372 | ||
811d04fd | 373 | def check_alternate(expr, expr_info): |
ab916fad | 374 | name = expr['alternate'] |
811d04fd EB |
375 | members = expr['data'] |
376 | values = { 'MAX': '(automatic)' } | |
377 | types_seen = {} | |
378 | ||
811d04fd EB |
379 | # Check every branch |
380 | for (key, value) in members.items(): | |
381 | # Check for conflicts in the generated enum | |
382 | c_key = _generate_enum_string(key) | |
383 | if c_key in values: | |
384 | raise QAPIExprError(expr_info, | |
ab916fad EB |
385 | "Alternate '%s' member '%s' clashes with '%s'" |
386 | % (name, key, values[c_key])) | |
811d04fd | 387 | values[c_key] = key |
44bd1276 | 388 | |
811d04fd EB |
389 | # Ensure alternates have no type conflicts. |
390 | if isinstance(value, list): | |
391 | raise QAPIExprError(expr_info, | |
ab916fad | 392 | "Alternate '%s' member '%s' must " |
811d04fd EB |
393 | "not be array type" % (name, key)) |
394 | qtype = find_alternate_member_qtype(value) | |
395 | if not qtype: | |
396 | raise QAPIExprError(expr_info, | |
ab916fad | 397 | "Alternate '%s' member '%s' has " |
811d04fd EB |
398 | "invalid type '%s'" % (name, key, value)) |
399 | if qtype in types_seen: | |
400 | raise QAPIExprError(expr_info, | |
ab916fad | 401 | "Alternate '%s' member '%s' can't " |
811d04fd EB |
402 | "be distinguished from member '%s'" |
403 | % (name, key, types_seen[qtype])) | |
404 | types_seen[qtype] = key | |
b86b05ed | 405 | |
cf393590 EB |
406 | def check_enum(expr, expr_info): |
407 | name = expr['enum'] | |
408 | members = expr.get('data') | |
409 | values = { 'MAX': '(automatic)' } | |
410 | ||
411 | if not isinstance(members, list): | |
412 | raise QAPIExprError(expr_info, | |
413 | "Enum '%s' requires an array for 'data'" % name) | |
414 | for member in members: | |
415 | if not isinstance(member, str): | |
416 | raise QAPIExprError(expr_info, | |
417 | "Enum '%s' member '%s' is not a string" | |
418 | % (name, member)) | |
419 | key = _generate_enum_string(member) | |
420 | if key in values: | |
421 | raise QAPIExprError(expr_info, | |
422 | "Enum '%s' member '%s' clashes with '%s'" | |
423 | % (name, member, values[key])) | |
424 | values[key] = member | |
425 | ||
b86b05ed WX |
426 | def check_exprs(schema): |
427 | for expr_elem in schema.exprs: | |
428 | expr = expr_elem['expr'] | |
cf393590 EB |
429 | info = expr_elem['info'] |
430 | ||
431 | if expr.has_key('enum'): | |
432 | check_enum(expr, info) | |
433 | elif expr.has_key('union'): | |
ab916fad EB |
434 | check_union(expr, info) |
435 | elif expr.has_key('alternate'): | |
436 | check_alternate(expr, info) | |
cf393590 EB |
437 | elif expr.has_key('event'): |
438 | check_event(expr, info) | |
b86b05ed | 439 | |
0545f6b8 EB |
440 | def check_keys(expr_elem, meta, required, optional=[]): |
441 | expr = expr_elem['expr'] | |
442 | info = expr_elem['info'] | |
443 | name = expr[meta] | |
444 | if not isinstance(name, str): | |
445 | raise QAPIExprError(info, | |
446 | "'%s' key must have a string value" % meta) | |
447 | required = required + [ meta ] | |
448 | for (key, value) in expr.items(): | |
449 | if not key in required and not key in optional: | |
450 | raise QAPIExprError(info, | |
451 | "Unknown key '%s' in %s '%s'" | |
452 | % (key, meta, name)) | |
453 | for key in required: | |
454 | if not expr.has_key(key): | |
455 | raise QAPIExprError(info, | |
456 | "Key '%s' is missing from %s '%s'" | |
457 | % (key, meta, name)) | |
458 | ||
459 | ||
33aaad52 | 460 | def parse_schema(input_file): |
4dc2e690 EB |
461 | global all_names |
462 | exprs = [] | |
463 | ||
268a1c5e | 464 | # First pass: read entire file into memory |
2caba36c | 465 | try: |
33aaad52 | 466 | schema = QAPISchema(open(input_file, "r")) |
a719a27c | 467 | except (QAPISchemaError, QAPIExprError), e: |
2caba36c MA |
468 | print >>sys.stderr, e |
469 | exit(1) | |
470 | ||
b86b05ed | 471 | try: |
0545f6b8 EB |
472 | # Next pass: learn the types and check for valid expression keys. At |
473 | # this point, top-level 'include' has already been flattened. | |
4dc2e690 EB |
474 | for builtin in builtin_types.keys(): |
475 | all_names[builtin] = 'built-in' | |
268a1c5e EB |
476 | for expr_elem in schema.exprs: |
477 | expr = expr_elem['expr'] | |
4dc2e690 | 478 | info = expr_elem['info'] |
268a1c5e | 479 | if expr.has_key('enum'): |
0545f6b8 | 480 | check_keys(expr_elem, 'enum', ['data']) |
4dc2e690 | 481 | add_enum(expr['enum'], info, expr['data']) |
268a1c5e | 482 | elif expr.has_key('union'): |
0545f6b8 EB |
483 | check_keys(expr_elem, 'union', ['data'], |
484 | ['base', 'discriminator']) | |
4dc2e690 | 485 | add_union(expr, info) |
0545f6b8 EB |
486 | elif expr.has_key('alternate'): |
487 | check_keys(expr_elem, 'alternate', ['data']) | |
4dc2e690 | 488 | add_name(expr['alternate'], info, 'alternate') |
268a1c5e | 489 | elif expr.has_key('type'): |
0545f6b8 | 490 | check_keys(expr_elem, 'type', ['data'], ['base']) |
4dc2e690 | 491 | add_struct(expr, info) |
0545f6b8 EB |
492 | elif expr.has_key('command'): |
493 | check_keys(expr_elem, 'command', [], | |
494 | ['data', 'returns', 'gen', 'success-response']) | |
4dc2e690 | 495 | add_name(expr['command'], info, 'command') |
0545f6b8 EB |
496 | elif expr.has_key('event'): |
497 | check_keys(expr_elem, 'event', [], ['data']) | |
4dc2e690 | 498 | add_name(expr['event'], info, 'event') |
0545f6b8 EB |
499 | else: |
500 | raise QAPIExprError(expr_elem['info'], | |
501 | "Expression is missing metatype") | |
268a1c5e EB |
502 | exprs.append(expr) |
503 | ||
504 | # Try again for hidden UnionKind enum | |
505 | for expr_elem in schema.exprs: | |
506 | expr = expr_elem['expr'] | |
507 | if expr.has_key('union'): | |
508 | if not discriminator_find_enum_define(expr): | |
4dc2e690 EB |
509 | add_enum('%sKind' % expr['union'], expr_elem['info'], |
510 | implicit=True) | |
ab916fad | 511 | elif expr.has_key('alternate'): |
4dc2e690 EB |
512 | add_enum('%sKind' % expr['alternate'], expr_elem['info'], |
513 | implicit=True) | |
268a1c5e EB |
514 | |
515 | # Final pass - validate that exprs make sense | |
b86b05ed WX |
516 | check_exprs(schema) |
517 | except QAPIExprError, e: | |
518 | print >>sys.stderr, e | |
519 | exit(1) | |
520 | ||
0f923be2 MR |
521 | return exprs |
522 | ||
523 | def parse_args(typeinfo): | |
fe2a9303 | 524 | if isinstance(typeinfo, str): |
b35284ea KW |
525 | struct = find_struct(typeinfo) |
526 | assert struct != None | |
527 | typeinfo = struct['data'] | |
528 | ||
0f923be2 MR |
529 | for member in typeinfo: |
530 | argname = member | |
531 | argentry = typeinfo[member] | |
532 | optional = False | |
533 | structured = False | |
534 | if member.startswith('*'): | |
535 | argname = member[1:] | |
536 | optional = True | |
537 | if isinstance(argentry, OrderedDict): | |
538 | structured = True | |
539 | yield (argname, argentry, optional, structured) | |
540 | ||
541 | def de_camel_case(name): | |
542 | new_name = '' | |
543 | for ch in name: | |
544 | if ch.isupper() and new_name: | |
545 | new_name += '_' | |
546 | if ch == '-': | |
547 | new_name += '_' | |
548 | else: | |
549 | new_name += ch.lower() | |
550 | return new_name | |
551 | ||
552 | def camel_case(name): | |
553 | new_name = '' | |
554 | first = True | |
555 | for ch in name: | |
556 | if ch in ['_', '-']: | |
557 | first = True | |
558 | elif first: | |
559 | new_name += ch.upper() | |
560 | first = False | |
561 | else: | |
562 | new_name += ch.lower() | |
563 | return new_name | |
564 | ||
eda50a65 | 565 | def c_var(name, protect=True): |
427a1a2c BS |
566 | # ANSI X3J11/88-090, 3.1.1 |
567 | c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue', | |
568 | 'default', 'do', 'double', 'else', 'enum', 'extern', 'float', | |
569 | 'for', 'goto', 'if', 'int', 'long', 'register', 'return', | |
570 | 'short', 'signed', 'sizeof', 'static', 'struct', 'switch', | |
571 | 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while']) | |
572 | # ISO/IEC 9899:1999, 6.4.1 | |
573 | c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary']) | |
574 | # ISO/IEC 9899:2011, 6.4.1 | |
575 | c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn', | |
576 | '_Static_assert', '_Thread_local']) | |
577 | # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html | |
578 | # excluding _.* | |
579 | gcc_words = set(['asm', 'typeof']) | |
6f88009e TS |
580 | # C++ ISO/IEC 14882:2003 2.11 |
581 | cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete', | |
582 | 'dynamic_cast', 'explicit', 'false', 'friend', 'mutable', | |
583 | 'namespace', 'new', 'operator', 'private', 'protected', | |
584 | 'public', 'reinterpret_cast', 'static_cast', 'template', | |
585 | 'this', 'throw', 'true', 'try', 'typeid', 'typename', | |
586 | 'using', 'virtual', 'wchar_t', | |
587 | # alternative representations | |
588 | 'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not', | |
589 | 'not_eq', 'or', 'or_eq', 'xor', 'xor_eq']) | |
1057725f | 590 | # namespace pollution: |
8592a545 | 591 | polluted_words = set(['unix', 'errno']) |
6f88009e | 592 | if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words): |
427a1a2c | 593 | return "q_" + name |
c9da228b FS |
594 | return name.replace('-', '_').lstrip("*") |
595 | ||
eda50a65 PB |
596 | def c_fun(name, protect=True): |
597 | return c_var(name, protect).replace('.', '_') | |
0f923be2 MR |
598 | |
599 | def c_list_type(name): | |
600 | return '%sList' % name | |
601 | ||
602 | def type_name(name): | |
603 | if type(name) == list: | |
604 | return c_list_type(name[0]) | |
605 | return name | |
606 | ||
4dc2e690 EB |
607 | def add_name(name, info, meta, implicit = False): |
608 | global all_names | |
609 | if name in all_names: | |
610 | raise QAPIExprError(info, | |
611 | "%s '%s' is already defined" | |
612 | % (all_names[name], name)) | |
613 | if not implicit and name[-4:] == 'Kind': | |
614 | raise QAPIExprError(info, | |
615 | "%s '%s' should not end in 'Kind'" | |
616 | % (meta, name)) | |
617 | all_names[name] = meta | |
b35284ea | 618 | |
4dc2e690 | 619 | def add_struct(definition, info): |
b35284ea | 620 | global struct_types |
4dc2e690 EB |
621 | name = definition['type'] |
622 | add_name(name, info, 'struct') | |
b35284ea KW |
623 | struct_types.append(definition) |
624 | ||
625 | def find_struct(name): | |
626 | global struct_types | |
627 | for struct in struct_types: | |
628 | if struct['type'] == name: | |
629 | return struct | |
630 | return None | |
0f923be2 | 631 | |
4dc2e690 | 632 | def add_union(definition, info): |
ea66c6d8 | 633 | global union_types |
4dc2e690 EB |
634 | name = definition['union'] |
635 | add_name(name, info, 'union') | |
ab916fad | 636 | union_types.append(definition) |
ea66c6d8 KW |
637 | |
638 | def find_union(name): | |
639 | global union_types | |
640 | for union in union_types: | |
641 | if union['union'] == name: | |
642 | return union | |
643 | return None | |
644 | ||
4dc2e690 | 645 | def add_enum(name, info, enum_values = None, implicit = False): |
0f923be2 | 646 | global enum_types |
4dc2e690 | 647 | add_name(name, info, 'enum', implicit) |
dad1fcab | 648 | enum_types.append({"enum_name": name, "enum_values": enum_values}) |
0f923be2 | 649 | |
dad1fcab | 650 | def find_enum(name): |
0f923be2 | 651 | global enum_types |
dad1fcab WX |
652 | for enum in enum_types: |
653 | if enum['enum_name'] == name: | |
654 | return enum | |
655 | return None | |
656 | ||
657 | def is_enum(name): | |
658 | return find_enum(name) != None | |
0f923be2 | 659 | |
05dfb26c AK |
660 | eatspace = '\033EATSPACE.' |
661 | ||
662 | # A special suffix is added in c_type() for pointer types, and it's | |
663 | # stripped in mcgen(). So please notice this when you check the return | |
664 | # value of c_type() outside mcgen(). | |
0d14eeb2 | 665 | def c_type(name, is_param=False): |
0f923be2 | 666 | if name == 'str': |
0d14eeb2 | 667 | if is_param: |
05dfb26c AK |
668 | return 'const char *' + eatspace |
669 | return 'char *' + eatspace | |
670 | ||
0f923be2 MR |
671 | elif name == 'int': |
672 | return 'int64_t' | |
c46f18ce LE |
673 | elif (name == 'int8' or name == 'int16' or name == 'int32' or |
674 | name == 'int64' or name == 'uint8' or name == 'uint16' or | |
675 | name == 'uint32' or name == 'uint64'): | |
676 | return name + '_t' | |
092705d4 LE |
677 | elif name == 'size': |
678 | return 'uint64_t' | |
0f923be2 MR |
679 | elif name == 'bool': |
680 | return 'bool' | |
681 | elif name == 'number': | |
682 | return 'double' | |
683 | elif type(name) == list: | |
05dfb26c | 684 | return '%s *%s' % (c_list_type(name[0]), eatspace) |
0f923be2 MR |
685 | elif is_enum(name): |
686 | return name | |
687 | elif name == None or len(name) == 0: | |
688 | return 'void' | |
4dc2e690 | 689 | elif name in events: |
05dfb26c | 690 | return '%sEvent *%s' % (camel_case(name), eatspace) |
0f923be2 | 691 | else: |
05dfb26c AK |
692 | return '%s *%s' % (name, eatspace) |
693 | ||
694 | def is_c_ptr(name): | |
695 | suffix = "*" + eatspace | |
696 | return c_type(name).endswith(suffix) | |
0f923be2 MR |
697 | |
698 | def genindent(count): | |
699 | ret = "" | |
700 | for i in range(count): | |
701 | ret += " " | |
702 | return ret | |
703 | ||
704 | indent_level = 0 | |
705 | ||
706 | def push_indent(indent_amount=4): | |
707 | global indent_level | |
708 | indent_level += indent_amount | |
709 | ||
710 | def pop_indent(indent_amount=4): | |
711 | global indent_level | |
712 | indent_level -= indent_amount | |
713 | ||
714 | def cgen(code, **kwds): | |
715 | indent = genindent(indent_level) | |
716 | lines = code.split('\n') | |
717 | lines = map(lambda x: indent + x, lines) | |
718 | return '\n'.join(lines) % kwds + '\n' | |
719 | ||
720 | def mcgen(code, **kwds): | |
05dfb26c AK |
721 | raw = cgen('\n'.join(code.split('\n')[1:-1]), **kwds) |
722 | return re.sub(re.escape(eatspace) + ' *', '', raw) | |
0f923be2 MR |
723 | |
724 | def basename(filename): | |
725 | return filename.split("/")[-1] | |
726 | ||
727 | def guardname(filename): | |
d8e1f214 MR |
728 | guard = basename(filename).rsplit(".", 1)[0] |
729 | for substr in [".", " ", "-"]: | |
730 | guard = guard.replace(substr, "_") | |
731 | return guard.upper() + '_H' | |
c0afa9c5 MR |
732 | |
733 | def guardstart(name): | |
734 | return mcgen(''' | |
735 | ||
736 | #ifndef %(name)s | |
737 | #define %(name)s | |
738 | ||
739 | ''', | |
740 | name=guardname(name)) | |
741 | ||
742 | def guardend(name): | |
743 | return mcgen(''' | |
744 | ||
745 | #endif /* %(name)s */ | |
746 | ||
747 | ''', | |
748 | name=guardname(name)) | |
6299659f | 749 | |
5d371f41 WX |
750 | # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1 |
751 | # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2 | |
752 | # ENUM24_Name -> ENUM24_NAME | |
753 | def _generate_enum_string(value): | |
754 | c_fun_str = c_fun(value, False) | |
b0b58195 | 755 | if value.isupper(): |
5d371f41 WX |
756 | return c_fun_str |
757 | ||
6299659f | 758 | new_name = '' |
5d371f41 WX |
759 | l = len(c_fun_str) |
760 | for i in range(l): | |
761 | c = c_fun_str[i] | |
762 | # When c is upper and no "_" appears before, do more checks | |
763 | if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_": | |
764 | # Case 1: next string is lower | |
765 | # Case 2: previous string is digit | |
766 | if (i < (l - 1) and c_fun_str[i + 1].islower()) or \ | |
767 | c_fun_str[i - 1].isdigit(): | |
768 | new_name += '_' | |
6299659f WX |
769 | new_name += c |
770 | return new_name.lstrip('_').upper() | |
b0b58195 WX |
771 | |
772 | def generate_enum_full_value(enum_name, enum_value): | |
5d371f41 WX |
773 | abbrev_string = _generate_enum_string(enum_name) |
774 | value_string = _generate_enum_string(enum_value) | |
b0b58195 | 775 | return "%s_%s" % (abbrev_string, value_string) |