]> Git Repo - qemu.git/blob - scripts/qapi.py
qapi: Fix errors for non-string, non-dictionary members
[qemu.git] / scripts / qapi.py
1 #
2 # QAPI helper library
3 #
4 # Copyright IBM, Corp. 2011
5 # Copyright (c) 2013-2015 Red Hat Inc.
6 #
7 # Authors:
8 #  Anthony Liguori <[email protected]>
9 #  Markus Armbruster <[email protected]>
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
14 import re
15 from ordereddict import OrderedDict
16 import errno
17 import getopt
18 import os
19 import sys
20 import string
21
22 builtin_types = {
23     'str':      'QTYPE_QSTRING',
24     'int':      'QTYPE_QINT',
25     'number':   'QTYPE_QFLOAT',
26     'bool':     'QTYPE_QBOOL',
27     'int8':     'QTYPE_QINT',
28     'int16':    'QTYPE_QINT',
29     'int32':    'QTYPE_QINT',
30     'int64':    'QTYPE_QINT',
31     'uint8':    'QTYPE_QINT',
32     'uint16':   'QTYPE_QINT',
33     'uint32':   'QTYPE_QINT',
34     'uint64':   'QTYPE_QINT',
35     'size':     'QTYPE_QINT',
36 }
37
38 # Whitelist of commands allowed to return a non-dictionary
39 returns_whitelist = [
40     # From QMP:
41     'human-monitor-command',
42     'query-migrate-cache-size',
43     'query-tpm-models',
44     'query-tpm-types',
45     'ringbuf-read',
46
47     # From QGA:
48     'guest-file-open',
49     'guest-fsfreeze-freeze',
50     'guest-fsfreeze-freeze-list',
51     'guest-fsfreeze-status',
52     'guest-fsfreeze-thaw',
53     'guest-get-time',
54     'guest-set-vcpus',
55     'guest-sync',
56     'guest-sync-delimited',
57
58     # From qapi-schema-test:
59     'user_def_cmd3',
60 ]
61
62 enum_types = []
63 struct_types = []
64 union_types = []
65 events = []
66 all_names = {}
67
68 #
69 # Parsing the schema into expressions
70 #
71
72 def error_path(parent):
73     res = ""
74     while parent:
75         res = ("In file included from %s:%d:\n" % (parent['file'],
76                                                    parent['line'])) + res
77         parent = parent['parent']
78     return res
79
80 class QAPISchemaError(Exception):
81     def __init__(self, schema, msg):
82         self.fname = schema.fname
83         self.msg = msg
84         self.col = 1
85         self.line = schema.line
86         for ch in schema.src[schema.line_pos:schema.pos]:
87             if ch == '\t':
88                 self.col = (self.col + 7) % 8 + 1
89             else:
90                 self.col += 1
91         self.info = schema.incl_info
92
93     def __str__(self):
94         return error_path(self.info) + \
95             "%s:%d:%d: %s" % (self.fname, self.line, self.col, self.msg)
96
97 class QAPIExprError(Exception):
98     def __init__(self, expr_info, msg):
99         self.info = expr_info
100         self.msg = msg
101
102     def __str__(self):
103         return error_path(self.info['parent']) + \
104             "%s:%d: %s" % (self.info['file'], self.info['line'], self.msg)
105
106 class QAPISchema:
107
108     def __init__(self, fp, previously_included = [], incl_info = None):
109         abs_fname = os.path.abspath(fp.name)
110         fname = fp.name
111         self.fname = fname
112         previously_included.append(abs_fname)
113         self.incl_info = incl_info
114         self.src = fp.read()
115         if self.src == '' or self.src[-1] != '\n':
116             self.src += '\n'
117         self.cursor = 0
118         self.line = 1
119         self.line_pos = 0
120         self.exprs = []
121         self.accept()
122
123         while self.tok != None:
124             expr_info = {'file': fname, 'line': self.line,
125                          'parent': self.incl_info}
126             expr = self.get_expr(False)
127             if isinstance(expr, dict) and "include" in expr:
128                 if len(expr) != 1:
129                     raise QAPIExprError(expr_info, "Invalid 'include' directive")
130                 include = expr["include"]
131                 if not isinstance(include, str):
132                     raise QAPIExprError(expr_info,
133                                         'Expected a file name (string), got: %s'
134                                         % include)
135                 incl_abs_fname = os.path.join(os.path.dirname(abs_fname),
136                                               include)
137                 # catch inclusion cycle
138                 inf = expr_info
139                 while inf:
140                     if incl_abs_fname == os.path.abspath(inf['file']):
141                         raise QAPIExprError(expr_info, "Inclusion loop for %s"
142                                             % include)
143                     inf = inf['parent']
144                 # skip multiple include of the same file
145                 if incl_abs_fname in previously_included:
146                     continue
147                 try:
148                     fobj = open(incl_abs_fname, 'r')
149                 except IOError, e:
150                     raise QAPIExprError(expr_info,
151                                         '%s: %s' % (e.strerror, include))
152                 exprs_include = QAPISchema(fobj, previously_included,
153                                            expr_info)
154                 self.exprs.extend(exprs_include.exprs)
155             else:
156                 expr_elem = {'expr': expr,
157                              'info': expr_info}
158                 self.exprs.append(expr_elem)
159
160     def accept(self):
161         while True:
162             self.tok = self.src[self.cursor]
163             self.pos = self.cursor
164             self.cursor += 1
165             self.val = None
166
167             if self.tok == '#':
168                 self.cursor = self.src.find('\n', self.cursor)
169             elif self.tok in ['{', '}', ':', ',', '[', ']']:
170                 return
171             elif self.tok == "'":
172                 string = ''
173                 esc = False
174                 while True:
175                     ch = self.src[self.cursor]
176                     self.cursor += 1
177                     if ch == '\n':
178                         raise QAPISchemaError(self,
179                                               'Missing terminating "\'"')
180                     if esc:
181                         if ch == 'b':
182                             string += '\b'
183                         elif ch == 'f':
184                             string += '\f'
185                         elif ch == 'n':
186                             string += '\n'
187                         elif ch == 'r':
188                             string += '\r'
189                         elif ch == 't':
190                             string += '\t'
191                         elif ch == 'u':
192                             value = 0
193                             for x in range(0, 4):
194                                 ch = self.src[self.cursor]
195                                 self.cursor += 1
196                                 if ch not in "0123456789abcdefABCDEF":
197                                     raise QAPISchemaError(self,
198                                                           '\\u escape needs 4 '
199                                                           'hex digits')
200                                 value = (value << 4) + int(ch, 16)
201                             # If Python 2 and 3 didn't disagree so much on
202                             # how to handle Unicode, then we could allow
203                             # Unicode string defaults.  But most of QAPI is
204                             # ASCII-only, so we aren't losing much for now.
205                             if not value or value > 0x7f:
206                                 raise QAPISchemaError(self,
207                                                       'For now, \\u escape '
208                                                       'only supports non-zero '
209                                                       'values up to \\u007f')
210                             string += chr(value)
211                         elif ch in "\\/'\"":
212                             string += ch
213                         else:
214                             raise QAPISchemaError(self,
215                                                   "Unknown escape \\%s" %ch)
216                         esc = False
217                     elif ch == "\\":
218                         esc = True
219                     elif ch == "'":
220                         self.val = string
221                         return
222                     else:
223                         string += ch
224             elif self.src.startswith("true", self.pos):
225                 self.val = True
226                 self.cursor += 3
227                 return
228             elif self.src.startswith("false", self.pos):
229                 self.val = False
230                 self.cursor += 4
231                 return
232             elif self.src.startswith("null", self.pos):
233                 self.val = None
234                 self.cursor += 3
235                 return
236             elif self.tok == '\n':
237                 if self.cursor == len(self.src):
238                     self.tok = None
239                     return
240                 self.line += 1
241                 self.line_pos = self.cursor
242             elif not self.tok.isspace():
243                 raise QAPISchemaError(self, 'Stray "%s"' % self.tok)
244
245     def get_members(self):
246         expr = OrderedDict()
247         if self.tok == '}':
248             self.accept()
249             return expr
250         if self.tok != "'":
251             raise QAPISchemaError(self, 'Expected string or "}"')
252         while True:
253             key = self.val
254             self.accept()
255             if self.tok != ':':
256                 raise QAPISchemaError(self, 'Expected ":"')
257             self.accept()
258             if key in expr:
259                 raise QAPISchemaError(self, 'Duplicate key "%s"' % key)
260             expr[key] = self.get_expr(True)
261             if self.tok == '}':
262                 self.accept()
263                 return expr
264             if self.tok != ',':
265                 raise QAPISchemaError(self, 'Expected "," or "}"')
266             self.accept()
267             if self.tok != "'":
268                 raise QAPISchemaError(self, 'Expected string')
269
270     def get_values(self):
271         expr = []
272         if self.tok == ']':
273             self.accept()
274             return expr
275         if not self.tok in "{['tfn":
276             raise QAPISchemaError(self, 'Expected "{", "[", "]", string, '
277                                   'boolean or "null"')
278         while True:
279             expr.append(self.get_expr(True))
280             if self.tok == ']':
281                 self.accept()
282                 return expr
283             if self.tok != ',':
284                 raise QAPISchemaError(self, 'Expected "," or "]"')
285             self.accept()
286
287     def get_expr(self, nested):
288         if self.tok != '{' and not nested:
289             raise QAPISchemaError(self, 'Expected "{"')
290         if self.tok == '{':
291             self.accept()
292             expr = self.get_members()
293         elif self.tok == '[':
294             self.accept()
295             expr = self.get_values()
296         elif self.tok in "'tfn":
297             expr = self.val
298             self.accept()
299         else:
300             raise QAPISchemaError(self, 'Expected "{", "[" or string')
301         return expr
302
303 #
304 # Semantic analysis of schema expressions
305 #
306
307 def find_base_fields(base):
308     base_struct_define = find_struct(base)
309     if not base_struct_define:
310         return None
311     return base_struct_define['data']
312
313 # Return the qtype of an alternate branch, or None on error.
314 def find_alternate_member_qtype(qapi_type):
315     if builtin_types.has_key(qapi_type):
316         return builtin_types[qapi_type]
317     elif find_struct(qapi_type):
318         return "QTYPE_QDICT"
319     elif find_enum(qapi_type):
320         return "QTYPE_QSTRING"
321     elif find_union(qapi_type):
322         return "QTYPE_QDICT"
323     return None
324
325 # Return the discriminator enum define if discriminator is specified as an
326 # enum type, otherwise return None.
327 def discriminator_find_enum_define(expr):
328     base = expr.get('base')
329     discriminator = expr.get('discriminator')
330
331     if not (discriminator and base):
332         return None
333
334     base_fields = find_base_fields(base)
335     if not base_fields:
336         return None
337
338     discriminator_type = base_fields.get(discriminator)
339     if not discriminator_type:
340         return None
341
342     return find_enum(discriminator_type)
343
344 # FIXME should enforce "other than downstream extensions [...], all
345 # names should begin with a letter".
346 valid_name = re.compile('^[a-zA-Z_][a-zA-Z0-9_.-]*$')
347 def check_name(expr_info, source, name, allow_optional = False,
348                enum_member = False):
349     global valid_name
350     membername = name
351
352     if not isinstance(name, str):
353         raise QAPIExprError(expr_info,
354                             "%s requires a string name" % source)
355     if name.startswith('*'):
356         membername = name[1:]
357         if not allow_optional:
358             raise QAPIExprError(expr_info,
359                                 "%s does not allow optional name '%s'"
360                                 % (source, name))
361     # Enum members can start with a digit, because the generated C
362     # code always prefixes it with the enum name
363     if enum_member:
364         membername = '_' + membername
365     if not valid_name.match(membername):
366         raise QAPIExprError(expr_info,
367                             "%s uses invalid name '%s'" % (source, name))
368
369 def add_name(name, info, meta, implicit = False):
370     global all_names
371     check_name(info, "'%s'" % meta, name)
372     # FIXME should reject names that differ only in '_' vs. '.'
373     # vs. '-', because they're liable to clash in generated C.
374     if name in all_names:
375         raise QAPIExprError(info,
376                             "%s '%s' is already defined"
377                             % (all_names[name], name))
378     if not implicit and name[-4:] == 'Kind':
379         raise QAPIExprError(info,
380                             "%s '%s' should not end in 'Kind'"
381                             % (meta, name))
382     all_names[name] = meta
383
384 def add_struct(definition, info):
385     global struct_types
386     name = definition['struct']
387     add_name(name, info, 'struct')
388     struct_types.append(definition)
389
390 def find_struct(name):
391     global struct_types
392     for struct in struct_types:
393         if struct['struct'] == name:
394             return struct
395     return None
396
397 def add_union(definition, info):
398     global union_types
399     name = definition['union']
400     add_name(name, info, 'union')
401     union_types.append(definition)
402
403 def find_union(name):
404     global union_types
405     for union in union_types:
406         if union['union'] == name:
407             return union
408     return None
409
410 def add_enum(name, info, enum_values = None, implicit = False):
411     global enum_types
412     add_name(name, info, 'enum', implicit)
413     enum_types.append({"enum_name": name, "enum_values": enum_values})
414
415 def find_enum(name):
416     global enum_types
417     for enum in enum_types:
418         if enum['enum_name'] == name:
419             return enum
420     return None
421
422 def is_enum(name):
423     return find_enum(name) != None
424
425 def check_type(expr_info, source, value, allow_array = False,
426                allow_dict = False, allow_optional = False,
427                allow_star = False, allow_metas = []):
428     global all_names
429     orig_value = value
430
431     if value is None:
432         return
433
434     if allow_star and value == '**':
435         return
436
437     # Check if array type for value is okay
438     if isinstance(value, list):
439         if not allow_array:
440             raise QAPIExprError(expr_info,
441                                 "%s cannot be an array" % source)
442         if len(value) != 1 or not isinstance(value[0], str):
443             raise QAPIExprError(expr_info,
444                                 "%s: array type must contain single type name"
445                                 % source)
446         value = value[0]
447         orig_value = "array of %s" %value
448
449     # Check if type name for value is okay
450     if isinstance(value, str):
451         if value == '**':
452             raise QAPIExprError(expr_info,
453                                 "%s uses '**' but did not request 'gen':false"
454                                 % source)
455         if not value in all_names:
456             raise QAPIExprError(expr_info,
457                                 "%s uses unknown type '%s'"
458                                 % (source, orig_value))
459         if not all_names[value] in allow_metas:
460             raise QAPIExprError(expr_info,
461                                 "%s cannot use %s type '%s'"
462                                 % (source, all_names[value], orig_value))
463         return
464
465     if not allow_dict:
466         raise QAPIExprError(expr_info,
467                             "%s should be a type name" % source)
468
469     if not isinstance(value, OrderedDict):
470         raise QAPIExprError(expr_info,
471                             "%s should be a dictionary or type name" % source)
472
473     # value is a dictionary, check that each member is okay
474     for (key, arg) in value.items():
475         check_name(expr_info, "Member of %s" % source, key,
476                    allow_optional=allow_optional)
477         # Todo: allow dictionaries to represent default values of
478         # an optional argument.
479         check_type(expr_info, "Member '%s' of %s" % (key, source), arg,
480                    allow_array=True, allow_star=allow_star,
481                    allow_metas=['built-in', 'union', 'alternate', 'struct',
482                                 'enum'])
483
484 def check_member_clash(expr_info, base_name, data, source = ""):
485     base = find_struct(base_name)
486     assert base
487     base_members = base['data']
488     for key in data.keys():
489         if key.startswith('*'):
490             key = key[1:]
491         if key in base_members or "*" + key in base_members:
492             raise QAPIExprError(expr_info,
493                                 "Member name '%s'%s clashes with base '%s'"
494                                 % (key, source, base_name))
495     if base.get('base'):
496         check_member_clash(expr_info, base['base'], data, source)
497
498 def check_command(expr, expr_info):
499     name = expr['command']
500     allow_star = expr.has_key('gen')
501
502     check_type(expr_info, "'data' for command '%s'" % name,
503                expr.get('data'), allow_dict=True, allow_optional=True,
504                allow_metas=['struct'], allow_star=allow_star)
505     returns_meta = ['union', 'struct']
506     if name in returns_whitelist:
507         returns_meta += ['built-in', 'alternate', 'enum']
508     check_type(expr_info, "'returns' for command '%s'" % name,
509                expr.get('returns'), allow_array=True,
510                allow_optional=True, allow_metas=returns_meta,
511                allow_star=allow_star)
512
513 def check_event(expr, expr_info):
514     global events
515     name = expr['event']
516
517     if name.upper() == 'MAX':
518         raise QAPIExprError(expr_info, "Event name 'MAX' cannot be created")
519     events.append(name)
520     check_type(expr_info, "'data' for event '%s'" % name,
521                expr.get('data'), allow_dict=True, allow_optional=True,
522                allow_metas=['struct'])
523
524 def check_union(expr, expr_info):
525     name = expr['union']
526     base = expr.get('base')
527     discriminator = expr.get('discriminator')
528     members = expr['data']
529     values = { 'MAX': '(automatic)' }
530
531     # Two types of unions, determined by discriminator.
532
533     # With no discriminator it is a simple union.
534     if discriminator is None:
535         enum_define = None
536         allow_metas=['built-in', 'union', 'alternate', 'struct', 'enum']
537         if base is not None:
538             raise QAPIExprError(expr_info,
539                                 "Simple union '%s' must not have a base"
540                                 % name)
541
542     # Else, it's a flat union.
543     else:
544         # The object must have a string member 'base'.
545         if not isinstance(base, str):
546             raise QAPIExprError(expr_info,
547                                 "Flat union '%s' must have a string base field"
548                                 % name)
549         base_fields = find_base_fields(base)
550         if not base_fields:
551             raise QAPIExprError(expr_info,
552                                 "Base '%s' is not a valid struct"
553                                 % base)
554
555         # The value of member 'discriminator' must name a non-optional
556         # member of the base struct.
557         check_name(expr_info, "Discriminator of flat union '%s'" % name,
558                    discriminator)
559         discriminator_type = base_fields.get(discriminator)
560         if not discriminator_type:
561             raise QAPIExprError(expr_info,
562                                 "Discriminator '%s' is not a member of base "
563                                 "struct '%s'"
564                                 % (discriminator, base))
565         enum_define = find_enum(discriminator_type)
566         allow_metas=['struct']
567         # Do not allow string discriminator
568         if not enum_define:
569             raise QAPIExprError(expr_info,
570                                 "Discriminator '%s' must be of enumeration "
571                                 "type" % discriminator)
572
573     # Check every branch
574     for (key, value) in members.items():
575         check_name(expr_info, "Member of union '%s'" % name, key)
576
577         # Each value must name a known type; furthermore, in flat unions,
578         # branches must be a struct with no overlapping member names
579         check_type(expr_info, "Member '%s' of union '%s'" % (key, name),
580                    value, allow_array=not base, allow_metas=allow_metas)
581         if base:
582             branch_struct = find_struct(value)
583             assert branch_struct
584             check_member_clash(expr_info, base, branch_struct['data'],
585                                " of branch '%s'" % key)
586
587         # If the discriminator names an enum type, then all members
588         # of 'data' must also be members of the enum type.
589         if enum_define:
590             if not key in enum_define['enum_values']:
591                 raise QAPIExprError(expr_info,
592                                     "Discriminator value '%s' is not found in "
593                                     "enum '%s'" %
594                                     (key, enum_define["enum_name"]))
595
596         # Otherwise, check for conflicts in the generated enum
597         else:
598             c_key = camel_to_upper(key)
599             if c_key in values:
600                 raise QAPIExprError(expr_info,
601                                     "Union '%s' member '%s' clashes with '%s'"
602                                     % (name, key, values[c_key]))
603             values[c_key] = key
604
605 def check_alternate(expr, expr_info):
606     name = expr['alternate']
607     members = expr['data']
608     values = { 'MAX': '(automatic)' }
609     types_seen = {}
610
611     # Check every branch
612     for (key, value) in members.items():
613         check_name(expr_info, "Member of alternate '%s'" % name, key)
614
615         # Check for conflicts in the generated enum
616         c_key = camel_to_upper(key)
617         if c_key in values:
618             raise QAPIExprError(expr_info,
619                                 "Alternate '%s' member '%s' clashes with '%s'"
620                                 % (name, key, values[c_key]))
621         values[c_key] = key
622
623         # Ensure alternates have no type conflicts.
624         check_type(expr_info, "Member '%s' of alternate '%s'" % (key, name),
625                    value,
626                    allow_metas=['built-in', 'union', 'struct', 'enum'])
627         qtype = find_alternate_member_qtype(value)
628         assert qtype
629         if qtype in types_seen:
630             raise QAPIExprError(expr_info,
631                                 "Alternate '%s' member '%s' can't "
632                                 "be distinguished from member '%s'"
633                                 % (name, key, types_seen[qtype]))
634         types_seen[qtype] = key
635
636 def check_enum(expr, expr_info):
637     name = expr['enum']
638     members = expr.get('data')
639     values = { 'MAX': '(automatic)' }
640
641     if not isinstance(members, list):
642         raise QAPIExprError(expr_info,
643                             "Enum '%s' requires an array for 'data'" % name)
644     for member in members:
645         check_name(expr_info, "Member of enum '%s'" %name, member,
646                    enum_member=True)
647         key = camel_to_upper(member)
648         if key in values:
649             raise QAPIExprError(expr_info,
650                                 "Enum '%s' member '%s' clashes with '%s'"
651                                 % (name, member, values[key]))
652         values[key] = member
653
654 def check_struct(expr, expr_info):
655     name = expr['struct']
656     members = expr['data']
657
658     check_type(expr_info, "'data' for struct '%s'" % name, members,
659                allow_dict=True, allow_optional=True)
660     check_type(expr_info, "'base' for struct '%s'" % name, expr.get('base'),
661                allow_metas=['struct'])
662     if expr.get('base'):
663         check_member_clash(expr_info, expr['base'], expr['data'])
664
665 def check_keys(expr_elem, meta, required, optional=[]):
666     expr = expr_elem['expr']
667     info = expr_elem['info']
668     name = expr[meta]
669     if not isinstance(name, str):
670         raise QAPIExprError(info,
671                             "'%s' key must have a string value" % meta)
672     required = required + [ meta ]
673     for (key, value) in expr.items():
674         if not key in required and not key in optional:
675             raise QAPIExprError(info,
676                                 "Unknown key '%s' in %s '%s'"
677                                 % (key, meta, name))
678         if (key == 'gen' or key == 'success-response') and value != False:
679             raise QAPIExprError(info,
680                                 "'%s' of %s '%s' should only use false value"
681                                 % (key, meta, name))
682     for key in required:
683         if not expr.has_key(key):
684             raise QAPIExprError(info,
685                                 "Key '%s' is missing from %s '%s'"
686                                 % (key, meta, name))
687
688 def check_exprs(exprs):
689     global all_names
690
691     # Learn the types and check for valid expression keys
692     for builtin in builtin_types.keys():
693         all_names[builtin] = 'built-in'
694     for expr_elem in exprs:
695         expr = expr_elem['expr']
696         info = expr_elem['info']
697         if expr.has_key('enum'):
698             check_keys(expr_elem, 'enum', ['data'])
699             add_enum(expr['enum'], info, expr['data'])
700         elif expr.has_key('union'):
701             check_keys(expr_elem, 'union', ['data'],
702                        ['base', 'discriminator'])
703             add_union(expr, info)
704         elif expr.has_key('alternate'):
705             check_keys(expr_elem, 'alternate', ['data'])
706             add_name(expr['alternate'], info, 'alternate')
707         elif expr.has_key('struct'):
708             check_keys(expr_elem, 'struct', ['data'], ['base'])
709             add_struct(expr, info)
710         elif expr.has_key('command'):
711             check_keys(expr_elem, 'command', [],
712                        ['data', 'returns', 'gen', 'success-response'])
713             add_name(expr['command'], info, 'command')
714         elif expr.has_key('event'):
715             check_keys(expr_elem, 'event', [], ['data'])
716             add_name(expr['event'], info, 'event')
717         else:
718             raise QAPIExprError(expr_elem['info'],
719                                 "Expression is missing metatype")
720
721     # Try again for hidden UnionKind enum
722     for expr_elem in exprs:
723         expr = expr_elem['expr']
724         if expr.has_key('union'):
725             if not discriminator_find_enum_define(expr):
726                 add_enum('%sKind' % expr['union'], expr_elem['info'],
727                          implicit=True)
728         elif expr.has_key('alternate'):
729             add_enum('%sKind' % expr['alternate'], expr_elem['info'],
730                      implicit=True)
731
732     # Validate that exprs make sense
733     for expr_elem in exprs:
734         expr = expr_elem['expr']
735         info = expr_elem['info']
736
737         if expr.has_key('enum'):
738             check_enum(expr, info)
739         elif expr.has_key('union'):
740             check_union(expr, info)
741         elif expr.has_key('alternate'):
742             check_alternate(expr, info)
743         elif expr.has_key('struct'):
744             check_struct(expr, info)
745         elif expr.has_key('command'):
746             check_command(expr, info)
747         elif expr.has_key('event'):
748             check_event(expr, info)
749         else:
750             assert False, 'unexpected meta type'
751
752     return map(lambda expr_elem: expr_elem['expr'], exprs)
753
754 def parse_schema(fname):
755     try:
756         schema = QAPISchema(open(fname, "r"))
757         return check_exprs(schema.exprs)
758     except (QAPISchemaError, QAPIExprError), e:
759         print >>sys.stderr, e
760         exit(1)
761
762 #
763 # Code generation helpers
764 #
765
766 def parse_args(typeinfo):
767     if isinstance(typeinfo, str):
768         struct = find_struct(typeinfo)
769         assert struct != None
770         typeinfo = struct['data']
771
772     for member in typeinfo:
773         argname = member
774         argentry = typeinfo[member]
775         optional = False
776         if member.startswith('*'):
777             argname = member[1:]
778             optional = True
779         # Todo: allow argentry to be OrderedDict, for providing the
780         # value of an optional argument.
781         yield (argname, argentry, optional)
782
783 def camel_case(name):
784     new_name = ''
785     first = True
786     for ch in name:
787         if ch in ['_', '-']:
788             first = True
789         elif first:
790             new_name += ch.upper()
791             first = False
792         else:
793             new_name += ch.lower()
794     return new_name
795
796 # ENUMName -> ENUM_NAME, EnumName1 -> ENUM_NAME1
797 # ENUM_NAME -> ENUM_NAME, ENUM_NAME1 -> ENUM_NAME1, ENUM_Name2 -> ENUM_NAME2
798 # ENUM24_Name -> ENUM24_NAME
799 def camel_to_upper(value):
800     c_fun_str = c_name(value, False)
801     if value.isupper():
802         return c_fun_str
803
804     new_name = ''
805     l = len(c_fun_str)
806     for i in range(l):
807         c = c_fun_str[i]
808         # When c is upper and no "_" appears before, do more checks
809         if c.isupper() and (i > 0) and c_fun_str[i - 1] != "_":
810             # Case 1: next string is lower
811             # Case 2: previous string is digit
812             if (i < (l - 1) and c_fun_str[i + 1].islower()) or \
813             c_fun_str[i - 1].isdigit():
814                 new_name += '_'
815         new_name += c
816     return new_name.lstrip('_').upper()
817
818 def c_enum_const(type_name, const_name):
819     return camel_to_upper(type_name + '_' + const_name)
820
821 c_name_trans = string.maketrans('.-', '__')
822
823 # Map @name to a valid C identifier.
824 # If @protect, avoid returning certain ticklish identifiers (like
825 # C keywords) by prepending "q_".
826 #
827 # Used for converting 'name' from a 'name':'type' qapi definition
828 # into a generated struct member, as well as converting type names
829 # into substrings of a generated C function name.
830 # '__a.b_c' -> '__a_b_c', 'x-foo' -> 'x_foo'
831 # protect=True: 'int' -> 'q_int'; protect=False: 'int' -> 'int'
832 def c_name(name, protect=True):
833     # ANSI X3J11/88-090, 3.1.1
834     c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
835                      'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
836                      'for', 'goto', 'if', 'int', 'long', 'register', 'return',
837                      'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
838                      'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
839     # ISO/IEC 9899:1999, 6.4.1
840     c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
841     # ISO/IEC 9899:2011, 6.4.1
842     c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
843                      '_Static_assert', '_Thread_local'])
844     # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
845     # excluding _.*
846     gcc_words = set(['asm', 'typeof'])
847     # C++ ISO/IEC 14882:2003 2.11
848     cpp_words = set(['bool', 'catch', 'class', 'const_cast', 'delete',
849                      'dynamic_cast', 'explicit', 'false', 'friend', 'mutable',
850                      'namespace', 'new', 'operator', 'private', 'protected',
851                      'public', 'reinterpret_cast', 'static_cast', 'template',
852                      'this', 'throw', 'true', 'try', 'typeid', 'typename',
853                      'using', 'virtual', 'wchar_t',
854                      # alternative representations
855                      'and', 'and_eq', 'bitand', 'bitor', 'compl', 'not',
856                      'not_eq', 'or', 'or_eq', 'xor', 'xor_eq'])
857     # namespace pollution:
858     polluted_words = set(['unix', 'errno'])
859     if protect and (name in c89_words | c99_words | c11_words | gcc_words | cpp_words | polluted_words):
860         return "q_" + name
861     return name.translate(c_name_trans)
862
863 # Map type @name to the C typedef name for the list form.
864 #
865 # ['Name'] -> 'NameList', ['x-Foo'] -> 'x_FooList', ['int'] -> 'intList'
866 def c_list_type(name):
867     return type_name(name) + 'List'
868
869 # Map type @value to the C typedef form.
870 #
871 # Used for converting 'type' from a 'member':'type' qapi definition
872 # into the alphanumeric portion of the type for a generated C parameter,
873 # as well as generated C function names.  See c_type() for the rest of
874 # the conversion such as adding '*' on pointer types.
875 # 'int' -> 'int', '[x-Foo]' -> 'x_FooList', '__a.b_c' -> '__a_b_c'
876 def type_name(value):
877     if type(value) == list:
878         return c_list_type(value[0])
879     if value in builtin_types.keys():
880         return value
881     return c_name(value)
882
883 eatspace = '\033EATSPACE.'
884 pointer_suffix = ' *' + eatspace
885
886 # Map type @name to its C type expression.
887 # If @is_param, const-qualify the string type.
888 #
889 # This function is used for computing the full C type of 'member':'name'.
890 # A special suffix is added in c_type() for pointer types, and it's
891 # stripped in mcgen(). So please notice this when you check the return
892 # value of c_type() outside mcgen().
893 def c_type(value, is_param=False):
894     if value == 'str':
895         if is_param:
896             return 'const char' + pointer_suffix
897         return 'char' + pointer_suffix
898
899     elif value == 'int':
900         return 'int64_t'
901     elif (value == 'int8' or value == 'int16' or value == 'int32' or
902           value == 'int64' or value == 'uint8' or value == 'uint16' or
903           value == 'uint32' or value == 'uint64'):
904         return value + '_t'
905     elif value == 'size':
906         return 'uint64_t'
907     elif value == 'bool':
908         return 'bool'
909     elif value == 'number':
910         return 'double'
911     elif type(value) == list:
912         return c_list_type(value[0]) + pointer_suffix
913     elif is_enum(value):
914         return c_name(value)
915     elif value == None:
916         return 'void'
917     elif value in events:
918         return camel_case(value) + 'Event' + pointer_suffix
919     else:
920         # complex type name
921         assert isinstance(value, str) and value != ""
922         return c_name(value) + pointer_suffix
923
924 def is_c_ptr(value):
925     return c_type(value).endswith(pointer_suffix)
926
927 def genindent(count):
928     ret = ""
929     for i in range(count):
930         ret += " "
931     return ret
932
933 indent_level = 0
934
935 def push_indent(indent_amount=4):
936     global indent_level
937     indent_level += indent_amount
938
939 def pop_indent(indent_amount=4):
940     global indent_level
941     indent_level -= indent_amount
942
943 # Generate @code with @kwds interpolated.
944 # Obey indent_level, and strip eatspace.
945 def cgen(code, **kwds):
946     raw = code % kwds
947     if indent_level:
948         indent = genindent(indent_level)
949         raw = re.subn("^.", indent + r'\g<0>', raw, 0, re.MULTILINE)
950         raw = raw[0]
951     return re.sub(re.escape(eatspace) + ' *', '', raw)
952
953 def mcgen(code, **kwds):
954     if code[0] == '\n':
955         code = code[1:]
956     return cgen(code, **kwds)
957
958
959 def guardname(filename):
960     return c_name(filename, protect=False).upper()
961
962 def guardstart(name):
963     return mcgen('''
964
965 #ifndef %(name)s
966 #define %(name)s
967
968 ''',
969                  name=guardname(name))
970
971 def guardend(name):
972     return mcgen('''
973
974 #endif /* %(name)s */
975
976 ''',
977                  name=guardname(name))
978
979 #
980 # Common command line parsing
981 #
982
983 def parse_command_line(extra_options = "", extra_long_options = []):
984
985     try:
986         opts, args = getopt.gnu_getopt(sys.argv[1:],
987                                        "chp:o:" + extra_options,
988                                        ["source", "header", "prefix=",
989                                         "output-dir="] + extra_long_options)
990     except getopt.GetoptError, err:
991         print >>sys.stderr, "%s: %s" % (sys.argv[0], str(err))
992         sys.exit(1)
993
994     output_dir = ""
995     prefix = ""
996     do_c = False
997     do_h = False
998     extra_opts = []
999
1000     for oa in opts:
1001         o, a = oa
1002         if o in ("-p", "--prefix"):
1003             match = re.match('([A-Za-z_.-][A-Za-z0-9_.-]*)?', a)
1004             if match.end() != len(a):
1005                 print >>sys.stderr, \
1006                     "%s: 'funny character '%s' in argument of --prefix" \
1007                     % (sys.argv[0], a[match.end()])
1008                 sys.exit(1)
1009             prefix = a
1010         elif o in ("-o", "--output-dir"):
1011             output_dir = a + "/"
1012         elif o in ("-c", "--source"):
1013             do_c = True
1014         elif o in ("-h", "--header"):
1015             do_h = True
1016         else:
1017             extra_opts.append(oa)
1018
1019     if not do_c and not do_h:
1020         do_c = True
1021         do_h = True
1022
1023     if len(args) != 1:
1024         print >>sys.stderr, "%s: need exactly one argument" % sys.argv[0]
1025         sys.exit(1)
1026     fname = args[0]
1027
1028     return (fname, output_dir, do_c, do_h, prefix, extra_opts)
1029
1030 #
1031 # Generate output files with boilerplate
1032 #
1033
1034 def open_output(output_dir, do_c, do_h, prefix, c_file, h_file,
1035                 c_comment, h_comment):
1036     guard = guardname(prefix + h_file)
1037     c_file = output_dir + prefix + c_file
1038     h_file = output_dir + prefix + h_file
1039
1040     try:
1041         os.makedirs(output_dir)
1042     except os.error, e:
1043         if e.errno != errno.EEXIST:
1044             raise
1045
1046     def maybe_open(really, name, opt):
1047         if really:
1048             return open(name, opt)
1049         else:
1050             import StringIO
1051             return StringIO.StringIO()
1052
1053     fdef = maybe_open(do_c, c_file, 'w')
1054     fdecl = maybe_open(do_h, h_file, 'w')
1055
1056     fdef.write(mcgen('''
1057 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1058 %(comment)s
1059 ''',
1060                      comment = c_comment))
1061
1062     fdecl.write(mcgen('''
1063 /* AUTOMATICALLY GENERATED, DO NOT MODIFY */
1064 %(comment)s
1065 #ifndef %(guard)s
1066 #define %(guard)s
1067
1068 ''',
1069                       comment = h_comment, guard = guard))
1070
1071     return (fdef, fdecl)
1072
1073 def close_output(fdef, fdecl):
1074     fdecl.write('''
1075 #endif
1076 ''')
1077     fdecl.close()
1078     fdef.close()
This page took 0.084059 seconds and 4 git commands to generate.