]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
Be more specific when invoking the interface methods.
[apitrace] / specs / stdapi.py
1 ##########################################################################
2 #
3 # Copyright 2008-2010 VMware, Inc.
4 # All Rights Reserved.
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24 ##########################################################################/
25
26 """C basic types"""
27
28
29 import debug
30
31
32 class Type:
33     """Base class for all types."""
34
35     __tags = set()
36
37     def __init__(self, expr, tag = None):
38         self.expr = expr
39
40         # Generate a default tag, used when naming functions that will operate
41         # on this type, so it should preferrably be something representative of
42         # the type.
43         if tag is None:
44             tag = ''.join([c for c in expr if c.isalnum() or c in '_'])
45         else:
46             for c in tag:
47                 assert c.isalnum() or c in '_'
48
49         # Ensure it is unique.
50         if tag in Type.__tags:
51             suffix = 1
52             while tag + str(suffix) in Type.__tags:
53                 suffix += 1
54             tag += str(suffix)
55
56         assert tag not in Type.__tags
57         Type.__tags.add(tag)
58
59         self.tag = tag
60
61     def __str__(self):
62         """Return the C/C++ type expression for this type."""
63         return self.expr
64
65     def visit(self, visitor, *args, **kwargs):
66         raise NotImplementedError
67
68
69
70 class _Void(Type):
71     """Singleton void type."""
72
73     def __init__(self):
74         Type.__init__(self, "void")
75
76     def visit(self, visitor, *args, **kwargs):
77         return visitor.visitVoid(self, *args, **kwargs)
78
79 Void = _Void()
80
81
82 class Literal(Type):
83     """Class to describe literal types.
84
85     Types which are not defined in terms of other types, such as integers and
86     floats."""
87
88     def __init__(self, expr, kind):
89         Type.__init__(self, expr)
90         self.kind = kind
91
92     def visit(self, visitor, *args, **kwargs):
93         return visitor.visitLiteral(self, *args, **kwargs)
94
95
96 class Const(Type):
97
98     def __init__(self, type):
99         # While "const foo" and "foo const" are synonymous, "const foo *" and
100         # "foo * const" are not quite the same, and some compilers do enforce
101         # strict const correctness.
102         if isinstance(type, String) or type is WString:
103             # For strings we never intend to say a const pointer to chars, but
104             # rather a point to const chars.
105             expr = "const " + type.expr
106         elif type.expr.startswith("const ") or '*' in type.expr:
107             expr = type.expr + " const"
108         else:
109             # The most legible
110             expr = "const " + type.expr
111
112         Type.__init__(self, expr, 'C' + type.tag)
113
114         self.type = type
115
116     def visit(self, visitor, *args, **kwargs):
117         return visitor.visitConst(self, *args, **kwargs)
118
119
120 class Pointer(Type):
121
122     def __init__(self, type):
123         Type.__init__(self, type.expr + " *", 'P' + type.tag)
124         self.type = type
125
126     def visit(self, visitor, *args, **kwargs):
127         return visitor.visitPointer(self, *args, **kwargs)
128
129
130 class IntPointer(Type):
131     '''Integer encoded as a pointer.'''
132
133     def visit(self, visitor, *args, **kwargs):
134         return visitor.visitIntPointer(self, *args, **kwargs)
135
136
137 class LinearPointer(Type):
138     '''Integer encoded as a pointer.'''
139
140     def __init__(self, type, size = None):
141         Type.__init__(self, type.expr + " *", 'P' + type.tag)
142         self.type = type
143         self.size = size
144
145     def visit(self, visitor, *args, **kwargs):
146         return visitor.visitLinearPointer(self, *args, **kwargs)
147
148
149 class Handle(Type):
150
151     def __init__(self, name, type, range=None, key=None):
152         Type.__init__(self, type.expr, 'P' + type.tag)
153         self.name = name
154         self.type = type
155         self.range = range
156         self.key = key
157
158     def visit(self, visitor, *args, **kwargs):
159         return visitor.visitHandle(self, *args, **kwargs)
160
161
162 def ConstPointer(type):
163     return Pointer(Const(type))
164
165
166 class Enum(Type):
167
168     __id = 0
169
170     def __init__(self, name, values):
171         Type.__init__(self, name)
172
173         self.id = Enum.__id
174         Enum.__id += 1
175
176         self.values = list(values)
177
178     def visit(self, visitor, *args, **kwargs):
179         return visitor.visitEnum(self, *args, **kwargs)
180
181
182 def FakeEnum(type, values):
183     return Enum(type.expr, values)
184
185
186 class Bitmask(Type):
187
188     __id = 0
189
190     def __init__(self, type, values):
191         Type.__init__(self, type.expr)
192
193         self.id = Bitmask.__id
194         Bitmask.__id += 1
195
196         self.type = type
197         self.values = values
198
199     def visit(self, visitor, *args, **kwargs):
200         return visitor.visitBitmask(self, *args, **kwargs)
201
202 Flags = Bitmask
203
204
205 class Array(Type):
206
207     def __init__(self, type, length):
208         Type.__init__(self, type.expr + " *")
209         self.type = type
210         self.length = length
211
212     def visit(self, visitor, *args, **kwargs):
213         return visitor.visitArray(self, *args, **kwargs)
214
215
216 class Blob(Type):
217
218     def __init__(self, type, size):
219         Type.__init__(self, type.expr + ' *')
220         self.type = type
221         self.size = size
222
223     def visit(self, visitor, *args, **kwargs):
224         return visitor.visitBlob(self, *args, **kwargs)
225
226
227 class Struct(Type):
228
229     __id = 0
230
231     def __init__(self, name, members):
232         Type.__init__(self, name)
233
234         self.id = Struct.__id
235         Struct.__id += 1
236
237         self.name = name
238         self.members = members
239
240     def visit(self, visitor, *args, **kwargs):
241         return visitor.visitStruct(self, *args, **kwargs)
242
243
244 class Alias(Type):
245
246     def __init__(self, expr, type):
247         Type.__init__(self, expr)
248         self.type = type
249
250     def visit(self, visitor, *args, **kwargs):
251         return visitor.visitAlias(self, *args, **kwargs)
252
253
254 def Out(type, name):
255     arg = Arg(type, name, output=True)
256     return arg
257
258
259 class Arg:
260
261     def __init__(self, type, name, output=False):
262         self.type = type
263         self.name = name
264         self.output = output
265         self.index = None
266
267     def __str__(self):
268         return '%s %s' % (self.type, self.name)
269
270
271 class Function:
272
273     # 0-3 are reserved to memcpy, malloc, free, and realloc
274     __id = 4
275
276     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
277         self.id = Function.__id
278         Function.__id += 1
279
280         self.type = type
281         self.name = name
282
283         self.args = []
284         index = 0
285         for arg in args:
286             if not isinstance(arg, Arg):
287                 if isinstance(arg, tuple):
288                     arg_type, arg_name = arg
289                 else:
290                     arg_type = arg
291                     arg_name = "arg%u" % index
292                 arg = Arg(arg_type, arg_name)
293             arg.index = index
294             index += 1
295             self.args.append(arg)
296
297         self.call = call
298         self.fail = fail
299         self.sideeffects = sideeffects
300
301     def prototype(self, name=None):
302         if name is not None:
303             name = name.strip()
304         else:
305             name = self.name
306         s = name
307         if self.call:
308             s = self.call + ' ' + s
309         if name.startswith('*'):
310             s = '(' + s + ')'
311         s = self.type.expr + ' ' + s
312         s += "("
313         if self.args:
314             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
315         else:
316             s += "void"
317         s += ")"
318         return s
319
320     def argNames(self):
321         return [arg.name for arg in self.args]
322
323
324 def StdFunction(*args, **kwargs):
325     kwargs.setdefault('call', '__stdcall')
326     return Function(*args, **kwargs)
327
328
329 def FunctionPointer(type, name, args, **kwargs):
330     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
331     return Opaque(name)
332
333
334 class Interface(Type):
335
336     def __init__(self, name, base=None):
337         Type.__init__(self, name)
338         self.name = name
339         self.base = base
340         self.methods = []
341
342     def visit(self, visitor, *args, **kwargs):
343         return visitor.visitInterface(self, *args, **kwargs)
344
345     def iterMethods(self):
346         if self.base is not None:
347             for method in self.base.iterMethods():
348                 yield method
349         for method in self.methods:
350             yield method
351         raise StopIteration
352
353     def iterBaseMethods(self):
354         if self.base is not None:
355             for iface, method in self.base.iterBaseMethods():
356                 yield iface, method
357         for method in self.methods:
358             yield self, method
359         raise StopIteration
360
361
362 class Method(Function):
363
364     def __init__(self, type, name, args):
365         Function.__init__(self, type, name, args, call = '__stdcall')
366         for index in range(len(self.args)):
367             self.args[index].index = index + 1
368
369
370 class String(Type):
371
372     def __init__(self, expr = "char *", length = None, kind = 'String'):
373         Type.__init__(self, expr)
374         self.length = length
375         self.kind = kind
376
377     def visit(self, visitor, *args, **kwargs):
378         return visitor.visitString(self, *args, **kwargs)
379
380
381 class Opaque(Type):
382     '''Opaque pointer.'''
383
384     def __init__(self, expr):
385         Type.__init__(self, expr)
386
387     def visit(self, visitor, *args, **kwargs):
388         return visitor.visitOpaque(self, *args, **kwargs)
389
390
391 def OpaquePointer(type, *args):
392     return Opaque(type.expr + ' *')
393
394 def OpaqueArray(type, size):
395     return Opaque(type.expr + ' *')
396
397 def OpaqueBlob(type, size):
398     return Opaque(type.expr + ' *')
399
400
401 class Polymorphic(Type):
402
403     def __init__(self, defaultType, switchExpr, switchTypes):
404         Type.__init__(self, defaultType.expr)
405         self.defaultType = defaultType
406         self.switchExpr = switchExpr
407         self.switchTypes = switchTypes
408
409     def visit(self, visitor, *args, **kwargs):
410         return visitor.visitPolymorphic(self, *args, **kwargs)
411
412     def iterSwitch(self):
413         cases = [['default']]
414         types = [self.defaultType]
415
416         for expr, type in self.switchTypes:
417             case = 'case %s' % expr
418             try:
419                 i = types.index(type)
420             except ValueError:
421                 cases.append([case])
422                 types.append(type)
423             else:
424                 cases[i].append(case)
425
426         return zip(cases, types)
427
428
429 class Visitor:
430     '''Abstract visitor for the type hierarchy.'''
431
432     def visit(self, type, *args, **kwargs):
433         return type.visit(self, *args, **kwargs)
434
435     def visitVoid(self, void, *args, **kwargs):
436         raise NotImplementedError
437
438     def visitLiteral(self, literal, *args, **kwargs):
439         raise NotImplementedError
440
441     def visitString(self, string, *args, **kwargs):
442         raise NotImplementedError
443
444     def visitConst(self, const, *args, **kwargs):
445         raise NotImplementedError
446
447     def visitStruct(self, struct, *args, **kwargs):
448         raise NotImplementedError
449
450     def visitArray(self, array, *args, **kwargs):
451         raise NotImplementedError
452
453     def visitBlob(self, blob, *args, **kwargs):
454         raise NotImplementedError
455
456     def visitEnum(self, enum, *args, **kwargs):
457         raise NotImplementedError
458
459     def visitBitmask(self, bitmask, *args, **kwargs):
460         raise NotImplementedError
461
462     def visitPointer(self, pointer, *args, **kwargs):
463         raise NotImplementedError
464
465     def visitIntPointer(self, pointer, *args, **kwargs):
466         raise NotImplementedError
467
468     def visitLinearPointer(self, pointer, *args, **kwargs):
469         raise NotImplementedError
470
471     def visitHandle(self, handle, *args, **kwargs):
472         raise NotImplementedError
473
474     def visitAlias(self, alias, *args, **kwargs):
475         raise NotImplementedError
476
477     def visitOpaque(self, opaque, *args, **kwargs):
478         raise NotImplementedError
479
480     def visitInterface(self, interface, *args, **kwargs):
481         raise NotImplementedError
482
483     def visitPolymorphic(self, polymorphic, *args, **kwargs):
484         raise NotImplementedError
485         #return self.visit(polymorphic.defaultType, *args, **kwargs)
486
487
488 class OnceVisitor(Visitor):
489     '''Visitor that guarantees that each type is visited only once.'''
490
491     def __init__(self):
492         self.__visited = set()
493
494     def visit(self, type, *args, **kwargs):
495         if type not in self.__visited:
496             self.__visited.add(type)
497             return type.visit(self, *args, **kwargs)
498         return None
499
500
501 class Rebuilder(Visitor):
502     '''Visitor which rebuild types as it visits them.
503
504     By itself it is a no-op -- it is intended to be overwritten.
505     '''
506
507     def visitVoid(self, void):
508         return void
509
510     def visitLiteral(self, literal):
511         return literal
512
513     def visitString(self, string):
514         return string
515
516     def visitConst(self, const):
517         return Const(const.type)
518
519     def visitStruct(self, struct):
520         members = [(self.visit(type), name) for type, name in struct.members]
521         return Struct(struct.name, members)
522
523     def visitArray(self, array):
524         type = self.visit(array.type)
525         return Array(type, array.length)
526
527     def visitBlob(self, blob):
528         type = self.visit(blob.type)
529         return Blob(type, blob.size)
530
531     def visitEnum(self, enum):
532         return enum
533
534     def visitBitmask(self, bitmask):
535         type = self.visit(bitmask.type)
536         return Bitmask(type, bitmask.values)
537
538     def visitPointer(self, pointer):
539         type = self.visit(pointer.type)
540         return Pointer(type)
541
542     def visitIntPointer(self, pointer):
543         return pointer
544
545     def visitLinearPointer(self, pointer):
546         type = self.visit(pointer.type)
547         return LinearPointer(type, pointer.size)
548
549     def visitHandle(self, handle):
550         type = self.visit(handle.type)
551         return Handle(handle.name, type, range=handle.range, key=handle.key)
552
553     def visitAlias(self, alias):
554         type = self.visit(alias.type)
555         return Alias(alias.expr, type)
556
557     def visitOpaque(self, opaque):
558         return opaque
559
560     def visitInterface(self, interface, *args, **kwargs):
561         return interface
562
563     def visitPolymorphic(self, polymorphic):
564         defaultType = self.visit(polymorphic.defaultType)
565         switchExpr = polymorphic.switchExpr
566         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
567         return Polymorphic(defaultType, switchExpr, switchTypes)
568
569
570 class Collector(Visitor):
571     '''Visitor which collects all unique types as it traverses them.'''
572
573     def __init__(self):
574         self.__visited = set()
575         self.types = []
576
577     def visit(self, type):
578         if type in self.__visited:
579             return
580         self.__visited.add(type)
581         Visitor.visit(self, type)
582         self.types.append(type)
583
584     def visitVoid(self, literal):
585         pass
586
587     def visitLiteral(self, literal):
588         pass
589
590     def visitString(self, string):
591         pass
592
593     def visitConst(self, const):
594         self.visit(const.type)
595
596     def visitStruct(self, struct):
597         for type, name in struct.members:
598             self.visit(type)
599
600     def visitArray(self, array):
601         self.visit(array.type)
602
603     def visitBlob(self, array):
604         pass
605
606     def visitEnum(self, enum):
607         pass
608
609     def visitBitmask(self, bitmask):
610         self.visit(bitmask.type)
611
612     def visitPointer(self, pointer):
613         self.visit(pointer.type)
614
615     def visitIntPointer(self, pointer):
616         pass
617
618     def visitLinearPointer(self, pointer):
619         self.visit(pointer.type)
620
621     def visitHandle(self, handle):
622         self.visit(handle.type)
623
624     def visitAlias(self, alias):
625         self.visit(alias.type)
626
627     def visitOpaque(self, opaque):
628         pass
629
630     def visitInterface(self, interface):
631         if interface.base is not None:
632             self.visit(interface.base)
633         for method in interface.iterMethods():
634             for arg in method.args:
635                 self.visit(arg.type)
636             self.visit(method.type)
637
638     def visitPolymorphic(self, polymorphic):
639         self.visit(polymorphic.defaultType)
640         for expr, type in polymorphic.switchTypes:
641             self.visit(type)
642
643
644 class API:
645     '''API abstraction.
646
647     Essentially, a collection of types, functions, and interfaces.
648     '''
649
650     def __init__(self, name = None):
651         self.name = name
652         self.headers = []
653         self.functions = []
654         self.interfaces = []
655
656     def getAllTypes(self):
657         collector = Collector()
658         for function in self.functions:
659             for arg in function.args:
660                 collector.visit(arg.type)
661             collector.visit(function.type)
662         for interface in self.interfaces:
663             collector.visit(interface)
664             for method in interface.iterMethods():
665                 for arg in method.args:
666                     collector.visit(arg.type)
667                 collector.visit(method.type)
668         return collector.types
669
670     def getAllInterfaces(self):
671         types = self.getAllTypes()
672         interfaces = [type for type in types if isinstance(type, Interface)]
673         for interface in self.interfaces:
674             if interface not in interfaces:
675                 interfaces.append(interface)
676         return interfaces
677
678     def addFunction(self, function):
679         self.functions.append(function)
680
681     def addFunctions(self, functions):
682         for function in functions:
683             self.addFunction(function)
684
685     def addInterface(self, interface):
686         self.interfaces.append(interface)
687
688     def addInterfaces(self, interfaces):
689         self.interfaces.extend(interfaces)
690
691     def addApi(self, api):
692         self.headers.extend(api.headers)
693         self.addFunctions(api.functions)
694         self.addInterfaces(api.interfaces)
695
696     def get_function_by_name(self, name):
697         for function in self.functions:
698             if function.name == name:
699                 return function
700         return None
701
702
703 Bool = Literal("bool", "Bool")
704 SChar = Literal("signed char", "SInt")
705 UChar = Literal("unsigned char", "UInt")
706 Short = Literal("short", "SInt")
707 Int = Literal("int", "SInt")
708 Long = Literal("long", "SInt")
709 LongLong = Literal("long long", "SInt")
710 UShort = Literal("unsigned short", "UInt")
711 UInt = Literal("unsigned int", "UInt")
712 ULong = Literal("unsigned long", "UInt")
713 ULongLong = Literal("unsigned long long", "UInt")
714 Float = Literal("float", "Float")
715 Double = Literal("double", "Double")
716 SizeT = Literal("size_t", "UInt")
717
718 # C string (i.e., zero terminated)
719 CString = String()
720 WString = String("wchar_t *", kind="WString")
721
722 Int8 = Literal("int8_t", "SInt")
723 UInt8 = Literal("uint8_t", "UInt")
724 Int16 = Literal("int16_t", "SInt")
725 UInt16 = Literal("uint16_t", "UInt")
726 Int32 = Literal("int32_t", "SInt")
727 UInt32 = Literal("uint32_t", "UInt")
728 Int64 = Literal("int64_t", "SInt")
729 UInt64 = Literal("uint64_t", "UInt")