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 LinearPointer(Type):
138 '''Integer encoded as a pointer.'''
140 def __init__(self, type, size = None):
141 Type.__init__(self, type.expr + " *", 'P' + type.tag)
145 def visit(self, visitor, *args, **kwargs):
146 return visitor.visitLinearPointer(self, *args, **kwargs)
149 class Reference(Type):
150 '''C++ references.'''
152 def __init__(self, type):
153 Type.__init__(self, type.expr + " &", 'R' + type.tag)
156 def visit(self, visitor, *args, **kwargs):
157 return visitor.visitReference(self, *args, **kwargs)
162 def __init__(self, name, type, range=None, key=None):
163 Type.__init__(self, type.expr, 'P' + type.tag)
169 def visit(self, visitor, *args, **kwargs):
170 return visitor.visitHandle(self, *args, **kwargs)
173 def ConstPointer(type):
174 return Pointer(Const(type))
181 def __init__(self, name, values):
182 Type.__init__(self, name)
187 self.values = list(values)
189 def visit(self, visitor, *args, **kwargs):
190 return visitor.visitEnum(self, *args, **kwargs)
193 def FakeEnum(type, values):
194 return Enum(type.expr, values)
201 def __init__(self, type, values):
202 Type.__init__(self, type.expr)
204 self.id = Bitmask.__id
210 def visit(self, visitor, *args, **kwargs):
211 return visitor.visitBitmask(self, *args, **kwargs)
218 def __init__(self, type, length):
219 Type.__init__(self, type.expr + " *")
223 def visit(self, visitor, *args, **kwargs):
224 return visitor.visitArray(self, *args, **kwargs)
229 def __init__(self, type, size):
230 Type.__init__(self, type.expr + ' *')
234 def visit(self, visitor, *args, **kwargs):
235 return visitor.visitBlob(self, *args, **kwargs)
242 def __init__(self, name, members):
243 Type.__init__(self, name)
245 self.id = Struct.__id
249 self.members = members
251 def visit(self, visitor, *args, **kwargs):
252 return visitor.visitStruct(self, *args, **kwargs)
257 def __init__(self, expr, type):
258 Type.__init__(self, expr)
261 def visit(self, visitor, *args, **kwargs):
262 return visitor.visitAlias(self, *args, **kwargs)
266 arg = Arg(type, name, output=True)
272 def __init__(self, type, name, output=False):
279 return '%s %s' % (self.type, self.name)
284 # 0-3 are reserved to memcpy, malloc, free, and realloc
287 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
288 self.id = Function.__id
297 if not isinstance(arg, Arg):
298 if isinstance(arg, tuple):
299 arg_type, arg_name = arg
302 arg_name = "arg%u" % index
303 arg = Arg(arg_type, arg_name)
306 self.args.append(arg)
310 self.sideeffects = sideeffects
312 def prototype(self, name=None):
319 s = self.call + ' ' + s
320 if name.startswith('*'):
322 s = self.type.expr + ' ' + s
325 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
332 return [arg.name for arg in self.args]
335 def StdFunction(*args, **kwargs):
336 kwargs.setdefault('call', '__stdcall')
337 return Function(*args, **kwargs)
340 def FunctionPointer(type, name, args, **kwargs):
341 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
345 class Interface(Type):
347 def __init__(self, name, base=None):
348 Type.__init__(self, name)
353 def visit(self, visitor, *args, **kwargs):
354 return visitor.visitInterface(self, *args, **kwargs)
356 def iterMethods(self):
357 if self.base is not None:
358 for method in self.base.iterMethods():
360 for method in self.methods:
364 def iterBaseMethods(self):
365 if self.base is not None:
366 for iface, method in self.base.iterBaseMethods():
368 for method in self.methods:
373 class Method(Function):
375 def __init__(self, type, name, args, const=False, sideeffects=True):
376 Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
377 for index in range(len(self.args)):
378 self.args[index].index = index + 1
381 def prototype(self, name=None):
382 s = Function.prototype(self, name)
390 def __init__(self, expr = "char *", length = None, kind = 'String'):
391 Type.__init__(self, expr)
395 def visit(self, visitor, *args, **kwargs):
396 return visitor.visitString(self, *args, **kwargs)
400 '''Opaque pointer.'''
402 def __init__(self, expr):
403 Type.__init__(self, expr)
405 def visit(self, visitor, *args, **kwargs):
406 return visitor.visitOpaque(self, *args, **kwargs)
409 def OpaquePointer(type, *args):
410 return Opaque(type.expr + ' *')
412 def OpaqueArray(type, size):
413 return Opaque(type.expr + ' *')
415 def OpaqueBlob(type, size):
416 return Opaque(type.expr + ' *')
419 class Polymorphic(Type):
421 def __init__(self, defaultType, switchExpr, switchTypes):
422 Type.__init__(self, defaultType.expr)
423 self.defaultType = defaultType
424 self.switchExpr = switchExpr
425 self.switchTypes = switchTypes
427 def visit(self, visitor, *args, **kwargs):
428 return visitor.visitPolymorphic(self, *args, **kwargs)
430 def iterSwitch(self):
431 cases = [['default']]
432 types = [self.defaultType]
434 for expr, type in self.switchTypes:
435 case = 'case %s' % expr
437 i = types.index(type)
442 cases[i].append(case)
444 return zip(cases, types)
448 '''Abstract visitor for the type hierarchy.'''
450 def visit(self, type, *args, **kwargs):
451 return type.visit(self, *args, **kwargs)
453 def visitVoid(self, void, *args, **kwargs):
454 raise NotImplementedError
456 def visitLiteral(self, literal, *args, **kwargs):
457 raise NotImplementedError
459 def visitString(self, string, *args, **kwargs):
460 raise NotImplementedError
462 def visitConst(self, const, *args, **kwargs):
463 raise NotImplementedError
465 def visitStruct(self, struct, *args, **kwargs):
466 raise NotImplementedError
468 def visitArray(self, array, *args, **kwargs):
469 raise NotImplementedError
471 def visitBlob(self, blob, *args, **kwargs):
472 raise NotImplementedError
474 def visitEnum(self, enum, *args, **kwargs):
475 raise NotImplementedError
477 def visitBitmask(self, bitmask, *args, **kwargs):
478 raise NotImplementedError
480 def visitPointer(self, pointer, *args, **kwargs):
481 raise NotImplementedError
483 def visitIntPointer(self, pointer, *args, **kwargs):
484 raise NotImplementedError
486 def visitLinearPointer(self, pointer, *args, **kwargs):
487 raise NotImplementedError
489 def visitReference(self, reference, *args, **kwargs):
490 raise NotImplementedError
492 def visitHandle(self, handle, *args, **kwargs):
493 raise NotImplementedError
495 def visitAlias(self, alias, *args, **kwargs):
496 raise NotImplementedError
498 def visitOpaque(self, opaque, *args, **kwargs):
499 raise NotImplementedError
501 def visitInterface(self, interface, *args, **kwargs):
502 raise NotImplementedError
504 def visitPolymorphic(self, polymorphic, *args, **kwargs):
505 raise NotImplementedError
506 #return self.visit(polymorphic.defaultType, *args, **kwargs)
509 class OnceVisitor(Visitor):
510 '''Visitor that guarantees that each type is visited only once.'''
513 self.__visited = set()
515 def visit(self, type, *args, **kwargs):
516 if type not in self.__visited:
517 self.__visited.add(type)
518 return type.visit(self, *args, **kwargs)
522 class Rebuilder(Visitor):
523 '''Visitor which rebuild types as it visits them.
525 By itself it is a no-op -- it is intended to be overwritten.
528 def visitVoid(self, void):
531 def visitLiteral(self, literal):
534 def visitString(self, string):
537 def visitConst(self, const):
538 return Const(const.type)
540 def visitStruct(self, struct):
541 members = [(self.visit(type), name) for type, name in struct.members]
542 return Struct(struct.name, members)
544 def visitArray(self, array):
545 type = self.visit(array.type)
546 return Array(type, array.length)
548 def visitBlob(self, blob):
549 type = self.visit(blob.type)
550 return Blob(type, blob.size)
552 def visitEnum(self, enum):
555 def visitBitmask(self, bitmask):
556 type = self.visit(bitmask.type)
557 return Bitmask(type, bitmask.values)
559 def visitPointer(self, pointer):
560 type = self.visit(pointer.type)
563 def visitIntPointer(self, pointer):
566 def visitLinearPointer(self, pointer):
567 type = self.visit(pointer.type)
568 return LinearPointer(type, pointer.size)
570 def visitReference(self, reference):
571 type = self.visit(reference.type)
572 return Reference(type)
574 def visitHandle(self, handle):
575 type = self.visit(handle.type)
576 return Handle(handle.name, type, range=handle.range, key=handle.key)
578 def visitAlias(self, alias):
579 type = self.visit(alias.type)
580 return Alias(alias.expr, type)
582 def visitOpaque(self, opaque):
585 def visitInterface(self, interface, *args, **kwargs):
588 def visitPolymorphic(self, polymorphic):
589 defaultType = self.visit(polymorphic.defaultType)
590 switchExpr = polymorphic.switchExpr
591 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
592 return Polymorphic(defaultType, switchExpr, switchTypes)
595 class Collector(Visitor):
596 '''Visitor which collects all unique types as it traverses them.'''
599 self.__visited = set()
602 def visit(self, type):
603 if type in self.__visited:
605 self.__visited.add(type)
606 Visitor.visit(self, type)
607 self.types.append(type)
609 def visitVoid(self, literal):
612 def visitLiteral(self, literal):
615 def visitString(self, string):
618 def visitConst(self, const):
619 self.visit(const.type)
621 def visitStruct(self, struct):
622 for type, name in struct.members:
625 def visitArray(self, array):
626 self.visit(array.type)
628 def visitBlob(self, array):
631 def visitEnum(self, enum):
634 def visitBitmask(self, bitmask):
635 self.visit(bitmask.type)
637 def visitPointer(self, pointer):
638 self.visit(pointer.type)
640 def visitIntPointer(self, pointer):
643 def visitLinearPointer(self, pointer):
644 self.visit(pointer.type)
646 def visitReference(self, reference):
647 self.visit(reference.type)
649 def visitHandle(self, handle):
650 self.visit(handle.type)
652 def visitAlias(self, alias):
653 self.visit(alias.type)
655 def visitOpaque(self, opaque):
658 def visitInterface(self, interface):
659 if interface.base is not None:
660 self.visit(interface.base)
661 for method in interface.iterMethods():
662 for arg in method.args:
664 self.visit(method.type)
666 def visitPolymorphic(self, polymorphic):
667 self.visit(polymorphic.defaultType)
668 for expr, type in polymorphic.switchTypes:
675 Essentially, a collection of types, functions, and interfaces.
678 def __init__(self, name = None):
684 def getAllTypes(self):
685 collector = Collector()
686 for function in self.functions:
687 for arg in function.args:
688 collector.visit(arg.type)
689 collector.visit(function.type)
690 for interface in self.interfaces:
691 collector.visit(interface)
692 for method in interface.iterMethods():
693 for arg in method.args:
694 collector.visit(arg.type)
695 collector.visit(method.type)
696 return collector.types
698 def getAllInterfaces(self):
699 types = self.getAllTypes()
700 interfaces = [type for type in types if isinstance(type, Interface)]
701 for interface in self.interfaces:
702 if interface not in interfaces:
703 interfaces.append(interface)
706 def addFunction(self, function):
707 self.functions.append(function)
709 def addFunctions(self, functions):
710 for function in functions:
711 self.addFunction(function)
713 def addInterface(self, interface):
714 self.interfaces.append(interface)
716 def addInterfaces(self, interfaces):
717 self.interfaces.extend(interfaces)
719 def addApi(self, api):
720 self.headers.extend(api.headers)
721 self.addFunctions(api.functions)
722 self.addInterfaces(api.interfaces)
724 def get_function_by_name(self, name):
725 for function in self.functions:
726 if function.name == name:
731 Bool = Literal("bool", "Bool")
732 SChar = Literal("signed char", "SInt")
733 UChar = Literal("unsigned char", "UInt")
734 Short = Literal("short", "SInt")
735 Int = Literal("int", "SInt")
736 Long = Literal("long", "SInt")
737 LongLong = Literal("long long", "SInt")
738 UShort = Literal("unsigned short", "UInt")
739 UInt = Literal("unsigned int", "UInt")
740 ULong = Literal("unsigned long", "UInt")
741 ULongLong = Literal("unsigned long long", "UInt")
742 Float = Literal("float", "Float")
743 Double = Literal("double", "Double")
744 SizeT = Literal("size_t", "UInt")
746 # C string (i.e., zero terminated)
748 WString = String("wchar_t *", kind="WString")
750 Int8 = Literal("int8_t", "SInt")
751 UInt8 = Literal("uint8_t", "UInt")
752 Int16 = Literal("int16_t", "SInt")
753 UInt16 = Literal("uint16_t", "UInt")
754 Int32 = Literal("int32_t", "SInt")
755 UInt32 = Literal("uint32_t", "UInt")
756 Int64 = Literal("int64_t", "SInt")
757 UInt64 = Literal("uint64_t", "UInt")