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 hasBase(self, *bases):
438 for iface in self.iterBases():
443 def iterBaseMethods(self):
444 if self.base is not None:
445 for iface, method in self.base.iterBaseMethods():
447 for method in self.methods:
452 class Method(Function):
454 def __init__(self, type, name, args, call = '', const=False, sideeffects=True):
455 assert call == '__stdcall'
456 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
457 for index in range(len(self.args)):
458 self.args[index].index = index + 1
461 def prototype(self, name=None):
462 s = Function.prototype(self, name)
468 def StdMethod(*args, **kwargs):
469 kwargs.setdefault('call', '__stdcall')
470 return Method(*args, **kwargs)
474 '''Human-legible character string.'''
476 def __init__(self, type = Char, length = None, wide = False):
477 assert isinstance(type, Type)
478 Type.__init__(self, type.expr + ' *')
483 def visit(self, visitor, *args, **kwargs):
484 return visitor.visitString(self, *args, **kwargs)
488 '''Opaque pointer.'''
490 def __init__(self, expr):
491 Type.__init__(self, expr)
493 def visit(self, visitor, *args, **kwargs):
494 return visitor.visitOpaque(self, *args, **kwargs)
497 def OpaquePointer(type, *args):
498 return Opaque(type.expr + ' *')
500 def OpaqueArray(type, size):
501 return Opaque(type.expr + ' *')
503 def OpaqueBlob(type, size):
504 return Opaque(type.expr + ' *')
507 class Polymorphic(Type):
509 def __init__(self, switchExpr, switchTypes, defaultType=None, contextLess=True):
510 if defaultType is None:
511 Type.__init__(self, None)
514 Type.__init__(self, defaultType.expr)
515 self.switchExpr = switchExpr
516 self.switchTypes = switchTypes
517 self.defaultType = defaultType
518 self.contextLess = contextLess
520 def visit(self, visitor, *args, **kwargs):
521 return visitor.visitPolymorphic(self, *args, **kwargs)
523 def iterSwitch(self):
527 if self.defaultType is not None:
528 cases.append(['default'])
529 types.append(self.defaultType)
531 for expr, type in self.switchTypes:
532 case = 'case %s' % expr
534 i = types.index(type)
539 cases[i].append(case)
541 return zip(cases, types)
544 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
545 enumValues = [expr for expr, type in switchTypes]
546 enum = Enum(enumName, enumValues)
547 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
548 return enum, polymorphic
552 '''Abstract visitor for the type hierarchy.'''
554 def visit(self, type, *args, **kwargs):
555 return type.visit(self, *args, **kwargs)
557 def visitVoid(self, void, *args, **kwargs):
558 raise NotImplementedError
560 def visitLiteral(self, literal, *args, **kwargs):
561 raise NotImplementedError
563 def visitString(self, string, *args, **kwargs):
564 raise NotImplementedError
566 def visitConst(self, const, *args, **kwargs):
567 raise NotImplementedError
569 def visitStruct(self, struct, *args, **kwargs):
570 raise NotImplementedError
572 def visitArray(self, array, *args, **kwargs):
573 raise NotImplementedError
575 def visitBlob(self, blob, *args, **kwargs):
576 raise NotImplementedError
578 def visitEnum(self, enum, *args, **kwargs):
579 raise NotImplementedError
581 def visitBitmask(self, bitmask, *args, **kwargs):
582 raise NotImplementedError
584 def visitPointer(self, pointer, *args, **kwargs):
585 raise NotImplementedError
587 def visitIntPointer(self, pointer, *args, **kwargs):
588 raise NotImplementedError
590 def visitObjPointer(self, pointer, *args, **kwargs):
591 raise NotImplementedError
593 def visitLinearPointer(self, pointer, *args, **kwargs):
594 raise NotImplementedError
596 def visitReference(self, reference, *args, **kwargs):
597 raise NotImplementedError
599 def visitHandle(self, handle, *args, **kwargs):
600 raise NotImplementedError
602 def visitAlias(self, alias, *args, **kwargs):
603 raise NotImplementedError
605 def visitOpaque(self, opaque, *args, **kwargs):
606 raise NotImplementedError
608 def visitInterface(self, interface, *args, **kwargs):
609 raise NotImplementedError
611 def visitPolymorphic(self, polymorphic, *args, **kwargs):
612 raise NotImplementedError
613 #return self.visit(polymorphic.defaultType, *args, **kwargs)
616 class OnceVisitor(Visitor):
617 '''Visitor that guarantees that each type is visited only once.'''
620 self.__visited = set()
622 def visit(self, type, *args, **kwargs):
623 if type not in self.__visited:
624 self.__visited.add(type)
625 return type.visit(self, *args, **kwargs)
629 class Rebuilder(Visitor):
630 '''Visitor which rebuild types as it visits them.
632 By itself it is a no-op -- it is intended to be overwritten.
635 def visitVoid(self, void):
638 def visitLiteral(self, literal):
641 def visitString(self, string):
642 string_type = self.visit(string.type)
643 if string_type is string.type:
646 return String(string_type, string.length, string.wide)
648 def visitConst(self, const):
649 const_type = self.visit(const.type)
650 if const_type is const.type:
653 return Const(const_type)
655 def visitStruct(self, struct):
656 members = [(self.visit(type), name) for type, name in struct.members]
657 return Struct(struct.name, members)
659 def visitArray(self, array):
660 type = self.visit(array.type)
661 return Array(type, array.length)
663 def visitBlob(self, blob):
664 type = self.visit(blob.type)
665 return Blob(type, blob.size)
667 def visitEnum(self, enum):
670 def visitBitmask(self, bitmask):
671 type = self.visit(bitmask.type)
672 return Bitmask(type, bitmask.values)
674 def visitPointer(self, pointer):
675 pointer_type = self.visit(pointer.type)
676 if pointer_type is pointer.type:
679 return Pointer(pointer_type)
681 def visitIntPointer(self, pointer):
684 def visitObjPointer(self, pointer):
685 pointer_type = self.visit(pointer.type)
686 if pointer_type is pointer.type:
689 return ObjPointer(pointer_type)
691 def visitLinearPointer(self, pointer):
692 pointer_type = self.visit(pointer.type)
693 if pointer_type is pointer.type:
696 return LinearPointer(pointer_type)
698 def visitReference(self, reference):
699 reference_type = self.visit(reference.type)
700 if reference_type is reference.type:
703 return Reference(reference_type)
705 def visitHandle(self, handle):
706 handle_type = self.visit(handle.type)
707 if handle_type is handle.type:
710 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
712 def visitAlias(self, alias):
713 alias_type = self.visit(alias.type)
714 if alias_type is alias.type:
717 return Alias(alias.expr, alias_type)
719 def visitOpaque(self, opaque):
722 def visitInterface(self, interface, *args, **kwargs):
725 def visitPolymorphic(self, polymorphic):
726 switchExpr = polymorphic.switchExpr
727 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
728 if polymorphic.defaultType is None:
731 defaultType = self.visit(polymorphic.defaultType)
732 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
735 class MutableRebuilder(Rebuilder):
736 '''Type visitor which derives a mutable type.'''
738 def visitString(self, string):
741 def visitConst(self, const):
742 # Strip out const qualifier
745 def visitAlias(self, alias):
746 # Tear the alias on type changes
747 type = self.visit(alias.type)
748 if type is alias.type:
752 def visitReference(self, reference):
753 # Strip out references
754 return reference.type
757 class Traverser(Visitor):
758 '''Visitor which all types.'''
760 def visitVoid(self, void, *args, **kwargs):
763 def visitLiteral(self, literal, *args, **kwargs):
766 def visitString(self, string, *args, **kwargs):
769 def visitConst(self, const, *args, **kwargs):
770 self.visit(const.type, *args, **kwargs)
772 def visitStruct(self, struct, *args, **kwargs):
773 for type, name in struct.members:
774 self.visit(type, *args, **kwargs)
776 def visitArray(self, array, *args, **kwargs):
777 self.visit(array.type, *args, **kwargs)
779 def visitBlob(self, array, *args, **kwargs):
782 def visitEnum(self, enum, *args, **kwargs):
785 def visitBitmask(self, bitmask, *args, **kwargs):
786 self.visit(bitmask.type, *args, **kwargs)
788 def visitPointer(self, pointer, *args, **kwargs):
789 self.visit(pointer.type, *args, **kwargs)
791 def visitIntPointer(self, pointer, *args, **kwargs):
794 def visitObjPointer(self, pointer, *args, **kwargs):
795 self.visit(pointer.type, *args, **kwargs)
797 def visitLinearPointer(self, pointer, *args, **kwargs):
798 self.visit(pointer.type, *args, **kwargs)
800 def visitReference(self, reference, *args, **kwargs):
801 self.visit(reference.type, *args, **kwargs)
803 def visitHandle(self, handle, *args, **kwargs):
804 self.visit(handle.type, *args, **kwargs)
806 def visitAlias(self, alias, *args, **kwargs):
807 self.visit(alias.type, *args, **kwargs)
809 def visitOpaque(self, opaque, *args, **kwargs):
812 def visitInterface(self, interface, *args, **kwargs):
813 if interface.base is not None:
814 self.visit(interface.base, *args, **kwargs)
815 for method in interface.iterMethods():
816 for arg in method.args:
817 self.visit(arg.type, *args, **kwargs)
818 self.visit(method.type, *args, **kwargs)
820 def visitPolymorphic(self, polymorphic, *args, **kwargs):
821 for expr, type in polymorphic.switchTypes:
822 self.visit(type, *args, **kwargs)
823 if polymorphic.defaultType is not None:
824 self.visit(polymorphic.defaultType, *args, **kwargs)
827 class Collector(Traverser):
828 '''Visitor which collects all unique types as it traverses them.'''
831 self.__visited = set()
834 def visit(self, type):
835 if type in self.__visited:
837 self.__visited.add(type)
838 Visitor.visit(self, type)
839 self.types.append(type)
843 '''Mixin class that provides a bunch of methods to expand C expressions
844 from the specifications.'''
849 def expand(self, expr):
850 # Expand a C expression, replacing certain variables
851 if not isinstance(expr, basestring):
855 if self.__structs is not None:
856 variables['self'] = '(%s)' % self.__structs[0]
857 if self.__indices is not None:
858 variables['i'] = self.__indices[0]
860 expandedExpr = expr.format(**variables)
861 if expandedExpr != expr and 0:
862 sys.stderr.write(" %r -> %r\n" % (expr, expandedExpr))
865 def visitMember(self, member, structInstance, *args, **kwargs):
866 memberType, memberName = member
867 if memberName is None:
868 # Anonymous structure/union member
869 memberInstance = structInstance
871 memberInstance = '(%s).%s' % (structInstance, memberName)
872 self.__structs = (structInstance, self.__structs)
874 return self.visit(memberType, memberInstance, *args, **kwargs)
876 _, self.__structs = self.__structs
878 def visitElement(self, elementIndex, elementType, *args, **kwargs):
879 self.__indices = (elementIndex, self.__indices)
881 return self.visit(elementType, *args, **kwargs)
883 _, self.__indices = self.__indices
887 '''A collection of functions.'''
889 def __init__(self, name = None):
895 def addFunctions(self, functions):
896 self.functions.extend(functions)
898 def addInterfaces(self, interfaces):
899 self.interfaces.extend(interfaces)
901 def mergeModule(self, module):
902 self.headers.extend(module.headers)
903 self.functions.extend(module.functions)
904 self.interfaces.extend(module.interfaces)
906 def getFunctionByName(self, name):
907 for function in self.functions:
908 if function.name == name:
916 Essentially, a collection of types, functions, and interfaces.
919 def __init__(self, modules = None):
921 if modules is not None:
922 self.modules.extend(modules)
924 def getAllTypes(self):
925 collector = Collector()
926 for module in self.modules:
927 for function in module.functions:
928 for arg in function.args:
929 collector.visit(arg.type)
930 collector.visit(function.type)
931 for interface in module.interfaces:
932 collector.visit(interface)
933 for method in interface.iterMethods():
934 for arg in method.args:
935 collector.visit(arg.type)
936 collector.visit(method.type)
937 return collector.types
939 def getAllFunctions(self):
941 for module in self.modules:
942 functions.extend(module.functions)
945 def getAllInterfaces(self):
946 types = self.getAllTypes()
947 interfaces = [type for type in types if isinstance(type, Interface)]
948 for module in self.modules:
949 for interface in module.interfaces:
950 if interface not in interfaces:
951 interfaces.append(interface)
954 def addModule(self, module):
955 self.modules.append(module)
957 def getFunctionByName(self, name):
958 for module in self.modules:
959 for function in module.functions:
960 if function.name == name:
965 # C string (i.e., zero terminated)
966 CString = String(Char)
967 WString = String(WChar, wide=True)
968 ConstCString = String(Const(Char))
969 ConstWString = String(Const(WChar), wide=True)