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 iterMethods(self):
405 if self.base is not None:
406 for method in self.base.iterMethods():
408 for method in self.methods:
414 while iface is not None:
419 def iterBaseMethods(self):
420 if self.base is not None:
421 for iface, method in self.base.iterBaseMethods():
423 for method in self.methods:
428 class Method(Function):
430 def __init__(self, type, name, args, call = '__stdcall', const=False, sideeffects=True):
431 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
432 for index in range(len(self.args)):
433 self.args[index].index = index + 1
436 def prototype(self, name=None):
437 s = Function.prototype(self, name)
443 def StdMethod(*args, **kwargs):
444 kwargs.setdefault('call', '__stdcall')
445 return Method(*args, **kwargs)
450 def __init__(self, expr = "char *", length = None, kind = 'String'):
451 Type.__init__(self, expr)
455 def visit(self, visitor, *args, **kwargs):
456 return visitor.visitString(self, *args, **kwargs)
460 '''Opaque pointer.'''
462 def __init__(self, expr):
463 Type.__init__(self, expr)
465 def visit(self, visitor, *args, **kwargs):
466 return visitor.visitOpaque(self, *args, **kwargs)
469 def OpaquePointer(type, *args):
470 return Opaque(type.expr + ' *')
472 def OpaqueArray(type, size):
473 return Opaque(type.expr + ' *')
475 def OpaqueBlob(type, size):
476 return Opaque(type.expr + ' *')
479 class Polymorphic(Type):
481 def __init__(self, defaultType, switchExpr, switchTypes):
482 Type.__init__(self, defaultType.expr)
483 self.defaultType = defaultType
484 self.switchExpr = switchExpr
485 self.switchTypes = switchTypes
487 def visit(self, visitor, *args, **kwargs):
488 return visitor.visitPolymorphic(self, *args, **kwargs)
490 def iterSwitch(self):
491 cases = [['default']]
492 types = [self.defaultType]
494 for expr, type in self.switchTypes:
495 case = 'case %s' % expr
497 i = types.index(type)
502 cases[i].append(case)
504 return zip(cases, types)
508 '''Abstract visitor for the type hierarchy.'''
510 def visit(self, type, *args, **kwargs):
511 return type.visit(self, *args, **kwargs)
513 def visitVoid(self, void, *args, **kwargs):
514 raise NotImplementedError
516 def visitLiteral(self, literal, *args, **kwargs):
517 raise NotImplementedError
519 def visitString(self, string, *args, **kwargs):
520 raise NotImplementedError
522 def visitConst(self, const, *args, **kwargs):
523 raise NotImplementedError
525 def visitStruct(self, struct, *args, **kwargs):
526 raise NotImplementedError
528 def visitArray(self, array, *args, **kwargs):
529 raise NotImplementedError
531 def visitBlob(self, blob, *args, **kwargs):
532 raise NotImplementedError
534 def visitEnum(self, enum, *args, **kwargs):
535 raise NotImplementedError
537 def visitBitmask(self, bitmask, *args, **kwargs):
538 raise NotImplementedError
540 def visitPointer(self, pointer, *args, **kwargs):
541 raise NotImplementedError
543 def visitIntPointer(self, pointer, *args, **kwargs):
544 raise NotImplementedError
546 def visitObjPointer(self, pointer, *args, **kwargs):
547 raise NotImplementedError
549 def visitLinearPointer(self, pointer, *args, **kwargs):
550 raise NotImplementedError
552 def visitReference(self, reference, *args, **kwargs):
553 raise NotImplementedError
555 def visitHandle(self, handle, *args, **kwargs):
556 raise NotImplementedError
558 def visitAlias(self, alias, *args, **kwargs):
559 raise NotImplementedError
561 def visitOpaque(self, opaque, *args, **kwargs):
562 raise NotImplementedError
564 def visitInterface(self, interface, *args, **kwargs):
565 raise NotImplementedError
567 def visitPolymorphic(self, polymorphic, *args, **kwargs):
568 raise NotImplementedError
569 #return self.visit(polymorphic.defaultType, *args, **kwargs)
572 class OnceVisitor(Visitor):
573 '''Visitor that guarantees that each type is visited only once.'''
576 self.__visited = set()
578 def visit(self, type, *args, **kwargs):
579 if type not in self.__visited:
580 self.__visited.add(type)
581 return type.visit(self, *args, **kwargs)
585 class Rebuilder(Visitor):
586 '''Visitor which rebuild types as it visits them.
588 By itself it is a no-op -- it is intended to be overwritten.
591 def visitVoid(self, void):
594 def visitLiteral(self, literal):
597 def visitString(self, string):
600 def visitConst(self, const):
601 const_type = self.visit(const.type)
602 if const_type is const.type:
605 return Const(const_type)
607 def visitStruct(self, struct):
608 members = [(self.visit(type), name) for type, name in struct.members]
609 return Struct(struct.name, members)
611 def visitArray(self, array):
612 type = self.visit(array.type)
613 return Array(type, array.length)
615 def visitBlob(self, blob):
616 type = self.visit(blob.type)
617 return Blob(type, blob.size)
619 def visitEnum(self, enum):
622 def visitBitmask(self, bitmask):
623 type = self.visit(bitmask.type)
624 return Bitmask(type, bitmask.values)
626 def visitPointer(self, pointer):
627 pointer_type = self.visit(pointer.type)
628 if pointer_type is pointer.type:
631 return Pointer(pointer_type)
633 def visitIntPointer(self, pointer):
636 def visitObjPointer(self, pointer):
637 pointer_type = self.visit(pointer.type)
638 if pointer_type is pointer.type:
641 return ObjPointer(pointer_type)
643 def visitLinearPointer(self, pointer):
644 pointer_type = self.visit(pointer.type)
645 if pointer_type is pointer.type:
648 return LinearPointer(pointer_type)
650 def visitReference(self, reference):
651 reference_type = self.visit(reference.type)
652 if reference_type is reference.type:
655 return Reference(reference_type)
657 def visitHandle(self, handle):
658 handle_type = self.visit(handle.type)
659 if handle_type is handle.type:
662 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
664 def visitAlias(self, alias):
665 alias_type = self.visit(alias.type)
666 if alias_type is alias.type:
669 return Alias(alias.expr, alias_type)
671 def visitOpaque(self, opaque):
674 def visitInterface(self, interface, *args, **kwargs):
677 def visitPolymorphic(self, polymorphic):
678 defaultType = self.visit(polymorphic.defaultType)
679 switchExpr = polymorphic.switchExpr
680 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
681 return Polymorphic(defaultType, switchExpr, switchTypes)
684 class MutableRebuilder(Rebuilder):
685 '''Type visitor which derives a mutable type.'''
687 def visitConst(self, const):
688 # Strip out const qualifier
691 def visitAlias(self, alias):
692 # Tear the alias on type changes
693 type = self.visit(alias.type)
694 if type is alias.type:
698 def visitReference(self, reference):
699 # Strip out references
700 return reference.type
703 class Traverser(Visitor):
704 '''Visitor which all types.'''
706 def visitVoid(self, void, *args, **kwargs):
709 def visitLiteral(self, literal, *args, **kwargs):
712 def visitString(self, string, *args, **kwargs):
715 def visitConst(self, const, *args, **kwargs):
716 self.visit(const.type, *args, **kwargs)
718 def visitStruct(self, struct, *args, **kwargs):
719 for type, name in struct.members:
720 self.visit(type, *args, **kwargs)
722 def visitArray(self, array, *args, **kwargs):
723 self.visit(array.type, *args, **kwargs)
725 def visitBlob(self, array, *args, **kwargs):
728 def visitEnum(self, enum, *args, **kwargs):
731 def visitBitmask(self, bitmask, *args, **kwargs):
732 self.visit(bitmask.type, *args, **kwargs)
734 def visitPointer(self, pointer, *args, **kwargs):
735 self.visit(pointer.type, *args, **kwargs)
737 def visitIntPointer(self, pointer, *args, **kwargs):
740 def visitObjPointer(self, pointer, *args, **kwargs):
741 self.visit(pointer.type, *args, **kwargs)
743 def visitLinearPointer(self, pointer, *args, **kwargs):
744 self.visit(pointer.type, *args, **kwargs)
746 def visitReference(self, reference, *args, **kwargs):
747 self.visit(reference.type, *args, **kwargs)
749 def visitHandle(self, handle, *args, **kwargs):
750 self.visit(handle.type, *args, **kwargs)
752 def visitAlias(self, alias, *args, **kwargs):
753 self.visit(alias.type, *args, **kwargs)
755 def visitOpaque(self, opaque, *args, **kwargs):
758 def visitInterface(self, interface, *args, **kwargs):
759 if interface.base is not None:
760 self.visit(interface.base, *args, **kwargs)
761 for method in interface.iterMethods():
762 for arg in method.args:
763 self.visit(arg.type, *args, **kwargs)
764 self.visit(method.type, *args, **kwargs)
766 def visitPolymorphic(self, polymorphic, *args, **kwargs):
767 self.visit(polymorphic.defaultType, *args, **kwargs)
768 for expr, type in polymorphic.switchTypes:
769 self.visit(type, *args, **kwargs)
772 class Collector(Traverser):
773 '''Visitor which collects all unique types as it traverses them.'''
776 self.__visited = set()
779 def visit(self, type):
780 if type in self.__visited:
782 self.__visited.add(type)
783 Visitor.visit(self, type)
784 self.types.append(type)
791 Essentially, a collection of types, functions, and interfaces.
794 def __init__(self, name = None):
800 def getAllTypes(self):
801 collector = Collector()
802 for function in self.functions:
803 for arg in function.args:
804 collector.visit(arg.type)
805 collector.visit(function.type)
806 for interface in self.interfaces:
807 collector.visit(interface)
808 for method in interface.iterMethods():
809 for arg in method.args:
810 collector.visit(arg.type)
811 collector.visit(method.type)
812 return collector.types
814 def getAllInterfaces(self):
815 types = self.getAllTypes()
816 interfaces = [type for type in types if isinstance(type, Interface)]
817 for interface in self.interfaces:
818 if interface not in interfaces:
819 interfaces.append(interface)
822 def addFunction(self, function):
823 self.functions.append(function)
825 def addFunctions(self, functions):
826 for function in functions:
827 self.addFunction(function)
829 def addInterface(self, interface):
830 self.interfaces.append(interface)
832 def addInterfaces(self, interfaces):
833 self.interfaces.extend(interfaces)
835 def addApi(self, api):
836 self.headers.extend(api.headers)
837 self.addFunctions(api.functions)
838 self.addInterfaces(api.interfaces)
840 def getFunctionByName(self, name):
841 for function in self.functions:
842 if function.name == name:
847 Bool = Literal("bool", "Bool")
848 SChar = Literal("signed char", "SInt")
849 UChar = Literal("unsigned char", "UInt")
850 Short = Literal("short", "SInt")
851 Int = Literal("int", "SInt")
852 Long = Literal("long", "SInt")
853 LongLong = Literal("long long", "SInt")
854 UShort = Literal("unsigned short", "UInt")
855 UInt = Literal("unsigned int", "UInt")
856 ULong = Literal("unsigned long", "UInt")
857 ULongLong = Literal("unsigned long long", "UInt")
858 Float = Literal("float", "Float")
859 Double = Literal("double", "Double")
860 SizeT = Literal("size_t", "UInt")
862 # C string (i.e., zero terminated)
864 WString = String("wchar_t *", kind="WString")
866 Int8 = Literal("int8_t", "SInt")
867 UInt8 = Literal("uint8_t", "UInt")
868 Int16 = Literal("int16_t", "SInt")
869 UInt16 = Literal("uint16_t", "UInt")
870 Int32 = Literal("int32_t", "SInt")
871 UInt32 = Literal("uint32_t", "UInt")
872 Int64 = Literal("int64_t", "SInt")
873 UInt64 = Literal("uint64_t", "UInt")