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 arg = Arg(type, name, output=True)
283 def __init__(self, type, name, output=False):
290 return '%s %s' % (self.type, self.name)
295 # 0-3 are reserved to memcpy, malloc, free, and realloc
298 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
299 self.id = Function.__id
308 if not isinstance(arg, Arg):
309 if isinstance(arg, tuple):
310 arg_type, arg_name = arg
313 arg_name = "arg%u" % index
314 arg = Arg(arg_type, arg_name)
317 self.args.append(arg)
321 self.sideeffects = sideeffects
323 def prototype(self, name=None):
330 s = self.call + ' ' + s
331 if name.startswith('*'):
333 s = self.type.expr + ' ' + s
336 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
343 return [arg.name for arg in self.args]
346 def StdFunction(*args, **kwargs):
347 kwargs.setdefault('call', '__stdcall')
348 return Function(*args, **kwargs)
351 def FunctionPointer(type, name, args, **kwargs):
352 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
356 class Interface(Type):
358 def __init__(self, name, base=None):
359 Type.__init__(self, name)
364 def visit(self, visitor, *args, **kwargs):
365 return visitor.visitInterface(self, *args, **kwargs)
367 def iterMethods(self):
368 if self.base is not None:
369 for method in self.base.iterMethods():
371 for method in self.methods:
375 def iterBaseMethods(self):
376 if self.base is not None:
377 for iface, method in self.base.iterBaseMethods():
379 for method in self.methods:
384 class Method(Function):
386 def __init__(self, type, name, args, const=False, sideeffects=True):
387 Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
388 for index in range(len(self.args)):
389 self.args[index].index = index + 1
392 def prototype(self, name=None):
393 s = Function.prototype(self, name)
401 def __init__(self, expr = "char *", length = None, kind = 'String'):
402 Type.__init__(self, expr)
406 def visit(self, visitor, *args, **kwargs):
407 return visitor.visitString(self, *args, **kwargs)
411 '''Opaque pointer.'''
413 def __init__(self, expr):
414 Type.__init__(self, expr)
416 def visit(self, visitor, *args, **kwargs):
417 return visitor.visitOpaque(self, *args, **kwargs)
420 def OpaquePointer(type, *args):
421 return Opaque(type.expr + ' *')
423 def OpaqueArray(type, size):
424 return Opaque(type.expr + ' *')
426 def OpaqueBlob(type, size):
427 return Opaque(type.expr + ' *')
430 class Polymorphic(Type):
432 def __init__(self, defaultType, switchExpr, switchTypes):
433 Type.__init__(self, defaultType.expr)
434 self.defaultType = defaultType
435 self.switchExpr = switchExpr
436 self.switchTypes = switchTypes
438 def visit(self, visitor, *args, **kwargs):
439 return visitor.visitPolymorphic(self, *args, **kwargs)
441 def iterSwitch(self):
442 cases = [['default']]
443 types = [self.defaultType]
445 for expr, type in self.switchTypes:
446 case = 'case %s' % expr
448 i = types.index(type)
453 cases[i].append(case)
455 return zip(cases, types)
459 '''Abstract visitor for the type hierarchy.'''
461 def visit(self, type, *args, **kwargs):
462 return type.visit(self, *args, **kwargs)
464 def visitVoid(self, void, *args, **kwargs):
465 raise NotImplementedError
467 def visitLiteral(self, literal, *args, **kwargs):
468 raise NotImplementedError
470 def visitString(self, string, *args, **kwargs):
471 raise NotImplementedError
473 def visitConst(self, const, *args, **kwargs):
474 raise NotImplementedError
476 def visitStruct(self, struct, *args, **kwargs):
477 raise NotImplementedError
479 def visitArray(self, array, *args, **kwargs):
480 raise NotImplementedError
482 def visitBlob(self, blob, *args, **kwargs):
483 raise NotImplementedError
485 def visitEnum(self, enum, *args, **kwargs):
486 raise NotImplementedError
488 def visitBitmask(self, bitmask, *args, **kwargs):
489 raise NotImplementedError
491 def visitPointer(self, pointer, *args, **kwargs):
492 raise NotImplementedError
494 def visitIntPointer(self, pointer, *args, **kwargs):
495 raise NotImplementedError
497 def visitObjPointer(self, pointer, *args, **kwargs):
498 raise NotImplementedError
500 def visitLinearPointer(self, pointer, *args, **kwargs):
501 raise NotImplementedError
503 def visitReference(self, reference, *args, **kwargs):
504 raise NotImplementedError
506 def visitHandle(self, handle, *args, **kwargs):
507 raise NotImplementedError
509 def visitAlias(self, alias, *args, **kwargs):
510 raise NotImplementedError
512 def visitOpaque(self, opaque, *args, **kwargs):
513 raise NotImplementedError
515 def visitInterface(self, interface, *args, **kwargs):
516 raise NotImplementedError
518 def visitPolymorphic(self, polymorphic, *args, **kwargs):
519 raise NotImplementedError
520 #return self.visit(polymorphic.defaultType, *args, **kwargs)
523 class OnceVisitor(Visitor):
524 '''Visitor that guarantees that each type is visited only once.'''
527 self.__visited = set()
529 def visit(self, type, *args, **kwargs):
530 if type not in self.__visited:
531 self.__visited.add(type)
532 return type.visit(self, *args, **kwargs)
536 class Rebuilder(Visitor):
537 '''Visitor which rebuild types as it visits them.
539 By itself it is a no-op -- it is intended to be overwritten.
542 def visitVoid(self, void):
545 def visitLiteral(self, literal):
548 def visitString(self, string):
551 def visitConst(self, const):
552 const_type = self.visit(const.type)
553 if const_type is const.type:
556 return Const(const_type)
558 def visitStruct(self, struct):
559 members = [(self.visit(type), name) for type, name in struct.members]
560 return Struct(struct.name, members)
562 def visitArray(self, array):
563 type = self.visit(array.type)
564 return Array(type, array.length)
566 def visitBlob(self, blob):
567 type = self.visit(blob.type)
568 return Blob(type, blob.size)
570 def visitEnum(self, enum):
573 def visitBitmask(self, bitmask):
574 type = self.visit(bitmask.type)
575 return Bitmask(type, bitmask.values)
577 def visitPointer(self, pointer):
578 pointer_type = self.visit(pointer.type)
579 if pointer_type is pointer.type:
582 return Pointer(pointer_type)
584 def visitIntPointer(self, pointer):
587 def visitObjPointer(self, pointer):
588 pointer_type = self.visit(pointer.type)
589 if pointer_type is pointer.type:
592 return ObjPointer(pointer_type)
594 def visitLinearPointer(self, pointer):
595 pointer_type = self.visit(pointer.type)
596 if pointer_type is pointer.type:
599 return LinearPointer(pointer_type)
601 def visitReference(self, reference):
602 reference_type = self.visit(reference.type)
603 if reference_type is reference.type:
606 return Reference(reference_type)
608 def visitHandle(self, handle):
609 handle_type = self.visit(handle.type)
610 if handle_type is handle.type:
613 return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
615 def visitAlias(self, alias):
616 alias_type = self.visit(alias.type)
617 if alias_type is alias.type:
620 return Alias(alias.expr, alias_type)
622 def visitOpaque(self, opaque):
625 def visitInterface(self, interface, *args, **kwargs):
628 def visitPolymorphic(self, polymorphic):
629 defaultType = self.visit(polymorphic.defaultType)
630 switchExpr = polymorphic.switchExpr
631 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
632 return Polymorphic(defaultType, switchExpr, switchTypes)
635 class Collector(Visitor):
636 '''Visitor which collects all unique types as it traverses them.'''
639 self.__visited = set()
642 def visit(self, type):
643 if type in self.__visited:
645 self.__visited.add(type)
646 Visitor.visit(self, type)
647 self.types.append(type)
649 def visitVoid(self, literal):
652 def visitLiteral(self, literal):
655 def visitString(self, string):
658 def visitConst(self, const):
659 self.visit(const.type)
661 def visitStruct(self, struct):
662 for type, name in struct.members:
665 def visitArray(self, array):
666 self.visit(array.type)
668 def visitBlob(self, array):
671 def visitEnum(self, enum):
674 def visitBitmask(self, bitmask):
675 self.visit(bitmask.type)
677 def visitPointer(self, pointer):
678 self.visit(pointer.type)
680 def visitIntPointer(self, pointer):
683 def visitObjPointer(self, pointer):
684 self.visit(pointer.type)
686 def visitLinearPointer(self, pointer):
687 self.visit(pointer.type)
689 def visitReference(self, reference):
690 self.visit(reference.type)
692 def visitHandle(self, handle):
693 self.visit(handle.type)
695 def visitAlias(self, alias):
696 self.visit(alias.type)
698 def visitOpaque(self, opaque):
701 def visitInterface(self, interface):
702 if interface.base is not None:
703 self.visit(interface.base)
704 for method in interface.iterMethods():
705 for arg in method.args:
707 self.visit(method.type)
709 def visitPolymorphic(self, polymorphic):
710 self.visit(polymorphic.defaultType)
711 for expr, type in polymorphic.switchTypes:
718 Essentially, a collection of types, functions, and interfaces.
721 def __init__(self, name = None):
727 def getAllTypes(self):
728 collector = Collector()
729 for function in self.functions:
730 for arg in function.args:
731 collector.visit(arg.type)
732 collector.visit(function.type)
733 for interface in self.interfaces:
734 collector.visit(interface)
735 for method in interface.iterMethods():
736 for arg in method.args:
737 collector.visit(arg.type)
738 collector.visit(method.type)
739 return collector.types
741 def getAllInterfaces(self):
742 types = self.getAllTypes()
743 interfaces = [type for type in types if isinstance(type, Interface)]
744 for interface in self.interfaces:
745 if interface not in interfaces:
746 interfaces.append(interface)
749 def addFunction(self, function):
750 self.functions.append(function)
752 def addFunctions(self, functions):
753 for function in functions:
754 self.addFunction(function)
756 def addInterface(self, interface):
757 self.interfaces.append(interface)
759 def addInterfaces(self, interfaces):
760 self.interfaces.extend(interfaces)
762 def addApi(self, api):
763 self.headers.extend(api.headers)
764 self.addFunctions(api.functions)
765 self.addInterfaces(api.interfaces)
767 def get_function_by_name(self, name):
768 for function in self.functions:
769 if function.name == name:
774 Bool = Literal("bool", "Bool")
775 SChar = Literal("signed char", "SInt")
776 UChar = Literal("unsigned char", "UInt")
777 Short = Literal("short", "SInt")
778 Int = Literal("int", "SInt")
779 Long = Literal("long", "SInt")
780 LongLong = Literal("long long", "SInt")
781 UShort = Literal("unsigned short", "UInt")
782 UInt = Literal("unsigned int", "UInt")
783 ULong = Literal("unsigned long", "UInt")
784 ULongLong = Literal("unsigned long long", "UInt")
785 Float = Literal("float", "Float")
786 Double = Literal("double", "Double")
787 SizeT = Literal("size_t", "UInt")
789 # C string (i.e., zero terminated)
791 WString = String("wchar_t *", kind="WString")
793 Int8 = Literal("int8_t", "SInt")
794 UInt8 = Literal("uint8_t", "UInt")
795 Int16 = Literal("int16_t", "SInt")
796 UInt16 = Literal("uint16_t", "UInt")
797 Int32 = Literal("int32_t", "SInt")
798 UInt32 = Literal("uint32_t", "UInt")
799 Int64 = Literal("int64_t", "SInt")
800 UInt64 = Literal("uint64_t", "UInt")