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:
412 def iterBaseMethods(self):
413 if self.base is not None:
414 for iface, method in self.base.iterBaseMethods():
416 for method in self.methods:
421 class Method(Function):
423 def __init__(self, type, name, args, call = '__stdcall', const=False, sideeffects=True):
424 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
425 for index in range(len(self.args)):
426 self.args[index].index = index + 1
429 def prototype(self, name=None):
430 s = Function.prototype(self, name)
435 def StdMethod(*args, **kwargs):
436 kwargs.setdefault('call', '__stdcall')
437 return Method(*args, **kwargs)
442 def __init__(self, expr = "char *", length = None, kind = 'String'):
443 Type.__init__(self, expr)
447 def visit(self, visitor, *args, **kwargs):
448 return visitor.visitString(self, *args, **kwargs)
452 '''Opaque pointer.'''
454 def __init__(self, expr):
455 Type.__init__(self, expr)
457 def visit(self, visitor, *args, **kwargs):
458 return visitor.visitOpaque(self, *args, **kwargs)
461 def OpaquePointer(type, *args):
462 return Opaque(type.expr + ' *')
464 def OpaqueArray(type, size):
465 return Opaque(type.expr + ' *')
467 def OpaqueBlob(type, size):
468 return Opaque(type.expr + ' *')
471 class Polymorphic(Type):
473 def __init__(self, defaultType, switchExpr, switchTypes):
474 Type.__init__(self, defaultType.expr)
475 self.defaultType = defaultType
476 self.switchExpr = switchExpr
477 self.switchTypes = switchTypes
479 def visit(self, visitor, *args, **kwargs):
480 return visitor.visitPolymorphic(self, *args, **kwargs)
482 def iterSwitch(self):
483 cases = [['default']]
484 types = [self.defaultType]
486 for expr, type in self.switchTypes:
487 case = 'case %s' % expr
489 i = types.index(type)
494 cases[i].append(case)
496 return zip(cases, types)
500 '''Abstract visitor for the type hierarchy.'''
502 def visit(self, type, *args, **kwargs):
503 return type.visit(self, *args, **kwargs)
505 def visitVoid(self, void, *args, **kwargs):
506 raise NotImplementedError
508 def visitLiteral(self, literal, *args, **kwargs):
509 raise NotImplementedError
511 def visitString(self, string, *args, **kwargs):
512 raise NotImplementedError
514 def visitConst(self, const, *args, **kwargs):
515 raise NotImplementedError
517 def visitStruct(self, struct, *args, **kwargs):
518 raise NotImplementedError
520 def visitArray(self, array, *args, **kwargs):
521 raise NotImplementedError
523 def visitBlob(self, blob, *args, **kwargs):
524 raise NotImplementedError
526 def visitEnum(self, enum, *args, **kwargs):
527 raise NotImplementedError
529 def visitBitmask(self, bitmask, *args, **kwargs):
530 raise NotImplementedError
532 def visitPointer(self, pointer, *args, **kwargs):
533 raise NotImplementedError
535 def visitIntPointer(self, pointer, *args, **kwargs):
536 raise NotImplementedError
538 def visitObjPointer(self, pointer, *args, **kwargs):
539 raise NotImplementedError
541 def visitLinearPointer(self, pointer, *args, **kwargs):
542 raise NotImplementedError
544 def visitReference(self, reference, *args, **kwargs):
545 raise NotImplementedError
547 def visitHandle(self, handle, *args, **kwargs):
548 raise NotImplementedError
550 def visitAlias(self, alias, *args, **kwargs):
551 raise NotImplementedError
553 def visitOpaque(self, opaque, *args, **kwargs):
554 raise NotImplementedError
556 def visitInterface(self, interface, *args, **kwargs):
557 raise NotImplementedError
559 def visitPolymorphic(self, polymorphic, *args, **kwargs):
560 raise NotImplementedError
561 #return self.visit(polymorphic.defaultType, *args, **kwargs)
564 class OnceVisitor(Visitor):
565 '''Visitor that guarantees that each type is visited only once.'''
568 self.__visited = set()
570 def visit(self, type, *args, **kwargs):
571 if type not in self.__visited:
572 self.__visited.add(type)
573 return type.visit(self, *args, **kwargs)
577 class Rebuilder(Visitor):
578 '''Visitor which rebuild types as it visits them.
580 By itself it is a no-op -- it is intended to be overwritten.
583 def visitVoid(self, void):
586 def visitLiteral(self, literal):
589 def visitString(self, string):
592 def visitConst(self, const):
593 const_type = self.visit(const.type)
594 if const_type is const.type:
597 return Const(const_type)
599 def visitStruct(self, struct):
600 members = [(self.visit(type), name) for type, name in struct.members]
601 return Struct(struct.name, members)
603 def visitArray(self, array):
604 type = self.visit(array.type)
605 return Array(type, array.length)
607 def visitBlob(self, blob):
608 type = self.visit(blob.type)
609 return Blob(type, blob.size)
611 def visitEnum(self, enum):
614 def visitBitmask(self, bitmask):
615 type = self.visit(bitmask.type)
616 return Bitmask(type, bitmask.values)
618 def visitPointer(self, pointer):
619 pointer_type = self.visit(pointer.type)
620 if pointer_type is pointer.type:
623 return Pointer(pointer_type)
625 def visitIntPointer(self, pointer):
628 def visitObjPointer(self, pointer):
629 pointer_type = self.visit(pointer.type)
630 if pointer_type is pointer.type:
633 return ObjPointer(pointer_type)
635 def visitLinearPointer(self, pointer):
636 pointer_type = self.visit(pointer.type)
637 if pointer_type is pointer.type:
640 return LinearPointer(pointer_type)
642 def visitReference(self, reference):
643 reference_type = self.visit(reference.type)
644 if reference_type is reference.type:
647 return Reference(reference_type)
649 def visitHandle(self, handle):
650 handle_type = self.visit(handle.type)
651 if handle_type is handle.type:
654 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
656 def visitAlias(self, alias):
657 alias_type = self.visit(alias.type)
658 if alias_type is alias.type:
661 return Alias(alias.expr, alias_type)
663 def visitOpaque(self, opaque):
666 def visitInterface(self, interface, *args, **kwargs):
669 def visitPolymorphic(self, polymorphic):
670 defaultType = self.visit(polymorphic.defaultType)
671 switchExpr = polymorphic.switchExpr
672 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
673 return Polymorphic(defaultType, switchExpr, switchTypes)
676 class MutableRebuilder(Rebuilder):
677 '''Type visitor which derives a mutable type.'''
679 def visitConst(self, const):
680 # Strip out const qualifier
683 def visitAlias(self, alias):
684 # Tear the alias on type changes
685 type = self.visit(alias.type)
686 if type is alias.type:
690 def visitReference(self, reference):
691 # Strip out references
692 return reference.type
695 class Traverser(Visitor):
696 '''Visitor which all types.'''
698 def visitVoid(self, void, *args, **kwargs):
701 def visitLiteral(self, literal, *args, **kwargs):
704 def visitString(self, string, *args, **kwargs):
707 def visitConst(self, const, *args, **kwargs):
708 self.visit(const.type, *args, **kwargs)
710 def visitStruct(self, struct, *args, **kwargs):
711 for type, name in struct.members:
712 self.visit(type, *args, **kwargs)
714 def visitArray(self, array, *args, **kwargs):
715 self.visit(array.type, *args, **kwargs)
717 def visitBlob(self, array, *args, **kwargs):
720 def visitEnum(self, enum, *args, **kwargs):
723 def visitBitmask(self, bitmask, *args, **kwargs):
724 self.visit(bitmask.type, *args, **kwargs)
726 def visitPointer(self, pointer, *args, **kwargs):
727 self.visit(pointer.type, *args, **kwargs)
729 def visitIntPointer(self, pointer, *args, **kwargs):
732 def visitObjPointer(self, pointer, *args, **kwargs):
733 self.visit(pointer.type, *args, **kwargs)
735 def visitLinearPointer(self, pointer, *args, **kwargs):
736 self.visit(pointer.type, *args, **kwargs)
738 def visitReference(self, reference, *args, **kwargs):
739 self.visit(reference.type, *args, **kwargs)
741 def visitHandle(self, handle, *args, **kwargs):
742 self.visit(handle.type, *args, **kwargs)
744 def visitAlias(self, alias, *args, **kwargs):
745 self.visit(alias.type, *args, **kwargs)
747 def visitOpaque(self, opaque, *args, **kwargs):
750 def visitInterface(self, interface, *args, **kwargs):
751 if interface.base is not None:
752 self.visit(interface.base, *args, **kwargs)
753 for method in interface.iterMethods():
754 for arg in method.args:
755 self.visit(arg.type, *args, **kwargs)
756 self.visit(method.type, *args, **kwargs)
758 def visitPolymorphic(self, polymorphic, *args, **kwargs):
759 self.visit(polymorphic.defaultType, *args, **kwargs)
760 for expr, type in polymorphic.switchTypes:
761 self.visit(type, *args, **kwargs)
764 class Collector(Traverser):
765 '''Visitor which collects all unique types as it traverses them.'''
768 self.__visited = set()
771 def visit(self, type):
772 if type in self.__visited:
774 self.__visited.add(type)
775 Visitor.visit(self, type)
776 self.types.append(type)
783 Essentially, a collection of types, functions, and interfaces.
786 def __init__(self, name = None):
792 def getAllTypes(self):
793 collector = Collector()
794 for function in self.functions:
795 for arg in function.args:
796 collector.visit(arg.type)
797 collector.visit(function.type)
798 for interface in self.interfaces:
799 collector.visit(interface)
800 for method in interface.iterMethods():
801 for arg in method.args:
802 collector.visit(arg.type)
803 collector.visit(method.type)
804 return collector.types
806 def getAllInterfaces(self):
807 types = self.getAllTypes()
808 interfaces = [type for type in types if isinstance(type, Interface)]
809 for interface in self.interfaces:
810 if interface not in interfaces:
811 interfaces.append(interface)
814 def addFunction(self, function):
815 self.functions.append(function)
817 def addFunctions(self, functions):
818 for function in functions:
819 self.addFunction(function)
821 def addInterface(self, interface):
822 self.interfaces.append(interface)
824 def addInterfaces(self, interfaces):
825 self.interfaces.extend(interfaces)
827 def addApi(self, api):
828 self.headers.extend(api.headers)
829 self.addFunctions(api.functions)
830 self.addInterfaces(api.interfaces)
832 def get_function_by_name(self, name):
833 for function in self.functions:
834 if function.name == name:
839 Bool = Literal("bool", "Bool")
840 SChar = Literal("signed char", "SInt")
841 UChar = Literal("unsigned char", "UInt")
842 Short = Literal("short", "SInt")
843 Int = Literal("int", "SInt")
844 Long = Literal("long", "SInt")
845 LongLong = Literal("long long", "SInt")
846 UShort = Literal("unsigned short", "UInt")
847 UInt = Literal("unsigned int", "UInt")
848 ULong = Literal("unsigned long", "UInt")
849 ULongLong = Literal("unsigned long long", "UInt")
850 Float = Literal("float", "Float")
851 Double = Literal("double", "Double")
852 SizeT = Literal("size_t", "UInt")
854 # C string (i.e., zero terminated)
856 WString = String("wchar_t *", kind="WString")
858 Int8 = Literal("int8_t", "SInt")
859 UInt8 = Literal("uint8_t", "UInt")
860 Int16 = Literal("int16_t", "SInt")
861 UInt16 = Literal("uint16_t", "UInt")
862 Int32 = Literal("int32_t", "SInt")
863 UInt32 = Literal("uint32_t", "UInt")
864 Int64 = Literal("int64_t", "SInt")
865 UInt64 = Literal("uint64_t", "UInt")