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