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