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)
275 def __init__(self, type, size):
276 Type.__init__(self, type.expr + ' *')
280 def visit(self, visitor, *args, **kwargs):
281 return visitor.visitBlob(self, *args, **kwargs)
288 def __init__(self, name, members):
289 Type.__init__(self, name)
291 self.id = Struct.__id
295 self.members = members
297 def visit(self, visitor, *args, **kwargs):
298 return visitor.visitStruct(self, *args, **kwargs)
301 def Union(kindExpr, kindTypes, contextLess=True):
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)
311 def __init__(self, expr, type):
312 Type.__init__(self, expr)
315 def visit(self, visitor, *args, **kwargs):
316 return visitor.visitAlias(self, *args, **kwargs)
320 def __init__(self, type, name, input=True, output=False):
328 return '%s %s' % (self.type, self.name)
332 return Arg(type, name, input=True, output=False)
335 return Arg(type, name, input=False, output=True)
337 def InOut(type, name):
338 return Arg(type, name, input=True, output=True)
343 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
350 if not isinstance(arg, Arg):
351 if isinstance(arg, tuple):
352 arg_type, arg_name = arg
355 arg_name = "arg%u" % index
356 arg = Arg(arg_type, arg_name)
359 self.args.append(arg)
363 self.sideeffects = sideeffects
364 self.internal = internal
366 def prototype(self, name=None):
373 s = self.call + ' ' + s
374 if name.startswith('*'):
376 s = self.type.expr + ' ' + s
379 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
386 return [arg.name for arg in self.args]
388 def getArgByName(self, name):
389 for arg in self.args:
395 def StdFunction(*args, **kwargs):
396 kwargs.setdefault('call', '__stdcall')
397 return Function(*args, **kwargs)
400 def FunctionPointer(type, name, args, **kwargs):
401 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
405 class Interface(Type):
407 def __init__(self, name, base=None):
408 Type.__init__(self, name)
413 def visit(self, visitor, *args, **kwargs):
414 return visitor.visitInterface(self, *args, **kwargs)
416 def getMethodByName(self, name):
417 for method in self.iterMethods():
418 if method.name == name:
422 def iterMethods(self):
423 if self.base is not None:
424 for method in self.base.iterMethods():
426 for method in self.methods:
432 while iface is not None:
437 def iterBaseMethods(self):
438 if self.base is not None:
439 for iface, method in self.base.iterBaseMethods():
441 for method in self.methods:
446 class Method(Function):
448 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
449 assert call == '__stdcall'
450 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
451 for index in range(len(self.args)):
452 self.args[index].index = index + 1
455 def prototype(self, name=None):
456 s = Function.prototype(self, name)
462 def StdMethod(*args, **kwargs):
463 kwargs.setdefault('call', '__stdcall')
464 return Method(*args, **kwargs)
468 '''Human-legible character string.'''
470 def __init__(self, type = Char, length = None, wide = False):
471 assert isinstance(type, Type)
472 Type.__init__(self, type.expr + ' *')
477 def visit(self, visitor, *args, **kwargs):
478 return visitor.visitString(self, *args, **kwargs)
482 '''Opaque pointer.'''
484 def __init__(self, expr):
485 Type.__init__(self, expr)
487 def visit(self, visitor, *args, **kwargs):
488 return visitor.visitOpaque(self, *args, **kwargs)
491 def OpaquePointer(type, *args):
492 return Opaque(type.expr + ' *')
494 def OpaqueArray(type, size):
495 return Opaque(type.expr + ' *')
497 def OpaqueBlob(type, size):
498 return Opaque(type.expr + ' *')
501 class Polymorphic(Type):
503 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
504 if defaultType is None:
505 Type.__init__(self, None)
508 Type.__init__(self, defaultType.expr)
509 self.switchExpr = switchExpr
510 self.switchTypes = switchTypes
511 self.defaultType = defaultType
512 self.contextLess = contextLess
514 def visit(self, visitor, *args, **kwargs):
515 return visitor.visitPolymorphic(self, *args, **kwargs)
517 def iterSwitch(self):
521 if self.defaultType is not None:
522 cases.append(['default'])
523 types.append(self.defaultType)
525 for expr, type in self.switchTypes:
526 case = 'case %s' % expr
528 i = types.index(type)
533 cases[i].append(case)
535 return zip(cases, types)
538 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
539 enumValues = [expr for expr, type in switchTypes]
540 enum = Enum(enumName, enumValues)
541 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
542 return enum, polymorphic
546 '''Abstract visitor for the type hierarchy.'''
548 def visit(self, type, *args, **kwargs):
549 return type.visit(self, *args, **kwargs)
551 def visitVoid(self, void, *args, **kwargs):
552 raise NotImplementedError
554 def visitLiteral(self, literal, *args, **kwargs):
555 raise NotImplementedError
557 def visitString(self, string, *args, **kwargs):
558 raise NotImplementedError
560 def visitConst(self, const, *args, **kwargs):
561 raise NotImplementedError
563 def visitStruct(self, struct, *args, **kwargs):
564 raise NotImplementedError
566 def visitArray(self, array, *args, **kwargs):
567 raise NotImplementedError
569 def visitBlob(self, blob, *args, **kwargs):
570 raise NotImplementedError
572 def visitEnum(self, enum, *args, **kwargs):
573 raise NotImplementedError
575 def visitBitmask(self, bitmask, *args, **kwargs):
576 raise NotImplementedError
578 def visitPointer(self, pointer, *args, **kwargs):
579 raise NotImplementedError
581 def visitIntPointer(self, pointer, *args, **kwargs):
582 raise NotImplementedError
584 def visitObjPointer(self, pointer, *args, **kwargs):
585 raise NotImplementedError
587 def visitLinearPointer(self, pointer, *args, **kwargs):
588 raise NotImplementedError
590 def visitReference(self, reference, *args, **kwargs):
591 raise NotImplementedError
593 def visitHandle(self, handle, *args, **kwargs):
594 raise NotImplementedError
596 def visitAlias(self, alias, *args, **kwargs):
597 raise NotImplementedError
599 def visitOpaque(self, opaque, *args, **kwargs):
600 raise NotImplementedError
602 def visitInterface(self, interface, *args, **kwargs):
603 raise NotImplementedError
605 def visitPolymorphic(self, polymorphic, *args, **kwargs):
606 raise NotImplementedError
607 #return self.visit(polymorphic.defaultType, *args, **kwargs)
610 class OnceVisitor(Visitor):
611 '''Visitor that guarantees that each type is visited only once.'''
614 self.__visited = set()
616 def visit(self, type, *args, **kwargs):
617 if type not in self.__visited:
618 self.__visited.add(type)
619 return type.visit(self, *args, **kwargs)
623 class Rebuilder(Visitor):
624 '''Visitor which rebuild types as it visits them.
626 By itself it is a no-op -- it is intended to be overwritten.
629 def visitVoid(self, void):
632 def visitLiteral(self, literal):
635 def visitString(self, string):
636 string_type = self.visit(string.type)
637 if string_type is string.type:
640 return String(string_type, string.length, string.wide)
642 def visitConst(self, const):
643 const_type = self.visit(const.type)
644 if const_type is const.type:
647 return Const(const_type)
649 def visitStruct(self, struct):
650 members = [(self.visit(type), name) for type, name in struct.members]
651 return Struct(struct.name, members)
653 def visitArray(self, array):
654 type = self.visit(array.type)
655 return Array(type, array.length)
657 def visitBlob(self, blob):
658 type = self.visit(blob.type)
659 return Blob(type, blob.size)
661 def visitEnum(self, enum):
664 def visitBitmask(self, bitmask):
665 type = self.visit(bitmask.type)
666 return Bitmask(type, bitmask.values)
668 def visitPointer(self, pointer):
669 pointer_type = self.visit(pointer.type)
670 if pointer_type is pointer.type:
673 return Pointer(pointer_type)
675 def visitIntPointer(self, pointer):
678 def visitObjPointer(self, pointer):
679 pointer_type = self.visit(pointer.type)
680 if pointer_type is pointer.type:
683 return ObjPointer(pointer_type)
685 def visitLinearPointer(self, pointer):
686 pointer_type = self.visit(pointer.type)
687 if pointer_type is pointer.type:
690 return LinearPointer(pointer_type)
692 def visitReference(self, reference):
693 reference_type = self.visit(reference.type)
694 if reference_type is reference.type:
697 return Reference(reference_type)
699 def visitHandle(self, handle):
700 handle_type = self.visit(handle.type)
701 if handle_type is handle.type:
704 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
706 def visitAlias(self, alias):
707 alias_type = self.visit(alias.type)
708 if alias_type is alias.type:
711 return Alias(alias.expr, alias_type)
713 def visitOpaque(self, opaque):
716 def visitInterface(self, interface, *args, **kwargs):
719 def visitPolymorphic(self, polymorphic):
720 switchExpr = polymorphic.switchExpr
721 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
722 if polymorphic.defaultType is None:
725 defaultType = self.visit(polymorphic.defaultType)
726 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
729 class MutableRebuilder(Rebuilder):
730 '''Type visitor which derives a mutable type.'''
732 def visitString(self, string):
735 def visitConst(self, const):
736 # Strip out const qualifier
739 def visitAlias(self, alias):
740 # Tear the alias on type changes
741 type = self.visit(alias.type)
742 if type is alias.type:
746 def visitReference(self, reference):
747 # Strip out references
748 return reference.type
751 class Traverser(Visitor):
752 '''Visitor which all types.'''
754 def visitVoid(self, void, *args, **kwargs):
757 def visitLiteral(self, literal, *args, **kwargs):
760 def visitString(self, string, *args, **kwargs):
763 def visitConst(self, const, *args, **kwargs):
764 self.visit(const.type, *args, **kwargs)
766 def visitStruct(self, struct, *args, **kwargs):
767 for type, name in struct.members:
768 self.visit(type, *args, **kwargs)
770 def visitArray(self, array, *args, **kwargs):
771 self.visit(array.type, *args, **kwargs)
773 def visitBlob(self, array, *args, **kwargs):
776 def visitEnum(self, enum, *args, **kwargs):
779 def visitBitmask(self, bitmask, *args, **kwargs):
780 self.visit(bitmask.type, *args, **kwargs)
782 def visitPointer(self, pointer, *args, **kwargs):
783 self.visit(pointer.type, *args, **kwargs)
785 def visitIntPointer(self, pointer, *args, **kwargs):
788 def visitObjPointer(self, pointer, *args, **kwargs):
789 self.visit(pointer.type, *args, **kwargs)
791 def visitLinearPointer(self, pointer, *args, **kwargs):
792 self.visit(pointer.type, *args, **kwargs)
794 def visitReference(self, reference, *args, **kwargs):
795 self.visit(reference.type, *args, **kwargs)
797 def visitHandle(self, handle, *args, **kwargs):
798 self.visit(handle.type, *args, **kwargs)
800 def visitAlias(self, alias, *args, **kwargs):
801 self.visit(alias.type, *args, **kwargs)
803 def visitOpaque(self, opaque, *args, **kwargs):
806 def visitInterface(self, interface, *args, **kwargs):
807 if interface.base is not None:
808 self.visit(interface.base, *args, **kwargs)
809 for method in interface.iterMethods():
810 for arg in method.args:
811 self.visit(arg.type, *args, **kwargs)
812 self.visit(method.type, *args, **kwargs)
814 def visitPolymorphic(self, polymorphic, *args, **kwargs):
815 for expr, type in polymorphic.switchTypes:
816 self.visit(type, *args, **kwargs)
817 if polymorphic.defaultType is not None:
818 self.visit(polymorphic.defaultType, *args, **kwargs)
821 class Collector(Traverser):
822 '''Visitor which collects all unique types as it traverses them.'''
825 self.__visited = set()
828 def visit(self, type):
829 if type in self.__visited:
831 self.__visited.add(type)
832 Visitor.visit(self, type)
833 self.types.append(type)
837 '''Mixin class that provides a bunch of methods to expand C expressions
838 from the specifications.'''
843 def expand(self, expr):
844 # Expand a C expression, replacing certain variables
845 if not isinstance(expr, basestring):
849 if self.__structs is not None:
850 variables['self'] = '(%s)' % self.__structs[0]
851 if self.__indices is not None:
852 variables['i'] = self.__indices[0]
854 expandedExpr = expr.format(**variables)
855 if expandedExpr != expr and 0:
856 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
859 def visitMember(self, member, structInstance, *args, **kwargs):
860 memberType, memberName = member
861 if memberName is None:
862 # Anonymous structure/union member
863 memberInstance = structInstance
865 memberInstance = '(%s).%s' % (structInstance, memberName)
866 self.__structs = (structInstance, self.__structs)
868 return self.visit(memberType, memberInstance, *args, **kwargs)
870 _, self.__structs = self.__structs
872 def visitElement(self, elementIndex, elementType, *args, **kwargs):
873 self.__indices = (elementIndex, self.__indices)
875 return self.visit(elementType, *args, **kwargs)
877 _, self.__indices = self.__indices
881 '''A collection of functions.'''
883 def __init__(self, name = None):
889 def addFunctions(self, functions):
890 self.functions.extend(functions)
892 def addInterfaces(self, interfaces):
893 self.interfaces.extend(interfaces)
895 def mergeModule(self, module):
896 self.headers.extend(module.headers)
897 self.functions.extend(module.functions)
898 self.interfaces.extend(module.interfaces)
900 def getFunctionByName(self, name):
901 for function in self.functions:
902 if function.name == name:
910 Essentially, a collection of types, functions, and interfaces.
913 def __init__(self, modules = None):
915 if modules is not None:
916 self.modules.extend(modules)
918 def getAllTypes(self):
919 collector = Collector()
920 for module in self.modules:
921 for function in module.functions:
922 for arg in function.args:
923 collector.visit(arg.type)
924 collector.visit(function.type)
925 for interface in module.interfaces:
926 collector.visit(interface)
927 for method in interface.iterMethods():
928 for arg in method.args:
929 collector.visit(arg.type)
930 collector.visit(method.type)
931 return collector.types
933 def getAllFunctions(self):
935 for module in self.modules:
936 functions.extend(module.functions)
939 def getAllInterfaces(self):
940 types = self.getAllTypes()
941 interfaces = [type for type in types if isinstance(type, Interface)]
942 for module in self.modules:
943 for interface in module.interfaces:
944 if interface not in interfaces:
945 interfaces.append(interface)
948 def addModule(self, module):
949 self.modules.append(module)
951 def getFunctionByName(self, name):
952 for module in self.modules:
953 for function in module.functions:
954 if function.name == name:
959 # C string (i.e., zero terminated)
960 CString = String(Char)
961 WString = String(WChar, wide=True)
962 ConstCString = String(Const(Char))
963 ConstWString = String(Const(WChar), wide=True)