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