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