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
44 tag = ''.join([c for c in expr if c.isalnum() or c in '_'])
47 assert c.isalnum() or c in '_'
49 # Ensure it is unique.
50 if tag in Type.__tags:
52 while tag + str(suffix) in Type.__tags:
56 assert tag not in Type.__tags
62 """Return the C/C++ type expression for this type."""
65 def visit(self, visitor, *args, **kwargs):
66 raise NotImplementedError
71 """Singleton void type."""
74 Type.__init__(self, "void")
76 def visit(self, visitor, *args, **kwargs):
77 return visitor.visitVoid(self, *args, **kwargs)
83 """Class to describe literal types.
85 Types which are not defined in terms of other types, such as integers and
88 def __init__(self, expr, kind):
89 Type.__init__(self, expr)
92 def visit(self, visitor, *args, **kwargs):
93 return visitor.visitLiteral(self, *args, **kwargs)
98 def __init__(self, type):
99 # While "const foo" and "foo const" are synonymous, "const foo *" and
100 # "foo * const" are not quite the same, and some compilers do enforce
101 # strict const correctness.
102 if isinstance(type, String) or type is WString:
103 # For strings we never intend to say a const pointer to chars, but
104 # rather a point to const chars.
105 expr = "const " + type.expr
106 elif type.expr.startswith("const ") or '*' in type.expr:
107 expr = type.expr + " const"
110 expr = "const " + type.expr
112 Type.__init__(self, expr, 'C' + type.tag)
116 def visit(self, visitor, *args, **kwargs):
117 return visitor.visitConst(self, *args, **kwargs)
122 def __init__(self, type):
123 Type.__init__(self, type.expr + " *", 'P' + type.tag)
126 def visit(self, visitor, *args, **kwargs):
127 return visitor.visitPointer(self, *args, **kwargs)
130 class IntPointer(Type):
131 '''Integer encoded as a pointer.'''
133 def visit(self, visitor, *args, **kwargs):
134 return visitor.visitIntPointer(self, *args, **kwargs)
137 class ObjPointer(Type):
138 '''Pointer to an object.'''
140 def __init__(self, type):
141 Type.__init__(self, type.expr + " *", 'P' + type.tag)
144 def visit(self, visitor, *args, **kwargs):
145 return visitor.visitObjPointer(self, *args, **kwargs)
148 class LinearPointer(Type):
149 '''Pointer to a linear range of memory.'''
151 def __init__(self, type, size = None):
152 Type.__init__(self, type.expr + " *", 'P' + type.tag)
156 def visit(self, visitor, *args, **kwargs):
157 return visitor.visitLinearPointer(self, *args, **kwargs)
160 class Reference(Type):
161 '''C++ references.'''
163 def __init__(self, type):
164 Type.__init__(self, type.expr + " &", 'R' + type.tag)
167 def visit(self, visitor, *args, **kwargs):
168 return visitor.visitReference(self, *args, **kwargs)
173 def __init__(self, name, type, range=None, key=None):
174 Type.__init__(self, type.expr, 'P' + type.tag)
180 def visit(self, visitor, *args, **kwargs):
181 return visitor.visitHandle(self, *args, **kwargs)
184 def ConstPointer(type):
185 return Pointer(Const(type))
192 def __init__(self, name, values):
193 Type.__init__(self, name)
198 self.values = list(values)
200 def visit(self, visitor, *args, **kwargs):
201 return visitor.visitEnum(self, *args, **kwargs)
204 def FakeEnum(type, values):
205 return Enum(type.expr, values)
212 def __init__(self, type, values):
213 Type.__init__(self, type.expr)
215 self.id = Bitmask.__id
221 def visit(self, visitor, *args, **kwargs):
222 return visitor.visitBitmask(self, *args, **kwargs)
229 def __init__(self, type, length):
230 Type.__init__(self, type.expr + " *")
234 def visit(self, visitor, *args, **kwargs):
235 return visitor.visitArray(self, *args, **kwargs)
240 def __init__(self, type, size):
241 Type.__init__(self, type.expr + ' *')
245 def visit(self, visitor, *args, **kwargs):
246 return visitor.visitBlob(self, *args, **kwargs)
253 def __init__(self, name, members):
254 Type.__init__(self, name)
256 self.id = Struct.__id
260 self.members = members
262 def visit(self, visitor, *args, **kwargs):
263 return visitor.visitStruct(self, *args, **kwargs)
268 def __init__(self, expr, type):
269 Type.__init__(self, expr)
272 def visit(self, visitor, *args, **kwargs):
273 return visitor.visitAlias(self, *args, **kwargs)
277 def __init__(self, type, name, input=True, output=False):
285 return '%s %s' % (self.type, self.name)
289 return Arg(type, name, input=True, output=False)
292 return Arg(type, name, input=False, output=True)
294 def InOut(type, name):
295 return Arg(type, name, input=True, output=True)
300 # 0-3 are reserved to memcpy, malloc, free, and realloc
303 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
304 self.id = Function.__id
313 if not isinstance(arg, Arg):
314 if isinstance(arg, tuple):
315 arg_type, arg_name = arg
318 arg_name = "arg%u" % index
319 arg = Arg(arg_type, arg_name)
322 self.args.append(arg)
326 self.sideeffects = sideeffects
328 def prototype(self, name=None):
335 s = self.call + ' ' + s
336 if name.startswith('*'):
338 s = self.type.expr + ' ' + s
341 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
348 return [arg.name for arg in self.args]
351 def StdFunction(*args, **kwargs):
352 kwargs.setdefault('call', '__stdcall')
353 return Function(*args, **kwargs)
356 def FunctionPointer(type, name, args, **kwargs):
357 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
361 class Interface(Type):
363 def __init__(self, name, base=None):
364 Type.__init__(self, name)
369 def visit(self, visitor, *args, **kwargs):
370 return visitor.visitInterface(self, *args, **kwargs)
372 def iterMethods(self):
373 if self.base is not None:
374 for method in self.base.iterMethods():
376 for method in self.methods:
380 def iterBaseMethods(self):
381 if self.base is not None:
382 for iface, method in self.base.iterBaseMethods():
384 for method in self.methods:
389 class Method(Function):
391 def __init__(self, type, name, args, const=False, sideeffects=True):
392 Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
393 for index in range(len(self.args)):
394 self.args[index].index = index + 1
397 def prototype(self, name=None):
398 s = Function.prototype(self, name)
406 def __init__(self, expr = "char *", length = None, kind = 'String'):
407 Type.__init__(self, expr)
411 def visit(self, visitor, *args, **kwargs):
412 return visitor.visitString(self, *args, **kwargs)
416 '''Opaque pointer.'''
418 def __init__(self, expr):
419 Type.__init__(self, expr)
421 def visit(self, visitor, *args, **kwargs):
422 return visitor.visitOpaque(self, *args, **kwargs)
425 def OpaquePointer(type, *args):
426 return Opaque(type.expr + ' *')
428 def OpaqueArray(type, size):
429 return Opaque(type.expr + ' *')
431 def OpaqueBlob(type, size):
432 return Opaque(type.expr + ' *')
435 class Polymorphic(Type):
437 def __init__(self, defaultType, switchExpr, switchTypes):
438 Type.__init__(self, defaultType.expr)
439 self.defaultType = defaultType
440 self.switchExpr = switchExpr
441 self.switchTypes = switchTypes
443 def visit(self, visitor, *args, **kwargs):
444 return visitor.visitPolymorphic(self, *args, **kwargs)
446 def iterSwitch(self):
447 cases = [['default']]
448 types = [self.defaultType]
450 for expr, type in self.switchTypes:
451 case = 'case %s' % expr
453 i = types.index(type)
458 cases[i].append(case)
460 return zip(cases, types)
464 '''Abstract visitor for the type hierarchy.'''
466 def visit(self, type, *args, **kwargs):
467 return type.visit(self, *args, **kwargs)
469 def visitVoid(self, void, *args, **kwargs):
470 raise NotImplementedError
472 def visitLiteral(self, literal, *args, **kwargs):
473 raise NotImplementedError
475 def visitString(self, string, *args, **kwargs):
476 raise NotImplementedError
478 def visitConst(self, const, *args, **kwargs):
479 raise NotImplementedError
481 def visitStruct(self, struct, *args, **kwargs):
482 raise NotImplementedError
484 def visitArray(self, array, *args, **kwargs):
485 raise NotImplementedError
487 def visitBlob(self, blob, *args, **kwargs):
488 raise NotImplementedError
490 def visitEnum(self, enum, *args, **kwargs):
491 raise NotImplementedError
493 def visitBitmask(self, bitmask, *args, **kwargs):
494 raise NotImplementedError
496 def visitPointer(self, pointer, *args, **kwargs):
497 raise NotImplementedError
499 def visitIntPointer(self, pointer, *args, **kwargs):
500 raise NotImplementedError
502 def visitObjPointer(self, pointer, *args, **kwargs):
503 raise NotImplementedError
505 def visitLinearPointer(self, pointer, *args, **kwargs):
506 raise NotImplementedError
508 def visitReference(self, reference, *args, **kwargs):
509 raise NotImplementedError
511 def visitHandle(self, handle, *args, **kwargs):
512 raise NotImplementedError
514 def visitAlias(self, alias, *args, **kwargs):
515 raise NotImplementedError
517 def visitOpaque(self, opaque, *args, **kwargs):
518 raise NotImplementedError
520 def visitInterface(self, interface, *args, **kwargs):
521 raise NotImplementedError
523 def visitPolymorphic(self, polymorphic, *args, **kwargs):
524 raise NotImplementedError
525 #return self.visit(polymorphic.defaultType, *args, **kwargs)
528 class OnceVisitor(Visitor):
529 '''Visitor that guarantees that each type is visited only once.'''
532 self.__visited = set()
534 def visit(self, type, *args, **kwargs):
535 if type not in self.__visited:
536 self.__visited.add(type)
537 return type.visit(self, *args, **kwargs)
541 class Rebuilder(Visitor):
542 '''Visitor which rebuild types as it visits them.
544 By itself it is a no-op -- it is intended to be overwritten.
547 def visitVoid(self, void):
550 def visitLiteral(self, literal):
553 def visitString(self, string):
556 def visitConst(self, const):
557 const_type = self.visit(const.type)
558 if const_type is const.type:
561 return Const(const_type)
563 def visitStruct(self, struct):
564 members = [(self.visit(type), name) for type, name in struct.members]
565 return Struct(struct.name, members)
567 def visitArray(self, array):
568 type = self.visit(array.type)
569 return Array(type, array.length)
571 def visitBlob(self, blob):
572 type = self.visit(blob.type)
573 return Blob(type, blob.size)
575 def visitEnum(self, enum):
578 def visitBitmask(self, bitmask):
579 type = self.visit(bitmask.type)
580 return Bitmask(type, bitmask.values)
582 def visitPointer(self, pointer):
583 pointer_type = self.visit(pointer.type)
584 if pointer_type is pointer.type:
587 return Pointer(pointer_type)
589 def visitIntPointer(self, pointer):
592 def visitObjPointer(self, pointer):
593 pointer_type = self.visit(pointer.type)
594 if pointer_type is pointer.type:
597 return ObjPointer(pointer_type)
599 def visitLinearPointer(self, pointer):
600 pointer_type = self.visit(pointer.type)
601 if pointer_type is pointer.type:
604 return LinearPointer(pointer_type)
606 def visitReference(self, reference):
607 reference_type = self.visit(reference.type)
608 if reference_type is reference.type:
611 return Reference(reference_type)
613 def visitHandle(self, handle):
614 handle_type = self.visit(handle.type)
615 if handle_type is handle.type:
618 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
620 def visitAlias(self, alias):
621 alias_type = self.visit(alias.type)
622 if alias_type is alias.type:
625 return Alias(alias.expr, alias_type)
627 def visitOpaque(self, opaque):
630 def visitInterface(self, interface, *args, **kwargs):
633 def visitPolymorphic(self, polymorphic):
634 defaultType = self.visit(polymorphic.defaultType)
635 switchExpr = polymorphic.switchExpr
636 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
637 return Polymorphic(defaultType, switchExpr, switchTypes)
640 class Collector(Visitor):
641 '''Visitor which collects all unique types as it traverses them.'''
644 self.__visited = set()
647 def visit(self, type):
648 if type in self.__visited:
650 self.__visited.add(type)
651 Visitor.visit(self, type)
652 self.types.append(type)
654 def visitVoid(self, literal):
657 def visitLiteral(self, literal):
660 def visitString(self, string):
663 def visitConst(self, const):
664 self.visit(const.type)
666 def visitStruct(self, struct):
667 for type, name in struct.members:
670 def visitArray(self, array):
671 self.visit(array.type)
673 def visitBlob(self, array):
676 def visitEnum(self, enum):
679 def visitBitmask(self, bitmask):
680 self.visit(bitmask.type)
682 def visitPointer(self, pointer):
683 self.visit(pointer.type)
685 def visitIntPointer(self, pointer):
688 def visitObjPointer(self, pointer):
689 self.visit(pointer.type)
691 def visitLinearPointer(self, pointer):
692 self.visit(pointer.type)
694 def visitReference(self, reference):
695 self.visit(reference.type)
697 def visitHandle(self, handle):
698 self.visit(handle.type)
700 def visitAlias(self, alias):
701 self.visit(alias.type)
703 def visitOpaque(self, opaque):
706 def visitInterface(self, interface):
707 if interface.base is not None:
708 self.visit(interface.base)
709 for method in interface.iterMethods():
710 for arg in method.args:
712 self.visit(method.type)
714 def visitPolymorphic(self, polymorphic):
715 self.visit(polymorphic.defaultType)
716 for expr, type in polymorphic.switchTypes:
723 Essentially, a collection of types, functions, and interfaces.
726 def __init__(self, name = None):
732 def getAllTypes(self):
733 collector = Collector()
734 for function in self.functions:
735 for arg in function.args:
736 collector.visit(arg.type)
737 collector.visit(function.type)
738 for interface in self.interfaces:
739 collector.visit(interface)
740 for method in interface.iterMethods():
741 for arg in method.args:
742 collector.visit(arg.type)
743 collector.visit(method.type)
744 return collector.types
746 def getAllInterfaces(self):
747 types = self.getAllTypes()
748 interfaces = [type for type in types if isinstance(type, Interface)]
749 for interface in self.interfaces:
750 if interface not in interfaces:
751 interfaces.append(interface)
754 def addFunction(self, function):
755 self.functions.append(function)
757 def addFunctions(self, functions):
758 for function in functions:
759 self.addFunction(function)
761 def addInterface(self, interface):
762 self.interfaces.append(interface)
764 def addInterfaces(self, interfaces):
765 self.interfaces.extend(interfaces)
767 def addApi(self, api):
768 self.headers.extend(api.headers)
769 self.addFunctions(api.functions)
770 self.addInterfaces(api.interfaces)
772 def get_function_by_name(self, name):
773 for function in self.functions:
774 if function.name == name:
779 Bool = Literal("bool", "Bool")
780 SChar = Literal("signed char", "SInt")
781 UChar = Literal("unsigned char", "UInt")
782 Short = Literal("short", "SInt")
783 Int = Literal("int", "SInt")
784 Long = Literal("long", "SInt")
785 LongLong = Literal("long long", "SInt")
786 UShort = Literal("unsigned short", "UInt")
787 UInt = Literal("unsigned int", "UInt")
788 ULong = Literal("unsigned long", "UInt")
789 ULongLong = Literal("unsigned long long", "UInt")
790 Float = Literal("float", "Float")
791 Double = Literal("double", "Double")
792 SizeT = Literal("size_t", "UInt")
794 # C string (i.e., zero terminated)
796 WString = String("wchar_t *", kind="WString")
798 Int8 = Literal("int8_t", "SInt")
799 UInt8 = Literal("uint8_t", "UInt")
800 Int16 = Literal("int16_t", "SInt")
801 UInt16 = Literal("uint16_t", "UInt")
802 Int32 = Literal("int32_t", "SInt")
803 UInt32 = Literal("uint32_t", "UInt")
804 Int64 = Literal("int64_t", "SInt")
805 UInt64 = Literal("uint64_t", "UInt")