summaryrefslogtreecommitdiff
path: root/specs/stdapi.py
blob: a92b9ba5669035725e9e54c5ca2d136119106caa (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
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
##########################################################################
#
# Copyright 2008-2010 VMware, Inc.
# 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.
#
##########################################################################/

"""C basic types"""


import debug


class Type:

    __all = {}
    __seq = 0

    def __init__(self, expr, id = ''):
        self.expr = expr
        
        for char in id:
            assert char.isalnum() or char in '_ '

        id = id.replace(' ', '_')
        
        if id in Type.__all:
            Type.__seq += 1
            id += str(Type.__seq)
        
        assert id not in Type.__all
        Type.__all[id] = self

        self.id = id

    def __str__(self):
        return self.expr

    def visit(self, visitor, *args, **kwargs):
        raise NotImplementedError



class _Void(Type):

    def __init__(self):
        Type.__init__(self, "void")

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_void(self, *args, **kwargs)

Void = _Void()


class Literal(Type):

    def __init__(self, expr, format, base=10):
        Type.__init__(self, expr)
        self.format = format

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_literal(self, *args, **kwargs)


class Const(Type):

    def __init__(self, type):
        # While "const foo" and "foo const" are synonymous, "const foo *" and
        # "foo * const" are not quite the same, and some compilers do enforce
        # strict const correctness.
        if isinstance(type, String) or type is WString:
            # For strings we never intend to say a const pointer to chars, but
            # rather a point to const chars.
            expr = "const " + type.expr
        elif type.expr.startswith("const ") or '*' in type.expr:
            expr = type.expr + " const"
        else:
            # The most legible
            expr = "const " + type.expr

        Type.__init__(self, expr, 'C' + type.id)

        self.type = type

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_const(self, *args, **kwargs)


class Pointer(Type):

    def __init__(self, type):
        Type.__init__(self, type.expr + " *", 'P' + type.id)
        self.type = type

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_pointer(self, *args, **kwargs)


class Handle(Type):

    def __init__(self, name, type, range=None, key=None):
        Type.__init__(self, type.expr, 'P' + type.id)
        self.name = name
        self.type = type
        self.range = range
        self.key = key

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_handle(self, *args, **kwargs)


def ConstPointer(type):
    return Pointer(Const(type))


class Enum(Type):

    def __init__(self, name, values):
        Type.__init__(self, name)
        self.values = list(values)
    
    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_enum(self, *args, **kwargs)


def FakeEnum(type, values):
    return Enum(type.expr, values)


class Bitmask(Type):

    def __init__(self, type, values):
        Type.__init__(self, type.expr)
        self.type = type
        self.values = values

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_bitmask(self, *args, **kwargs)

Flags = Bitmask


class Array(Type):

    def __init__(self, type, length):
        Type.__init__(self, type.expr + " *")
        self.type = type
        self.length = length

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_array(self, *args, **kwargs)


class Blob(Type):

    def __init__(self, type, size):
        Type.__init__(self, type.expr + ' *')
        self.type = type
        self.size = size

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_blob(self, *args, **kwargs)


class Struct(Type):

    def __init__(self, name, members):
        Type.__init__(self, name)
        self.name = name
        self.members = members

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_struct(self, *args, **kwargs)


class Alias(Type):

    def __init__(self, expr, type):
        Type.__init__(self, expr)
        self.type = type

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_alias(self, *args, **kwargs)


def Out(type, name):
    arg = Arg(type, name, output=True)
    return arg


class Arg:

    def __init__(self, type, name, output=False):
        self.type = type
        self.name = name
        self.output = output
        self.index = None

    def __str__(self):
        return '%s %s' % (self.type, self.name)


class Function:

    # 0-3 are reserved to memcpy, malloc, free, and realloc
    __id = 4

    def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
        self.id = Function.__id
        Function.__id += 1

        self.type = type
        self.name = name

        self.args = []
        index = 0
        for arg in args:
            if not isinstance(arg, Arg):
                if isinstance(arg, tuple):
                    arg_type, arg_name = arg
                else:
                    arg_type = arg
                    arg_name = "arg%u" % index
                arg = Arg(arg_type, arg_name)
            arg.index = index
            index += 1
            self.args.append(arg)

        self.call = call
        self.fail = fail
        self.sideeffects = sideeffects

    def prototype(self, name=None):
        if name is not None:
            name = name.strip()
        else:
            name = self.name
        s = name
        if self.call:
            s = self.call + ' ' + s
        if name.startswith('*'):
            s = '(' + s + ')'
        s = self.type.expr + ' ' + s
        s += "("
        if self.args:
            s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
        else:
            s += "void"
        s += ")"
        return s


def StdFunction(*args, **kwargs):
    kwargs.setdefault('call', '__stdcall')
    return Function(*args, **kwargs)


def FunctionPointer(type, name, args, **kwargs):
    # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
    return Opaque(name)


class Interface(Type):

    def __init__(self, name, base=None):
        Type.__init__(self, name)
        self.name = name
        self.base = base
        self.methods = []

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_interface(self, *args, **kwargs)

    def itermethods(self):
        if self.base is not None:
            for method in self.base.itermethods():
                yield method
        for method in self.methods:
            yield method
        raise StopIteration


class Method(Function):

    def __init__(self, type, name, args):
        Function.__init__(self, type, name, args, call = '__stdcall')
        for index in range(len(self.args)):
            self.args[index].index = index + 1


class String(Type):

    def __init__(self, expr = "char *", length = None):
        Type.__init__(self, expr)
        self.length = length

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_string(self, *args, **kwargs)

# C string (i.e., zero terminated)
CString = String()


class Opaque(Type):
    '''Opaque pointer.'''

    def __init__(self, expr):
        Type.__init__(self, expr)

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_opaque(self, *args, **kwargs)


def OpaquePointer(type, *args):
    return Opaque(type.expr + ' *')

def OpaqueArray(type, size):
    return Opaque(type.expr + ' *')

def OpaqueBlob(type, size):
    return Opaque(type.expr + ' *')


class Polymorphic(Type):

    def __init__(self, default_type, switch_expr, switch_types):
        Type.__init__(self, default_type.expr)
        self.default_type = default_type
        self.switch_expr = switch_expr
        self.switch_types = switch_types

    def visit(self, visitor, *args, **kwargs):
        return visitor.visit_polymorphic(self, *args, **kwargs)

    def iterswitch(self):
        cases = [['default']]
        types = [self.default_type]

        for expr, type in self.switch_types:
            case = 'case %s' % expr
            try:
                i = types.index(type)
            except ValueError:
                cases.append([case])
                types.append(type)
            else:
                cases[i].append(case)

        return zip(cases, types)


class Visitor:

    def visit(self, type, *args, **kwargs):
        return type.visit(self, *args, **kwargs)

    def visit_void(self, void, *args, **kwargs):
        raise NotImplementedError

    def visit_literal(self, literal, *args, **kwargs):
        raise NotImplementedError

    def visit_string(self, string, *args, **kwargs):
        raise NotImplementedError

    def visit_const(self, const, *args, **kwargs):
        raise NotImplementedError

    def visit_struct(self, struct, *args, **kwargs):
        raise NotImplementedError

    def visit_array(self, array, *args, **kwargs):
        raise NotImplementedError

    def visit_blob(self, blob, *args, **kwargs):
        raise NotImplementedError

    def visit_enum(self, enum, *args, **kwargs):
        raise NotImplementedError

    def visit_bitmask(self, bitmask, *args, **kwargs):
        raise NotImplementedError

    def visit_pointer(self, pointer, *args, **kwargs):
        raise NotImplementedError

    def visit_handle(self, handle, *args, **kwargs):
        raise NotImplementedError

    def visit_alias(self, alias, *args, **kwargs):
        raise NotImplementedError

    def visit_opaque(self, opaque, *args, **kwargs):
        raise NotImplementedError

    def visit_interface(self, interface, *args, **kwargs):
        raise NotImplementedError

    def visit_polymorphic(self, polymorphic, *args, **kwargs):
        raise NotImplementedError
        #return self.visit(polymorphic.default_type, *args, **kwargs)


class OnceVisitor(Visitor):

    def __init__(self):
        self.__visited = set()

    def visit(self, type, *args, **kwargs):
        if type not in self.__visited:
            self.__visited.add(type)
            return type.visit(self, *args, **kwargs)
        return None


class Rebuilder(Visitor):

    def visit_void(self, void):
        return void

    def visit_literal(self, literal):
        return literal

    def visit_string(self, string):
        return string

    def visit_const(self, const):
        return Const(const.type)

    def visit_struct(self, struct):
        members = [(self.visit(type), name) for type, name in struct.members]
        return Struct(struct.name, members)

    def visit_array(self, array):
        type = self.visit(array.type)
        return Array(type, array.length)

    def visit_blob(self, blob):
        type = self.visit(blob.type)
        return Blob(type, blob.size)

    def visit_enum(self, enum):
        return enum

    def visit_bitmask(self, bitmask):
        type = self.visit(bitmask.type)
        return Bitmask(type, bitmask.values)

    def visit_pointer(self, pointer):
        type = self.visit(pointer.type)
        return Pointer(type)

    def visit_handle(self, handle):
        type = self.visit(handle.type)
        return Handle(handle.name, type, range=handle.range, key=handle.key)

    def visit_alias(self, alias):
        type = self.visit(alias.type)
        return Alias(alias.expr, type)

    def visit_opaque(self, opaque):
        return opaque

    def visit_polymorphic(self, polymorphic):
        default_type = self.visit(polymorphic.default_type)
        switch_expr = polymorphic.switch_expr
        switch_types = [(expr, self.visit(type)) for expr, type in polymorphic.switch_types]
        return Polymorphic(default_type, switch_expr, switch_types)


class Collector(Visitor):
    '''Collect.'''

    def __init__(self):
        self.__visited = set()
        self.types = []

    def visit(self, type):
        if type in self.__visited:
            return
        self.__visited.add(type)
        Visitor.visit(self, type)
        self.types.append(type)

    def visit_void(self, literal):
        pass

    def visit_literal(self, literal):
        pass

    def visit_string(self, string):
        pass

    def visit_const(self, const):
        self.visit(const.type)

    def visit_struct(self, struct):
        for type, name in struct.members:
            self.visit(type)

    def visit_array(self, array):
        self.visit(array.type)

    def visit_blob(self, array):
        pass

    def visit_enum(self, enum):
        pass

    def visit_bitmask(self, bitmask):
        self.visit(bitmask.type)

    def visit_pointer(self, pointer):
        self.visit(pointer.type)

    def visit_handle(self, handle):
        self.visit(handle.type)

    def visit_alias(self, alias):
        self.visit(alias.type)

    def visit_opaque(self, opaque):
        pass

    def visit_interface(self, interface):
        if interface.base is not None:
            self.visit(interface.base)
        for method in interface.itermethods():
            for arg in method.args:
                self.visit(arg.type)
            self.visit(method.type)

    def visit_polymorphic(self, polymorphic):
        self.visit(polymorphic.default_type)
        for expr, type in polymorphic.switch_types:
            self.visit(type)


class API:

    def __init__(self, name = None):
        self.name = name
        self.headers = []
        self.functions = []
        self.interfaces = []

    def all_types(self):
        collector = Collector()
        for function in self.functions:
            for arg in function.args:
                collector.visit(arg.type)
            collector.visit(function.type)
        for interface in self.interfaces:
            collector.visit(interface)
            for method in interface.itermethods():
                for arg in method.args:
                    collector.visit(arg.type)
                collector.visit(method.type)
        return collector.types

    def add_function(self, function):
        self.functions.append(function)

    def add_functions(self, functions):
        for function in functions:
            self.add_function(function)

    def add_interface(self, interface):
        self.interfaces.append(interface)

    def add_interfaces(self, interfaces):
        self.interfaces.extend(interfaces)

    def add_api(self, api):
        self.headers.extend(api.headers)
        self.add_functions(api.functions)
        self.add_interfaces(api.interfaces)

    def get_function_by_name(self, name):
        for function in self.functions:
            if function.name == name:
                return function
        return None


Bool = Literal("bool", "Bool")
SChar = Literal("signed char", "SInt")
UChar = Literal("unsigned char", "UInt")
Short = Literal("short", "SInt")
Int = Literal("int", "SInt")
Long = Literal("long", "SInt")
LongLong = Literal("long long", "SInt")
UShort = Literal("unsigned short", "UInt")
UInt = Literal("unsigned int", "UInt")
ULong = Literal("unsigned long", "UInt")
ULongLong = Literal("unsigned long long", "UInt")
Float = Literal("float", "Float")
Double = Literal("double", "Double")
SizeT = Literal("size_t", "UInt")
WString = Literal("wchar_t *", "WString")

Int8 = Literal("int8_t", "SInt")
UInt8 = Literal("uint8_t", "UInt")
Int16 = Literal("int16_t", "SInt")
UInt16 = Literal("uint16_t", "UInt")
Int32 = Literal("int32_t", "SInt")
UInt32 = Literal("uint32_t", "UInt")
Int64 = Literal("int64_t", "SInt")
UInt64 = Literal("uint64_t", "UInt")