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
74 """Singleton void type."""
77 Type.__init__(self, "void")
79 def visit(self, visitor, *args, **kwargs):
80 return visitor.visitVoid(self, *args, **kwargs)
86 """Class to describe literal types.
88 Types which are not defined in terms of other types, such as integers and
91 def __init__(self, expr, kind):
92 Type.__init__(self, expr)
95 def visit(self, visitor, *args, **kwargs):
96 return visitor.visitLiteral(self, *args, **kwargs)
101 def __init__(self, type):
102 # While "const foo" and "foo const" are synonymous, "const foo *" and
103 # "foo * const" are not quite the same, and some compilers do enforce
104 # strict const correctness.
105 if isinstance(type, String) or type is WString:
106 # For strings we never intend to say a const pointer to chars, but
107 # rather a point to const chars.
108 expr = "const " + type.expr
109 elif type.expr.startswith("const ") or '*' in type.expr:
110 expr = type.expr + " const"
113 expr = "const " + type.expr
115 Type.__init__(self, expr, 'C' + type.tag)
119 def visit(self, visitor, *args, **kwargs):
120 return visitor.visitConst(self, *args, **kwargs)
125 def __init__(self, type):
126 Type.__init__(self, type.expr + " *", 'P' + type.tag)
129 def visit(self, visitor, *args, **kwargs):
130 return visitor.visitPointer(self, *args, **kwargs)
133 class IntPointer(Type):
134 '''Integer encoded as a pointer.'''
136 def visit(self, visitor, *args, **kwargs):
137 return visitor.visitIntPointer(self, *args, **kwargs)
140 class ObjPointer(Type):
141 '''Pointer to an object.'''
143 def __init__(self, type):
144 Type.__init__(self, type.expr + " *", 'P' + type.tag)
147 def visit(self, visitor, *args, **kwargs):
148 return visitor.visitObjPointer(self, *args, **kwargs)
151 class LinearPointer(Type):
152 '''Pointer to a linear range of memory.'''
154 def __init__(self, type, size = None):
155 Type.__init__(self, type.expr + " *", 'P' + type.tag)
159 def visit(self, visitor, *args, **kwargs):
160 return visitor.visitLinearPointer(self, *args, **kwargs)
163 class Reference(Type):
164 '''C++ references.'''
166 def __init__(self, type):
167 Type.__init__(self, type.expr + " &", 'R' + type.tag)
170 def visit(self, visitor, *args, **kwargs):
171 return visitor.visitReference(self, *args, **kwargs)
176 def __init__(self, name, type, range=None, key=None):
177 Type.__init__(self, type.expr, 'P' + type.tag)
183 def visit(self, visitor, *args, **kwargs):
184 return visitor.visitHandle(self, *args, **kwargs)
187 def ConstPointer(type):
188 return Pointer(Const(type))
195 def __init__(self, name, values):
196 Type.__init__(self, name)
201 self.values = list(values)
203 def visit(self, visitor, *args, **kwargs):
204 return visitor.visitEnum(self, *args, **kwargs)
207 def FakeEnum(type, values):
208 return Enum(type.expr, values)
215 def __init__(self, type, values):
216 Type.__init__(self, type.expr)
218 self.id = Bitmask.__id
224 def visit(self, visitor, *args, **kwargs):
225 return visitor.visitBitmask(self, *args, **kwargs)
232 def __init__(self, type, length):
233 Type.__init__(self, type.expr + " *")
237 def visit(self, visitor, *args, **kwargs):
238 return visitor.visitArray(self, *args, **kwargs)
243 def __init__(self, type, size):
244 Type.__init__(self, type.expr + ' *')
248 def visit(self, visitor, *args, **kwargs):
249 return visitor.visitBlob(self, *args, **kwargs)
256 def __init__(self, name, members):
257 Type.__init__(self, name)
259 self.id = Struct.__id
265 # Eliminate anonymous unions
266 for type, name in members:
268 self.members.append((type, name))
270 assert isinstance(type, Union)
271 assert type.name is None
272 self.members.extend(type.members)
274 def visit(self, visitor, *args, **kwargs):
275 return visitor.visitStruct(self, *args, **kwargs)
282 def __init__(self, name, members):
283 Type.__init__(self, name)
289 self.members = members
294 def __init__(self, expr, type):
295 Type.__init__(self, expr)
298 def visit(self, visitor, *args, **kwargs):
299 return visitor.visitAlias(self, *args, **kwargs)
303 def __init__(self, type, name, input=True, output=False):
311 return '%s %s' % (self.type, self.name)
315 return Arg(type, name, input=True, output=False)
318 return Arg(type, name, input=False, output=True)
320 def InOut(type, name):
321 return Arg(type, name, input=True, output=True)
326 # 0-3 are reserved to memcpy, malloc, free, and realloc
329 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
330 self.id = Function.__id
339 if not isinstance(arg, Arg):
340 if isinstance(arg, tuple):
341 arg_type, arg_name = arg
344 arg_name = "arg%u" % index
345 arg = Arg(arg_type, arg_name)
348 self.args.append(arg)
352 self.sideeffects = sideeffects
354 def prototype(self, name=None):
361 s = self.call + ' ' + s
362 if name.startswith('*'):
364 s = self.type.expr + ' ' + s
367 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
374 return [arg.name for arg in self.args]
377 def StdFunction(*args, **kwargs):
378 kwargs.setdefault('call', '__stdcall')
379 return Function(*args, **kwargs)
382 def FunctionPointer(type, name, args, **kwargs):
383 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
387 class Interface(Type):
389 def __init__(self, name, base=None):
390 Type.__init__(self, name)
395 def visit(self, visitor, *args, **kwargs):
396 return visitor.visitInterface(self, *args, **kwargs)
398 def iterMethods(self):
399 if self.base is not None:
400 for method in self.base.iterMethods():
402 for method in self.methods:
406 def iterBaseMethods(self):
407 if self.base is not None:
408 for iface, method in self.base.iterBaseMethods():
410 for method in self.methods:
415 class Method(Function):
417 def __init__(self, type, name, args, call = '__stdcall', const=False, sideeffects=True):
418 Function.__init__(self, type, name, args, call = call, sideeffects=sideeffects)
419 for index in range(len(self.args)):
420 self.args[index].index = index + 1
423 def prototype(self, name=None):
424 s = Function.prototype(self, name)
429 def StdMethod(*args, **kwargs):
430 kwargs.setdefault('call', '__stdcall')
431 return Method(*args, **kwargs)
436 def __init__(self, expr = "char *", length = None, kind = 'String'):
437 Type.__init__(self, expr)
441 def visit(self, visitor, *args, **kwargs):
442 return visitor.visitString(self, *args, **kwargs)
446 '''Opaque pointer.'''
448 def __init__(self, expr):
449 Type.__init__(self, expr)
451 def visit(self, visitor, *args, **kwargs):
452 return visitor.visitOpaque(self, *args, **kwargs)
455 def OpaquePointer(type, *args):
456 return Opaque(type.expr + ' *')
458 def OpaqueArray(type, size):
459 return Opaque(type.expr + ' *')
461 def OpaqueBlob(type, size):
462 return Opaque(type.expr + ' *')
465 class Polymorphic(Type):
467 def __init__(self, defaultType, switchExpr, switchTypes):
468 Type.__init__(self, defaultType.expr)
469 self.defaultType = defaultType
470 self.switchExpr = switchExpr
471 self.switchTypes = switchTypes
473 def visit(self, visitor, *args, **kwargs):
474 return visitor.visitPolymorphic(self, *args, **kwargs)
476 def iterSwitch(self):
477 cases = [['default']]
478 types = [self.defaultType]
480 for expr, type in self.switchTypes:
481 case = 'case %s' % expr
483 i = types.index(type)
488 cases[i].append(case)
490 return zip(cases, types)
494 '''Abstract visitor for the type hierarchy.'''
496 def visit(self, type, *args, **kwargs):
497 return type.visit(self, *args, **kwargs)
499 def visitVoid(self, void, *args, **kwargs):
500 raise NotImplementedError
502 def visitLiteral(self, literal, *args, **kwargs):
503 raise NotImplementedError
505 def visitString(self, string, *args, **kwargs):
506 raise NotImplementedError
508 def visitConst(self, const, *args, **kwargs):
509 raise NotImplementedError
511 def visitStruct(self, struct, *args, **kwargs):
512 raise NotImplementedError
514 def visitArray(self, array, *args, **kwargs):
515 raise NotImplementedError
517 def visitBlob(self, blob, *args, **kwargs):
518 raise NotImplementedError
520 def visitEnum(self, enum, *args, **kwargs):
521 raise NotImplementedError
523 def visitBitmask(self, bitmask, *args, **kwargs):
524 raise NotImplementedError
526 def visitPointer(self, pointer, *args, **kwargs):
527 raise NotImplementedError
529 def visitIntPointer(self, pointer, *args, **kwargs):
530 raise NotImplementedError
532 def visitObjPointer(self, pointer, *args, **kwargs):
533 raise NotImplementedError
535 def visitLinearPointer(self, pointer, *args, **kwargs):
536 raise NotImplementedError
538 def visitReference(self, reference, *args, **kwargs):
539 raise NotImplementedError
541 def visitHandle(self, handle, *args, **kwargs):
542 raise NotImplementedError
544 def visitAlias(self, alias, *args, **kwargs):
545 raise NotImplementedError
547 def visitOpaque(self, opaque, *args, **kwargs):
548 raise NotImplementedError
550 def visitInterface(self, interface, *args, **kwargs):
551 raise NotImplementedError
553 def visitPolymorphic(self, polymorphic, *args, **kwargs):
554 raise NotImplementedError
555 #return self.visit(polymorphic.defaultType, *args, **kwargs)
558 class OnceVisitor(Visitor):
559 '''Visitor that guarantees that each type is visited only once.'''
562 self.__visited = set()
564 def visit(self, type, *args, **kwargs):
565 if type not in self.__visited:
566 self.__visited.add(type)
567 return type.visit(self, *args, **kwargs)
571 class Rebuilder(Visitor):
572 '''Visitor which rebuild types as it visits them.
574 By itself it is a no-op -- it is intended to be overwritten.
577 def visitVoid(self, void):
580 def visitLiteral(self, literal):
583 def visitString(self, string):
586 def visitConst(self, const):
587 const_type = self.visit(const.type)
588 if const_type is const.type:
591 return Const(const_type)
593 def visitStruct(self, struct):
594 members = [(self.visit(type), name) for type, name in struct.members]
595 return Struct(struct.name, members)
597 def visitArray(self, array):
598 type = self.visit(array.type)
599 return Array(type, array.length)
601 def visitBlob(self, blob):
602 type = self.visit(blob.type)
603 return Blob(type, blob.size)
605 def visitEnum(self, enum):
608 def visitBitmask(self, bitmask):
609 type = self.visit(bitmask.type)
610 return Bitmask(type, bitmask.values)
612 def visitPointer(self, pointer):
613 pointer_type = self.visit(pointer.type)
614 if pointer_type is pointer.type:
617 return Pointer(pointer_type)
619 def visitIntPointer(self, pointer):
622 def visitObjPointer(self, pointer):
623 pointer_type = self.visit(pointer.type)
624 if pointer_type is pointer.type:
627 return ObjPointer(pointer_type)
629 def visitLinearPointer(self, pointer):
630 pointer_type = self.visit(pointer.type)
631 if pointer_type is pointer.type:
634 return LinearPointer(pointer_type)
636 def visitReference(self, reference):
637 reference_type = self.visit(reference.type)
638 if reference_type is reference.type:
641 return Reference(reference_type)
643 def visitHandle(self, handle):
644 handle_type = self.visit(handle.type)
645 if handle_type is handle.type:
648 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
650 def visitAlias(self, alias):
651 alias_type = self.visit(alias.type)
652 if alias_type is alias.type:
655 return Alias(alias.expr, alias_type)
657 def visitOpaque(self, opaque):
660 def visitInterface(self, interface, *args, **kwargs):
663 def visitPolymorphic(self, polymorphic):
664 defaultType = self.visit(polymorphic.defaultType)
665 switchExpr = polymorphic.switchExpr
666 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
667 return Polymorphic(defaultType, switchExpr, switchTypes)
670 class Collector(Visitor):
671 '''Visitor which collects all unique types as it traverses them.'''
674 self.__visited = set()
677 def visit(self, type):
678 if type in self.__visited:
680 self.__visited.add(type)
681 Visitor.visit(self, type)
682 self.types.append(type)
684 def visitVoid(self, literal):
687 def visitLiteral(self, literal):
690 def visitString(self, string):
693 def visitConst(self, const):
694 self.visit(const.type)
696 def visitStruct(self, struct):
697 for type, name in struct.members:
700 def visitArray(self, array):
701 self.visit(array.type)
703 def visitBlob(self, array):
706 def visitEnum(self, enum):
709 def visitBitmask(self, bitmask):
710 self.visit(bitmask.type)
712 def visitPointer(self, pointer):
713 self.visit(pointer.type)
715 def visitIntPointer(self, pointer):
718 def visitObjPointer(self, pointer):
719 self.visit(pointer.type)
721 def visitLinearPointer(self, pointer):
722 self.visit(pointer.type)
724 def visitReference(self, reference):
725 self.visit(reference.type)
727 def visitHandle(self, handle):
728 self.visit(handle.type)
730 def visitAlias(self, alias):
731 self.visit(alias.type)
733 def visitOpaque(self, opaque):
736 def visitInterface(self, interface):
737 if interface.base is not None:
738 self.visit(interface.base)
739 for method in interface.iterMethods():
740 for arg in method.args:
742 self.visit(method.type)
744 def visitPolymorphic(self, polymorphic):
745 self.visit(polymorphic.defaultType)
746 for expr, type in polymorphic.switchTypes:
753 Essentially, a collection of types, functions, and interfaces.
756 def __init__(self, name = None):
762 def getAllTypes(self):
763 collector = Collector()
764 for function in self.functions:
765 for arg in function.args:
766 collector.visit(arg.type)
767 collector.visit(function.type)
768 for interface in self.interfaces:
769 collector.visit(interface)
770 for method in interface.iterMethods():
771 for arg in method.args:
772 collector.visit(arg.type)
773 collector.visit(method.type)
774 return collector.types
776 def getAllInterfaces(self):
777 types = self.getAllTypes()
778 interfaces = [type for type in types if isinstance(type, Interface)]
779 for interface in self.interfaces:
780 if interface not in interfaces:
781 interfaces.append(interface)
784 def addFunction(self, function):
785 self.functions.append(function)
787 def addFunctions(self, functions):
788 for function in functions:
789 self.addFunction(function)
791 def addInterface(self, interface):
792 self.interfaces.append(interface)
794 def addInterfaces(self, interfaces):
795 self.interfaces.extend(interfaces)
797 def addApi(self, api):
798 self.headers.extend(api.headers)
799 self.addFunctions(api.functions)
800 self.addInterfaces(api.interfaces)
802 def get_function_by_name(self, name):
803 for function in self.functions:
804 if function.name == name:
809 Bool = Literal("bool", "Bool")
810 SChar = Literal("signed char", "SInt")
811 UChar = Literal("unsigned char", "UInt")
812 Short = Literal("short", "SInt")
813 Int = Literal("int", "SInt")
814 Long = Literal("long", "SInt")
815 LongLong = Literal("long long", "SInt")
816 UShort = Literal("unsigned short", "UInt")
817 UInt = Literal("unsigned int", "UInt")
818 ULong = Literal("unsigned long", "UInt")
819 ULongLong = Literal("unsigned long long", "UInt")
820 Float = Literal("float", "Float")
821 Double = Literal("double", "Double")
822 SizeT = Literal("size_t", "UInt")
824 # C string (i.e., zero terminated)
826 WString = String("wchar_t *", kind="WString")
828 Int8 = Literal("int8_t", "SInt")
829 UInt8 = Literal("uint8_t", "UInt")
830 Int16 = Literal("int16_t", "SInt")
831 UInt16 = Literal("uint16_t", "UInt")
832 Int32 = Literal("int32_t", "SInt")
833 UInt32 = Literal("uint32_t", "UInt")
834 Int64 = Literal("int64_t", "SInt")
835 UInt64 = Literal("uint64_t", "UInt")