]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
88711e1af10f713ad0f02c8f8e7d542e70701301
[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             if expr is not None:
45                 tag = ''.join([c for c in expr if c.isalnum() or c in '_'])
46             else:
47                 tag = 'anonynoums'
48         else:
49             for c in tag:
50                 assert c.isalnum() or c in '_'
51
52         # Ensure it is unique.
53         if tag in Type.__tags:
54             suffix = 1
55             while tag + str(suffix) in Type.__tags:
56                 suffix += 1
57             tag += str(suffix)
58
59         assert tag not in Type.__tags
60         Type.__tags.add(tag)
61
62         self.tag = tag
63
64     def __str__(self):
65         """Return the C/C++ type expression for this type."""
66         return self.expr
67
68     def visit(self, visitor, *args, **kwargs):
69         raise NotImplementedError
70
71     def mutable(self):
72         '''Return a mutable version of this type.
73
74         Convenience wrapper around MutableRebuilder.'''
75         visitor = MutableRebuilder()
76         return visitor.visit(self)
77
78
79 class _Void(Type):
80     """Singleton void type."""
81
82     def __init__(self):
83         Type.__init__(self, "void")
84
85     def visit(self, visitor, *args, **kwargs):
86         return visitor.visitVoid(self, *args, **kwargs)
87
88 Void = _Void()
89
90
91 class Literal(Type):
92     """Class to describe literal types.
93
94     Types which are not defined in terms of other types, such as integers and
95     floats."""
96
97     def __init__(self, expr, kind):
98         Type.__init__(self, expr)
99         self.kind = kind
100
101     def visit(self, visitor, *args, **kwargs):
102         return visitor.visitLiteral(self, *args, **kwargs)
103
104
105 Bool = Literal("bool", "Bool")
106 SChar = Literal("signed char", "SInt")
107 UChar = Literal("unsigned char", "UInt")
108 Short = Literal("short", "SInt")
109 Int = Literal("int", "SInt")
110 Long = Literal("long", "SInt")
111 LongLong = Literal("long long", "SInt")
112 UShort = Literal("unsigned short", "UInt")
113 UInt = Literal("unsigned int", "UInt")
114 ULong = Literal("unsigned long", "UInt")
115 ULongLong = Literal("unsigned long long", "UInt")
116 Float = Literal("float", "Float")
117 Double = Literal("double", "Double")
118 SizeT = Literal("size_t", "UInt")
119
120 Char = Literal("char", "SInt")
121 WChar = Literal("wchar_t", "SInt")
122
123 Int8 = Literal("int8_t", "SInt")
124 UInt8 = Literal("uint8_t", "UInt")
125 Int16 = Literal("int16_t", "SInt")
126 UInt16 = Literal("uint16_t", "UInt")
127 Int32 = Literal("int32_t", "SInt")
128 UInt32 = Literal("uint32_t", "UInt")
129 Int64 = Literal("int64_t", "SInt")
130 UInt64 = Literal("uint64_t", "UInt")
131
132 IntPtr = Literal("intptr_t", "SInt")
133 UIntPtr = Literal("uintptr_t", "UInt")
134
135 class Const(Type):
136
137     def __init__(self, type):
138         # While "const foo" and "foo const" are synonymous, "const foo *" and
139         # "foo * const" are not quite the same, and some compilers do enforce
140         # strict const correctness.
141         if type.expr.startswith("const ") or '*' in type.expr:
142             expr = type.expr + " const"
143         else:
144             # The most legible
145             expr = "const " + type.expr
146
147         Type.__init__(self, expr, 'C' + type.tag)
148
149         self.type = type
150
151     def visit(self, visitor, *args, **kwargs):
152         return visitor.visitConst(self, *args, **kwargs)
153
154
155 class Pointer(Type):
156
157     def __init__(self, type):
158         Type.__init__(self, type.expr + " *", 'P' + type.tag)
159         self.type = type
160
161     def visit(self, visitor, *args, **kwargs):
162         return visitor.visitPointer(self, *args, **kwargs)
163
164
165 class IntPointer(Type):
166     '''Integer encoded as a pointer.'''
167
168     def visit(self, visitor, *args, **kwargs):
169         return visitor.visitIntPointer(self, *args, **kwargs)
170
171
172 class ObjPointer(Type):
173     '''Pointer to an object.'''
174
175     def __init__(self, type):
176         Type.__init__(self, type.expr + " *", 'P' + type.tag)
177         self.type = type
178
179     def visit(self, visitor, *args, **kwargs):
180         return visitor.visitObjPointer(self, *args, **kwargs)
181
182
183 class LinearPointer(Type):
184     '''Pointer to a linear range of memory.'''
185
186     def __init__(self, type, size = None):
187         Type.__init__(self, type.expr + " *", 'P' + type.tag)
188         self.type = type
189         self.size = size
190
191     def visit(self, visitor, *args, **kwargs):
192         return visitor.visitLinearPointer(self, *args, **kwargs)
193
194
195 class Reference(Type):
196     '''C++ references.'''
197
198     def __init__(self, type):
199         Type.__init__(self, type.expr + " &", 'R' + type.tag)
200         self.type = type
201
202     def visit(self, visitor, *args, **kwargs):
203         return visitor.visitReference(self, *args, **kwargs)
204
205
206 class Handle(Type):
207
208     def __init__(self, name, type, range=None, key=None):
209         Type.__init__(self, type.expr, 'P' + type.tag)
210         self.name = name
211         self.type = type
212         self.range = range
213         self.key = key
214
215     def visit(self, visitor, *args, **kwargs):
216         return visitor.visitHandle(self, *args, **kwargs)
217
218
219 def ConstPointer(type):
220     return Pointer(Const(type))
221
222
223 class Enum(Type):
224
225     __id = 0
226
227     def __init__(self, name, values):
228         Type.__init__(self, name)
229
230         self.id = Enum.__id
231         Enum.__id += 1
232
233         self.values = list(values)
234
235     def visit(self, visitor, *args, **kwargs):
236         return visitor.visitEnum(self, *args, **kwargs)
237
238
239 def FakeEnum(type, values):
240     return Enum(type.expr, values)
241
242
243 class Bitmask(Type):
244
245     __id = 0
246
247     def __init__(self, type, values):
248         Type.__init__(self, type.expr)
249
250         self.id = Bitmask.__id
251         Bitmask.__id += 1
252
253         self.type = type
254         self.values = values
255
256     def visit(self, visitor, *args, **kwargs):
257         return visitor.visitBitmask(self, *args, **kwargs)
258
259 Flags = Bitmask
260
261
262 class Array(Type):
263
264     def __init__(self, type, length):
265         Type.__init__(self, type.expr + " *")
266         self.type = type
267         self.length = length
268
269     def visit(self, visitor, *args, **kwargs):
270         return visitor.visitArray(self, *args, **kwargs)
271
272
273 class AttribArray(Type):
274
275     def __init__(self, keyType, valueTypes, isConst = True, terminator = '0'):
276         if isConst:
277             Type.__init__(self, (Pointer(Const(Int))).expr)
278         else:
279             Type.__init__(self, (Pointer(Int)).expr)
280         self.type = (Pointer(Const(Int))) # for function prototypes and such
281         self.keyType = keyType
282         self.valueTypes = valueTypes
283         self.terminator = terminator
284         self.hasKeysWithoutValues = False
285         for key, value in valueTypes:
286             if value is None:
287                 self.hasKeysWithoutValues = True
288
289     def visit(self, visitor, *args, **kwargs):
290         return visitor.visitAttribArray(self, *args, **kwargs)
291
292
293 class Blob(Type):
294
295     def __init__(self, type, size):
296         Type.__init__(self, type.expr + ' *')
297         self.type = type
298         self.size = size
299
300     def visit(self, visitor, *args, **kwargs):
301         return visitor.visitBlob(self, *args, **kwargs)
302
303
304 class Struct(Type):
305
306     __id = 0
307
308     def __init__(self, name, members):
309         Type.__init__(self, name)
310
311         self.id = Struct.__id
312         Struct.__id += 1
313
314         self.name = name
315         self.members = members
316
317     def visit(self, visitor, *args, **kwargs):
318         return visitor.visitStruct(self, *args, **kwargs)
319
320
321 def Union(kindExpr, kindTypes, contextLess=True):
322     switchTypes = []
323     for kindCase, kindType, kindMemberName in kindTypes:
324         switchType = Struct(None, [(kindType, kindMemberName)])
325         switchTypes.append((kindCase, switchType))
326     return Polymorphic(kindExpr, switchTypes, contextLess=contextLess)
327
328
329 class Alias(Type):
330
331     def __init__(self, expr, type):
332         Type.__init__(self, expr)
333         self.type = type
334
335     def visit(self, visitor, *args, **kwargs):
336         return visitor.visitAlias(self, *args, **kwargs)
337
338 class Arg:
339
340     def __init__(self, type, name, input=True, output=False):
341         self.type = type
342         self.name = name
343         self.input = input
344         self.output = output
345         self.index = None
346
347     def __str__(self):
348         return '%s %s' % (self.type, self.name)
349
350
351 def In(type, name):
352     return Arg(type, name, input=True, output=False)
353
354 def Out(type, name):
355     return Arg(type, name, input=False, output=True)
356
357 def InOut(type, name):
358     return Arg(type, name, input=True, output=True)
359
360
361 class Function:
362
363     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
364         self.type = type
365         self.name = name
366
367         self.args = []
368         index = 0
369         for arg in args:
370             if not isinstance(arg, Arg):
371                 if isinstance(arg, tuple):
372                     arg_type, arg_name = arg
373                 else:
374                     arg_type = arg
375                     arg_name = "arg%u" % index
376                 arg = Arg(arg_type, arg_name)
377             arg.index = index
378             index += 1
379             self.args.append(arg)
380
381         self.call = call
382         self.fail = fail
383         self.sideeffects = sideeffects
384         self.internal = internal
385
386     def prototype(self, name=None):
387         if name is not None:
388             name = name.strip()
389         else:
390             name = self.name
391         s = name
392         if self.call:
393             s = self.call + ' ' + s
394         if name.startswith('*'):
395             s = '(' + s + ')'
396         s = self.type.expr + ' ' + s
397         s += "("
398         if self.args:
399             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
400         else:
401             s += "void"
402         s += ")"
403         return s
404
405     def argNames(self):
406         return [arg.name for arg in self.args]
407
408     def getArgByName(self, name):
409         for arg in self.args:
410             if arg.name == name:
411                 return arg
412         return None
413
414
415 def StdFunction(*args, **kwargs):
416     kwargs.setdefault('call', '__stdcall')
417     return Function(*args, **kwargs)
418
419
420 def FunctionPointer(type, name, args, **kwargs):
421     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
422     return Opaque(name)
423
424
425 class Interface(Type):
426
427     def __init__(self, name, base=None):
428         Type.__init__(self, name)
429         self.name = name
430         self.base = base
431         self.methods = []
432
433     def visit(self, visitor, *args, **kwargs):
434         return visitor.visitInterface(self, *args, **kwargs)
435
436     def getMethodByName(self, name):
437         for method in self.iterMethods():
438             if method.name == name:
439                 return method
440         return None
441
442     def iterMethods(self):
443         if self.base is not None:
444             for method in self.base.iterMethods():
445                 yield method
446         for method in self.methods:
447             yield method
448         raise StopIteration
449
450     def iterBases(self):
451         iface = self
452         while iface is not None:
453             yield iface
454             iface = iface.base
455         raise StopIteration
456
457     def hasBase(self, *bases):
458         for iface in self.iterBases():
459             if iface in bases:
460                 return True
461         return False
462
463     def iterBaseMethods(self):
464         if self.base is not None:
465             for iface, method in self.base.iterBaseMethods():
466                 yield iface, method
467         for method in self.methods:
468             yield self, method
469         raise StopIteration
470
471
472 class Method(Function):
473
474     def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
475         assert call == '__stdcall'
476         Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
477         for index in range(len(self.args)):
478             self.args[index].index = index + 1
479         self.const = const
480
481     def prototype(self, name=None):
482         s = Function.prototype(self, name)
483         if self.const:
484             s += ' const'
485         return s
486
487
488 def StdMethod(*args, **kwargs):
489     kwargs.setdefault('call', '__stdcall')
490     return Method(*args, **kwargs)
491
492
493 class String(Type):
494     '''Human-legible character string.'''
495
496     def __init__(self, type = Char, length = None, wide = False):
497         assert isinstance(type, Type)
498         Type.__init__(self, type.expr + ' *')
499         self.type = type
500         self.length = length
501         self.wide = wide
502
503     def visit(self, visitor, *args, **kwargs):
504         return visitor.visitString(self, *args, **kwargs)
505
506
507 class Opaque(Type):
508     '''Opaque pointer.'''
509
510     def __init__(self, expr):
511         Type.__init__(self, expr)
512
513     def visit(self, visitor, *args, **kwargs):
514         return visitor.visitOpaque(self, *args, **kwargs)
515
516
517 def OpaquePointer(type, *args):
518     return Opaque(type.expr + ' *')
519
520 def OpaqueArray(type, size):
521     return Opaque(type.expr + ' *')
522
523 def OpaqueBlob(type, size):
524     return Opaque(type.expr + ' *')
525
526
527 class Polymorphic(Type):
528
529     def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
530         if defaultType is None:
531             Type.__init__(self, None)
532             contextLess = False
533         else:
534             Type.__init__(self, defaultType.expr)
535         self.switchExpr = switchExpr
536         self.switchTypes = switchTypes
537         self.defaultType = defaultType
538         self.contextLess = contextLess
539
540     def visit(self, visitor, *args, **kwargs):
541         return visitor.visitPolymorphic(self, *args, **kwargs)
542
543     def iterSwitch(self):
544         cases = []
545         types = []
546
547         if self.defaultType is not None:
548             cases.append(['default'])
549             types.append(self.defaultType)
550
551         for expr, type in self.switchTypes:
552             case = 'case %s' % expr
553             try:
554                 i = types.index(type)
555             except ValueError:
556                 cases.append([case])
557                 types.append(type)
558             else:
559                 cases[i].append(case)
560
561         return zip(cases, types)
562
563
564 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
565     enumValues = [expr for expr, type in switchTypes]
566     enum = Enum(enumName, enumValues)
567     polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
568     return enum, polymorphic
569
570
571 class Visitor:
572     '''Abstract visitor for the type hierarchy.'''
573
574     def visit(self, type, *args, **kwargs):
575         return type.visit(self, *args, **kwargs)
576
577     def visitVoid(self, void, *args, **kwargs):
578         raise NotImplementedError
579
580     def visitLiteral(self, literal, *args, **kwargs):
581         raise NotImplementedError
582
583     def visitString(self, string, *args, **kwargs):
584         raise NotImplementedError
585
586     def visitConst(self, const, *args, **kwargs):
587         raise NotImplementedError
588
589     def visitStruct(self, struct, *args, **kwargs):
590         raise NotImplementedError
591
592     def visitArray(self, array, *args, **kwargs):
593         raise NotImplementedError
594
595     def visitAttribArray(self, array, *args, **kwargs):
596         raise NotImplementedError
597
598     def visitBlob(self, blob, *args, **kwargs):
599         raise NotImplementedError
600
601     def visitEnum(self, enum, *args, **kwargs):
602         raise NotImplementedError
603
604     def visitBitmask(self, bitmask, *args, **kwargs):
605         raise NotImplementedError
606
607     def visitPointer(self, pointer, *args, **kwargs):
608         raise NotImplementedError
609
610     def visitIntPointer(self, pointer, *args, **kwargs):
611         raise NotImplementedError
612
613     def visitObjPointer(self, pointer, *args, **kwargs):
614         raise NotImplementedError
615
616     def visitLinearPointer(self, pointer, *args, **kwargs):
617         raise NotImplementedError
618
619     def visitReference(self, reference, *args, **kwargs):
620         raise NotImplementedError
621
622     def visitHandle(self, handle, *args, **kwargs):
623         raise NotImplementedError
624
625     def visitAlias(self, alias, *args, **kwargs):
626         raise NotImplementedError
627
628     def visitOpaque(self, opaque, *args, **kwargs):
629         raise NotImplementedError
630
631     def visitInterface(self, interface, *args, **kwargs):
632         raise NotImplementedError
633
634     def visitPolymorphic(self, polymorphic, *args, **kwargs):
635         raise NotImplementedError
636         #return self.visit(polymorphic.defaultType, *args, **kwargs)
637
638
639 class OnceVisitor(Visitor):
640     '''Visitor that guarantees that each type is visited only once.'''
641
642     def __init__(self):
643         self.__visited = set()
644
645     def visit(self, type, *args, **kwargs):
646         if type not in self.__visited:
647             self.__visited.add(type)
648             return type.visit(self, *args, **kwargs)
649         return None
650
651
652 class Rebuilder(Visitor):
653     '''Visitor which rebuild types as it visits them.
654
655     By itself it is a no-op -- it is intended to be overwritten.
656     '''
657
658     def visitVoid(self, void):
659         return void
660
661     def visitLiteral(self, literal):
662         return literal
663
664     def visitString(self, string):
665         string_type = self.visit(string.type)
666         if string_type is string.type:
667             return string
668         else:
669             return String(string_type, string.length, string.wide)
670
671     def visitConst(self, const):
672         const_type = self.visit(const.type)
673         if const_type is const.type:
674             return const
675         else:
676             return Const(const_type)
677
678     def visitStruct(self, struct):
679         members = [(self.visit(type), name) for type, name in struct.members]
680         return Struct(struct.name, members)
681
682     def visitArray(self, array):
683         type = self.visit(array.type)
684         return Array(type, array.length)
685
686     def visitBlob(self, blob):
687         type = self.visit(blob.type)
688         return Blob(type, blob.size)
689
690     def visitEnum(self, enum):
691         return enum
692
693     def visitBitmask(self, bitmask):
694         type = self.visit(bitmask.type)
695         return Bitmask(type, bitmask.values)
696
697     def visitPointer(self, pointer):
698         pointer_type = self.visit(pointer.type)
699         if pointer_type is pointer.type:
700             return pointer
701         else:
702             return Pointer(pointer_type)
703
704     def visitIntPointer(self, pointer):
705         return pointer
706
707     def visitObjPointer(self, pointer):
708         pointer_type = self.visit(pointer.type)
709         if pointer_type is pointer.type:
710             return pointer
711         else:
712             return ObjPointer(pointer_type)
713
714     def visitLinearPointer(self, pointer):
715         pointer_type = self.visit(pointer.type)
716         if pointer_type is pointer.type:
717             return pointer
718         else:
719             return LinearPointer(pointer_type)
720
721     def visitReference(self, reference):
722         reference_type = self.visit(reference.type)
723         if reference_type is reference.type:
724             return reference
725         else:
726             return Reference(reference_type)
727
728     def visitHandle(self, handle):
729         handle_type = self.visit(handle.type)
730         if handle_type is handle.type:
731             return handle
732         else:
733             return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
734
735     def visitAlias(self, alias):
736         alias_type = self.visit(alias.type)
737         if alias_type is alias.type:
738             return alias
739         else:
740             return Alias(alias.expr, alias_type)
741
742     def visitOpaque(self, opaque):
743         return opaque
744
745     def visitInterface(self, interface, *args, **kwargs):
746         return interface
747
748     def visitPolymorphic(self, polymorphic):
749         switchExpr = polymorphic.switchExpr
750         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
751         if polymorphic.defaultType is None:
752             defaultType = None
753         else:
754             defaultType = self.visit(polymorphic.defaultType)
755         return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
756
757
758 class MutableRebuilder(Rebuilder):
759     '''Type visitor which derives a mutable type.'''
760
761     def visitString(self, string):
762         return string
763
764     def visitConst(self, const):
765         # Strip out const qualifier
766         return const.type
767
768     def visitAlias(self, alias):
769         # Tear the alias on type changes
770         type = self.visit(alias.type)
771         if type is alias.type:
772             return alias
773         return type
774
775     def visitReference(self, reference):
776         # Strip out references
777         return reference.type
778
779
780 class Traverser(Visitor):
781     '''Visitor which all types.'''
782
783     def visitVoid(self, void, *args, **kwargs):
784         pass
785
786     def visitLiteral(self, literal, *args, **kwargs):
787         pass
788
789     def visitString(self, string, *args, **kwargs):
790         pass
791
792     def visitConst(self, const, *args, **kwargs):
793         self.visit(const.type, *args, **kwargs)
794
795     def visitStruct(self, struct, *args, **kwargs):
796         for type, name in struct.members:
797             self.visit(type, *args, **kwargs)
798
799     def visitArray(self, array, *args, **kwargs):
800         self.visit(array.type, *args, **kwargs)
801
802     def visitAttribArray(self, attribs, *args, **kwargs):
803         for key, valueType in attribs.valueTypes:
804             if valueType is not None:
805                 self.visit(valueType, *args, **kwargs)
806
807     def visitBlob(self, array, *args, **kwargs):
808         pass
809
810     def visitEnum(self, enum, *args, **kwargs):
811         pass
812
813     def visitBitmask(self, bitmask, *args, **kwargs):
814         self.visit(bitmask.type, *args, **kwargs)
815
816     def visitPointer(self, pointer, *args, **kwargs):
817         self.visit(pointer.type, *args, **kwargs)
818
819     def visitIntPointer(self, pointer, *args, **kwargs):
820         pass
821
822     def visitObjPointer(self, pointer, *args, **kwargs):
823         self.visit(pointer.type, *args, **kwargs)
824
825     def visitLinearPointer(self, pointer, *args, **kwargs):
826         self.visit(pointer.type, *args, **kwargs)
827
828     def visitReference(self, reference, *args, **kwargs):
829         self.visit(reference.type, *args, **kwargs)
830
831     def visitHandle(self, handle, *args, **kwargs):
832         self.visit(handle.type, *args, **kwargs)
833
834     def visitAlias(self, alias, *args, **kwargs):
835         self.visit(alias.type, *args, **kwargs)
836
837     def visitOpaque(self, opaque, *args, **kwargs):
838         pass
839
840     def visitInterface(self, interface, *args, **kwargs):
841         if interface.base is not None:
842             self.visit(interface.base, *args, **kwargs)
843         for method in interface.iterMethods():
844             for arg in method.args:
845                 self.visit(arg.type, *args, **kwargs)
846             self.visit(method.type, *args, **kwargs)
847
848     def visitPolymorphic(self, polymorphic, *args, **kwargs):
849         for expr, type in polymorphic.switchTypes:
850             self.visit(type, *args, **kwargs)
851         if polymorphic.defaultType is not None:
852             self.visit(polymorphic.defaultType, *args, **kwargs)
853
854
855 class Collector(Traverser):
856     '''Visitor which collects all unique types as it traverses them.'''
857
858     def __init__(self):
859         self.__visited = set()
860         self.types = []
861
862     def visit(self, type):
863         if type in self.__visited:
864             return
865         self.__visited.add(type)
866         Visitor.visit(self, type)
867         self.types.append(type)
868
869
870 class ExpanderMixin:
871     '''Mixin class that provides a bunch of methods to expand C expressions
872     from the specifications.'''
873
874     __structs = None
875     __indices = None
876
877     def expand(self, expr):
878         # Expand a C expression, replacing certain variables
879         if not isinstance(expr, basestring):
880             return expr
881         variables = {}
882
883         if self.__structs is not None:
884             variables['self'] = '(%s)' % self.__structs[0]
885         if self.__indices is not None:
886             variables['i'] = self.__indices[0]
887
888         expandedExpr = expr.format(**variables)
889         if expandedExpr != expr and 0:
890             sys.stderr.write("  %r -> %r\n" % (expr, expandedExpr))
891         return expandedExpr
892
893     def visitMember(self, member, structInstance, *args, **kwargs):
894         memberType, memberName = member
895         if memberName is None:
896             # Anonymous structure/union member
897             memberInstance = structInstance
898         else:
899             memberInstance = '(%s).%s' % (structInstance, memberName)
900         self.__structs = (structInstance, self.__structs)
901         try:
902             return self.visit(memberType, memberInstance, *args, **kwargs)
903         finally:
904             _, self.__structs = self.__structs
905
906     def visitElement(self, elementIndex, elementType, *args, **kwargs):
907         self.__indices = (elementIndex, self.__indices)
908         try:
909             return self.visit(elementType, *args, **kwargs)
910         finally:
911             _, self.__indices = self.__indices
912
913
914 class Module:
915     '''A collection of functions.'''
916
917     def __init__(self, name = None):
918         self.name = name
919         self.headers = []
920         self.functions = []
921         self.interfaces = []
922
923     def addFunctions(self, functions):
924         self.functions.extend(functions)
925
926     def addInterfaces(self, interfaces):
927         self.interfaces.extend(interfaces)
928
929     def mergeModule(self, module):
930         self.headers.extend(module.headers)
931         self.functions.extend(module.functions)
932         self.interfaces.extend(module.interfaces)
933
934     def getFunctionByName(self, name):
935         for function in self.functions:
936             if function.name == name:
937                 return function
938         return None
939
940
941 class API:
942     '''API abstraction.
943
944     Essentially, a collection of types, functions, and interfaces.
945     '''
946
947     def __init__(self, modules = None):
948         self.modules = []
949         if modules is not None:
950             self.modules.extend(modules)
951
952     def getAllTypes(self):
953         collector = Collector()
954         for module in self.modules:
955             for function in module.functions:
956                 for arg in function.args:
957                     collector.visit(arg.type)
958                 collector.visit(function.type)
959             for interface in module.interfaces:
960                 collector.visit(interface)
961                 for method in interface.iterMethods():
962                     for arg in method.args:
963                         collector.visit(arg.type)
964                     collector.visit(method.type)
965         return collector.types
966
967     def getAllFunctions(self):
968         functions = []
969         for module in self.modules:
970             functions.extend(module.functions)
971         return functions
972
973     def getAllInterfaces(self):
974         types = self.getAllTypes()
975         interfaces = [type for type in types if isinstance(type, Interface)]
976         for module in self.modules:
977             for interface in module.interfaces:
978                 if interface not in interfaces:
979                     interfaces.append(interface)
980         return interfaces
981
982     def addModule(self, module):
983         self.modules.append(module)
984
985     def getFunctionByName(self, name):
986         for module in self.modules:
987             for function in module.functions:
988                 if function.name == name:
989                     return function
990         return None
991
992
993 # C string (i.e., zero terminated)
994 CString = String(Char)
995 WString = String(WChar, wide=True)
996 ConstCString = String(Const(Char))
997 ConstWString = String(Const(WChar), wide=True)