4 # Copyright IBM, Corp. 2011
7 # Anthony Liguori <aliguori@us.ibm.com>
9 # This work is licensed under the terms of the GNU GPLv2.
10 # See the COPYING.LIB file in the top-level directory.
12 from ordereddict
import OrderedDict
15 'str', 'int', 'number', 'bool',
16 'int8', 'int16', 'int32', 'int64',
17 'uint8', 'uint16', 'uint32', 'uint64'
20 builtin_type_qtypes
= {
21 'str': 'QTYPE_QSTRING',
23 'number': 'QTYPE_QFLOAT',
24 'bool': 'QTYPE_QBOOL',
26 'int16': 'QTYPE_QINT',
27 'int32': 'QTYPE_QINT',
28 'int64': 'QTYPE_QINT',
29 'uint8': 'QTYPE_QINT',
30 'uint16': 'QTYPE_QINT',
31 'uint32': 'QTYPE_QINT',
32 'uint64': 'QTYPE_QINT',
39 if ch
in ['{', '}', ':', ',', '[', ']']:
48 raise Exception("Mismatched quotes")
66 while tokens
[0] != '}':
70 tokens
= tokens
[1:] # :
72 value
, tokens
= parse(tokens
)
80 elif tokens
[0] == '[':
83 while tokens
[0] != ']':
84 value
, tokens
= parse(tokens
)
91 return tokens
[0], tokens
[1:]
94 return parse(map(lambda x
: x
, tokenize(string
)))[0]
100 if line
.startswith('#') or line
== '\n':
103 if line
.startswith(' '):
114 def parse_schema(fp
):
117 for expr
in get_expr(fp
):
118 expr_eval
= evaluate(expr
)
120 if expr_eval
.has_key('enum'):
121 add_enum(expr_eval
['enum'])
122 elif expr_eval
.has_key('union'):
124 add_enum('%sKind' % expr_eval
['union'])
125 elif expr_eval
.has_key('type'):
126 add_struct(expr_eval
)
127 exprs
.append(expr_eval
)
131 def parse_args(typeinfo
):
132 if isinstance(typeinfo
, basestring
):
133 struct
= find_struct(typeinfo
)
134 assert struct
!= None
135 typeinfo
= struct
['data']
137 for member
in typeinfo
:
139 argentry
= typeinfo
[member
]
142 if member
.startswith('*'):
145 if isinstance(argentry
, OrderedDict
):
147 yield (argname
, argentry
, optional
, structured
)
149 def de_camel_case(name
):
152 if ch
.isupper() and new_name
:
157 new_name
+= ch
.lower()
160 def camel_case(name
):
167 new_name
+= ch
.upper()
170 new_name
+= ch
.lower()
173 def c_var(name
, protect
=True):
174 # ANSI X3J11/88-090, 3.1.1
175 c89_words
= set(['auto', 'break', 'case', 'char', 'const', 'continue',
176 'default', 'do', 'double', 'else', 'enum', 'extern', 'float',
177 'for', 'goto', 'if', 'int', 'long', 'register', 'return',
178 'short', 'signed', 'sizeof', 'static', 'struct', 'switch',
179 'typedef', 'union', 'unsigned', 'void', 'volatile', 'while'])
180 # ISO/IEC 9899:1999, 6.4.1
181 c99_words
= set(['inline', 'restrict', '_Bool', '_Complex', '_Imaginary'])
182 # ISO/IEC 9899:2011, 6.4.1
183 c11_words
= set(['_Alignas', '_Alignof', '_Atomic', '_Generic', '_Noreturn',
184 '_Static_assert', '_Thread_local'])
185 # GCC http://gcc.gnu.org/onlinedocs/gcc-4.7.1/gcc/C-Extensions.html
187 gcc_words
= set(['asm', 'typeof'])
188 # namespace pollution:
189 polluted_words
= set(['unix'])
190 if protect
and (name
in c89_words | c99_words | c11_words | gcc_words | polluted_words
):
192 return name
.replace('-', '_').lstrip("*")
194 def c_fun(name
, protect
=True):
195 return c_var(name
, protect
).replace('.', '_')
197 def c_list_type(name
):
198 return '%sList' % name
201 if type(name
) == list:
202 return c_list_type(name
[0])
209 def add_struct(definition
):
211 struct_types
.append(definition
)
213 def find_struct(name
):
215 for struct
in struct_types
:
216 if struct
['type'] == name
:
220 def add_union(definition
):
222 union_types
.append(definition
)
224 def find_union(name
):
226 for union
in union_types
:
227 if union
['union'] == name
:
233 enum_types
.append(name
)
237 return (name
in enum_types
)
244 elif (name
== 'int8' or name
== 'int16' or name
== 'int32' or
245 name
== 'int64' or name
== 'uint8' or name
== 'uint16' or
246 name
== 'uint32' or name
== 'uint64'):
252 elif name
== 'number':
254 elif type(name
) == list:
255 return '%s *' % c_list_type(name
[0])
258 elif name
== None or len(name
) == 0:
260 elif name
== name
.upper():
261 return '%sEvent *' % camel_case(name
)
265 def genindent(count
):
267 for i
in range(count
):
273 def push_indent(indent_amount
=4):
275 indent_level
+= indent_amount
277 def pop_indent(indent_amount
=4):
279 indent_level
-= indent_amount
281 def cgen(code
, **kwds
):
282 indent
= genindent(indent_level
)
283 lines
= code
.split('\n')
284 lines
= map(lambda x
: indent
+ x
, lines
)
285 return '\n'.join(lines
) % kwds
+ '\n'
287 def mcgen(code
, **kwds
):
288 return cgen('\n'.join(code
.split('\n')[1:-1]), **kwds
)
290 def basename(filename
):
291 return filename
.split("/")[-1]
293 def guardname(filename
):
294 guard
= basename(filename
).rsplit(".", 1)[0]
295 for substr
in [".", " ", "-"]:
296 guard
= guard
.replace(substr
, "_")
297 return guard
.upper() + '_H'
299 def guardstart(name
):
306 name
=guardname(name
))
311 #endif /* %(name)s */
314 name
=guardname(name
))