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): 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 if name in c89_words | c99_words | c11_words | gcc_words: 160 return "q_" + name 161 return name.replace('-', '_').lstrip("*") 162 163def c_fun(name): 164 return c_var(name).replace('.', '_') 165 166def c_list_type(name): 167 return '%sList' % name 168 169def type_name(name): 170 if type(name) == list: 171 return c_list_type(name[0]) 172 return name 173 174enum_types = [] 175 176def add_enum(name): 177 global enum_types 178 enum_types.append(name) 179 180def is_enum(name): 181 global enum_types 182 return (name in enum_types) 183 184def c_type(name): 185 if name == 'str': 186 return 'char *' 187 elif name == 'int': 188 return 'int64_t' 189 elif (name == 'int8' or name == 'int16' or name == 'int32' or 190 name == 'int64' or name == 'uint8' or name == 'uint16' or 191 name == 'uint32' or name == 'uint64'): 192 return name + '_t' 193 elif name == 'size': 194 return 'uint64_t' 195 elif name == 'bool': 196 return 'bool' 197 elif name == 'number': 198 return 'double' 199 elif type(name) == list: 200 return '%s *' % c_list_type(name[0]) 201 elif is_enum(name): 202 return name 203 elif name == None or len(name) == 0: 204 return 'void' 205 elif name == name.upper(): 206 return '%sEvent *' % camel_case(name) 207 else: 208 return '%s *' % name 209 210def genindent(count): 211 ret = "" 212 for i in range(count): 213 ret += " " 214 return ret 215 216indent_level = 0 217 218def push_indent(indent_amount=4): 219 global indent_level 220 indent_level += indent_amount 221 222def pop_indent(indent_amount=4): 223 global indent_level 224 indent_level -= indent_amount 225 226def cgen(code, **kwds): 227 indent = genindent(indent_level) 228 lines = code.split('\n') 229 lines = map(lambda x: indent + x, lines) 230 return '\n'.join(lines) % kwds + '\n' 231 232def mcgen(code, **kwds): 233 return cgen('\n'.join(code.split('\n')[1:-1]), **kwds) 234 235def basename(filename): 236 return filename.split("/")[-1] 237 238def guardname(filename): 239 guard = basename(filename).rsplit(".", 1)[0] 240 for substr in [".", " ", "-"]: 241 guard = guard.replace(substr, "_") 242 return guard.upper() + '_H' 243