]> git.cworth.org Git - apitrace/blob - specs/scripts/cdecl.py
ef04cfca88489b73403ec0f34a80612cf7062cac
[apitrace] / specs / scripts / cdecl.py
1 #!/usr/bin/env python
2 ##########################################################################
3 #
4 # Copyright 2011 Jose Fonseca
5 # All Rights Reserved.
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
16 #
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 # THE SOFTWARE.
24 #
25 ##########################################################################/
26
27
28 '''Script to parse C declarations and spew API definitions.
29 '''
30
31
32 import sys
33 import re
34 import optparse
35
36
37 class DeclParser:
38
39     token_re = re.compile(r'(\d[x0-9a-fA-F.UL]*|\w+|\s+|.)')
40
41     multi_comment_re = re.compile(r'/\*.*?\*/', flags = re.DOTALL)
42     single_comment_re = re.compile(r'//.*',)
43
44     def __init__(self):
45         self.tokens = []
46
47     def has_side_effects(self, name):
48         return True
49
50
51     def tokenize(self, s):
52         s = self.multi_comment_re.sub('', s)
53         s = self.single_comment_re.sub('', s)
54         self.tokens = self.token_re.split(s)
55         self.tokens = [token for token in self.tokens if self.filter_token(token)]
56
57     def filter_token(self, token):
58         if not token or token.isspace():
59             return False
60         if token.startswith('AVAILABLE_') or token.startswith('DEPRECATED_'):
61             return False
62         if token in ['FAR']:
63             return False
64         return True
65
66     def lookahead(self, index = 0):
67         try:
68             return self.tokens[index]
69         except KeyError:
70             return None
71
72     def match(self, *ref_tokens):
73         return self.lookahead() in ref_tokens
74
75     def consume(self, *ref_tokens):
76         if not self.tokens:
77             raise Exception('unexpected EOF')
78         token = self.tokens.pop(0)
79         if ref_tokens and token not in ref_tokens:
80             raise Exception('token mismatch', token, ref_tokens)
81         return token
82
83     def eof(self):
84         return not self.tokens
85
86
87     def parse(self, s):
88         self.tokenize(s)
89
90         while not self.eof():
91             #print self.tokens[0:10]
92             self.parse_declaration()
93
94     def parse_declaration(self):
95         self.parse_tags()
96         if self.match('#'):
97             self.parse_define()
98         elif self.match('enum'):
99             self.parse_enum()
100         elif self.match('class', 'interface'):
101             self.parse_interface(self.lookahead())
102         elif self.match('mask'):
103             self.parse_value('mask', 'Flags')
104         elif self.match('struct'):
105             self.parse_struct()
106         elif self.match('value'):
107             self.parse_value('value', 'FakeEnum')
108         elif self.match('typedef'):
109             self.parse_typedef()
110         else:
111             self.parse_prototype()
112         if not self.eof() and self.match(';'):
113             self.consume(';')
114
115     def parse_typedef(self):
116         self.consume('typedef')
117         if self.lookahead(2) in (';', ','):
118             base_type = self.consume()
119             while True:
120                 type = base_type
121                 if self.match('*'):
122                     self.consume()
123                     type = 'Pointer(%s)' % type
124                 name = self.consume()
125                 print '%s = Alias("%s", %s)' % (name, name, type)
126                 if self.match(','):
127                     self.consume()
128                 else:
129                     break
130         else:
131             self.parse_declaration()
132             self.consume()
133
134     def parse_enum(self):
135         self.consume('enum')
136         name = self.consume()
137         self.consume('{')
138
139         print '%s = Enum("%s", [' % (name, name)
140
141         #value = 0
142         while self.lookahead() != '}':
143             name = self.consume()
144             if self.match('='):
145                 self.consume('=')
146                 value = self.consume()
147             if self.match(','):
148                 self.consume(',')
149             tags = self.parse_tags()
150             #print '    "%s",\t# %s' % (name, value) 
151             print '    "%s",' % (name,) 
152             #value += 1
153         self.consume('}')
154
155         print '])'
156         print
157
158     def parse_value(self, ref_token, constructor):
159         self.consume(ref_token)
160         type = self.consume()
161         name = self.consume()
162         self.consume('{')
163
164         print '%s = %s(%s, [' % (name, constructor, type)
165
166         while self.lookahead() != '}':
167             name, value = self.parse_define()
168         self.consume('}')
169
170         print '])'
171         print
172
173     def parse_define(self):
174         self.consume('#')
175         self.consume('define')
176         name = self.consume()
177         value = self.consume()
178         #print '    "%s",\t# %s' % (name, value) 
179         print '    "%s",' % (name,) 
180         return name, value
181
182     def parse_struct(self):
183         self.consume('struct')
184         name = self.consume()
185         self.consume('{')
186
187         print '%s = Struct("%s", [' % (name, name)
188
189         value = 0
190         while self.lookahead() != '}':
191             type, name = self.parse_named_type()
192
193             if self.match(':'):
194                 self.consume()
195                 self.consume()
196
197             if self.match(','):
198                 self.consume(',')
199             self.consume(';')
200             print '    (%s, "%s"),' % (type, name) 
201             value += 1
202         self.consume('}')
203
204         print '])'
205         print
206
207     def parse_interface(self, ref_token):
208         self.consume(ref_token)
209         name = self.consume()
210         if self.match(';'):
211             return
212         self.consume(':')
213         if self.lookahead() in ('public', 'protected'):
214             self.consume()
215         base = self.consume()
216         self.consume('{')
217
218         print '%s = Interface("%s", %s)' % (name, name, base)
219         print '%s.methods += [' % (name,)
220
221         while self.lookahead() != '}':
222             if self.lookahead() in ('public', 'private'):
223                 self.consume()
224                 self.consume(':')
225             else:
226                 self.parse_prototype('Method')
227                 self.consume(';')
228         self.consume('}')
229
230         print ']'
231         print
232
233     def parse_prototype(self, creator = 'Function'):
234         if self.match('extern', 'virtual'):
235             self.consume()
236
237         ret = self.parse_type()
238
239         if self.match('__stdcall', 'WINAPI'):
240             self.consume()
241             creator = 'Std' + creator
242
243         name = self.consume()
244         extra = ''
245         if not self.has_side_effects(name):
246             extra += ', sideeffects=False'
247         name = name
248
249         self.consume('(')
250         args = []
251         if self.match('void') and self.tokens[1] == ')':
252             self.consume()
253         while self.lookahead() != ')':
254             arg = self.parse_arg()
255             args.append(arg)
256             if self.match(','):
257                 self.consume()
258         self.consume(')')
259         if self.lookahead() == 'const':
260             self.consume()
261             extra = ', const=True' + extra
262
263         if self.lookahead() == '=':
264             self.consume()
265             self.consume('0')
266         
267         print '    %s(%s, "%s", [%s]%s),' % (creator, ret, name, ', '.join(args), extra)
268
269     def parse_arg(self):
270         tags = self.parse_tags()
271
272         type, name = self.parse_named_type()
273
274         arg = '(%s, "%s")' % (type, name)
275         if 'out' in tags or 'inout' in tags:
276             arg = 'Out' + arg
277
278         if self.match('='):
279             self.consume()
280             while not self.match(',', ')'):
281                 self.consume()
282
283         return arg
284
285     def parse_tags(self):
286         tags = []
287         if self.match('['):
288             self.consume()
289             while not self.match(']'):
290                 tag = self.consume()
291                 tags.append(tag)
292             self.consume(']')
293         if self.lookahead().startswith('__'):
294             # Parse __in, __out, etc tags
295             tag = self.consume()[2:]
296             if self.match('('):
297                 self.consume()
298                 while not self.match(')'):
299                     self.consume()
300                 self.consume(')')
301             tags.extend(tag.split('_'))
302         return tags
303
304     def parse_named_type(self):
305         type = self.parse_type()
306         name = self.consume()
307         if self.match('['):
308             self.consume()
309             length = self.consume()
310             self.consume(']')
311             try:
312                 int(length)
313             except ValueError:
314                 length = "%s" % length
315             type = 'Array(%s, %s)' % (type, length)
316         return type, name
317
318     int_tokens = ('unsigned', 'signed', 'int', 'long', 'short', 'char')
319
320     type_table = {
321         'float':    'Float',
322         'double':   'Double',
323         'int8_t':   'Int8',
324         'uint8_t':  'UInt8',
325         'int16_t':  'Int16',
326         'uint16_t': 'UInt16',
327         'int32_t':  'Int32',
328         'uint32_t': 'UInt32',
329         'int64_t' : 'Int64',
330         'uint64_t': 'UInt64',
331     }
332
333     def parse_type(self):
334         const = False
335         token = self.consume()
336         if token == 'const':
337             token = self.consume()
338             const = True
339         if token == 'void':
340             type = 'Void'
341         elif token in self.int_tokens:
342             unsigned = False
343             signed = False
344             long = 0
345             short = 0
346             char = False
347             while token in self.int_tokens:
348                 if token == 'unsigned':
349                     unsigned = True
350                 if token == 'signed':
351                     signed = True
352                 if token == 'long':
353                     long += 1
354                 if token == 'short':
355                     short += 1
356                 if token == 'char':
357                     char = False
358                 if self.lookahead() in self.int_tokens:
359                     token = self.consume()
360                 else:
361                     token = None
362             if char:
363                 type = 'Char'
364                 if signed:
365                     type = 'S' + type
366             elif short:
367                 type = 'Short'
368             elif long:
369                 type = 'Long' * long
370             else:
371                 type = 'Int'
372             if unsigned:
373                 type = 'U' + type
374         else:
375             type = self.type_table.get(token, token)
376         if const:
377             type = 'Const(%s)' % type
378         while True:
379             if self.match('*'):
380                 self.consume('*')
381                 type = 'Pointer(%s)' % type
382             elif self.match('const'):
383                 self.consume('const')
384                 type = 'Const(%s)' % type
385             else:
386                 break
387         return type
388
389
390 def main():
391     args = sys.argv[1:]
392
393     parser = DeclParser()
394     if args:
395         for arg in args:
396             parser.parse(open(arg, 'rt').read())
397     else:
398         parser.parse(sys.stdin.read())
399     
400
401 if __name__ == '__main__':
402     main()