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