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):
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
284 def visit(self, visitor, *args, **kwargs):
285 return visitor.visitAttribArray(self, *args, **kwargs)
290 def __init__(self, type, size):
291 Type.__init__(self, type.expr + ' *')
295 def visit(self, visitor, *args, **kwargs):
296 return visitor.visitBlob(self, *args, **kwargs)
303 def __init__(self, name, members):
304 Type.__init__(self, name)
306 self.id = Struct.__id
310 self.members = members
312 def visit(self, visitor, *args, **kwargs):
313 return visitor.visitStruct(self, *args, **kwargs)
316 def Union(kindExpr, kindTypes, contextLess=True):
318 for kindCase, kindType, kindMemberName in kindTypes:
319 switchType = Struct(None, [(kindType, kindMemberName)])
320 switchTypes.append((kindCase, switchType))
321 return Polymorphic(kindExpr, switchTypes, contextLess=contextLess)
326 def __init__(self, expr, type):
327 Type.__init__(self, expr)
330 def visit(self, visitor, *args, **kwargs):
331 return visitor.visitAlias(self, *args, **kwargs)
335 def __init__(self, type, name, input=True, output=False):
343 return '%s %s' % (self.type, self.name)
347 return Arg(type, name, input=True, output=False)
350 return Arg(type, name, input=False, output=True)
352 def InOut(type, name):
353 return Arg(type, name, input=True, output=True)
358 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True, internal=False):
365 if not isinstance(arg, Arg):
366 if isinstance(arg, tuple):
367 arg_type, arg_name = arg
370 arg_name = "arg%u" % index
371 arg = Arg(arg_type, arg_name)
374 self.args.append(arg)
378 self.sideeffects = sideeffects
379 self.internal = internal
381 def prototype(self, name=None):
388 s = self.call + ' ' + s
389 if name.startswith('*'):
391 s = self.type.expr + ' ' + s
394 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
401 return [arg.name for arg in self.args]
403 def getArgByName(self, name):
404 for arg in self.args:
410 def StdFunction(*args, **kwargs):
411 kwargs.setdefault('call', '__stdcall')
412 return Function(*args, **kwargs)
415 def FunctionPointer(type, name, args, **kwargs):
416 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
420 class Interface(Type):
422 def __init__(self, name, base=None):
423 Type.__init__(self, name)
428 def visit(self, visitor, *args, **kwargs):
429 return visitor.visitInterface(self, *args, **kwargs)
431 def getMethodByName(self, name):
432 for method in self.iterMethods():
433 if method.name == name:
437 def iterMethods(self):
438 if self.base is not None:
439 for method in self.base.iterMethods():
441 for method in self.methods:
447 while iface is not None:
452 def hasBase(self, *bases):
453 for iface in self.iterBases():
458 def iterBaseMethods(self):
459 if self.base is not None:
460 for iface, method in self.base.iterBaseMethods():
462 for method in self.methods:
467 class Method(Function):
469 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
470 assert call == '__stdcall'
471 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
472 for index in range(len(self.args)):
473 self.args[index].index = index + 1
476 def prototype(self, name=None):
477 s = Function.prototype(self, name)
483 def StdMethod(*args, **kwargs):
484 kwargs.setdefault('call', '__stdcall')
485 return Method(*args, **kwargs)
489 '''Human-legible character string.'''
491 def __init__(self, type = Char, length = None, wide = False):
492 assert isinstance(type, Type)
493 Type.__init__(self, type.expr + ' *')
498 def visit(self, visitor, *args, **kwargs):
499 return visitor.visitString(self, *args, **kwargs)
503 '''Opaque pointer.'''
505 def __init__(self, expr):
506 Type.__init__(self, expr)
508 def visit(self, visitor, *args, **kwargs):
509 return visitor.visitOpaque(self, *args, **kwargs)
512 def OpaquePointer(type, *args):
513 return Opaque(type.expr + ' *')
515 def OpaqueArray(type, size):
516 return Opaque(type.expr + ' *')
518 def OpaqueBlob(type, size):
519 return Opaque(type.expr + ' *')
522 class Polymorphic(Type):
524 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
525 if defaultType is None:
526 Type.__init__(self, None)
529 Type.__init__(self, defaultType.expr)
530 self.switchExpr = switchExpr
531 self.switchTypes = switchTypes
532 self.defaultType = defaultType
533 self.contextLess = contextLess
535 def visit(self, visitor, *args, **kwargs):
536 return visitor.visitPolymorphic(self, *args, **kwargs)
538 def iterSwitch(self):
542 if self.defaultType is not None:
543 cases.append(['default'])
544 types.append(self.defaultType)
546 for expr, type in self.switchTypes:
547 case = 'case %s' % expr
549 i = types.index(type)
554 cases[i].append(case)
556 return zip(cases, types)
559 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
560 enumValues = [expr for expr, type in switchTypes]
561 enum = Enum(enumName, enumValues)
562 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
563 return enum, polymorphic
567 '''Abstract visitor for the type hierarchy.'''
569 def visit(self, type, *args, **kwargs):
570 return type.visit(self, *args, **kwargs)
572 def visitVoid(self, void, *args, **kwargs):
573 raise NotImplementedError
575 def visitLiteral(self, literal, *args, **kwargs):
576 raise NotImplementedError
578 def visitString(self, string, *args, **kwargs):
579 raise NotImplementedError
581 def visitConst(self, const, *args, **kwargs):
582 raise NotImplementedError
584 def visitStruct(self, struct, *args, **kwargs):
585 raise NotImplementedError
587 def visitArray(self, array, *args, **kwargs):
588 raise NotImplementedError
590 def visitAttribArray(self, array, *args, **kwargs):
591 raise NotImplementedError
593 def visitBlob(self, blob, *args, **kwargs):
594 raise NotImplementedError
596 def visitEnum(self, enum, *args, **kwargs):
597 raise NotImplementedError
599 def visitBitmask(self, bitmask, *args, **kwargs):
600 raise NotImplementedError
602 def visitPointer(self, pointer, *args, **kwargs):
603 raise NotImplementedError
605 def visitIntPointer(self, pointer, *args, **kwargs):
606 raise NotImplementedError
608 def visitObjPointer(self, pointer, *args, **kwargs):
609 raise NotImplementedError
611 def visitLinearPointer(self, pointer, *args, **kwargs):
612 raise NotImplementedError
614 def visitReference(self, reference, *args, **kwargs):
615 raise NotImplementedError
617 def visitHandle(self, handle, *args, **kwargs):
618 raise NotImplementedError
620 def visitAlias(self, alias, *args, **kwargs):
621 raise NotImplementedError
623 def visitOpaque(self, opaque, *args, **kwargs):
624 raise NotImplementedError
626 def visitInterface(self, interface, *args, **kwargs):
627 raise NotImplementedError
629 def visitPolymorphic(self, polymorphic, *args, **kwargs):
630 raise NotImplementedError
631 #return self.visit(polymorphic.defaultType, *args, **kwargs)
634 class OnceVisitor(Visitor):
635 '''Visitor that guarantees that each type is visited only once.'''
638 self.__visited = set()
640 def visit(self, type, *args, **kwargs):
641 if type not in self.__visited:
642 self.__visited.add(type)
643 return type.visit(self, *args, **kwargs)
647 class Rebuilder(Visitor):
648 '''Visitor which rebuild types as it visits them.
650 By itself it is a no-op -- it is intended to be overwritten.
653 def visitVoid(self, void):
656 def visitLiteral(self, literal):
659 def visitString(self, string):
660 string_type = self.visit(string.type)
661 if string_type is string.type:
664 return String(string_type, string.length, string.wide)
666 def visitConst(self, const):
667 const_type = self.visit(const.type)
668 if const_type is const.type:
671 return Const(const_type)
673 def visitStruct(self, struct):
674 members = [(self.visit(type), name) for type, name in struct.members]
675 return Struct(struct.name, members)
677 def visitArray(self, array):
678 type = self.visit(array.type)
679 return Array(type, array.length)
681 def visitBlob(self, blob):
682 type = self.visit(blob.type)
683 return Blob(type, blob.size)
685 def visitEnum(self, enum):
688 def visitBitmask(self, bitmask):
689 type = self.visit(bitmask.type)
690 return Bitmask(type, bitmask.values)
692 def visitPointer(self, pointer):
693 pointer_type = self.visit(pointer.type)
694 if pointer_type is pointer.type:
697 return Pointer(pointer_type)
699 def visitIntPointer(self, pointer):
702 def visitObjPointer(self, pointer):
703 pointer_type = self.visit(pointer.type)
704 if pointer_type is pointer.type:
707 return ObjPointer(pointer_type)
709 def visitLinearPointer(self, pointer):
710 pointer_type = self.visit(pointer.type)
711 if pointer_type is pointer.type:
714 return LinearPointer(pointer_type)
716 def visitReference(self, reference):
717 reference_type = self.visit(reference.type)
718 if reference_type is reference.type:
721 return Reference(reference_type)
723 def visitHandle(self, handle):
724 handle_type = self.visit(handle.type)
725 if handle_type is handle.type:
728 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
730 def visitAlias(self, alias):
731 alias_type = self.visit(alias.type)
732 if alias_type is alias.type:
735 return Alias(alias.expr, alias_type)
737 def visitOpaque(self, opaque):
740 def visitInterface(self, interface, *args, **kwargs):
743 def visitPolymorphic(self, polymorphic):
744 switchExpr = polymorphic.switchExpr
745 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
746 if polymorphic.defaultType is None:
749 defaultType = self.visit(polymorphic.defaultType)
750 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
753 class MutableRebuilder(Rebuilder):
754 '''Type visitor which derives a mutable type.'''
756 def visitString(self, string):
759 def visitConst(self, const):
760 # Strip out const qualifier
763 def visitAlias(self, alias):
764 # Tear the alias on type changes
765 type = self.visit(alias.type)
766 if type is alias.type:
770 def visitReference(self, reference):
771 # Strip out references
772 return reference.type
775 class Traverser(Visitor):
776 '''Visitor which all types.'''
778 def visitVoid(self, void, *args, **kwargs):
781 def visitLiteral(self, literal, *args, **kwargs):
784 def visitString(self, string, *args, **kwargs):
787 def visitConst(self, const, *args, **kwargs):
788 self.visit(const.type, *args, **kwargs)
790 def visitStruct(self, struct, *args, **kwargs):
791 for type, name in struct.members:
792 self.visit(type, *args, **kwargs)
794 def visitArray(self, array, *args, **kwargs):
795 self.visit(array.type, *args, **kwargs)
797 def visitAttribArray(self, attribs, *args, **kwargs):
798 for key, valueType in attribs.valueTypes:
799 self.visit(valueType, *args, **kwargs)
801 def visitBlob(self, array, *args, **kwargs):
804 def visitEnum(self, enum, *args, **kwargs):
807 def visitBitmask(self, bitmask, *args, **kwargs):
808 self.visit(bitmask.type, *args, **kwargs)
810 def visitPointer(self, pointer, *args, **kwargs):
811 self.visit(pointer.type, *args, **kwargs)
813 def visitIntPointer(self, pointer, *args, **kwargs):
816 def visitObjPointer(self, pointer, *args, **kwargs):
817 self.visit(pointer.type, *args, **kwargs)
819 def visitLinearPointer(self, pointer, *args, **kwargs):
820 self.visit(pointer.type, *args, **kwargs)
822 def visitReference(self, reference, *args, **kwargs):
823 self.visit(reference.type, *args, **kwargs)
825 def visitHandle(self, handle, *args, **kwargs):
826 self.visit(handle.type, *args, **kwargs)
828 def visitAlias(self, alias, *args, **kwargs):
829 self.visit(alias.type, *args, **kwargs)
831 def visitOpaque(self, opaque, *args, **kwargs):
834 def visitInterface(self, interface, *args, **kwargs):
835 if interface.base is not None:
836 self.visit(interface.base, *args, **kwargs)
837 for method in interface.iterMethods():
838 for arg in method.args:
839 self.visit(arg.type, *args, **kwargs)
840 self.visit(method.type, *args, **kwargs)
842 def visitPolymorphic(self, polymorphic, *args, **kwargs):
843 for expr, type in polymorphic.switchTypes:
844 self.visit(type, *args, **kwargs)
845 if polymorphic.defaultType is not None:
846 self.visit(polymorphic.defaultType, *args, **kwargs)
849 class Collector(Traverser):
850 '''Visitor which collects all unique types as it traverses them.'''
853 self.__visited = set()
856 def visit(self, type):
857 if type in self.__visited:
859 self.__visited.add(type)
860 Visitor.visit(self, type)
861 self.types.append(type)
865 '''Mixin class that provides a bunch of methods to expand C expressions
866 from the specifications.'''
871 def expand(self, expr):
872 # Expand a C expression, replacing certain variables
873 if not isinstance(expr, basestring):
877 if self.__structs is not None:
878 variables['self'] = '(%s)' % self.__structs[0]
879 if self.__indices is not None:
880 variables['i'] = self.__indices[0]
882 expandedExpr = expr.format(**variables)
883 if expandedExpr != expr and 0:
884 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
887 def visitMember(self, member, structInstance, *args, **kwargs):
888 memberType, memberName = member
889 if memberName is None:
890 # Anonymous structure/union member
891 memberInstance = structInstance
893 memberInstance = '(%s).%s' % (structInstance, memberName)
894 self.__structs = (structInstance, self.__structs)
896 return self.visit(memberType, memberInstance, *args, **kwargs)
898 _, self.__structs = self.__structs
900 def visitElement(self, elementIndex, elementType, *args, **kwargs):
901 self.__indices = (elementIndex, self.__indices)
903 return self.visit(elementType, *args, **kwargs)
905 _, self.__indices = self.__indices
909 '''A collection of functions.'''
911 def __init__(self, name = None):
917 def addFunctions(self, functions):
918 self.functions.extend(functions)
920 def addInterfaces(self, interfaces):
921 self.interfaces.extend(interfaces)
923 def mergeModule(self, module):
924 self.headers.extend(module.headers)
925 self.functions.extend(module.functions)
926 self.interfaces.extend(module.interfaces)
928 def getFunctionByName(self, name):
929 for function in self.functions:
930 if function.name == name:
938 Essentially, a collection of types, functions, and interfaces.
941 def __init__(self, modules = None):
943 if modules is not None:
944 self.modules.extend(modules)
946 def getAllTypes(self):
947 collector = Collector()
948 for module in self.modules:
949 for function in module.functions:
950 for arg in function.args:
951 collector.visit(arg.type)
952 collector.visit(function.type)
953 for interface in module.interfaces:
954 collector.visit(interface)
955 for method in interface.iterMethods():
956 for arg in method.args:
957 collector.visit(arg.type)
958 collector.visit(method.type)
959 return collector.types
961 def getAllFunctions(self):
963 for module in self.modules:
964 functions.extend(module.functions)
967 def getAllInterfaces(self):
968 types = self.getAllTypes()
969 interfaces = [type for type in types if isinstance(type, Interface)]
970 for module in self.modules:
971 for interface in module.interfaces:
972 if interface not in interfaces:
973 interfaces.append(interface)
976 def addModule(self, module):
977 self.modules.append(module)
979 def getFunctionByName(self, name):
980 for module in self.modules:
981 for function in module.functions:
982 if function.name == name:
987 # C string (i.e., zero terminated)
988 CString = String(Char)
989 WString = String(WChar, wide=True)
990 ConstCString = String(Const(Char))
991 ConstWString = String(Const(WChar), wide=True)