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)
436 def StdMethod(*args, **kwargs):
437 kwargs.setdefault('call', '__stdcall')
438 return Method(*args, **kwargs)
443 def __init__(self, expr = "char *", length = None, kind = 'String'):
444 Type.__init__(self, expr)
448 def visit(self, visitor, *args, **kwargs):
449 return visitor.visitString(self, *args, **kwargs)
453 '''Opaque pointer.'''
455 def __init__(self, expr):
456 Type.__init__(self, expr)
458 def visit(self, visitor, *args, **kwargs):
459 return visitor.visitOpaque(self, *args, **kwargs)
462 def OpaquePointer(type, *args):
463 return Opaque(type.expr + ' *')
465 def OpaqueArray(type, size):
466 return Opaque(type.expr + ' *')
468 def OpaqueBlob(type, size):
469 return Opaque(type.expr + ' *')
472 class Polymorphic(Type):
474 def __init__(self, defaultType, switchExpr, switchTypes):
475 Type.__init__(self, defaultType.expr)
476 self.defaultType = defaultType
477 self.switchExpr = switchExpr
478 self.switchTypes = switchTypes
480 def visit(self, visitor, *args, **kwargs):
481 return visitor.visitPolymorphic(self, *args, **kwargs)
483 def iterSwitch(self):
484 cases = [['default']]
485 types = [self.defaultType]
487 for expr, type in self.switchTypes:
488 case = 'case %s' % expr
490 i = types.index(type)
495 cases[i].append(case)
497 return zip(cases, types)
501 '''Abstract visitor for the type hierarchy.'''
503 def visit(self, type, *args, **kwargs):
504 return type.visit(self, *args, **kwargs)
506 def visitVoid(self, void, *args, **kwargs):
507 raise NotImplementedError
509 def visitLiteral(self, literal, *args, **kwargs):
510 raise NotImplementedError
512 def visitString(self, string, *args, **kwargs):
513 raise NotImplementedError
515 def visitConst(self, const, *args, **kwargs):
516 raise NotImplementedError
518 def visitStruct(self, struct, *args, **kwargs):
519 raise NotImplementedError
521 def visitArray(self, array, *args, **kwargs):
522 raise NotImplementedError
524 def visitBlob(self, blob, *args, **kwargs):
525 raise NotImplementedError
527 def visitEnum(self, enum, *args, **kwargs):
528 raise NotImplementedError
530 def visitBitmask(self, bitmask, *args, **kwargs):
531 raise NotImplementedError
533 def visitPointer(self, pointer, *args, **kwargs):
534 raise NotImplementedError
536 def visitIntPointer(self, pointer, *args, **kwargs):
537 raise NotImplementedError
539 def visitObjPointer(self, pointer, *args, **kwargs):
540 raise NotImplementedError
542 def visitLinearPointer(self, pointer, *args, **kwargs):
543 raise NotImplementedError
545 def visitReference(self, reference, *args, **kwargs):
546 raise NotImplementedError
548 def visitHandle(self, handle, *args, **kwargs):
549 raise NotImplementedError
551 def visitAlias(self, alias, *args, **kwargs):
552 raise NotImplementedError
554 def visitOpaque(self, opaque, *args, **kwargs):
555 raise NotImplementedError
557 def visitInterface(self, interface, *args, **kwargs):
558 raise NotImplementedError
560 def visitPolymorphic(self, polymorphic, *args, **kwargs):
561 raise NotImplementedError
562 #return self.visit(polymorphic.defaultType, *args, **kwargs)
565 class OnceVisitor(Visitor):
566 '''Visitor that guarantees that each type is visited only once.'''
569 self.__visited = set()
571 def visit(self, type, *args, **kwargs):
572 if type not in self.__visited:
573 self.__visited.add(type)
574 return type.visit(self, *args, **kwargs)
578 class Rebuilder(Visitor):
579 '''Visitor which rebuild types as it visits them.
581 By itself it is a no-op -- it is intended to be overwritten.
584 def visitVoid(self, void):
587 def visitLiteral(self, literal):
590 def visitString(self, string):
593 def visitConst(self, const):
594 const_type = self.visit(const.type)
595 if const_type is const.type:
598 return Const(const_type)
600 def visitStruct(self, struct):
601 members = [(self.visit(type), name) for type, name in struct.members]
602 return Struct(struct.name, members)
604 def visitArray(self, array):
605 type = self.visit(array.type)
606 return Array(type, array.length)
608 def visitBlob(self, blob):
609 type = self.visit(blob.type)
610 return Blob(type, blob.size)
612 def visitEnum(self, enum):
615 def visitBitmask(self, bitmask):
616 type = self.visit(bitmask.type)
617 return Bitmask(type, bitmask.values)
619 def visitPointer(self, pointer):
620 pointer_type = self.visit(pointer.type)
621 if pointer_type is pointer.type:
624 return Pointer(pointer_type)
626 def visitIntPointer(self, pointer):
629 def visitObjPointer(self, pointer):
630 pointer_type = self.visit(pointer.type)
631 if pointer_type is pointer.type:
634 return ObjPointer(pointer_type)
636 def visitLinearPointer(self, pointer):
637 pointer_type = self.visit(pointer.type)
638 if pointer_type is pointer.type:
641 return LinearPointer(pointer_type)
643 def visitReference(self, reference):
644 reference_type = self.visit(reference.type)
645 if reference_type is reference.type:
648 return Reference(reference_type)
650 def visitHandle(self, handle):
651 handle_type = self.visit(handle.type)
652 if handle_type is handle.type:
655 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
657 def visitAlias(self, alias):
658 alias_type = self.visit(alias.type)
659 if alias_type is alias.type:
662 return Alias(alias.expr, alias_type)
664 def visitOpaque(self, opaque):
667 def visitInterface(self, interface, *args, **kwargs):
670 def visitPolymorphic(self, polymorphic):
671 defaultType = self.visit(polymorphic.defaultType)
672 switchExpr = polymorphic.switchExpr
673 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
674 return Polymorphic(defaultType, switchExpr, switchTypes)
677 class MutableRebuilder(Rebuilder):
678 '''Type visitor which derives a mutable type.'''
680 def visitConst(self, const):
681 # Strip out const qualifier
684 def visitAlias(self, alias):
685 # Tear the alias on type changes
686 type = self.visit(alias.type)
687 if type is alias.type:
691 def visitReference(self, reference):
692 # Strip out references
693 return reference.type
696 class Traverser(Visitor):
697 '''Visitor which all types.'''
699 def visitVoid(self, void, *args, **kwargs):
702 def visitLiteral(self, literal, *args, **kwargs):
705 def visitString(self, string, *args, **kwargs):
708 def visitConst(self, const, *args, **kwargs):
709 self.visit(const.type, *args, **kwargs)
711 def visitStruct(self, struct, *args, **kwargs):
712 for type, name in struct.members:
713 self.visit(type, *args, **kwargs)
715 def visitArray(self, array, *args, **kwargs):
716 self.visit(array.type, *args, **kwargs)
718 def visitBlob(self, array, *args, **kwargs):
721 def visitEnum(self, enum, *args, **kwargs):
724 def visitBitmask(self, bitmask, *args, **kwargs):
725 self.visit(bitmask.type, *args, **kwargs)
727 def visitPointer(self, pointer, *args, **kwargs):
728 self.visit(pointer.type, *args, **kwargs)
730 def visitIntPointer(self, pointer, *args, **kwargs):
733 def visitObjPointer(self, pointer, *args, **kwargs):
734 self.visit(pointer.type, *args, **kwargs)
736 def visitLinearPointer(self, pointer, *args, **kwargs):
737 self.visit(pointer.type, *args, **kwargs)
739 def visitReference(self, reference, *args, **kwargs):
740 self.visit(reference.type, *args, **kwargs)
742 def visitHandle(self, handle, *args, **kwargs):
743 self.visit(handle.type, *args, **kwargs)
745 def visitAlias(self, alias, *args, **kwargs):
746 self.visit(alias.type, *args, **kwargs)
748 def visitOpaque(self, opaque, *args, **kwargs):
751 def visitInterface(self, interface, *args, **kwargs):
752 if interface.base is not None:
753 self.visit(interface.base, *args, **kwargs)
754 for method in interface.iterMethods():
755 for arg in method.args:
756 self.visit(arg.type, *args, **kwargs)
757 self.visit(method.type, *args, **kwargs)
759 def visitPolymorphic(self, polymorphic, *args, **kwargs):
760 self.visit(polymorphic.defaultType, *args, **kwargs)
761 for expr, type in polymorphic.switchTypes:
762 self.visit(type, *args, **kwargs)
765 class Collector(Traverser):
766 '''Visitor which collects all unique types as it traverses them.'''
769 self.__visited = set()
772 def visit(self, type):
773 if type in self.__visited:
775 self.__visited.add(type)
776 Visitor.visit(self, type)
777 self.types.append(type)
784 Essentially, a collection of types, functions, and interfaces.
787 def __init__(self, name = None):
793 def getAllTypes(self):
794 collector = Collector()
795 for function in self.functions:
796 for arg in function.args:
797 collector.visit(arg.type)
798 collector.visit(function.type)
799 for interface in self.interfaces:
800 collector.visit(interface)
801 for method in interface.iterMethods():
802 for arg in method.args:
803 collector.visit(arg.type)
804 collector.visit(method.type)
805 return collector.types
807 def getAllInterfaces(self):
808 types = self.getAllTypes()
809 interfaces = [type for type in types if isinstance(type, Interface)]
810 for interface in self.interfaces:
811 if interface not in interfaces:
812 interfaces.append(interface)
815 def addFunction(self, function):
816 self.functions.append(function)
818 def addFunctions(self, functions):
819 for function in functions:
820 self.addFunction(function)
822 def addInterface(self, interface):
823 self.interfaces.append(interface)
825 def addInterfaces(self, interfaces):
826 self.interfaces.extend(interfaces)
828 def addApi(self, api):
829 self.headers.extend(api.headers)
830 self.addFunctions(api.functions)
831 self.addInterfaces(api.interfaces)
833 def get_function_by_name(self, name):
834 for function in self.functions:
835 if function.name == name:
840 Bool = Literal("bool", "Bool")
841 SChar = Literal("signed char", "SInt")
842 UChar = Literal("unsigned char", "UInt")
843 Short = Literal("short", "SInt")
844 Int = Literal("int", "SInt")
845 Long = Literal("long", "SInt")
846 LongLong = Literal("long long", "SInt")
847 UShort = Literal("unsigned short", "UInt")
848 UInt = Literal("unsigned int", "UInt")
849 ULong = Literal("unsigned long", "UInt")
850 ULongLong = Literal("unsigned long long", "UInt")
851 Float = Literal("float", "Float")
852 Double = Literal("double", "Double")
853 SizeT = Literal("size_t", "UInt")
855 # C string (i.e., zero terminated)
857 WString = String("wchar_t *", kind="WString")
859 Int8 = Literal("int8_t", "SInt")
860 UInt8 = Literal("uint8_t", "UInt")
861 Int16 = Literal("int16_t", "SInt")
862 UInt16 = Literal("uint16_t", "UInt")
863 Int32 = Literal("int32_t", "SInt")
864 UInt32 = Literal("uint32_t", "UInt")
865 Int64 = Literal("int64_t", "SInt")
866 UInt64 = Literal("uint64_t", "UInt")