]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
1988c6588068389304a2dcf6d22488959782a049
[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, baseType, valueTypes, isConst = True, terminator = '0'):
276         self.baseType = baseType
277         if isConst:
278             Type.__init__(self, (Pointer(Const(self.baseType))).expr)
279         else:
280             Type.__init__(self, (Pointer(self.baseType)).expr)
281         self.valueTypes = valueTypes
282         self.terminator = terminator
283         self.hasKeysWithoutValues = False
284         for key, value in valueTypes:
285             if value is None:
286                 self.hasKeysWithoutValues = True
287
288     def visit(self, visitor, *args, **kwargs):
289         return visitor.visitAttribArray(self, *args, **kwargs)
290
291
292 class Blob(Type):
293
294     def __init__(self, type, size):
295         Type.__init__(self, type.expr + ' *')
296         self.type = type
297         self.size = size
298
299     def visit(self, visitor, *args, **kwargs):
300         return visitor.visitBlob(self, *args, **kwargs)
301
302
303 class Struct(Type):
304
305     __id = 0
306
307     def __init__(self, name, members):
308         Type.__init__(self, name)
309
310         self.id = Struct.__id
311         Struct.__id += 1
312
313         self.name = name
314         self.members = members
315
316     def visit(self, visitor, *args, **kwargs):
317         return visitor.visitStruct(self, *args, **kwargs)
318
319
320 def Union(kindExpr, kindTypes, contextLess=True):
321     switchTypes = []
322     for kindCase, kindType, kindMemberName in kindTypes:
323         switchType = Struct(None, [(kindType, kindMemberName)])
324         switchTypes.append((kindCase, switchType))
325     return Polymorphic(kindExpr, switchTypes, contextLess=contextLess)
326
327
328 class Alias(Type):
329
330     def __init__(self, expr, type):
331         Type.__init__(self, expr)
332         self.type = type
333
334     def visit(self, visitor, *args, **kwargs):
335         return visitor.visitAlias(self, *args, **kwargs)
336
337 class Arg:
338
339     def __init__(self, type, name, input=True, output=False):
340         self.type = type
341         self.name = name
342         self.input = input
343         self.output = output
344         self.index = None
345
346     def __str__(self):
347         return '%s %s' % (self.type, self.name)
348
349
350 def In(type, name):
351     return Arg(type, name, input=True, output=False)
352
353 def Out(type, name):
354     return Arg(type, name, input=False, output=True)
355
356 def InOut(type, name):
357     return Arg(type, name, input=True, output=True)
358
359
360 class Function:
361
362     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
363         self.type = type
364         self.name = name
365
366         self.args = []
367         index = 0
368         for arg in args:
369             if not isinstance(arg, Arg):
370                 if isinstance(arg, tuple):
371                     arg_type, arg_name = arg
372                 else:
373                     arg_type = arg
374                     arg_name = "arg%u" % index
375                 arg = Arg(arg_type, arg_name)
376             arg.index = index
377             index += 1
378             self.args.append(arg)
379
380         self.call = call
381         self.fail = fail
382         self.sideeffects = sideeffects
383         self.internal = internal
384
385     def prototype(self, name=None):
386         if name is not None:
387             name = name.strip()
388         else:
389             name = self.name
390         s = name
391         if self.call:
392             s = self.call + ' ' + s
393         if name.startswith('*'):
394             s = '(' + s + ')'
395         s = self.type.expr + ' ' + s
396         s += "("
397         if self.args:
398             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
399         else:
400             s += "void"
401         s += ")"
402         return s
403
404     def argNames(self):
405         return [arg.name for arg in self.args]
406
407     def getArgByName(self, name):
408         for arg in self.args:
409             if arg.name == name:
410                 return arg
411         return None
412
413
414 def StdFunction(*args, **kwargs):
415     kwargs.setdefault('call', '__stdcall')
416     return Function(*args, **kwargs)
417
418
419 def FunctionPointer(type, name, args, **kwargs):
420     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
421     return Opaque(name)
422
423
424 class Interface(Type):
425
426     def __init__(self, name, base=None):
427         Type.__init__(self, name)
428         self.name = name
429         self.base = base
430         self.methods = []
431
432     def visit(self, visitor, *args, **kwargs):
433         return visitor.visitInterface(self, *args, **kwargs)
434
435     def getMethodByName(self, name):
436         for method in self.iterMethods():
437             if method.name == name:
438                 return method
439         return None
440
441     def iterMethods(self):
442         if self.base is not None:
443             for method in self.base.iterMethods():
444                 yield method
445         for method in self.methods:
446             yield method
447         raise StopIteration
448
449     def iterBases(self):
450         iface = self
451         while iface is not None:
452             yield iface
453             iface = iface.base
454         raise StopIteration
455
456     def hasBase(self, *bases):
457         for iface in self.iterBases():
458             if iface in bases:
459                 return True
460         return False
461
462     def iterBaseMethods(self):
463         if self.base is not None:
464             for iface, method in self.base.iterBaseMethods():
465                 yield iface, method
466         for method in self.methods:
467             yield self, method
468         raise StopIteration
469
470
471 class Method(Function):
472
473     def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
474         assert call == '__stdcall'
475         Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
476         for index in range(len(self.args)):
477             self.args[index].index = index + 1
478         self.const = const
479
480     def prototype(self, name=None):
481         s = Function.prototype(self, name)
482         if self.const:
483             s += ' const'
484         return s
485
486
487 def StdMethod(*args, **kwargs):
488     kwargs.setdefault('call', '__stdcall')
489     return Method(*args, **kwargs)
490
491
492 class String(Type):
493     '''Human-legible character string.'''
494
495     def __init__(self, type = Char, length = None, wide = False):
496         assert isinstance(type, Type)
497         Type.__init__(self, type.expr + ' *')
498         self.type = type
499         self.length = length
500         self.wide = wide
501
502     def visit(self, visitor, *args, **kwargs):
503         return visitor.visitString(self, *args, **kwargs)
504
505
506 class Opaque(Type):
507     '''Opaque pointer.'''
508
509     def __init__(self, expr):
510         Type.__init__(self, expr)
511
512     def visit(self, visitor, *args, **kwargs):
513         return visitor.visitOpaque(self, *args, **kwargs)
514
515
516 def OpaquePointer(type, *args):
517     return Opaque(type.expr + ' *')
518
519 def OpaqueArray(type, size):
520     return Opaque(type.expr + ' *')
521
522 def OpaqueBlob(type, size):
523     return Opaque(type.expr + ' *')
524
525
526 class Polymorphic(Type):
527
528     def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
529         if defaultType is None:
530             Type.__init__(self, None)
531             contextLess = False
532         else:
533             Type.__init__(self, defaultType.expr)
534         self.switchExpr = switchExpr
535         self.switchTypes = switchTypes
536         self.defaultType = defaultType
537         self.contextLess = contextLess
538
539     def visit(self, visitor, *args, **kwargs):
540         return visitor.visitPolymorphic(self, *args, **kwargs)
541
542     def iterSwitch(self):
543         cases = []
544         types = []
545
546         if self.defaultType is not None:
547             cases.append(['default'])
548             types.append(self.defaultType)
549
550         for expr, type in self.switchTypes:
551             case = 'case %s' % expr
552             try:
553                 i = types.index(type)
554             except ValueError:
555                 cases.append([case])
556                 types.append(type)
557             else:
558                 cases[i].append(case)
559
560         return zip(cases, types)
561
562
563 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
564     enumValues = [expr for expr, type in switchTypes]
565     enum = Enum(enumName, enumValues)
566     polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
567     return enum, polymorphic
568
569
570 class Visitor:
571     '''Abstract visitor for the type hierarchy.'''
572
573     def visit(self, type, *args, **kwargs):
574         return type.visit(self, *args, **kwargs)
575
576     def visitVoid(self, void, *args, **kwargs):
577         raise NotImplementedError
578
579     def visitLiteral(self, literal, *args, **kwargs):
580         raise NotImplementedError
581
582     def visitString(self, string, *args, **kwargs):
583         raise NotImplementedError
584
585     def visitConst(self, const, *args, **kwargs):
586         raise NotImplementedError
587
588     def visitStruct(self, struct, *args, **kwargs):
589         raise NotImplementedError
590
591     def visitArray(self, array, *args, **kwargs):
592         raise NotImplementedError
593
594     def visitAttribArray(self, array, *args, **kwargs):
595         raise NotImplementedError
596
597     def visitBlob(self, blob, *args, **kwargs):
598         raise NotImplementedError
599
600     def visitEnum(self, enum, *args, **kwargs):
601         raise NotImplementedError
602
603     def visitBitmask(self, bitmask, *args, **kwargs):
604         raise NotImplementedError
605
606     def visitPointer(self, pointer, *args, **kwargs):
607         raise NotImplementedError
608
609     def visitIntPointer(self, pointer, *args, **kwargs):
610         raise NotImplementedError
611
612     def visitObjPointer(self, pointer, *args, **kwargs):
613         raise NotImplementedError
614
615     def visitLinearPointer(self, pointer, *args, **kwargs):
616         raise NotImplementedError
617
618     def visitReference(self, reference, *args, **kwargs):
619         raise NotImplementedError
620
621     def visitHandle(self, handle, *args, **kwargs):
622         raise NotImplementedError
623
624     def visitAlias(self, alias, *args, **kwargs):
625         raise NotImplementedError
626
627     def visitOpaque(self, opaque, *args, **kwargs):
628         raise NotImplementedError
629
630     def visitInterface(self, interface, *args, **kwargs):
631         raise NotImplementedError
632
633     def visitPolymorphic(self, polymorphic, *args, **kwargs):
634         raise NotImplementedError
635         #return self.visit(polymorphic.defaultType, *args, **kwargs)
636
637
638 class OnceVisitor(Visitor):
639     '''Visitor that guarantees that each type is visited only once.'''
640
641     def __init__(self):
642         self.__visited = set()
643
644     def visit(self, type, *args, **kwargs):
645         if type not in self.__visited:
646             self.__visited.add(type)
647             return type.visit(self, *args, **kwargs)
648         return None
649
650
651 class Rebuilder(Visitor):
652     '''Visitor which rebuild types as it visits them.
653
654     By itself it is a no-op -- it is intended to be overwritten.
655     '''
656
657     def visitVoid(self, void):
658         return void
659
660     def visitLiteral(self, literal):
661         return literal
662
663     def visitString(self, string):
664         string_type = self.visit(string.type)
665         if string_type is string.type:
666             return string
667         else:
668             return String(string_type, string.length, string.wide)
669
670     def visitConst(self, const):
671         const_type = self.visit(const.type)
672         if const_type is const.type:
673             return const
674         else:
675             return Const(const_type)
676
677     def visitStruct(self, struct):
678         members = [(self.visit(type), name) for type, name in struct.members]
679         return Struct(struct.name, members)
680
681     def visitArray(self, array):
682         type = self.visit(array.type)
683         return Array(type, array.length)
684
685     def visitBlob(self, blob):
686         type = self.visit(blob.type)
687         return Blob(type, blob.size)
688
689     def visitEnum(self, enum):
690         return enum
691
692     def visitBitmask(self, bitmask):
693         type = self.visit(bitmask.type)
694         return Bitmask(type, bitmask.values)
695
696     def visitPointer(self, pointer):
697         pointer_type = self.visit(pointer.type)
698         if pointer_type is pointer.type:
699             return pointer
700         else:
701             return Pointer(pointer_type)
702
703     def visitIntPointer(self, pointer):
704         return pointer
705
706     def visitObjPointer(self, pointer):
707         pointer_type = self.visit(pointer.type)
708         if pointer_type is pointer.type:
709             return pointer
710         else:
711             return ObjPointer(pointer_type)
712
713     def visitLinearPointer(self, pointer):
714         pointer_type = self.visit(pointer.type)
715         if pointer_type is pointer.type:
716             return pointer
717         else:
718             return LinearPointer(pointer_type)
719
720     def visitReference(self, reference):
721         reference_type = self.visit(reference.type)
722         if reference_type is reference.type:
723             return reference
724         else:
725             return Reference(reference_type)
726
727     def visitHandle(self, handle):
728         handle_type = self.visit(handle.type)
729         if handle_type is handle.type:
730             return handle
731         else:
732             return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
733
734     def visitAlias(self, alias):
735         alias_type = self.visit(alias.type)
736         if alias_type is alias.type:
737             return alias
738         else:
739             return Alias(alias.expr, alias_type)
740
741     def visitOpaque(self, opaque):
742         return opaque
743
744     def visitInterface(self, interface, *args, **kwargs):
745         return interface
746
747     def visitPolymorphic(self, polymorphic):
748         switchExpr = polymorphic.switchExpr
749         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
750         if polymorphic.defaultType is None:
751             defaultType = None
752         else:
753             defaultType = self.visit(polymorphic.defaultType)
754         return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
755
756
757 class MutableRebuilder(Rebuilder):
758     '''Type visitor which derives a mutable type.'''
759
760     def visitString(self, string):
761         return string
762
763     def visitConst(self, const):
764         # Strip out const qualifier
765         return const.type
766
767     def visitAlias(self, alias):
768         # Tear the alias on type changes
769         type = self.visit(alias.type)
770         if type is alias.type:
771             return alias
772         return type
773
774     def visitReference(self, reference):
775         # Strip out references
776         return reference.type
777
778
779 class Traverser(Visitor):
780     '''Visitor which all types.'''
781
782     def visitVoid(self, void, *args, **kwargs):
783         pass
784
785     def visitLiteral(self, literal, *args, **kwargs):
786         pass
787
788     def visitString(self, string, *args, **kwargs):
789         pass
790
791     def visitConst(self, const, *args, **kwargs):
792         self.visit(const.type, *args, **kwargs)
793
794     def visitStruct(self, struct, *args, **kwargs):
795         for type, name in struct.members:
796             self.visit(type, *args, **kwargs)
797
798     def visitArray(self, array, *args, **kwargs):
799         self.visit(array.type, *args, **kwargs)
800
801     def visitAttribArray(self, attribs, *args, **kwargs):
802         for key, valueType in attribs.valueTypes:
803             if valueType is not None:
804                 self.visit(valueType, *args, **kwargs)
805
806     def visitBlob(self, array, *args, **kwargs):
807         pass
808
809     def visitEnum(self, enum, *args, **kwargs):
810         pass
811
812     def visitBitmask(self, bitmask, *args, **kwargs):
813         self.visit(bitmask.type, *args, **kwargs)
814
815     def visitPointer(self, pointer, *args, **kwargs):
816         self.visit(pointer.type, *args, **kwargs)
817
818     def visitIntPointer(self, pointer, *args, **kwargs):
819         pass
820
821     def visitObjPointer(self, pointer, *args, **kwargs):
822         self.visit(pointer.type, *args, **kwargs)
823
824     def visitLinearPointer(self, pointer, *args, **kwargs):
825         self.visit(pointer.type, *args, **kwargs)
826
827     def visitReference(self, reference, *args, **kwargs):
828         self.visit(reference.type, *args, **kwargs)
829
830     def visitHandle(self, handle, *args, **kwargs):
831         self.visit(handle.type, *args, **kwargs)
832
833     def visitAlias(self, alias, *args, **kwargs):
834         self.visit(alias.type, *args, **kwargs)
835
836     def visitOpaque(self, opaque, *args, **kwargs):
837         pass
838
839     def visitInterface(self, interface, *args, **kwargs):
840         if interface.base is not None:
841             self.visit(interface.base, *args, **kwargs)
842         for method in interface.iterMethods():
843             for arg in method.args:
844                 self.visit(arg.type, *args, **kwargs)
845             self.visit(method.type, *args, **kwargs)
846
847     def visitPolymorphic(self, polymorphic, *args, **kwargs):
848         for expr, type in polymorphic.switchTypes:
849             self.visit(type, *args, **kwargs)
850         if polymorphic.defaultType is not None:
851             self.visit(polymorphic.defaultType, *args, **kwargs)
852
853
854 class Collector(Traverser):
855     '''Visitor which collects all unique types as it traverses them.'''
856
857     def __init__(self):
858         self.__visited = set()
859         self.types = []
860
861     def visit(self, type):
862         if type in self.__visited:
863             return
864         self.__visited.add(type)
865         Visitor.visit(self, type)
866         self.types.append(type)
867
868
869 class ExpanderMixin:
870     '''Mixin class that provides a bunch of methods to expand C expressions
871     from the specifications.'''
872
873     __structs = None
874     __indices = None
875
876     def expand(self, expr):
877         # Expand a C expression, replacing certain variables
878         if not isinstance(expr, basestring):
879             return expr
880         variables = {}
881
882         if self.__structs is not None:
883             variables['self'] = '(%s)' % self.__structs[0]
884         if self.__indices is not None:
885             variables['i'] = self.__indices[0]
886
887         expandedExpr = expr.format(**variables)
888         if expandedExpr != expr and 0:
889             sys.stderr.write("  %r -> %r\n" % (expr, expandedExpr))
890         return expandedExpr
891
892     def visitMember(self, member, structInstance, *args, **kwargs):
893         memberType, memberName = member
894         if memberName is None:
895             # Anonymous structure/union member
896             memberInstance = structInstance
897         else:
898             memberInstance = '(%s).%s' % (structInstance, memberName)
899         self.__structs = (structInstance, self.__structs)
900         try:
901             return self.visit(memberType, memberInstance, *args, **kwargs)
902         finally:
903             _, self.__structs = self.__structs
904
905     def visitElement(self, elementIndex, elementType, *args, **kwargs):
906         self.__indices = (elementIndex, self.__indices)
907         try:
908             return self.visit(elementType, *args, **kwargs)
909         finally:
910             _, self.__indices = self.__indices
911
912
913 class Module:
914     '''A collection of functions.'''
915
916     def __init__(self, name = None):
917         self.name = name
918         self.headers = []
919         self.functions = []
920         self.interfaces = []
921
922     def addFunctions(self, functions):
923         self.functions.extend(functions)
924
925     def addInterfaces(self, interfaces):
926         self.interfaces.extend(interfaces)
927
928     def mergeModule(self, module):
929         self.headers.extend(module.headers)
930         self.functions.extend(module.functions)
931         self.interfaces.extend(module.interfaces)
932
933     def getFunctionByName(self, name):
934         for function in self.functions:
935             if function.name == name:
936                 return function
937         return None
938
939
940 class API:
941     '''API abstraction.
942
943     Essentially, a collection of types, functions, and interfaces.
944     '''
945
946     def __init__(self, modules = None):
947         self.modules = []
948         if modules is not None:
949             self.modules.extend(modules)
950
951     def getAllTypes(self):
952         collector = Collector()
953         for module in self.modules:
954             for function in module.functions:
955                 for arg in function.args:
956                     collector.visit(arg.type)
957                 collector.visit(function.type)
958             for interface in module.interfaces:
959                 collector.visit(interface)
960                 for method in interface.iterMethods():
961                     for arg in method.args:
962                         collector.visit(arg.type)
963                     collector.visit(method.type)
964         return collector.types
965
966     def getAllFunctions(self):
967         functions = []
968         for module in self.modules:
969             functions.extend(module.functions)
970         return functions
971
972     def getAllInterfaces(self):
973         types = self.getAllTypes()
974         interfaces = [type for type in types if isinstance(type, Interface)]
975         for module in self.modules:
976             for interface in module.interfaces:
977                 if interface not in interfaces:
978                     interfaces.append(interface)
979         return interfaces
980
981     def addModule(self, module):
982         self.modules.append(module)
983
984     def getFunctionByName(self, name):
985         for module in self.modules:
986             for function in module.functions:
987                 if function.name == name:
988                     return function
989         return None
990
991
992 # C string (i.e., zero terminated)
993 CString = String(Char)
994 WString = String(WChar, wide=True)
995 ConstCString = String(Const(Char))
996 ConstWString = String(Const(WChar), wide=True)