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]
389 def StdFunction(*args, **kwargs):
390 kwargs.setdefault('call', '__stdcall')
391 return Function(*args, **kwargs)
394 def FunctionPointer(type, name, args, **kwargs):
395 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
399 class Interface(Type):
401 def __init__(self, name, base=None):
402 Type.__init__(self, name)
407 def visit(self, visitor, *args, **kwargs):
408 return visitor.visitInterface(self, *args, **kwargs)
410 def getMethodByName(self, name):
411 for method in self.iterMethods():
412 if method.name == name:
416 def iterMethods(self):
417 if self.base is not None:
418 for method in self.base.iterMethods():
420 for method in self.methods:
426 while iface is not None:
431 def iterBaseMethods(self):
432 if self.base is not None:
433 for iface, method in self.base.iterBaseMethods():
435 for method in self.methods:
440 class Method(Function):
442 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
443 assert call == '__stdcall'
444 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
445 for index in range(len(self.args)):
446 self.args[index].index = index + 1
449 def prototype(self, name=None):
450 s = Function.prototype(self, name)
456 def StdMethod(*args, **kwargs):
457 kwargs.setdefault('call', '__stdcall')
458 return Method(*args, **kwargs)
462 '''Human-legible character string.'''
464 def __init__(self, type = Char, length = None, wide = False):
465 assert isinstance(type, Type)
466 Type.__init__(self, type.expr + ' *')
471 def visit(self, visitor, *args, **kwargs):
472 return visitor.visitString(self, *args, **kwargs)
476 '''Opaque pointer.'''
478 def __init__(self, expr):
479 Type.__init__(self, expr)
481 def visit(self, visitor, *args, **kwargs):
482 return visitor.visitOpaque(self, *args, **kwargs)
485 def OpaquePointer(type, *args):
486 return Opaque(type.expr + ' *')
488 def OpaqueArray(type, size):
489 return Opaque(type.expr + ' *')
491 def OpaqueBlob(type, size):
492 return Opaque(type.expr + ' *')
495 class Polymorphic(Type):
497 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
498 if defaultType is None:
499 Type.__init__(self, None)
502 Type.__init__(self, defaultType.expr)
503 self.switchExpr = switchExpr
504 self.switchTypes = switchTypes
505 self.defaultType = defaultType
506 self.contextLess = contextLess
508 def visit(self, visitor, *args, **kwargs):
509 return visitor.visitPolymorphic(self, *args, **kwargs)
511 def iterSwitch(self):
515 if self.defaultType is not None:
516 cases.append(['default'])
517 types.append(self.defaultType)
519 for expr, type in self.switchTypes:
520 case = 'case %s' % expr
522 i = types.index(type)
527 cases[i].append(case)
529 return zip(cases, types)
532 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
533 enumValues = [expr for expr, type in switchTypes]
534 enum = Enum(enumName, enumValues)
535 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
536 return enum, polymorphic
540 '''Abstract visitor for the type hierarchy.'''
542 def visit(self, type, *args, **kwargs):
543 return type.visit(self, *args, **kwargs)
545 def visitVoid(self, void, *args, **kwargs):
546 raise NotImplementedError
548 def visitLiteral(self, literal, *args, **kwargs):
549 raise NotImplementedError
551 def visitString(self, string, *args, **kwargs):
552 raise NotImplementedError
554 def visitConst(self, const, *args, **kwargs):
555 raise NotImplementedError
557 def visitStruct(self, struct, *args, **kwargs):
558 raise NotImplementedError
560 def visitArray(self, array, *args, **kwargs):
561 raise NotImplementedError
563 def visitBlob(self, blob, *args, **kwargs):
564 raise NotImplementedError
566 def visitEnum(self, enum, *args, **kwargs):
567 raise NotImplementedError
569 def visitBitmask(self, bitmask, *args, **kwargs):
570 raise NotImplementedError
572 def visitPointer(self, pointer, *args, **kwargs):
573 raise NotImplementedError
575 def visitIntPointer(self, pointer, *args, **kwargs):
576 raise NotImplementedError
578 def visitObjPointer(self, pointer, *args, **kwargs):
579 raise NotImplementedError
581 def visitLinearPointer(self, pointer, *args, **kwargs):
582 raise NotImplementedError
584 def visitReference(self, reference, *args, **kwargs):
585 raise NotImplementedError
587 def visitHandle(self, handle, *args, **kwargs):
588 raise NotImplementedError
590 def visitAlias(self, alias, *args, **kwargs):
591 raise NotImplementedError
593 def visitOpaque(self, opaque, *args, **kwargs):
594 raise NotImplementedError
596 def visitInterface(self, interface, *args, **kwargs):
597 raise NotImplementedError
599 def visitPolymorphic(self, polymorphic, *args, **kwargs):
600 raise NotImplementedError
601 #return self.visit(polymorphic.defaultType, *args, **kwargs)
604 class OnceVisitor(Visitor):
605 '''Visitor that guarantees that each type is visited only once.'''
608 self.__visited = set()
610 def visit(self, type, *args, **kwargs):
611 if type not in self.__visited:
612 self.__visited.add(type)
613 return type.visit(self, *args, **kwargs)
617 class Rebuilder(Visitor):
618 '''Visitor which rebuild types as it visits them.
620 By itself it is a no-op -- it is intended to be overwritten.
623 def visitVoid(self, void):
626 def visitLiteral(self, literal):
629 def visitString(self, string):
630 string_type = self.visit(string.type)
631 if string_type is string.type:
634 return String(string_type, string.length, string.wide)
636 def visitConst(self, const):
637 const_type = self.visit(const.type)
638 if const_type is const.type:
641 return Const(const_type)
643 def visitStruct(self, struct):
644 members = [(self.visit(type), name) for type, name in struct.members]
645 return Struct(struct.name, members)
647 def visitArray(self, array):
648 type = self.visit(array.type)
649 return Array(type, array.length)
651 def visitBlob(self, blob):
652 type = self.visit(blob.type)
653 return Blob(type, blob.size)
655 def visitEnum(self, enum):
658 def visitBitmask(self, bitmask):
659 type = self.visit(bitmask.type)
660 return Bitmask(type, bitmask.values)
662 def visitPointer(self, pointer):
663 pointer_type = self.visit(pointer.type)
664 if pointer_type is pointer.type:
667 return Pointer(pointer_type)
669 def visitIntPointer(self, pointer):
672 def visitObjPointer(self, pointer):
673 pointer_type = self.visit(pointer.type)
674 if pointer_type is pointer.type:
677 return ObjPointer(pointer_type)
679 def visitLinearPointer(self, pointer):
680 pointer_type = self.visit(pointer.type)
681 if pointer_type is pointer.type:
684 return LinearPointer(pointer_type)
686 def visitReference(self, reference):
687 reference_type = self.visit(reference.type)
688 if reference_type is reference.type:
691 return Reference(reference_type)
693 def visitHandle(self, handle):
694 handle_type = self.visit(handle.type)
695 if handle_type is handle.type:
698 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
700 def visitAlias(self, alias):
701 alias_type = self.visit(alias.type)
702 if alias_type is alias.type:
705 return Alias(alias.expr, alias_type)
707 def visitOpaque(self, opaque):
710 def visitInterface(self, interface, *args, **kwargs):
713 def visitPolymorphic(self, polymorphic):
714 switchExpr = polymorphic.switchExpr
715 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
716 if polymorphic.defaultType is None:
719 defaultType = self.visit(polymorphic.defaultType)
720 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
723 class MutableRebuilder(Rebuilder):
724 '''Type visitor which derives a mutable type.'''
726 def visitString(self, string):
729 def visitConst(self, const):
730 # Strip out const qualifier
733 def visitAlias(self, alias):
734 # Tear the alias on type changes
735 type = self.visit(alias.type)
736 if type is alias.type:
740 def visitReference(self, reference):
741 # Strip out references
742 return reference.type
745 class Traverser(Visitor):
746 '''Visitor which all types.'''
748 def visitVoid(self, void, *args, **kwargs):
751 def visitLiteral(self, literal, *args, **kwargs):
754 def visitString(self, string, *args, **kwargs):
757 def visitConst(self, const, *args, **kwargs):
758 self.visit(const.type, *args, **kwargs)
760 def visitStruct(self, struct, *args, **kwargs):
761 for type, name in struct.members:
762 self.visit(type, *args, **kwargs)
764 def visitArray(self, array, *args, **kwargs):
765 self.visit(array.type, *args, **kwargs)
767 def visitBlob(self, array, *args, **kwargs):
770 def visitEnum(self, enum, *args, **kwargs):
773 def visitBitmask(self, bitmask, *args, **kwargs):
774 self.visit(bitmask.type, *args, **kwargs)
776 def visitPointer(self, pointer, *args, **kwargs):
777 self.visit(pointer.type, *args, **kwargs)
779 def visitIntPointer(self, pointer, *args, **kwargs):
782 def visitObjPointer(self, pointer, *args, **kwargs):
783 self.visit(pointer.type, *args, **kwargs)
785 def visitLinearPointer(self, pointer, *args, **kwargs):
786 self.visit(pointer.type, *args, **kwargs)
788 def visitReference(self, reference, *args, **kwargs):
789 self.visit(reference.type, *args, **kwargs)
791 def visitHandle(self, handle, *args, **kwargs):
792 self.visit(handle.type, *args, **kwargs)
794 def visitAlias(self, alias, *args, **kwargs):
795 self.visit(alias.type, *args, **kwargs)
797 def visitOpaque(self, opaque, *args, **kwargs):
800 def visitInterface(self, interface, *args, **kwargs):
801 if interface.base is not None:
802 self.visit(interface.base, *args, **kwargs)
803 for method in interface.iterMethods():
804 for arg in method.args:
805 self.visit(arg.type, *args, **kwargs)
806 self.visit(method.type, *args, **kwargs)
808 def visitPolymorphic(self, polymorphic, *args, **kwargs):
809 for expr, type in polymorphic.switchTypes:
810 self.visit(type, *args, **kwargs)
811 if polymorphic.defaultType is not None:
812 self.visit(polymorphic.defaultType, *args, **kwargs)
815 class Collector(Traverser):
816 '''Visitor which collects all unique types as it traverses them.'''
819 self.__visited = set()
822 def visit(self, type):
823 if type in self.__visited:
825 self.__visited.add(type)
826 Visitor.visit(self, type)
827 self.types.append(type)
831 '''Mixin class that provides a bunch of methods to expand C expressions
832 from the specifications.'''
837 def expand(self, expr):
838 # Expand a C expression, replacing certain variables
839 if not isinstance(expr, basestring):
843 if self.__structs is not None:
844 variables['self'] = '(%s)' % self.__structs[0]
845 if self.__indices is not None:
846 variables['i'] = self.__indices[0]
848 expandedExpr = expr.format(**variables)
849 if expandedExpr != expr and 0:
850 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
853 def visitMember(self, member, structInstance, *args, **kwargs):
854 memberType, memberName = member
855 if memberName is None:
856 # Anonymous structure/union member
857 memberInstance = structInstance
859 memberInstance = '(%s).%s' % (structInstance, memberName)
860 self.__structs = (structInstance, self.__structs)
862 return self.visit(memberType, memberInstance, *args, **kwargs)
864 _, self.__structs = self.__structs
866 def visitElement(self, elementIndex, elementType, *args, **kwargs):
867 self.__indices = (elementIndex, self.__indices)
869 return self.visit(elementType, *args, **kwargs)
871 _, self.__indices = self.__indices
875 '''A collection of functions.'''
877 def __init__(self, name = None):
883 def addFunctions(self, functions):
884 self.functions.extend(functions)
886 def addInterfaces(self, interfaces):
887 self.interfaces.extend(interfaces)
889 def mergeModule(self, module):
890 self.headers.extend(module.headers)
891 self.functions.extend(module.functions)
892 self.interfaces.extend(module.interfaces)
894 def getFunctionByName(self, name):
895 for function in self.functions:
896 if function.name == name:
904 Essentially, a collection of types, functions, and interfaces.
907 def __init__(self, modules = None):
909 if modules is not None:
910 self.modules.extend(modules)
912 def getAllTypes(self):
913 collector = Collector()
914 for module in self.modules:
915 for function in module.functions:
916 for arg in function.args:
917 collector.visit(arg.type)
918 collector.visit(function.type)
919 for interface in module.interfaces:
920 collector.visit(interface)
921 for method in interface.iterMethods():
922 for arg in method.args:
923 collector.visit(arg.type)
924 collector.visit(method.type)
925 return collector.types
927 def getAllFunctions(self):
929 for module in self.modules:
930 functions.extend(module.functions)
933 def getAllInterfaces(self):
934 types = self.getAllTypes()
935 interfaces = [type for type in types if isinstance(type, Interface)]
936 for module in self.modules:
937 for interface in module.interfaces:
938 if interface not in interfaces:
939 interfaces.append(interface)
942 def addModule(self, module):
943 self.modules.append(module)
945 def getFunctionByName(self, name):
946 for module in self.modules:
947 for function in module.functions:
948 if function.name == name:
953 # C string (i.e., zero terminated)
954 CString = String(Char)
955 WString = String(WChar, wide=True)
956 ConstCString = String(Const(Char))
957 ConstWString = String(Const(WChar), wide=True)