]> git.cworth.org Git - apitrace/blob - specs/scripts/cdecl.py
Merge branch 'master' into d2d
[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('interface'):
101             self.parse_interface()
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):
208         self.consume('interface')
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             self.parse_prototype('Method')
223             self.consume(';')
224         self.consume('}')
225
226         print ']'
227         print
228
229     def parse_prototype(self, creator = 'Function'):
230         if self.match('extern'):
231             self.consume()
232
233         ret = self.parse_type()
234
235         if self.match('__stdcall', 'WINAPI'):
236             self.consume()
237             creator = 'StdFunction'
238
239         name = self.consume()
240         extra = ''
241         if not self.has_side_effects(name):
242             extra += ', sideeffects=False'
243         name = name
244
245         self.consume('(')
246         args = []
247         if self.match('void') and self.tokens[1] == ')':
248             self.consume()
249         while self.lookahead() != ')':
250             arg = self.parse_arg()
251             args.append(arg)
252             if self.match(','):
253                 self.consume()
254         self.consume(')')
255         if self.lookahead() == 'const':
256             self.consume()
257             extra = ', const=True' + extra
258         
259         print '    %s(%s, "%s", [%s]%s),' % (creator, ret, name, ', '.join(args), extra)
260
261     def parse_arg(self):
262         tags = self.parse_tags()
263
264         type, name = self.parse_named_type()
265
266         arg = '(%s, "%s")' % (type, name)
267         if 'out' in tags:
268             arg = 'Out' + arg
269
270         if self.match('='):
271             self.consume()
272             while not self.match(',', ')'):
273                 self.consume()
274
275         return arg
276
277     def parse_tags(self):
278         tags = []
279         if self.match('['):
280             self.consume()
281             while not self.match(']'):
282                 tag = self.consume()
283                 tags.append(tag)
284             self.consume(']')
285         return tags
286
287     def parse_named_type(self):
288         type = self.parse_type()
289         name = self.consume()
290         if self.match('['):
291             self.consume()
292             length = self.consume()
293             self.consume(']')
294             try:
295                 int(length)
296             except ValueError:
297                 length = "%s" % length
298             type = 'Array(%s, %s)' % (type, length)
299         return type, name
300
301     int_tokens = ('unsigned', 'signed', 'int', 'long', 'short', 'char')
302
303     type_table = {
304         'float':    'Float',
305         'double':   'Double',
306         'int8_t':   'Int8',
307         'uint8_t':  'UInt8',
308         'int16_t':  'Int16',
309         'uint16_t': 'UInt16',
310         'int32_t':  'Int32',
311         'uint32_t': 'UInt32',
312         'int64_t' : 'Int64',
313         'uint64_t': 'UInt64',
314     }
315
316     def parse_type(self):
317         const = False
318         token = self.consume()
319         if token == 'const':
320             token = self.consume()
321             const = True
322         if token == 'void':
323             type = 'Void'
324         elif token in self.int_tokens:
325             unsigned = False
326             signed = False
327             long = 0
328             short = 0
329             char = False
330             while token in self.int_tokens:
331                 if token == 'unsigned':
332                     unsigned = True
333                 if token == 'signed':
334                     signed = True
335                 if token == 'long':
336                     long += 1
337                 if token == 'short':
338                     short += 1
339                 if token == 'char':
340                     char = False
341                 if self.lookahead() in self.int_tokens:
342                     token = self.consume()
343                 else:
344                     token = None
345             if char:
346                 type = 'Char'
347                 if signed:
348                     type = 'S' + type
349             elif short:
350                 type = 'Short'
351             elif long:
352                 type = 'Long' * long
353             else:
354                 type = 'Int'
355             if unsigned:
356                 type = 'U' + type
357         else:
358             type = self.type_table.get(token, token)
359         if const:
360             type = 'Const(%s)' % type
361         while True:
362             if self.match('*'):
363                 self.consume('*')
364                 type = 'OpaquePointer(%s)' % type
365             elif self.match('const'):
366                 self.consume('const')
367                 type = 'Const(%s)' % type
368             else:
369                 break
370         return type
371
372
373 def main():
374     args = sys.argv[1:]
375
376     parser = DeclParser()
377     if args:
378         for arg in args:
379             parser.parse(open(arg, 'rt').read())
380     else:
381         parser.parse(sys.stdin.read())
382     
383
384 if __name__ == '__main__':
385     main()