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)
107 def __init__(self, type):
108 # While "const foo" and "foo const" are synonymous, "const foo *" and
109 # "foo * const" are not quite the same, and some compilers do enforce
110 # strict const correctness.
111 if isinstance(type, String) or type is WString:
112 # For strings we never intend to say a const pointer to chars, but
113 # rather a point to const chars.
114 expr = "const " + type.expr
115 elif type.expr.startswith("const ") or '*' in type.expr:
116 expr = type.expr + " const"
119 expr = "const " + type.expr
121 Type.__init__(self, expr, 'C' + type.tag)
125 def visit(self, visitor, *args, **kwargs):
126 return visitor.visitConst(self, *args, **kwargs)
131 def __init__(self, type):
132 Type.__init__(self, type.expr + " *", 'P' + type.tag)
135 def visit(self, visitor, *args, **kwargs):
136 return visitor.visitPointer(self, *args, **kwargs)
139 class IntPointer(Type):
140 '''Integer encoded as a pointer.'''
142 def visit(self, visitor, *args, **kwargs):
143 return visitor.visitIntPointer(self, *args, **kwargs)
146 class ObjPointer(Type):
147 '''Pointer to an object.'''
149 def __init__(self, type):
150 Type.__init__(self, type.expr + " *", 'P' + type.tag)
153 def visit(self, visitor, *args, **kwargs):
154 return visitor.visitObjPointer(self, *args, **kwargs)
157 class LinearPointer(Type):
158 '''Pointer to a linear range of memory.'''
160 def __init__(self, type, size = None):
161 Type.__init__(self, type.expr + " *", 'P' + type.tag)
165 def visit(self, visitor, *args, **kwargs):
166 return visitor.visitLinearPointer(self, *args, **kwargs)
169 class Reference(Type):
170 '''C++ references.'''
172 def __init__(self, type):
173 Type.__init__(self, type.expr + " &", 'R' + type.tag)
176 def visit(self, visitor, *args, **kwargs):
177 return visitor.visitReference(self, *args, **kwargs)
182 def __init__(self, name, type, range=None, key=None):
183 Type.__init__(self, type.expr, 'P' + type.tag)
189 def visit(self, visitor, *args, **kwargs):
190 return visitor.visitHandle(self, *args, **kwargs)
193 def ConstPointer(type):
194 return Pointer(Const(type))
201 def __init__(self, name, values):
202 Type.__init__(self, name)
207 self.values = list(values)
209 def visit(self, visitor, *args, **kwargs):
210 return visitor.visitEnum(self, *args, **kwargs)
213 def FakeEnum(type, values):
214 return Enum(type.expr, values)
221 def __init__(self, type, values):
222 Type.__init__(self, type.expr)
224 self.id = Bitmask.__id
230 def visit(self, visitor, *args, **kwargs):
231 return visitor.visitBitmask(self, *args, **kwargs)
238 def __init__(self, type, length):
239 Type.__init__(self, type.expr + " *")
243 def visit(self, visitor, *args, **kwargs):
244 return visitor.visitArray(self, *args, **kwargs)
249 def __init__(self, type, size):
250 Type.__init__(self, type.expr + ' *')
254 def visit(self, visitor, *args, **kwargs):
255 return visitor.visitBlob(self, *args, **kwargs)
262 def __init__(self, name, members):
263 Type.__init__(self, name)
265 self.id = Struct.__id
271 # Eliminate anonymous unions
272 for type, name in members:
274 self.members.append((type, name))
276 assert isinstance(type, Union)
277 assert type.name is None
278 self.members.extend(type.members)
280 def visit(self, visitor, *args, **kwargs):
281 return visitor.visitStruct(self, *args, **kwargs)
288 def __init__(self, name, members):
289 Type.__init__(self, name)
295 self.members = members
300 def __init__(self, expr, type):
301 Type.__init__(self, expr)
304 def visit(self, visitor, *args, **kwargs):
305 return visitor.visitAlias(self, *args, **kwargs)
309 def __init__(self, type, name, input=True, output=False):
317 return '%s %s' % (self.type, self.name)
321 return Arg(type, name, input=True, output=False)
324 return Arg(type, name, input=False, output=True)
326 def InOut(type, name):
327 return Arg(type, name, input=True, output=True)
332 # 0-3 are reserved to memcpy, malloc, free, and realloc
335 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
336 self.id = Function.__id
345 if not isinstance(arg, Arg):
346 if isinstance(arg, tuple):
347 arg_type, arg_name = arg
350 arg_name = "arg%u" % index
351 arg = Arg(arg_type, arg_name)
354 self.args.append(arg)
358 self.sideeffects = sideeffects
360 def prototype(self, name=None):
367 s = self.call + ' ' + s
368 if name.startswith('*'):
370 s = self.type.expr + ' ' + s
373 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
380 return [arg.name for arg in self.args]
383 def StdFunction(*args, **kwargs):
384 kwargs.setdefault('call', '__stdcall')
385 return Function(*args, **kwargs)
388 def FunctionPointer(type, name, args, **kwargs):
389 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
393 class Interface(Type):
395 def __init__(self, name, base=None):
396 Type.__init__(self, name)
401 def visit(self, visitor, *args, **kwargs):
402 return visitor.visitInterface(self, *args, **kwargs)
404 def getMethodByName(self, name):
405 for methods in self.methods:
406 if methods.name == name:
410 def iterMethods(self):
411 if self.base is not None:
412 for method in self.base.iterMethods():
414 for method in self.methods:
420 while iface is not None:
425 def iterBaseMethods(self):
426 if self.base is not None:
427 for iface, method in self.base.iterBaseMethods():
429 for method in self.methods:
434 class Method(Function):
436 def __init__(self, type, name, args, call = '__stdcall', const=False, sideeffects=True):
437 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
438 for index in range(len(self.args)):
439 self.args[index].index = index + 1
442 def prototype(self, name=None):
443 s = Function.prototype(self, name)
449 def StdMethod(*args, **kwargs):
450 kwargs.setdefault('call', '__stdcall')
451 return Method(*args, **kwargs)
456 def __init__(self, expr = "char *", length = None, kind = 'String'):
457 Type.__init__(self, expr)
461 def visit(self, visitor, *args, **kwargs):
462 return visitor.visitString(self, *args, **kwargs)
466 '''Opaque pointer.'''
468 def __init__(self, expr):
469 Type.__init__(self, expr)
471 def visit(self, visitor, *args, **kwargs):
472 return visitor.visitOpaque(self, *args, **kwargs)
475 def OpaquePointer(type, *args):
476 return Opaque(type.expr + ' *')
478 def OpaqueArray(type, size):
479 return Opaque(type.expr + ' *')
481 def OpaqueBlob(type, size):
482 return Opaque(type.expr + ' *')
485 class Polymorphic(Type):
487 def __init__(self, switchExpr, switchTypes, defaultType, contextLess=True):
488 Type.__init__(self, defaultType.expr)
489 self.switchExpr = switchExpr
490 self.switchTypes = switchTypes
491 self.defaultType = defaultType
492 self.contextLess = contextLess
494 def visit(self, visitor, *args, **kwargs):
495 return visitor.visitPolymorphic(self, *args, **kwargs)
497 def iterSwitch(self):
498 cases = [['default']]
499 types = [self.defaultType]
501 for expr, type in self.switchTypes:
502 case = 'case %s' % expr
504 i = types.index(type)
509 cases[i].append(case)
511 return zip(cases, types)
514 def EnumPolymorphic(enumName, switchExpr, switchTypes, defaultType, contextLess=True):
515 enumValues = [expr for expr, type in switchTypes]
516 enum = Enum(enumName, enumValues)
517 polymorphic = Polymorphic(switchExpr, switchTypes, defaultType, contextLess)
518 return enum, polymorphic
522 '''Abstract visitor for the type hierarchy.'''
524 def visit(self, type, *args, **kwargs):
525 return type.visit(self, *args, **kwargs)
527 def visitVoid(self, void, *args, **kwargs):
528 raise NotImplementedError
530 def visitLiteral(self, literal, *args, **kwargs):
531 raise NotImplementedError
533 def visitString(self, string, *args, **kwargs):
534 raise NotImplementedError
536 def visitConst(self, const, *args, **kwargs):
537 raise NotImplementedError
539 def visitStruct(self, struct, *args, **kwargs):
540 raise NotImplementedError
542 def visitArray(self, array, *args, **kwargs):
543 raise NotImplementedError
545 def visitBlob(self, blob, *args, **kwargs):
546 raise NotImplementedError
548 def visitEnum(self, enum, *args, **kwargs):
549 raise NotImplementedError
551 def visitBitmask(self, bitmask, *args, **kwargs):
552 raise NotImplementedError
554 def visitPointer(self, pointer, *args, **kwargs):
555 raise NotImplementedError
557 def visitIntPointer(self, pointer, *args, **kwargs):
558 raise NotImplementedError
560 def visitObjPointer(self, pointer, *args, **kwargs):
561 raise NotImplementedError
563 def visitLinearPointer(self, pointer, *args, **kwargs):
564 raise NotImplementedError
566 def visitReference(self, reference, *args, **kwargs):
567 raise NotImplementedError
569 def visitHandle(self, handle, *args, **kwargs):
570 raise NotImplementedError
572 def visitAlias(self, alias, *args, **kwargs):
573 raise NotImplementedError
575 def visitOpaque(self, opaque, *args, **kwargs):
576 raise NotImplementedError
578 def visitInterface(self, interface, *args, **kwargs):
579 raise NotImplementedError
581 def visitPolymorphic(self, polymorphic, *args, **kwargs):
582 raise NotImplementedError
583 #return self.visit(polymorphic.defaultType, *args, **kwargs)
586 class OnceVisitor(Visitor):
587 '''Visitor that guarantees that each type is visited only once.'''
590 self.__visited = set()
592 def visit(self, type, *args, **kwargs):
593 if type not in self.__visited:
594 self.__visited.add(type)
595 return type.visit(self, *args, **kwargs)
599 class Rebuilder(Visitor):
600 '''Visitor which rebuild types as it visits them.
602 By itself it is a no-op -- it is intended to be overwritten.
605 def visitVoid(self, void):
608 def visitLiteral(self, literal):
611 def visitString(self, string):
614 def visitConst(self, const):
615 const_type = self.visit(const.type)
616 if const_type is const.type:
619 return Const(const_type)
621 def visitStruct(self, struct):
622 members = [(self.visit(type), name) for type, name in struct.members]
623 return Struct(struct.name, members)
625 def visitArray(self, array):
626 type = self.visit(array.type)
627 return Array(type, array.length)
629 def visitBlob(self, blob):
630 type = self.visit(blob.type)
631 return Blob(type, blob.size)
633 def visitEnum(self, enum):
636 def visitBitmask(self, bitmask):
637 type = self.visit(bitmask.type)
638 return Bitmask(type, bitmask.values)
640 def visitPointer(self, pointer):
641 pointer_type = self.visit(pointer.type)
642 if pointer_type is pointer.type:
645 return Pointer(pointer_type)
647 def visitIntPointer(self, pointer):
650 def visitObjPointer(self, pointer):
651 pointer_type = self.visit(pointer.type)
652 if pointer_type is pointer.type:
655 return ObjPointer(pointer_type)
657 def visitLinearPointer(self, pointer):
658 pointer_type = self.visit(pointer.type)
659 if pointer_type is pointer.type:
662 return LinearPointer(pointer_type)
664 def visitReference(self, reference):
665 reference_type = self.visit(reference.type)
666 if reference_type is reference.type:
669 return Reference(reference_type)
671 def visitHandle(self, handle):
672 handle_type = self.visit(handle.type)
673 if handle_type is handle.type:
676 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
678 def visitAlias(self, alias):
679 alias_type = self.visit(alias.type)
680 if alias_type is alias.type:
683 return Alias(alias.expr, alias_type)
685 def visitOpaque(self, opaque):
688 def visitInterface(self, interface, *args, **kwargs):
691 def visitPolymorphic(self, polymorphic):
692 switchExpr = polymorphic.switchExpr
693 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
694 defaultType = self.visit(polymorphic.defaultType)
695 return Polymorphic(switchExpr, switchTypes, defaultType, polymorphic.contextLess)
698 class MutableRebuilder(Rebuilder):
699 '''Type visitor which derives a mutable type.'''
701 def visitConst(self, const):
702 # Strip out const qualifier
705 def visitAlias(self, alias):
706 # Tear the alias on type changes
707 type = self.visit(alias.type)
708 if type is alias.type:
712 def visitReference(self, reference):
713 # Strip out references
714 return reference.type
717 class Traverser(Visitor):
718 '''Visitor which all types.'''
720 def visitVoid(self, void, *args, **kwargs):
723 def visitLiteral(self, literal, *args, **kwargs):
726 def visitString(self, string, *args, **kwargs):
729 def visitConst(self, const, *args, **kwargs):
730 self.visit(const.type, *args, **kwargs)
732 def visitStruct(self, struct, *args, **kwargs):
733 for type, name in struct.members:
734 self.visit(type, *args, **kwargs)
736 def visitArray(self, array, *args, **kwargs):
737 self.visit(array.type, *args, **kwargs)
739 def visitBlob(self, array, *args, **kwargs):
742 def visitEnum(self, enum, *args, **kwargs):
745 def visitBitmask(self, bitmask, *args, **kwargs):
746 self.visit(bitmask.type, *args, **kwargs)
748 def visitPointer(self, pointer, *args, **kwargs):
749 self.visit(pointer.type, *args, **kwargs)
751 def visitIntPointer(self, pointer, *args, **kwargs):
754 def visitObjPointer(self, pointer, *args, **kwargs):
755 self.visit(pointer.type, *args, **kwargs)
757 def visitLinearPointer(self, pointer, *args, **kwargs):
758 self.visit(pointer.type, *args, **kwargs)
760 def visitReference(self, reference, *args, **kwargs):
761 self.visit(reference.type, *args, **kwargs)
763 def visitHandle(self, handle, *args, **kwargs):
764 self.visit(handle.type, *args, **kwargs)
766 def visitAlias(self, alias, *args, **kwargs):
767 self.visit(alias.type, *args, **kwargs)
769 def visitOpaque(self, opaque, *args, **kwargs):
772 def visitInterface(self, interface, *args, **kwargs):
773 if interface.base is not None:
774 self.visit(interface.base, *args, **kwargs)
775 for method in interface.iterMethods():
776 for arg in method.args:
777 self.visit(arg.type, *args, **kwargs)
778 self.visit(method.type, *args, **kwargs)
780 def visitPolymorphic(self, polymorphic, *args, **kwargs):
781 self.visit(polymorphic.defaultType, *args, **kwargs)
782 for expr, type in polymorphic.switchTypes:
783 self.visit(type, *args, **kwargs)
786 class Collector(Traverser):
787 '''Visitor which collects all unique types as it traverses them.'''
790 self.__visited = set()
793 def visit(self, type):
794 if type in self.__visited:
796 self.__visited.add(type)
797 Visitor.visit(self, type)
798 self.types.append(type)
805 Essentially, a collection of types, functions, and interfaces.
808 def __init__(self, name = None):
814 def getAllTypes(self):
815 collector = Collector()
816 for function in self.functions:
817 for arg in function.args:
818 collector.visit(arg.type)
819 collector.visit(function.type)
820 for interface in self.interfaces:
821 collector.visit(interface)
822 for method in interface.iterMethods():
823 for arg in method.args:
824 collector.visit(arg.type)
825 collector.visit(method.type)
826 return collector.types
828 def getAllInterfaces(self):
829 types = self.getAllTypes()
830 interfaces = [type for type in types if isinstance(type, Interface)]
831 for interface in self.interfaces:
832 if interface not in interfaces:
833 interfaces.append(interface)
836 def addFunction(self, function):
837 self.functions.append(function)
839 def addFunctions(self, functions):
840 for function in functions:
841 self.addFunction(function)
843 def addInterface(self, interface):
844 self.interfaces.append(interface)
846 def addInterfaces(self, interfaces):
847 self.interfaces.extend(interfaces)
849 def addApi(self, api):
850 self.headers.extend(api.headers)
851 self.addFunctions(api.functions)
852 self.addInterfaces(api.interfaces)
854 def getFunctionByName(self, name):
855 for function in self.functions:
856 if function.name == name:
861 Bool = Literal("bool", "Bool")
862 SChar = Literal("signed char", "SInt")
863 UChar = Literal("unsigned char", "UInt")
864 Short = Literal("short", "SInt")
865 Int = Literal("int", "SInt")
866 Long = Literal("long", "SInt")
867 LongLong = Literal("long long", "SInt")
868 UShort = Literal("unsigned short", "UInt")
869 UInt = Literal("unsigned int", "UInt")
870 ULong = Literal("unsigned long", "UInt")
871 ULongLong = Literal("unsigned long long", "UInt")
872 Float = Literal("float", "Float")
873 Double = Literal("double", "Double")
874 SizeT = Literal("size_t", "UInt")
876 # C string (i.e., zero terminated)
878 WString = String("wchar_t *", kind="WString")
880 Int8 = Literal("int8_t", "SInt")
881 UInt8 = Literal("uint8_t", "UInt")
882 Int16 = Literal("int16_t", "SInt")
883 UInt16 = Literal("uint16_t", "UInt")
884 Int32 = Literal("int32_t", "SInt")
885 UInt32 = Literal("uint32_t", "UInt")
886 Int64 = Literal("int64_t", "SInt")
887 UInt64 = Literal("uint64_t", "UInt")