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 return Const(const.type)
554 def visitStruct(self, struct):
555 members = [(self.visit(type), name) for type, name in struct.members]
556 return Struct(struct.name, members)
558 def visitArray(self, array):
559 type = self.visit(array.type)
560 return Array(type, array.length)
562 def visitBlob(self, blob):
563 type = self.visit(blob.type)
564 return Blob(type, blob.size)
566 def visitEnum(self, enum):
569 def visitBitmask(self, bitmask):
570 type = self.visit(bitmask.type)
571 return Bitmask(type, bitmask.values)
573 def visitPointer(self, pointer):
574 type = self.visit(pointer.type)
577 def visitIntPointer(self, pointer):
580 def visitObjPointer(self, pointer):
581 type = self.visit(pointer.type)
582 return ObjPointer(type)
584 def visitLinearPointer(self, pointer):
585 type = self.visit(pointer.type)
586 return LinearPointer(type, pointer.size)
588 def visitReference(self, reference):
589 type = self.visit(reference.type)
590 return Reference(type)
592 def visitHandle(self, handle):
593 type = self.visit(handle.type)
594 return Handle(handle.name, type, range=handle.range, key=handle.key)
596 def visitAlias(self, alias):
597 type = self.visit(alias.type)
598 return Alias(alias.expr, type)
600 def visitOpaque(self, opaque):
603 def visitInterface(self, interface, *args, **kwargs):
606 def visitPolymorphic(self, polymorphic):
607 defaultType = self.visit(polymorphic.defaultType)
608 switchExpr = polymorphic.switchExpr
609 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
610 return Polymorphic(defaultType, switchExpr, switchTypes)
613 class Collector(Visitor):
614 '''Visitor which collects all unique types as it traverses them.'''
617 self.__visited = set()
620 def visit(self, type):
621 if type in self.__visited:
623 self.__visited.add(type)
624 Visitor.visit(self, type)
625 self.types.append(type)
627 def visitVoid(self, literal):
630 def visitLiteral(self, literal):
633 def visitString(self, string):
636 def visitConst(self, const):
637 self.visit(const.type)
639 def visitStruct(self, struct):
640 for type, name in struct.members:
643 def visitArray(self, array):
644 self.visit(array.type)
646 def visitBlob(self, array):
649 def visitEnum(self, enum):
652 def visitBitmask(self, bitmask):
653 self.visit(bitmask.type)
655 def visitPointer(self, pointer):
656 self.visit(pointer.type)
658 def visitIntPointer(self, pointer):
661 def visitObjPointer(self, pointer):
662 self.visit(pointer.type)
664 def visitLinearPointer(self, pointer):
665 self.visit(pointer.type)
667 def visitReference(self, reference):
668 self.visit(reference.type)
670 def visitHandle(self, handle):
671 self.visit(handle.type)
673 def visitAlias(self, alias):
674 self.visit(alias.type)
676 def visitOpaque(self, opaque):
679 def visitInterface(self, interface):
680 if interface.base is not None:
681 self.visit(interface.base)
682 for method in interface.iterMethods():
683 for arg in method.args:
685 self.visit(method.type)
687 def visitPolymorphic(self, polymorphic):
688 self.visit(polymorphic.defaultType)
689 for expr, type in polymorphic.switchTypes:
696 Essentially, a collection of types, functions, and interfaces.
699 def __init__(self, name = None):
705 def getAllTypes(self):
706 collector = Collector()
707 for function in self.functions:
708 for arg in function.args:
709 collector.visit(arg.type)
710 collector.visit(function.type)
711 for interface in self.interfaces:
712 collector.visit(interface)
713 for method in interface.iterMethods():
714 for arg in method.args:
715 collector.visit(arg.type)
716 collector.visit(method.type)
717 return collector.types
719 def getAllInterfaces(self):
720 types = self.getAllTypes()
721 interfaces = [type for type in types if isinstance(type, Interface)]
722 for interface in self.interfaces:
723 if interface not in interfaces:
724 interfaces.append(interface)
727 def addFunction(self, function):
728 self.functions.append(function)
730 def addFunctions(self, functions):
731 for function in functions:
732 self.addFunction(function)
734 def addInterface(self, interface):
735 self.interfaces.append(interface)
737 def addInterfaces(self, interfaces):
738 self.interfaces.extend(interfaces)
740 def addApi(self, api):
741 self.headers.extend(api.headers)
742 self.addFunctions(api.functions)
743 self.addInterfaces(api.interfaces)
745 def get_function_by_name(self, name):
746 for function in self.functions:
747 if function.name == name:
752 Bool = Literal("bool", "Bool")
753 SChar = Literal("signed char", "SInt")
754 UChar = Literal("unsigned char", "UInt")
755 Short = Literal("short", "SInt")
756 Int = Literal("int", "SInt")
757 Long = Literal("long", "SInt")
758 LongLong = Literal("long long", "SInt")
759 UShort = Literal("unsigned short", "UInt")
760 UInt = Literal("unsigned int", "UInt")
761 ULong = Literal("unsigned long", "UInt")
762 ULongLong = Literal("unsigned long long", "UInt")
763 Float = Literal("float", "Float")
764 Double = Literal("double", "Double")
765 SizeT = Literal("size_t", "UInt")
767 # C string (i.e., zero terminated)
769 WString = String("wchar_t *", kind="WString")
771 Int8 = Literal("int8_t", "SInt")
772 UInt8 = Literal("uint8_t", "UInt")
773 Int16 = Literal("int16_t", "SInt")
774 UInt16 = Literal("uint16_t", "UInt")
775 Int32 = Literal("int32_t", "SInt")
776 UInt32 = Literal("uint32_t", "UInt")
777 Int64 = Literal("int64_t", "SInt")
778 UInt64 = Literal("uint64_t", "UInt")