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