1 ##########################################################################
3 # Copyright 2008-2010 VMware, Inc.
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:
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
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
24 ##########################################################################/
33 """Base class for all types."""
37 def __init__(self, expr, tag = None):
40 # Generate a default tag, used when naming functions that will operate
41 # on this type, so it should preferrably be something representative of
45 tag = ''.join([c for c in expr if c.isalnum() or c in '_'])
50 assert c.isalnum() or c in '_'
52 # Ensure it is unique.
53 if tag in Type.__tags:
55 while tag + str(suffix) in Type.__tags:
59 assert tag not in Type.__tags
65 """Return the C/C++ type expression for this type."""
68 def visit(self, visitor, *args, **kwargs):
69 raise NotImplementedError
72 '''Return a mutable version of this type.
74 Convenience wrapper around MutableRebuilder.'''
75 visitor = MutableRebuilder()
76 return visitor.visit(self)
80 """Singleton void type."""
83 Type.__init__(self, "void")
85 def visit(self, visitor, *args, **kwargs):
86 return visitor.visitVoid(self, *args, **kwargs)
92 """Class to describe literal types.
94 Types which are not defined in terms of other types, such as integers and
97 def __init__(self, expr, kind):
98 Type.__init__(self, expr)
101 def visit(self, visitor, *args, **kwargs):
102 return visitor.visitLiteral(self, *args, **kwargs)
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")
120 Char = Literal("char", "SInt")
121 WChar = Literal("wchar_t", "SInt")
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")
132 IntPtr = Literal("intptr_t", "SInt")
133 UIntPtr = Literal("uintptr_t", "UInt")
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"
145 expr = "const " + type.expr
147 Type.__init__(self, expr, 'C' + type.tag)
151 def visit(self, visitor, *args, **kwargs):
152 return visitor.visitConst(self, *args, **kwargs)
157 def __init__(self, type):
158 Type.__init__(self, type.expr + " *", 'P' + type.tag)
161 def visit(self, visitor, *args, **kwargs):
162 return visitor.visitPointer(self, *args, **kwargs)
165 class IntPointer(Type):
166 '''Integer encoded as a pointer.'''
168 def visit(self, visitor, *args, **kwargs):
169 return visitor.visitIntPointer(self, *args, **kwargs)
172 class ObjPointer(Type):
173 '''Pointer to an object.'''
175 def __init__(self, type):
176 Type.__init__(self, type.expr + " *", 'P' + type.tag)
179 def visit(self, visitor, *args, **kwargs):
180 return visitor.visitObjPointer(self, *args, **kwargs)
183 class LinearPointer(Type):
184 '''Pointer to a linear range of memory.'''
186 def __init__(self, type, size = None):
187 Type.__init__(self, type.expr + " *", 'P' + type.tag)
191 def visit(self, visitor, *args, **kwargs):
192 return visitor.visitLinearPointer(self, *args, **kwargs)
195 class Reference(Type):
196 '''C++ references.'''
198 def __init__(self, type):
199 Type.__init__(self, type.expr + " &", 'R' + type.tag)
202 def visit(self, visitor, *args, **kwargs):
203 return visitor.visitReference(self, *args, **kwargs)
208 def __init__(self, name, type, range=None, key=None):
209 Type.__init__(self, type.expr, 'P' + type.tag)
215 def visit(self, visitor, *args, **kwargs):
216 return visitor.visitHandle(self, *args, **kwargs)
219 def ConstPointer(type):
220 return Pointer(Const(type))
227 def __init__(self, name, values):
228 Type.__init__(self, name)
233 self.values = list(values)
235 def visit(self, visitor, *args, **kwargs):
236 return visitor.visitEnum(self, *args, **kwargs)
239 def FakeEnum(type, values):
240 return Enum(type.expr, values)
247 def __init__(self, type, values):
248 Type.__init__(self, type.expr)
250 self.id = Bitmask.__id
256 def visit(self, visitor, *args, **kwargs):
257 return visitor.visitBitmask(self, *args, **kwargs)
264 def __init__(self, type, length):
265 Type.__init__(self, type.expr + " *")
269 def visit(self, visitor, *args, **kwargs):
270 return visitor.visitArray(self, *args, **kwargs)
273 class AttribArray(Type):
275 def __init__(self, baseType, valueTypes, isConst = True, terminator = '0'):
276 self.baseType = baseType
278 Type.__init__(self, (Pointer(Const(self.baseType))).expr)
280 Type.__init__(self, (Pointer(self.baseType)).expr)
281 self.valueTypes = valueTypes
282 self.terminator = terminator
283 self.hasKeysWithoutValues = False
284 for key, value in valueTypes:
286 self.hasKeysWithoutValues = True
288 def visit(self, visitor, *args, **kwargs):
289 return visitor.visitAttribArray(self, *args, **kwargs)
294 def __init__(self, type, size):
295 Type.__init__(self, type.expr + ' *')
299 def visit(self, visitor, *args, **kwargs):
300 return visitor.visitBlob(self, *args, **kwargs)
307 def __init__(self, name, members):
308 Type.__init__(self, name)
310 self.id = Struct.__id
314 self.members = members
316 def visit(self, visitor, *args, **kwargs):
317 return visitor.visitStruct(self, *args, **kwargs)
320 def Union(kindExpr, kindTypes, contextLess=True):
322 for kindCase, kindType, kindMemberName in kindTypes:
323 switchType = Struct(None, [(kindType, kindMemberName)])
324 switchTypes.append((kindCase, switchType))
325 return Polymorphic(kindExpr, switchTypes, contextLess=contextLess)
330 def __init__(self, expr, type):
331 Type.__init__(self, expr)
334 def visit(self, visitor, *args, **kwargs):
335 return visitor.visitAlias(self, *args, **kwargs)
339 def __init__(self, type, name, input=True, output=False):
347 return '%s %s' % (self.type, self.name)
351 return Arg(type, name, input=True, output=False)
354 return Arg(type, name, input=False, output=True)
356 def InOut(type, name):
357 return Arg(type, name, input=True, output=True)
362 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
369 if not isinstance(arg, Arg):
370 if isinstance(arg, tuple):
371 arg_type, arg_name = arg
374 arg_name = "arg%u" % index
375 arg = Arg(arg_type, arg_name)
378 self.args.append(arg)
382 self.sideeffects = sideeffects
383 self.internal = internal
385 def prototype(self, name=None):
392 s = self.call + ' ' + s
393 if name.startswith('*'):
395 s = self.type.expr + ' ' + s
398 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
405 return [arg.name for arg in self.args]
407 def getArgByName(self, name):
408 for arg in self.args:
414 def StdFunction(*args, **kwargs):
415 kwargs.setdefault('call', '__stdcall')
416 return Function(*args, **kwargs)
419 def FunctionPointer(type, name, args, **kwargs):
420 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
424 class Interface(Type):
426 def __init__(self, name, base=None):
427 Type.__init__(self, name)
432 def visit(self, visitor, *args, **kwargs):
433 return visitor.visitInterface(self, *args, **kwargs)
435 def getMethodByName(self, name):
436 for method in self.iterMethods():
437 if method.name == name:
441 def iterMethods(self):
442 if self.base is not None:
443 for method in self.base.iterMethods():
445 for method in self.methods:
451 while iface is not None:
456 def hasBase(self, *bases):
457 for iface in self.iterBases():
462 def iterBaseMethods(self):
463 if self.base is not None:
464 for iface, method in self.base.iterBaseMethods():
466 for method in self.methods:
471 class Method(Function):
473 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
474 assert call == '__stdcall'
475 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
476 for index in range(len(self.args)):
477 self.args[index].index = index + 1
480 def prototype(self, name=None):
481 s = Function.prototype(self, name)
487 def StdMethod(*args, **kwargs):
488 kwargs.setdefault('call', '__stdcall')
489 return Method(*args, **kwargs)
493 '''Human-legible character string.'''
495 def __init__(self, type = Char, length = None, wide = False):
496 assert isinstance(type, Type)
497 Type.__init__(self, type.expr + ' *')
502 def visit(self, visitor, *args, **kwargs):
503 return visitor.visitString(self, *args, **kwargs)
507 '''Opaque pointer.'''
509 def __init__(self, expr):
510 Type.__init__(self, expr)
512 def visit(self, visitor, *args, **kwargs):
513 return visitor.visitOpaque(self, *args, **kwargs)
516 def OpaquePointer(type, *args):
517 return Opaque(type.expr + ' *')
519 def OpaqueArray(type, size):
520 return Opaque(type.expr + ' *')
522 def OpaqueBlob(type, size):
523 return Opaque(type.expr + ' *')
526 class Polymorphic(Type):
528 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
529 if defaultType is None:
530 Type.__init__(self, None)
533 Type.__init__(self, defaultType.expr)
534 self.switchExpr = switchExpr
535 self.switchTypes = switchTypes
536 self.defaultType = defaultType
537 self.contextLess = contextLess
539 def visit(self, visitor, *args, **kwargs):
540 return visitor.visitPolymorphic(self, *args, **kwargs)
542 def iterSwitch(self):
546 if self.defaultType is not None:
547 cases.append(['default'])
548 types.append(self.defaultType)
550 for expr, type in self.switchTypes:
551 case = 'case %s' % expr
553 i = types.index(type)
558 cases[i].append(case)
560 return zip(cases, types)
563 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
564 enumValues = [expr for expr, type in switchTypes]
565 enum = Enum(enumName, enumValues)
566 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
567 return enum, polymorphic
571 '''Abstract visitor for the type hierarchy.'''
573 def visit(self, type, *args, **kwargs):
574 return type.visit(self, *args, **kwargs)
576 def visitVoid(self, void, *args, **kwargs):
577 raise NotImplementedError
579 def visitLiteral(self, literal, *args, **kwargs):
580 raise NotImplementedError
582 def visitString(self, string, *args, **kwargs):
583 raise NotImplementedError
585 def visitConst(self, const, *args, **kwargs):
586 raise NotImplementedError
588 def visitStruct(self, struct, *args, **kwargs):
589 raise NotImplementedError
591 def visitArray(self, array, *args, **kwargs):
592 raise NotImplementedError
594 def visitAttribArray(self, array, *args, **kwargs):
595 raise NotImplementedError
597 def visitBlob(self, blob, *args, **kwargs):
598 raise NotImplementedError
600 def visitEnum(self, enum, *args, **kwargs):
601 raise NotImplementedError
603 def visitBitmask(self, bitmask, *args, **kwargs):
604 raise NotImplementedError
606 def visitPointer(self, pointer, *args, **kwargs):
607 raise NotImplementedError
609 def visitIntPointer(self, pointer, *args, **kwargs):
610 raise NotImplementedError
612 def visitObjPointer(self, pointer, *args, **kwargs):
613 raise NotImplementedError
615 def visitLinearPointer(self, pointer, *args, **kwargs):
616 raise NotImplementedError
618 def visitReference(self, reference, *args, **kwargs):
619 raise NotImplementedError
621 def visitHandle(self, handle, *args, **kwargs):
622 raise NotImplementedError
624 def visitAlias(self, alias, *args, **kwargs):
625 raise NotImplementedError
627 def visitOpaque(self, opaque, *args, **kwargs):
628 raise NotImplementedError
630 def visitInterface(self, interface, *args, **kwargs):
631 raise NotImplementedError
633 def visitPolymorphic(self, polymorphic, *args, **kwargs):
634 raise NotImplementedError
635 #return self.visit(polymorphic.defaultType, *args, **kwargs)
638 class OnceVisitor(Visitor):
639 '''Visitor that guarantees that each type is visited only once.'''
642 self.__visited = set()
644 def visit(self, type, *args, **kwargs):
645 if type not in self.__visited:
646 self.__visited.add(type)
647 return type.visit(self, *args, **kwargs)
651 class Rebuilder(Visitor):
652 '''Visitor which rebuild types as it visits them.
654 By itself it is a no-op -- it is intended to be overwritten.
657 def visitVoid(self, void):
660 def visitLiteral(self, literal):
663 def visitString(self, string):
664 string_type = self.visit(string.type)
665 if string_type is string.type:
668 return String(string_type, string.length, string.wide)
670 def visitConst(self, const):
671 const_type = self.visit(const.type)
672 if const_type is const.type:
675 return Const(const_type)
677 def visitStruct(self, struct):
678 members = [(self.visit(type), name) for type, name in struct.members]
679 return Struct(struct.name, members)
681 def visitArray(self, array):
682 type = self.visit(array.type)
683 return Array(type, array.length)
685 def visitBlob(self, blob):
686 type = self.visit(blob.type)
687 return Blob(type, blob.size)
689 def visitEnum(self, enum):
692 def visitBitmask(self, bitmask):
693 type = self.visit(bitmask.type)
694 return Bitmask(type, bitmask.values)
696 def visitPointer(self, pointer):
697 pointer_type = self.visit(pointer.type)
698 if pointer_type is pointer.type:
701 return Pointer(pointer_type)
703 def visitIntPointer(self, pointer):
706 def visitObjPointer(self, pointer):
707 pointer_type = self.visit(pointer.type)
708 if pointer_type is pointer.type:
711 return ObjPointer(pointer_type)
713 def visitLinearPointer(self, pointer):
714 pointer_type = self.visit(pointer.type)
715 if pointer_type is pointer.type:
718 return LinearPointer(pointer_type)
720 def visitReference(self, reference):
721 reference_type = self.visit(reference.type)
722 if reference_type is reference.type:
725 return Reference(reference_type)
727 def visitHandle(self, handle):
728 handle_type = self.visit(handle.type)
729 if handle_type is handle.type:
732 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
734 def visitAlias(self, alias):
735 alias_type = self.visit(alias.type)
736 if alias_type is alias.type:
739 return Alias(alias.expr, alias_type)
741 def visitOpaque(self, opaque):
744 def visitInterface(self, interface, *args, **kwargs):
747 def visitPolymorphic(self, polymorphic):
748 switchExpr = polymorphic.switchExpr
749 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
750 if polymorphic.defaultType is None:
753 defaultType = self.visit(polymorphic.defaultType)
754 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
757 class MutableRebuilder(Rebuilder):
758 '''Type visitor which derives a mutable type.'''
760 def visitString(self, string):
763 def visitConst(self, const):
764 # Strip out const qualifier
767 def visitAlias(self, alias):
768 # Tear the alias on type changes
769 type = self.visit(alias.type)
770 if type is alias.type:
774 def visitReference(self, reference):
775 # Strip out references
776 return reference.type
779 class Traverser(Visitor):
780 '''Visitor which all types.'''
782 def visitVoid(self, void, *args, **kwargs):
785 def visitLiteral(self, literal, *args, **kwargs):
788 def visitString(self, string, *args, **kwargs):
791 def visitConst(self, const, *args, **kwargs):
792 self.visit(const.type, *args, **kwargs)
794 def visitStruct(self, struct, *args, **kwargs):
795 for type, name in struct.members:
796 self.visit(type, *args, **kwargs)
798 def visitArray(self, array, *args, **kwargs):
799 self.visit(array.type, *args, **kwargs)
801 def visitAttribArray(self, attribs, *args, **kwargs):
802 for key, valueType in attribs.valueTypes:
803 if valueType is not None:
804 self.visit(valueType, *args, **kwargs)
806 def visitBlob(self, array, *args, **kwargs):
809 def visitEnum(self, enum, *args, **kwargs):
812 def visitBitmask(self, bitmask, *args, **kwargs):
813 self.visit(bitmask.type, *args, **kwargs)
815 def visitPointer(self, pointer, *args, **kwargs):
816 self.visit(pointer.type, *args, **kwargs)
818 def visitIntPointer(self, pointer, *args, **kwargs):
821 def visitObjPointer(self, pointer, *args, **kwargs):
822 self.visit(pointer.type, *args, **kwargs)
824 def visitLinearPointer(self, pointer, *args, **kwargs):
825 self.visit(pointer.type, *args, **kwargs)
827 def visitReference(self, reference, *args, **kwargs):
828 self.visit(reference.type, *args, **kwargs)
830 def visitHandle(self, handle, *args, **kwargs):
831 self.visit(handle.type, *args, **kwargs)
833 def visitAlias(self, alias, *args, **kwargs):
834 self.visit(alias.type, *args, **kwargs)
836 def visitOpaque(self, opaque, *args, **kwargs):
839 def visitInterface(self, interface, *args, **kwargs):
840 if interface.base is not None:
841 self.visit(interface.base, *args, **kwargs)
842 for method in interface.iterMethods():
843 for arg in method.args:
844 self.visit(arg.type, *args, **kwargs)
845 self.visit(method.type, *args, **kwargs)
847 def visitPolymorphic(self, polymorphic, *args, **kwargs):
848 for expr, type in polymorphic.switchTypes:
849 self.visit(type, *args, **kwargs)
850 if polymorphic.defaultType is not None:
851 self.visit(polymorphic.defaultType, *args, **kwargs)
854 class Collector(Traverser):
855 '''Visitor which collects all unique types as it traverses them.'''
858 self.__visited = set()
861 def visit(self, type):
862 if type in self.__visited:
864 self.__visited.add(type)
865 Visitor.visit(self, type)
866 self.types.append(type)
870 '''Mixin class that provides a bunch of methods to expand C expressions
871 from the specifications.'''
876 def expand(self, expr):
877 # Expand a C expression, replacing certain variables
878 if not isinstance(expr, basestring):
882 if self.__structs is not None:
883 variables['self'] = '(%s)' % self.__structs[0]
884 if self.__indices is not None:
885 variables['i'] = self.__indices[0]
887 expandedExpr = expr.format(**variables)
888 if expandedExpr != expr and 0:
889 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
892 def visitMember(self, member, structInstance, *args, **kwargs):
893 memberType, memberName = member
894 if memberName is None:
895 # Anonymous structure/union member
896 memberInstance = structInstance
898 memberInstance = '(%s).%s' % (structInstance, memberName)
899 self.__structs = (structInstance, self.__structs)
901 return self.visit(memberType, memberInstance, *args, **kwargs)
903 _, self.__structs = self.__structs
905 def visitElement(self, elementIndex, elementType, *args, **kwargs):
906 self.__indices = (elementIndex, self.__indices)
908 return self.visit(elementType, *args, **kwargs)
910 _, self.__indices = self.__indices
914 '''A collection of functions.'''
916 def __init__(self, name = None):
922 def addFunctions(self, functions):
923 self.functions.extend(functions)
925 def addInterfaces(self, interfaces):
926 self.interfaces.extend(interfaces)
928 def mergeModule(self, module):
929 self.headers.extend(module.headers)
930 self.functions.extend(module.functions)
931 self.interfaces.extend(module.interfaces)
933 def getFunctionByName(self, name):
934 for function in self.functions:
935 if function.name == name:
943 Essentially, a collection of types, functions, and interfaces.
946 def __init__(self, modules = None):
948 if modules is not None:
949 self.modules.extend(modules)
951 def getAllTypes(self):
952 collector = Collector()
953 for module in self.modules:
954 for function in module.functions:
955 for arg in function.args:
956 collector.visit(arg.type)
957 collector.visit(function.type)
958 for interface in module.interfaces:
959 collector.visit(interface)
960 for method in interface.iterMethods():
961 for arg in method.args:
962 collector.visit(arg.type)
963 collector.visit(method.type)
964 return collector.types
966 def getAllFunctions(self):
968 for module in self.modules:
969 functions.extend(module.functions)
972 def getAllInterfaces(self):
973 types = self.getAllTypes()
974 interfaces = [type for type in types if isinstance(type, Interface)]
975 for module in self.modules:
976 for interface in module.interfaces:
977 if interface not in interfaces:
978 interfaces.append(interface)
981 def addModule(self, module):
982 self.modules.append(module)
984 def getFunctionByName(self, name):
985 for module in self.modules:
986 for function in module.functions:
987 if function.name == name:
992 # C string (i.e., zero terminated)
993 CString = String(Char)
994 WString = String(WChar, wide=True)
995 ConstCString = String(Const(Char))
996 ConstWString = String(Const(WChar), wide=True)