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, keyType, valueTypes, isConst = True, terminator = '0'):
277 Type.__init__(self, (Pointer(Const(Int))).expr)
279 Type.__init__(self, (Pointer(Int)).expr)
280 self.type = (Pointer(Const(Int))) # for function prototypes and such
281 self.keyType = keyType
282 self.valueTypes = valueTypes
283 self.terminator = terminator
284 self.hasKeysWithoutValues = False
285 for key, value in valueTypes:
287 self.hasKeysWithoutValues = True
289 def visit(self, visitor, *args, **kwargs):
290 return visitor.visitAttribArray(self, *args, **kwargs)
295 def __init__(self, type, size):
296 Type.__init__(self, type.expr + ' *')
300 def visit(self, visitor, *args, **kwargs):
301 return visitor.visitBlob(self, *args, **kwargs)
308 def __init__(self, name, members):
309 Type.__init__(self, name)
311 self.id = Struct.__id
315 self.members = members
317 def visit(self, visitor, *args, **kwargs):
318 return visitor.visitStruct(self, *args, **kwargs)
321 def Union(kindExpr, kindTypes, contextLess=True):
323 for kindCase, kindType, kindMemberName in kindTypes:
324 switchType = Struct(None, [(kindType, kindMemberName)])
325 switchTypes.append((kindCase, switchType))
326 return Polymorphic(kindExpr, switchTypes, contextLess=contextLess)
331 def __init__(self, expr, type):
332 Type.__init__(self, expr)
335 def visit(self, visitor, *args, **kwargs):
336 return visitor.visitAlias(self, *args, **kwargs)
340 def __init__(self, type, name, input=True, output=False):
348 return '%s %s' % (self.type, self.name)
352 return Arg(type, name, input=True, output=False)
355 return Arg(type, name, input=False, output=True)
357 def InOut(type, name):
358 return Arg(type, name, input=True, output=True)
363 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
370 if not isinstance(arg, Arg):
371 if isinstance(arg, tuple):
372 arg_type, arg_name = arg
375 arg_name = "arg%u" % index
376 arg = Arg(arg_type, arg_name)
379 self.args.append(arg)
383 self.sideeffects = sideeffects
384 self.internal = internal
386 def prototype(self, name=None):
393 s = self.call + ' ' + s
394 if name.startswith('*'):
396 s = self.type.expr + ' ' + s
399 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
406 return [arg.name for arg in self.args]
408 def getArgByName(self, name):
409 for arg in self.args:
415 def StdFunction(*args, **kwargs):
416 kwargs.setdefault('call', '__stdcall')
417 return Function(*args, **kwargs)
420 def FunctionPointer(type, name, args, **kwargs):
421 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
425 class Interface(Type):
427 def __init__(self, name, base=None):
428 Type.__init__(self, name)
433 def visit(self, visitor, *args, **kwargs):
434 return visitor.visitInterface(self, *args, **kwargs)
436 def getMethodByName(self, name):
437 for method in self.iterMethods():
438 if method.name == name:
442 def iterMethods(self):
443 if self.base is not None:
444 for method in self.base.iterMethods():
446 for method in self.methods:
452 while iface is not None:
457 def hasBase(self, *bases):
458 for iface in self.iterBases():
463 def iterBaseMethods(self):
464 if self.base is not None:
465 for iface, method in self.base.iterBaseMethods():
467 for method in self.methods:
472 class Method(Function):
474 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
475 assert call == '__stdcall'
476 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
477 for index in range(len(self.args)):
478 self.args[index].index = index + 1
481 def prototype(self, name=None):
482 s = Function.prototype(self, name)
488 def StdMethod(*args, **kwargs):
489 kwargs.setdefault('call', '__stdcall')
490 return Method(*args, **kwargs)
494 '''Human-legible character string.'''
496 def __init__(self, type = Char, length = None, wide = False):
497 assert isinstance(type, Type)
498 Type.__init__(self, type.expr + ' *')
503 def visit(self, visitor, *args, **kwargs):
504 return visitor.visitString(self, *args, **kwargs)
508 '''Opaque pointer.'''
510 def __init__(self, expr):
511 Type.__init__(self, expr)
513 def visit(self, visitor, *args, **kwargs):
514 return visitor.visitOpaque(self, *args, **kwargs)
517 def OpaquePointer(type, *args):
518 return Opaque(type.expr + ' *')
520 def OpaqueArray(type, size):
521 return Opaque(type.expr + ' *')
523 def OpaqueBlob(type, size):
524 return Opaque(type.expr + ' *')
527 class Polymorphic(Type):
529 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
530 if defaultType is None:
531 Type.__init__(self, None)
534 Type.__init__(self, defaultType.expr)
535 self.switchExpr = switchExpr
536 self.switchTypes = switchTypes
537 self.defaultType = defaultType
538 self.contextLess = contextLess
540 def visit(self, visitor, *args, **kwargs):
541 return visitor.visitPolymorphic(self, *args, **kwargs)
543 def iterSwitch(self):
547 if self.defaultType is not None:
548 cases.append(['default'])
549 types.append(self.defaultType)
551 for expr, type in self.switchTypes:
552 case = 'case %s' % expr
554 i = types.index(type)
559 cases[i].append(case)
561 return zip(cases, types)
564 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
565 enumValues = [expr for expr, type in switchTypes]
566 enum = Enum(enumName, enumValues)
567 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
568 return enum, polymorphic
572 '''Abstract visitor for the type hierarchy.'''
574 def visit(self, type, *args, **kwargs):
575 return type.visit(self, *args, **kwargs)
577 def visitVoid(self, void, *args, **kwargs):
578 raise NotImplementedError
580 def visitLiteral(self, literal, *args, **kwargs):
581 raise NotImplementedError
583 def visitString(self, string, *args, **kwargs):
584 raise NotImplementedError
586 def visitConst(self, const, *args, **kwargs):
587 raise NotImplementedError
589 def visitStruct(self, struct, *args, **kwargs):
590 raise NotImplementedError
592 def visitArray(self, array, *args, **kwargs):
593 raise NotImplementedError
595 def visitAttribArray(self, array, *args, **kwargs):
596 raise NotImplementedError
598 def visitBlob(self, blob, *args, **kwargs):
599 raise NotImplementedError
601 def visitEnum(self, enum, *args, **kwargs):
602 raise NotImplementedError
604 def visitBitmask(self, bitmask, *args, **kwargs):
605 raise NotImplementedError
607 def visitPointer(self, pointer, *args, **kwargs):
608 raise NotImplementedError
610 def visitIntPointer(self, pointer, *args, **kwargs):
611 raise NotImplementedError
613 def visitObjPointer(self, pointer, *args, **kwargs):
614 raise NotImplementedError
616 def visitLinearPointer(self, pointer, *args, **kwargs):
617 raise NotImplementedError
619 def visitReference(self, reference, *args, **kwargs):
620 raise NotImplementedError
622 def visitHandle(self, handle, *args, **kwargs):
623 raise NotImplementedError
625 def visitAlias(self, alias, *args, **kwargs):
626 raise NotImplementedError
628 def visitOpaque(self, opaque, *args, **kwargs):
629 raise NotImplementedError
631 def visitInterface(self, interface, *args, **kwargs):
632 raise NotImplementedError
634 def visitPolymorphic(self, polymorphic, *args, **kwargs):
635 raise NotImplementedError
636 #return self.visit(polymorphic.defaultType, *args, **kwargs)
639 class OnceVisitor(Visitor):
640 '''Visitor that guarantees that each type is visited only once.'''
643 self.__visited = set()
645 def visit(self, type, *args, **kwargs):
646 if type not in self.__visited:
647 self.__visited.add(type)
648 return type.visit(self, *args, **kwargs)
652 class Rebuilder(Visitor):
653 '''Visitor which rebuild types as it visits them.
655 By itself it is a no-op -- it is intended to be overwritten.
658 def visitVoid(self, void):
661 def visitLiteral(self, literal):
664 def visitString(self, string):
665 string_type = self.visit(string.type)
666 if string_type is string.type:
669 return String(string_type, string.length, string.wide)
671 def visitConst(self, const):
672 const_type = self.visit(const.type)
673 if const_type is const.type:
676 return Const(const_type)
678 def visitStruct(self, struct):
679 members = [(self.visit(type), name) for type, name in struct.members]
680 return Struct(struct.name, members)
682 def visitArray(self, array):
683 type = self.visit(array.type)
684 return Array(type, array.length)
686 def visitBlob(self, blob):
687 type = self.visit(blob.type)
688 return Blob(type, blob.size)
690 def visitEnum(self, enum):
693 def visitBitmask(self, bitmask):
694 type = self.visit(bitmask.type)
695 return Bitmask(type, bitmask.values)
697 def visitPointer(self, pointer):
698 pointer_type = self.visit(pointer.type)
699 if pointer_type is pointer.type:
702 return Pointer(pointer_type)
704 def visitIntPointer(self, pointer):
707 def visitObjPointer(self, pointer):
708 pointer_type = self.visit(pointer.type)
709 if pointer_type is pointer.type:
712 return ObjPointer(pointer_type)
714 def visitLinearPointer(self, pointer):
715 pointer_type = self.visit(pointer.type)
716 if pointer_type is pointer.type:
719 return LinearPointer(pointer_type)
721 def visitReference(self, reference):
722 reference_type = self.visit(reference.type)
723 if reference_type is reference.type:
726 return Reference(reference_type)
728 def visitHandle(self, handle):
729 handle_type = self.visit(handle.type)
730 if handle_type is handle.type:
733 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
735 def visitAlias(self, alias):
736 alias_type = self.visit(alias.type)
737 if alias_type is alias.type:
740 return Alias(alias.expr, alias_type)
742 def visitOpaque(self, opaque):
745 def visitInterface(self, interface, *args, **kwargs):
748 def visitPolymorphic(self, polymorphic):
749 switchExpr = polymorphic.switchExpr
750 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
751 if polymorphic.defaultType is None:
754 defaultType = self.visit(polymorphic.defaultType)
755 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
758 class MutableRebuilder(Rebuilder):
759 '''Type visitor which derives a mutable type.'''
761 def visitString(self, string):
764 def visitConst(self, const):
765 # Strip out const qualifier
768 def visitAlias(self, alias):
769 # Tear the alias on type changes
770 type = self.visit(alias.type)
771 if type is alias.type:
775 def visitReference(self, reference):
776 # Strip out references
777 return reference.type
780 class Traverser(Visitor):
781 '''Visitor which all types.'''
783 def visitVoid(self, void, *args, **kwargs):
786 def visitLiteral(self, literal, *args, **kwargs):
789 def visitString(self, string, *args, **kwargs):
792 def visitConst(self, const, *args, **kwargs):
793 self.visit(const.type, *args, **kwargs)
795 def visitStruct(self, struct, *args, **kwargs):
796 for type, name in struct.members:
797 self.visit(type, *args, **kwargs)
799 def visitArray(self, array, *args, **kwargs):
800 self.visit(array.type, *args, **kwargs)
802 def visitAttribArray(self, attribs, *args, **kwargs):
803 for key, valueType in attribs.valueTypes:
804 if valueType is not None:
805 self.visit(valueType, *args, **kwargs)
807 def visitBlob(self, array, *args, **kwargs):
810 def visitEnum(self, enum, *args, **kwargs):
813 def visitBitmask(self, bitmask, *args, **kwargs):
814 self.visit(bitmask.type, *args, **kwargs)
816 def visitPointer(self, pointer, *args, **kwargs):
817 self.visit(pointer.type, *args, **kwargs)
819 def visitIntPointer(self, pointer, *args, **kwargs):
822 def visitObjPointer(self, pointer, *args, **kwargs):
823 self.visit(pointer.type, *args, **kwargs)
825 def visitLinearPointer(self, pointer, *args, **kwargs):
826 self.visit(pointer.type, *args, **kwargs)
828 def visitReference(self, reference, *args, **kwargs):
829 self.visit(reference.type, *args, **kwargs)
831 def visitHandle(self, handle, *args, **kwargs):
832 self.visit(handle.type, *args, **kwargs)
834 def visitAlias(self, alias, *args, **kwargs):
835 self.visit(alias.type, *args, **kwargs)
837 def visitOpaque(self, opaque, *args, **kwargs):
840 def visitInterface(self, interface, *args, **kwargs):
841 if interface.base is not None:
842 self.visit(interface.base, *args, **kwargs)
843 for method in interface.iterMethods():
844 for arg in method.args:
845 self.visit(arg.type, *args, **kwargs)
846 self.visit(method.type, *args, **kwargs)
848 def visitPolymorphic(self, polymorphic, *args, **kwargs):
849 for expr, type in polymorphic.switchTypes:
850 self.visit(type, *args, **kwargs)
851 if polymorphic.defaultType is not None:
852 self.visit(polymorphic.defaultType, *args, **kwargs)
855 class Collector(Traverser):
856 '''Visitor which collects all unique types as it traverses them.'''
859 self.__visited = set()
862 def visit(self, type):
863 if type in self.__visited:
865 self.__visited.add(type)
866 Visitor.visit(self, type)
867 self.types.append(type)
871 '''Mixin class that provides a bunch of methods to expand C expressions
872 from the specifications.'''
877 def expand(self, expr):
878 # Expand a C expression, replacing certain variables
879 if not isinstance(expr, basestring):
883 if self.__structs is not None:
884 variables['self'] = '(%s)' % self.__structs[0]
885 if self.__indices is not None:
886 variables['i'] = self.__indices[0]
888 expandedExpr = expr.format(**variables)
889 if expandedExpr != expr and 0:
890 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
893 def visitMember(self, member, structInstance, *args, **kwargs):
894 memberType, memberName = member
895 if memberName is None:
896 # Anonymous structure/union member
897 memberInstance = structInstance
899 memberInstance = '(%s).%s' % (structInstance, memberName)
900 self.__structs = (structInstance, self.__structs)
902 return self.visit(memberType, memberInstance, *args, **kwargs)
904 _, self.__structs = self.__structs
906 def visitElement(self, elementIndex, elementType, *args, **kwargs):
907 self.__indices = (elementIndex, self.__indices)
909 return self.visit(elementType, *args, **kwargs)
911 _, self.__indices = self.__indices
915 '''A collection of functions.'''
917 def __init__(self, name = None):
923 def addFunctions(self, functions):
924 self.functions.extend(functions)
926 def addInterfaces(self, interfaces):
927 self.interfaces.extend(interfaces)
929 def mergeModule(self, module):
930 self.headers.extend(module.headers)
931 self.functions.extend(module.functions)
932 self.interfaces.extend(module.interfaces)
934 def getFunctionByName(self, name):
935 for function in self.functions:
936 if function.name == name:
944 Essentially, a collection of types, functions, and interfaces.
947 def __init__(self, modules = None):
949 if modules is not None:
950 self.modules.extend(modules)
952 def getAllTypes(self):
953 collector = Collector()
954 for module in self.modules:
955 for function in module.functions:
956 for arg in function.args:
957 collector.visit(arg.type)
958 collector.visit(function.type)
959 for interface in module.interfaces:
960 collector.visit(interface)
961 for method in interface.iterMethods():
962 for arg in method.args:
963 collector.visit(arg.type)
964 collector.visit(method.type)
965 return collector.types
967 def getAllFunctions(self):
969 for module in self.modules:
970 functions.extend(module.functions)
973 def getAllInterfaces(self):
974 types = self.getAllTypes()
975 interfaces = [type for type in types if isinstance(type, Interface)]
976 for module in self.modules:
977 for interface in module.interfaces:
978 if interface not in interfaces:
979 interfaces.append(interface)
982 def addModule(self, module):
983 self.modules.append(module)
985 def getFunctionByName(self, name):
986 for module in self.modules:
987 for function in module.functions:
988 if function.name == name:
993 # C string (i.e., zero terminated)
994 CString = String(Char)
995 WString = String(WChar, wide=True)
996 ConstCString = String(Const(Char))
997 ConstWString = String(Const(WChar), wide=True)