summaryrefslogtreecommitdiff
path: root/specs/scripts/cdecl.py
blob: 7c1568aed544a4a56452f6c3e0cd475a9eb4512c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env python
##########################################################################
#
# Copyright 2011 Jose Fonseca
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
##########################################################################/


'''Script to parse C declarations and spew API definitions.
'''


import sys
import re
import optparse


class DeclParser:

    token_re = re.compile(r'(\d[x0-9a-fA-F.UL]*|\w+|\s+|"[^"]*"|.)')

    multi_comment_re = re.compile(r'/\*.*?\*/', flags = re.DOTALL)
    single_comment_re = re.compile(r'//.*',)

    def __init__(self):
        self.tokens = []

    def has_side_effects(self, name):
        return True


    def tokenize(self, s):
        s = self.multi_comment_re.sub('', s)
        s = self.single_comment_re.sub('', s)
        self.tokens = self.token_re.split(s)
        self.tokens = [token for token in self.tokens if self.filter_token(token)]

    def filter_token(self, token):
        if not token or token.isspace():
            return False
        if token.startswith('AVAILABLE_') or token.startswith('DEPRECATED_'):
            return False
        if token in ['FAR']:
            return False
        return True

    def lookahead(self, index = 0):
        try:
            return self.tokens[index]
        except KeyError:
            return None

    def match(self, *ref_tokens):
        return self.lookahead() in ref_tokens

    def consume(self, *ref_tokens):
        if not self.tokens:
            raise Exception('unexpected EOF')
        token = self.tokens.pop(0)
        if ref_tokens and token not in ref_tokens:
            raise Exception('token mismatch', token, ref_tokens)
        return token

    def eof(self):
        return not self.tokens


    def parse(self, s):
        self.tokenize(s)

        while not self.eof():
            #print self.tokens[0:10]
            self.parse_declaration()

    def parse_declaration(self):
        self.parse_tags()
        if self.match('#'):
            self.parse_define()
        elif self.match('enum'):
            self.parse_enum()
        elif self.match('class', 'interface'):
            self.parse_interface(self.lookahead())
        elif self.match('mask'):
            self.parse_value('mask', 'Flags')
        elif self.match('struct'):
            self.parse_struct()
        elif self.match('value'):
            self.parse_value('value', 'FakeEnum')
        elif self.match('typedef'):
            self.parse_typedef()
        else:
            self.parse_prototype()
        if not self.eof() and self.match(';'):
            self.consume(';')

    def parse_typedef(self):
        self.consume('typedef')
        if self.lookahead(2) in (';', ','):
            base_type = self.consume()
            while True:
                type = base_type
                if self.match('*'):
                    self.consume()
                    type = 'Pointer(%s)' % type
                name = self.consume()
                print '%s = Alias("%s", %s)' % (name, name, type)
                if self.match(','):
                    self.consume()
                else:
                    break
        else:
            self.parse_declaration()
            self.consume()

    def parse_enum(self):
        self.consume('enum')
        name = self.consume()
        self.consume('{')

        print '%s = Enum("%s", [' % (name, name)

        #value = 0
        while self.lookahead() != '}':
            name = self.consume()
            if self.match('='):
                self.consume('=')
                value = self.consume()
            if self.match(','):
                self.consume(',')
            tags = self.parse_tags()
            #print '    "%s",\t# %s' % (name, value) 
            print '    "%s",' % (name,) 
            #value += 1
        self.consume('}')

        print '])'
        print

    def parse_value(self, ref_token, constructor):
        self.consume(ref_token)
        type = self.consume()
        name = self.consume()
        self.consume('{')

        print '%s = %s(%s, [' % (name, constructor, type)

        while self.lookahead() != '}':
            name, value = self.parse_define()
        self.consume('}')

        print '])'
        print

    def parse_define(self):
        self.consume('#')
        self.consume('define')
        name = self.consume()
        value = self.consume()
        #print '    "%s",\t# %s' % (name, value) 
        print '    "%s",' % (name,) 
        return name, value

    def parse_struct(self):
        self.consume('struct')
        name = self.consume()

        print '%s = Struct("%s", [' % (name, name)
        for type, name in self.parse_members():
            print '    (%s, "%s"),' % (type, name)
        print '])'
        print

    def parse_union(self):
        self.consume('union')
        if not self.match('{'):
            name = self.consume()
        else:
            name = None
        members = self.parse_members()
        return 'Union("%s", [%s])' % (name, ', '.join('%s, "%s"' % member for member in members))

    def parse_members(self):
        members = []
        self.consume('{')
        while self.lookahead() != '}':
            type, name = self.parse_named_type()

            if self.match(':'):
                self.consume()
                self.consume()

            if self.match(','):
                self.consume(',')
            self.consume(';')
            members.append((type, name))
        self.consume('}')
        return members

    def parse_interface(self, ref_token):
        self.consume(ref_token)
        name = self.consume()
        if self.match(';'):
            return
        self.consume(':')
        if self.lookahead() in ('public', 'protected'):
            self.consume()
        base = self.consume()
        self.consume('{')

        print '%s = Interface("%s", %s)' % (name, name, base)
        print '%s.methods += [' % (name,)

        while self.lookahead() != '}':
            if self.lookahead() in ('public', 'private'):
                self.consume()
                self.consume(':')
            else:
                self.parse_prototype('StdMethod')
                self.consume(';')
        self.consume('}')

        print ']'
        print

    def parse_prototype(self, creator = 'Function'):
        if self.match('extern', 'virtual'):
            self.consume()

        ret = self.parse_type()

        if self.match('__stdcall', 'WINAPI'):
            self.consume()
            creator = 'Std' + creator

        name = self.consume()
        extra = ''
        if not self.has_side_effects(name):
            extra += ', sideeffects=False'
        name = name

        self.consume('(')
        args = []
        if self.match('void') and self.tokens[1] == ')':
            self.consume()
        while self.lookahead() != ')':
            arg = self.parse_arg()
            args.append(arg)
            if self.match(','):
                self.consume()
        self.consume(')')
        if self.match('const', 'CONST'):
            self.consume()
            extra = ', const=True' + extra

        if self.lookahead() == '=':
            self.consume()
            self.consume('0')
        
        print '    %s(%s, "%s", [%s]%s),' % (creator, ret, name, ', '.join(args), extra)

    def parse_arg(self):
        tags = self.parse_tags()

        type, name = self.parse_named_type()

        arg = '(%s, "%s")' % (type, name)
        if 'out' in tags or 'inout' in tags:
            arg = 'Out' + arg

        if self.match('='):
            self.consume()
            while not self.match(',', ')'):
                self.consume()

        return arg

    def parse_tags(self):
        tags = []
        if self.match('['):
            self.consume()
            while not self.match(']'):
                tag = self.consume()
                tags.append(tag)
            self.consume(']')
            if tags[0] == 'annotation':
                assert tags[1] == '('
                assert tags[3] == ')'
                tags = tags[2]
                assert tags[0] == '"'
                assert tags[-1] == '"'
                tags = tags[1:-1]
                tags = parse_sal_annotation(tags)
        token = self.lookahead()
        if token[0] == '_' and (token[1] == '_' or token[-1] == '_'):
            # Parse __in, __out, etc tags
            tag = self.consume()
            if self.match('('):
                tag += self.consume()
                while not self.match(')'):
                    tag += self.consume()
                tag += self.consume(')')
            tags.extend(self.parse_sal_annotation(tag))
        return tags

    def parse_sal_annotation(self, tags):
        try:
            tags, args = tags.split('(')
        except ValueError:
            pass
        assert tags[0] == '_'
        if tags[1] == '_':
            tags = tags[2:]
        if tags[-1] == '_':
            tags = tags[1:-1]
        tags = tags.lower()
        tags = tags.split('_')
        return tags

    def parse_named_type(self):
        type = self.parse_type()
        
        if self.match(',', ';', '}', ')'):
            name = None
        else:
            name = self.consume()
            if self.match('['):
                self.consume()
                length = ''
                while not self.match(']'):
                    length += self.consume()
                self.consume(']')
                try:
                    int(length)
                except ValueError:
                    length = '"%s"' % length
                type = 'Array(%s, %s)' % (type, length)
        return type, name

    int_tokens = ('unsigned', 'signed', 'int', 'long', 'short', 'char')

    type_table = {
        'float':    'Float',
        'double':   'Double',
        'int8_t':   'Int8',
        'uint8_t':  'UInt8',
        'int16_t':  'Int16',
        'uint16_t': 'UInt16',
        'int32_t':  'Int32',
        'uint32_t': 'UInt32',
        'int64_t' : 'Int64',
        'uint64_t': 'UInt64',
    }

    def parse_type(self):
        const = False
        if self.match('const', 'CONST'):
            self.consume()
            const = True
        if self.match('void'):
            self.consume()
            type = 'Void'
        elif self.match('union'):
            type = self.parse_union()
        elif self.match(*self.int_tokens):
            unsigned = False
            signed = False
            long = 0
            short = 0
            char = False
            while self.match(*self.int_tokens):
                token = self.consume()
                if token == 'unsigned':
                    unsigned = True
                if token == 'signed':
                    signed = True
                if token == 'long':
                    long += 1
                if token == 'short':
                    short += 1
                if token == 'char':
                    char = False
            if char:
                type = 'Char'
                if signed:
                    type = 'S' + type
            elif short:
                type = 'Short'
            elif long:
                type = 'Long' * long
            else:
                type = 'Int'
            if unsigned:
                type = 'U' + type
        else:
            token = self.consume()
            type = self.type_table.get(token, token)
        if const:
            type = 'Const(%s)' % type
        while True:
            if self.match('*'):
                self.consume('*')
                type = 'Pointer(%s)' % type
            elif self.match('const', 'CONST'):
                self.consume()
                type = 'Const(%s)' % type
            else:
                break
        return type


def main():
    args = sys.argv[1:]

    parser = DeclParser()
    if args:
        for arg in args:
            parser.parse(open(arg, 'rt').read())
    else:
        parser.parse(sys.stdin.read())
    

if __name__ == '__main__':
    main()