qemu/scripts/qapi.py
<<
>>
Prefs
   1#
   2# QAPI helper library
   3#
   4# Copyright IBM, Corp. 2011
   5#
   6# Authors:
   7#  Anthony Liguori <aliguori@us.ibm.com>
   8#
   9# This work is licensed under the terms of the GNU GPLv2.
  10# See the COPYING.LIB file in the top-level directory.
  11
  12from ordereddict import OrderedDict
  13
  14def tokenize(data):
  15    while len(data):
  16        ch = data[0]
  17        data = data[1:]
  18        if ch in ['{', '}', ':', ',', '[', ']']:
  19            yield ch
  20        elif ch in ' \n':
  21            None
  22        elif ch == "'":
  23            string = ''
  24            esc = False
  25            while True:
  26                if (data == ''):
  27                    raise Exception("Mismatched quotes")
  28                ch = data[0]
  29                data = data[1:]
  30                if esc:
  31                    string += ch
  32                    esc = False
  33                elif ch == "\\":
  34                    esc = True
  35                elif ch == "'":
  36                    break
  37                else:
  38                    string += ch
  39            yield string
  40
  41def parse(tokens):
  42    if tokens[0] == '{':
  43        ret = OrderedDict()
  44        tokens = tokens[1:]
  45        while tokens[0] != '}':
  46            key = tokens[0]
  47            tokens = tokens[1:]
  48
  49            tokens = tokens[1:] # :
  50
  51            value, tokens = parse(tokens)
  52
  53            if tokens[0] == ',':
  54                tokens = tokens[1:]
  55
  56            ret[key] = value
  57        tokens = tokens[1:]
  58        return ret, tokens
  59    elif tokens[0] == '[':
  60        ret = []
  61        tokens = tokens[1:]
  62        while tokens[0] != ']':
  63            value, tokens = parse(tokens)
  64            if tokens[0] == ',':
  65                tokens = tokens[1:]
  66            ret.append(value)
  67        tokens = tokens[1:]
  68        return ret, tokens
  69    else:
  70        return tokens[0], tokens[1:]
  71
  72def evaluate(string):
  73    return parse(map(lambda x: x, tokenize(string)))[0]
  74
  75def parse_schema(fp):
  76    exprs = []
  77    expr = ''
  78    expr_eval = None
  79
  80    for line in fp:
  81        if line.startswith('#') or line == '\n':
  82            continue
  83
  84        if line.startswith(' '):
  85            expr += line
  86        elif expr:
  87            expr_eval = evaluate(expr)
  88            if expr_eval.has_key('enum'):
  89                add_enum(expr_eval['enum'])
  90            elif expr_eval.has_key('union'):
  91                add_enum('%sKind' % expr_eval['union'])
  92            exprs.append(expr_eval)
  93            expr = line
  94        else:
  95            expr += line
  96
  97    if expr:
  98        expr_eval = evaluate(expr)
  99        if expr_eval.has_key('enum'):
 100            add_enum(expr_eval['enum'])
 101        elif expr_eval.has_key('union'):
 102            add_enum('%sKind' % expr_eval['union'])
 103        exprs.append(expr_eval)
 104
 105    return exprs
 106
 107def parse_args(typeinfo):
 108    for member in typeinfo:
 109        argname = member
 110        argentry = typeinfo[member]
 111        optional = False
 112        structured = False
 113        if member.startswith('*'):
 114            argname = member[1:]
 115            optional = True
 116        if isinstance(argentry, OrderedDict):
 117            structured = True
 118        yield (argname, argentry, optional, structured)
 119
 120def de_camel_case(name):
 121    new_name = ''
 122    for ch in name:
 123        if ch.isupper() and new_name:
 124            new_name += '_'
 125        if ch == '-':
 126            new_name += '_'
 127        else:
 128            new_name += ch.lower()
 129    return new_name
 130
 131def camel_case(name):
 132    new_name = ''
 133    first = True
 134    for ch in name:
 135        if ch in ['_', '-']:
 136            first = True
 137        elif first:
 138            new_name += ch.upper()
 139            first = False
 140        else:
 141            new_name += ch.lower()
 142    return new_name
 143
 144def c_var(name, protect=True):
 145    # ANSI X3J11/88-090, 3.1.1
 146    c89_words = set(['auto', 'break', 'case', 'char', 'const', 'continue',
 147                     'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
 148                     'for', 'goto', 'if', 'int', 'long', 'register', 'return',
 149                     'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
 150                     'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
 151    # ISO/IEC 9899:1999, 6.4.1
 152    c99_words = set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
 153    # ISO/IEC 9899:2011, 6.4.1
 154    c11_words = set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
 155                     '_Static_assert', '_Thread_local'])
 156    # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
 157    # excluding _.*
 158    gcc_words = set(['asm', 'typeof'])
 159    # namespace pollution:
 160    polluted_words = set(['unix'])
 161    if protect and (name in c89_words | c99_words | c11_words | gcc_words | polluted_words):
 162        return "q_" + name
 163    return name.replace('-', '_').lstrip("*")
 164
 165def c_fun(name, protect=True):
 166    return c_var(name, protect).replace('.', '_')
 167
 168def c_list_type(name):
 169    return '%sList' % name
 170
 171def type_name(name):
 172    if type(name) == list:
 173        return c_list_type(name[0])
 174    return name
 175
 176enum_types = []
 177
 178def add_enum(name):
 179    global enum_types
 180    enum_types.append(name)
 181
 182def is_enum(name):
 183    global enum_types
 184    return (name in enum_types)
 185
 186def c_type(name):
 187    if name == 'str':
 188        return 'char *'
 189    elif name == 'int':
 190        return 'int64_t'
 191    elif (name == 'int8' or name == 'int16' or name == 'int32' or
 192          name == 'int64' or name == 'uint8' or name == 'uint16' or
 193          name == 'uint32' or name == 'uint64'):
 194        return name + '_t'
 195    elif name == 'size':
 196        return 'uint64_t'
 197    elif name == 'bool':
 198        return 'bool'
 199    elif name == 'number':
 200        return 'double'
 201    elif type(name) == list:
 202        return '%s *' % c_list_type(name[0])
 203    elif is_enum(name):
 204        return name
 205    elif name == None or len(name) == 0:
 206        return 'void'
 207    elif name == name.upper():
 208        return '%sEvent *' % camel_case(name)
 209    else:
 210        return '%s *' % name
 211
 212def genindent(count):
 213    ret = ""
 214    for i in range(count):
 215        ret += " "
 216    return ret
 217
 218indent_level = 0
 219
 220def push_indent(indent_amount=4):
 221    global indent_level
 222    indent_level += indent_amount
 223
 224def pop_indent(indent_amount=4):
 225    global indent_level
 226    indent_level -= indent_amount
 227
 228def cgen(code, **kwds):
 229    indent = genindent(indent_level)
 230    lines = code.split('\n')
 231    lines = map(lambda x: indent + x, lines)
 232    return '\n'.join(lines) % kwds + '\n'
 233
 234def mcgen(code, **kwds):
 235    return cgen('\n'.join(code.split('\n')[1:-1]), **kwds)
 236
 237def basename(filename):
 238    return filename.split("/")[-1]
 239
 240def guardname(filename):
 241    guard = basename(filename).rsplit(".", 1)[0]
 242    for substr in [".", " ", "-"]:
 243        guard = guard.replace(substr, "_")
 244    return guard.upper() + '_H'
 245