]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
Avoid rebuilding types unnecessarily.
[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 ObjPointer(Type):
138     '''Pointer to an object.'''
139
140     def __init__(self, type):
141         Type.__init__(self, type.expr + " *", 'P' + type.tag)
142         self.type = type
143
144     def visit(self, visitor, *args, **kwargs):
145         return visitor.visitObjPointer(self, *args, **kwargs)
146
147
148 class LinearPointer(Type):
149     '''Pointer to a linear range of memory.'''
150
151     def __init__(self, type, size = None):
152         Type.__init__(self, type.expr + " *", 'P' + type.tag)
153         self.type = type
154         self.size = size
155
156     def visit(self, visitor, *args, **kwargs):
157         return visitor.visitLinearPointer(self, *args, **kwargs)
158
159
160 class Reference(Type):
161     '''C++ references.'''
162
163     def __init__(self, type):
164         Type.__init__(self, type.expr + " &", 'R' + type.tag)
165         self.type = type
166
167     def visit(self, visitor, *args, **kwargs):
168         return visitor.visitReference(self, *args, **kwargs)
169
170
171 class Handle(Type):
172
173     def __init__(self, name, type, range=None, key=None):
174         Type.__init__(self, type.expr, 'P' + type.tag)
175         self.name = name
176         self.type = type
177         self.range = range
178         self.key = key
179
180     def visit(self, visitor, *args, **kwargs):
181         return visitor.visitHandle(self, *args, **kwargs)
182
183
184 def ConstPointer(type):
185     return Pointer(Const(type))
186
187
188 class Enum(Type):
189
190     __id = 0
191
192     def __init__(self, name, values):
193         Type.__init__(self, name)
194
195         self.id = Enum.__id
196         Enum.__id += 1
197
198         self.values = list(values)
199
200     def visit(self, visitor, *args, **kwargs):
201         return visitor.visitEnum(self, *args, **kwargs)
202
203
204 def FakeEnum(type, values):
205     return Enum(type.expr, values)
206
207
208 class Bitmask(Type):
209
210     __id = 0
211
212     def __init__(self, type, values):
213         Type.__init__(self, type.expr)
214
215         self.id = Bitmask.__id
216         Bitmask.__id += 1
217
218         self.type = type
219         self.values = values
220
221     def visit(self, visitor, *args, **kwargs):
222         return visitor.visitBitmask(self, *args, **kwargs)
223
224 Flags = Bitmask
225
226
227 class Array(Type):
228
229     def __init__(self, type, length):
230         Type.__init__(self, type.expr + " *")
231         self.type = type
232         self.length = length
233
234     def visit(self, visitor, *args, **kwargs):
235         return visitor.visitArray(self, *args, **kwargs)
236
237
238 class Blob(Type):
239
240     def __init__(self, type, size):
241         Type.__init__(self, type.expr + ' *')
242         self.type = type
243         self.size = size
244
245     def visit(self, visitor, *args, **kwargs):
246         return visitor.visitBlob(self, *args, **kwargs)
247
248
249 class Struct(Type):
250
251     __id = 0
252
253     def __init__(self, name, members):
254         Type.__init__(self, name)
255
256         self.id = Struct.__id
257         Struct.__id += 1
258
259         self.name = name
260         self.members = members
261
262     def visit(self, visitor, *args, **kwargs):
263         return visitor.visitStruct(self, *args, **kwargs)
264
265
266 class Alias(Type):
267
268     def __init__(self, expr, type):
269         Type.__init__(self, expr)
270         self.type = type
271
272     def visit(self, visitor, *args, **kwargs):
273         return visitor.visitAlias(self, *args, **kwargs)
274
275
276 def Out(type, name):
277     arg = Arg(type, name, output=True)
278     return arg
279
280
281 class Arg:
282
283     def __init__(self, type, name, output=False):
284         self.type = type
285         self.name = name
286         self.output = output
287         self.index = None
288
289     def __str__(self):
290         return '%s %s' % (self.type, self.name)
291
292
293 class Function:
294
295     # 0-3 are reserved to memcpy, malloc, free, and realloc
296     __id = 4
297
298     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
299         self.id = Function.__id
300         Function.__id += 1
301
302         self.type = type
303         self.name = name
304
305         self.args = []
306         index = 0
307         for arg in args:
308             if not isinstance(arg, Arg):
309                 if isinstance(arg, tuple):
310                     arg_type, arg_name = arg
311                 else:
312                     arg_type = arg
313                     arg_name = "arg%u" % index
314                 arg = Arg(arg_type, arg_name)
315             arg.index = index
316             index += 1
317             self.args.append(arg)
318
319         self.call = call
320         self.fail = fail
321         self.sideeffects = sideeffects
322
323     def prototype(self, name=None):
324         if name is not None:
325             name = name.strip()
326         else:
327             name = self.name
328         s = name
329         if self.call:
330             s = self.call + ' ' + s
331         if name.startswith('*'):
332             s = '(' + s + ')'
333         s = self.type.expr + ' ' + s
334         s += "("
335         if self.args:
336             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
337         else:
338             s += "void"
339         s += ")"
340         return s
341
342     def argNames(self):
343         return [arg.name for arg in self.args]
344
345
346 def StdFunction(*args, **kwargs):
347     kwargs.setdefault('call', '__stdcall')
348     return Function(*args, **kwargs)
349
350
351 def FunctionPointer(type, name, args, **kwargs):
352     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
353     return Opaque(name)
354
355
356 class Interface(Type):
357
358     def __init__(self, name, base=None):
359         Type.__init__(self, name)
360         self.name = name
361         self.base = base
362         self.methods = []
363
364     def visit(self, visitor, *args, **kwargs):
365         return visitor.visitInterface(self, *args, **kwargs)
366
367     def iterMethods(self):
368         if self.base is not None:
369             for method in self.base.iterMethods():
370                 yield method
371         for method in self.methods:
372             yield method
373         raise StopIteration
374
375     def iterBaseMethods(self):
376         if self.base is not None:
377             for iface, method in self.base.iterBaseMethods():
378                 yield iface, method
379         for method in self.methods:
380             yield self, method
381         raise StopIteration
382
383
384 class Method(Function):
385
386     def __init__(self, type, name, args, const=False, sideeffects=True):
387         Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
388         for index in range(len(self.args)):
389             self.args[index].index = index + 1
390         self.const = const
391
392     def prototype(self, name=None):
393         s = Function.prototype(self, name)
394         if self.const:
395             s += ' const'
396         return s
397
398
399 class String(Type):
400
401     def __init__(self, expr = "char *", length = None, kind = 'String'):
402         Type.__init__(self, expr)
403         self.length = length
404         self.kind = kind
405
406     def visit(self, visitor, *args, **kwargs):
407         return visitor.visitString(self, *args, **kwargs)
408
409
410 class Opaque(Type):
411     '''Opaque pointer.'''
412
413     def __init__(self, expr):
414         Type.__init__(self, expr)
415
416     def visit(self, visitor, *args, **kwargs):
417         return visitor.visitOpaque(self, *args, **kwargs)
418
419
420 def OpaquePointer(type, *args):
421     return Opaque(type.expr + ' *')
422
423 def OpaqueArray(type, size):
424     return Opaque(type.expr + ' *')
425
426 def OpaqueBlob(type, size):
427     return Opaque(type.expr + ' *')
428
429
430 class Polymorphic(Type):
431
432     def __init__(self, defaultType, switchExpr, switchTypes):
433         Type.__init__(self, defaultType.expr)
434         self.defaultType = defaultType
435         self.switchExpr = switchExpr
436         self.switchTypes = switchTypes
437
438     def visit(self, visitor, *args, **kwargs):
439         return visitor.visitPolymorphic(self, *args, **kwargs)
440
441     def iterSwitch(self):
442         cases = [['default']]
443         types = [self.defaultType]
444
445         for expr, type in self.switchTypes:
446             case = 'case %s' % expr
447             try:
448                 i = types.index(type)
449             except ValueError:
450                 cases.append([case])
451                 types.append(type)
452             else:
453                 cases[i].append(case)
454
455         return zip(cases, types)
456
457
458 class Visitor:
459     '''Abstract visitor for the type hierarchy.'''
460
461     def visit(self, type, *args, **kwargs):
462         return type.visit(self, *args, **kwargs)
463
464     def visitVoid(self, void, *args, **kwargs):
465         raise NotImplementedError
466
467     def visitLiteral(self, literal, *args, **kwargs):
468         raise NotImplementedError
469
470     def visitString(self, string, *args, **kwargs):
471         raise NotImplementedError
472
473     def visitConst(self, const, *args, **kwargs):
474         raise NotImplementedError
475
476     def visitStruct(self, struct, *args, **kwargs):
477         raise NotImplementedError
478
479     def visitArray(self, array, *args, **kwargs):
480         raise NotImplementedError
481
482     def visitBlob(self, blob, *args, **kwargs):
483         raise NotImplementedError
484
485     def visitEnum(self, enum, *args, **kwargs):
486         raise NotImplementedError
487
488     def visitBitmask(self, bitmask, *args, **kwargs):
489         raise NotImplementedError
490
491     def visitPointer(self, pointer, *args, **kwargs):
492         raise NotImplementedError
493
494     def visitIntPointer(self, pointer, *args, **kwargs):
495         raise NotImplementedError
496
497     def visitObjPointer(self, pointer, *args, **kwargs):
498         raise NotImplementedError
499
500     def visitLinearPointer(self, pointer, *args, **kwargs):
501         raise NotImplementedError
502
503     def visitReference(self, reference, *args, **kwargs):
504         raise NotImplementedError
505
506     def visitHandle(self, handle, *args, **kwargs):
507         raise NotImplementedError
508
509     def visitAlias(self, alias, *args, **kwargs):
510         raise NotImplementedError
511
512     def visitOpaque(self, opaque, *args, **kwargs):
513         raise NotImplementedError
514
515     def visitInterface(self, interface, *args, **kwargs):
516         raise NotImplementedError
517
518     def visitPolymorphic(self, polymorphic, *args, **kwargs):
519         raise NotImplementedError
520         #return self.visit(polymorphic.defaultType, *args, **kwargs)
521
522
523 class OnceVisitor(Visitor):
524     '''Visitor that guarantees that each type is visited only once.'''
525
526     def __init__(self):
527         self.__visited = set()
528
529     def visit(self, type, *args, **kwargs):
530         if type not in self.__visited:
531             self.__visited.add(type)
532             return type.visit(self, *args, **kwargs)
533         return None
534
535
536 class Rebuilder(Visitor):
537     '''Visitor which rebuild types as it visits them.
538
539     By itself it is a no-op -- it is intended to be overwritten.
540     '''
541
542     def visitVoid(self, void):
543         return void
544
545     def visitLiteral(self, literal):
546         return literal
547
548     def visitString(self, string):
549         return string
550
551     def visitConst(self, const):
552         const_type = self.visit(const.type)
553         if const_type is const.type:
554             return const
555         else:
556             return Const(const_type)
557
558     def visitStruct(self, struct):
559         members = [(self.visit(type), name) for type, name in struct.members]
560         return Struct(struct.name, members)
561
562     def visitArray(self, array):
563         type = self.visit(array.type)
564         return Array(type, array.length)
565
566     def visitBlob(self, blob):
567         type = self.visit(blob.type)
568         return Blob(type, blob.size)
569
570     def visitEnum(self, enum):
571         return enum
572
573     def visitBitmask(self, bitmask):
574         type = self.visit(bitmask.type)
575         return Bitmask(type, bitmask.values)
576
577     def visitPointer(self, pointer):
578         pointer_type = self.visit(pointer.type)
579         if pointer_type is pointer.type:
580             return pointer
581         else:
582             return Pointer(pointer_type)
583
584     def visitIntPointer(self, pointer):
585         return pointer
586
587     def visitObjPointer(self, pointer):
588         pointer_type = self.visit(pointer.type)
589         if pointer_type is pointer.type:
590             return pointer
591         else:
592             return ObjPointer(pointer_type)
593
594     def visitLinearPointer(self, pointer):
595         pointer_type = self.visit(pointer.type)
596         if pointer_type is pointer.type:
597             return pointer
598         else:
599             return LinearPointer(pointer_type)
600
601     def visitReference(self, reference):
602         reference_type = self.visit(reference.type)
603         if reference_type is reference.type:
604             return reference
605         else:
606             return Reference(reference_type)
607
608     def visitHandle(self, handle):
609         handle_type = self.visit(handle.type)
610         if handle_type is handle.type:
611             return handle
612         else:
613             return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
614
615     def visitAlias(self, alias):
616         alias_type = self.visit(alias.type)
617         if alias_type is alias.type:
618             return alias
619         else:
620             return Alias(alias.expr, alias_type)
621
622     def visitOpaque(self, opaque):
623         return opaque
624
625     def visitInterface(self, interface, *args, **kwargs):
626         return interface
627
628     def visitPolymorphic(self, polymorphic):
629         defaultType = self.visit(polymorphic.defaultType)
630         switchExpr = polymorphic.switchExpr
631         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
632         return Polymorphic(defaultType, switchExpr, switchTypes)
633
634
635 class Collector(Visitor):
636     '''Visitor which collects all unique types as it traverses them.'''
637
638     def __init__(self):
639         self.__visited = set()
640         self.types = []
641
642     def visit(self, type):
643         if type in self.__visited:
644             return
645         self.__visited.add(type)
646         Visitor.visit(self, type)
647         self.types.append(type)
648
649     def visitVoid(self, literal):
650         pass
651
652     def visitLiteral(self, literal):
653         pass
654
655     def visitString(self, string):
656         pass
657
658     def visitConst(self, const):
659         self.visit(const.type)
660
661     def visitStruct(self, struct):
662         for type, name in struct.members:
663             self.visit(type)
664
665     def visitArray(self, array):
666         self.visit(array.type)
667
668     def visitBlob(self, array):
669         pass
670
671     def visitEnum(self, enum):
672         pass
673
674     def visitBitmask(self, bitmask):
675         self.visit(bitmask.type)
676
677     def visitPointer(self, pointer):
678         self.visit(pointer.type)
679
680     def visitIntPointer(self, pointer):
681         pass
682
683     def visitObjPointer(self, pointer):
684         self.visit(pointer.type)
685
686     def visitLinearPointer(self, pointer):
687         self.visit(pointer.type)
688
689     def visitReference(self, reference):
690         self.visit(reference.type)
691
692     def visitHandle(self, handle):
693         self.visit(handle.type)
694
695     def visitAlias(self, alias):
696         self.visit(alias.type)
697
698     def visitOpaque(self, opaque):
699         pass
700
701     def visitInterface(self, interface):
702         if interface.base is not None:
703             self.visit(interface.base)
704         for method in interface.iterMethods():
705             for arg in method.args:
706                 self.visit(arg.type)
707             self.visit(method.type)
708
709     def visitPolymorphic(self, polymorphic):
710         self.visit(polymorphic.defaultType)
711         for expr, type in polymorphic.switchTypes:
712             self.visit(type)
713
714
715 class API:
716     '''API abstraction.
717
718     Essentially, a collection of types, functions, and interfaces.
719     '''
720
721     def __init__(self, name = None):
722         self.name = name
723         self.headers = []
724         self.functions = []
725         self.interfaces = []
726
727     def getAllTypes(self):
728         collector = Collector()
729         for function in self.functions:
730             for arg in function.args:
731                 collector.visit(arg.type)
732             collector.visit(function.type)
733         for interface in self.interfaces:
734             collector.visit(interface)
735             for method in interface.iterMethods():
736                 for arg in method.args:
737                     collector.visit(arg.type)
738                 collector.visit(method.type)
739         return collector.types
740
741     def getAllInterfaces(self):
742         types = self.getAllTypes()
743         interfaces = [type for type in types if isinstance(type, Interface)]
744         for interface in self.interfaces:
745             if interface not in interfaces:
746                 interfaces.append(interface)
747         return interfaces
748
749     def addFunction(self, function):
750         self.functions.append(function)
751
752     def addFunctions(self, functions):
753         for function in functions:
754             self.addFunction(function)
755
756     def addInterface(self, interface):
757         self.interfaces.append(interface)
758
759     def addInterfaces(self, interfaces):
760         self.interfaces.extend(interfaces)
761
762     def addApi(self, api):
763         self.headers.extend(api.headers)
764         self.addFunctions(api.functions)
765         self.addInterfaces(api.interfaces)
766
767     def get_function_by_name(self, name):
768         for function in self.functions:
769             if function.name == name:
770                 return function
771         return None
772
773
774 Bool = Literal("bool", "Bool")
775 SChar = Literal("signed char", "SInt")
776 UChar = Literal("unsigned char", "UInt")
777 Short = Literal("short", "SInt")
778 Int = Literal("int", "SInt")
779 Long = Literal("long", "SInt")
780 LongLong = Literal("long long", "SInt")
781 UShort = Literal("unsigned short", "UInt")
782 UInt = Literal("unsigned int", "UInt")
783 ULong = Literal("unsigned long", "UInt")
784 ULongLong = Literal("unsigned long long", "UInt")
785 Float = Literal("float", "Float")
786 Double = Literal("double", "Double")
787 SizeT = Literal("size_t", "UInt")
788
789 # C string (i.e., zero terminated)
790 CString = String()
791 WString = String("wchar_t *", kind="WString")
792
793 Int8 = Literal("int8_t", "SInt")
794 UInt8 = Literal("uint8_t", "UInt")
795 Int16 = Literal("int16_t", "SInt")
796 UInt16 = Literal("uint16_t", "UInt")
797 Int32 = Literal("int32_t", "SInt")
798 UInt32 = Literal("uint32_t", "UInt")
799 Int64 = Literal("int64_t", "SInt")
800 UInt64 = Literal("uint64_t", "UInt")