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