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)
151 def __init__(self, name, type, range=None, key=None):
152 Type.__init__(self, type.expr, 'P' + type.tag)
158 def visit(self, visitor, *args, **kwargs):
159 return visitor.visitHandle(self, *args, **kwargs)
162 def ConstPointer(type):
163 return Pointer(Const(type))
170 def __init__(self, name, values):
171 Type.__init__(self, name)
176 self.values = list(values)
178 def visit(self, visitor, *args, **kwargs):
179 return visitor.visitEnum(self, *args, **kwargs)
182 def FakeEnum(type, values):
183 return Enum(type.expr, values)
190 def __init__(self, type, values):
191 Type.__init__(self, type.expr)
193 self.id = Bitmask.__id
199 def visit(self, visitor, *args, **kwargs):
200 return visitor.visitBitmask(self, *args, **kwargs)
207 def __init__(self, type, length):
208 Type.__init__(self, type.expr + " *")
212 def visit(self, visitor, *args, **kwargs):
213 return visitor.visitArray(self, *args, **kwargs)
218 def __init__(self, type, size):
219 Type.__init__(self, type.expr + ' *')
223 def visit(self, visitor, *args, **kwargs):
224 return visitor.visitBlob(self, *args, **kwargs)
231 def __init__(self, name, members):
232 Type.__init__(self, name)
234 self.id = Struct.__id
238 self.members = members
240 def visit(self, visitor, *args, **kwargs):
241 return visitor.visitStruct(self, *args, **kwargs)
246 def __init__(self, expr, type):
247 Type.__init__(self, expr)
250 def visit(self, visitor, *args, **kwargs):
251 return visitor.visitAlias(self, *args, **kwargs)
255 arg = Arg(type, name, output=True)
261 def __init__(self, type, name, output=False):
268 return '%s %s' % (self.type, self.name)
273 # 0-3 are reserved to memcpy, malloc, free, and realloc
276 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
277 self.id = Function.__id
286 if not isinstance(arg, Arg):
287 if isinstance(arg, tuple):
288 arg_type, arg_name = arg
291 arg_name = "arg%u" % index
292 arg = Arg(arg_type, arg_name)
295 self.args.append(arg)
299 self.sideeffects = sideeffects
301 def prototype(self, name=None):
308 s = self.call + ' ' + s
309 if name.startswith('*'):
311 s = self.type.expr + ' ' + s
314 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
321 return [arg.name for arg in self.args]
324 def StdFunction(*args, **kwargs):
325 kwargs.setdefault('call', '__stdcall')
326 return Function(*args, **kwargs)
329 def FunctionPointer(type, name, args, **kwargs):
330 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
334 class Interface(Type):
336 def __init__(self, name, base=None):
337 Type.__init__(self, name)
342 def visit(self, visitor, *args, **kwargs):
343 return visitor.visitInterface(self, *args, **kwargs)
345 def iterMethods(self):
346 if self.base is not None:
347 for method in self.base.iterMethods():
349 for method in self.methods:
353 def iterBaseMethods(self):
354 if self.base is not None:
355 for iface, method in self.base.iterBaseMethods():
357 for method in self.methods:
362 class Method(Function):
364 def __init__(self, type, name, args):
365 Function.__init__(self, type, name, args, call = '__stdcall')
366 for index in range(len(self.args)):
367 self.args[index].index = index + 1
372 def __init__(self, expr = "char *", length = None, kind = 'String'):
373 Type.__init__(self, expr)
377 def visit(self, visitor, *args, **kwargs):
378 return visitor.visitString(self, *args, **kwargs)
382 '''Opaque pointer.'''
384 def __init__(self, expr):
385 Type.__init__(self, expr)
387 def visit(self, visitor, *args, **kwargs):
388 return visitor.visitOpaque(self, *args, **kwargs)
391 def OpaquePointer(type, *args):
392 return Opaque(type.expr + ' *')
394 def OpaqueArray(type, size):
395 return Opaque(type.expr + ' *')
397 def OpaqueBlob(type, size):
398 return Opaque(type.expr + ' *')
401 class Polymorphic(Type):
403 def __init__(self, defaultType, switchExpr, switchTypes):
404 Type.__init__(self, defaultType.expr)
405 self.defaultType = defaultType
406 self.switchExpr = switchExpr
407 self.switchTypes = switchTypes
409 def visit(self, visitor, *args, **kwargs):
410 return visitor.visitPolymorphic(self, *args, **kwargs)
412 def iterSwitch(self):
413 cases = [['default']]
414 types = [self.defaultType]
416 for expr, type in self.switchTypes:
417 case = 'case %s' % expr
419 i = types.index(type)
424 cases[i].append(case)
426 return zip(cases, types)
430 '''Abstract visitor for the type hierarchy.'''
432 def visit(self, type, *args, **kwargs):
433 return type.visit(self, *args, **kwargs)
435 def visitVoid(self, void, *args, **kwargs):
436 raise NotImplementedError
438 def visitLiteral(self, literal, *args, **kwargs):
439 raise NotImplementedError
441 def visitString(self, string, *args, **kwargs):
442 raise NotImplementedError
444 def visitConst(self, const, *args, **kwargs):
445 raise NotImplementedError
447 def visitStruct(self, struct, *args, **kwargs):
448 raise NotImplementedError
450 def visitArray(self, array, *args, **kwargs):
451 raise NotImplementedError
453 def visitBlob(self, blob, *args, **kwargs):
454 raise NotImplementedError
456 def visitEnum(self, enum, *args, **kwargs):
457 raise NotImplementedError
459 def visitBitmask(self, bitmask, *args, **kwargs):
460 raise NotImplementedError
462 def visitPointer(self, pointer, *args, **kwargs):
463 raise NotImplementedError
465 def visitIntPointer(self, pointer, *args, **kwargs):
466 raise NotImplementedError
468 def visitLinearPointer(self, pointer, *args, **kwargs):
469 raise NotImplementedError
471 def visitHandle(self, handle, *args, **kwargs):
472 raise NotImplementedError
474 def visitAlias(self, alias, *args, **kwargs):
475 raise NotImplementedError
477 def visitOpaque(self, opaque, *args, **kwargs):
478 raise NotImplementedError
480 def visitInterface(self, interface, *args, **kwargs):
481 raise NotImplementedError
483 def visitPolymorphic(self, polymorphic, *args, **kwargs):
484 raise NotImplementedError
485 #return self.visit(polymorphic.defaultType, *args, **kwargs)
488 class OnceVisitor(Visitor):
489 '''Visitor that guarantees that each type is visited only once.'''
492 self.__visited = set()
494 def visit(self, type, *args, **kwargs):
495 if type not in self.__visited:
496 self.__visited.add(type)
497 return type.visit(self, *args, **kwargs)
501 class Rebuilder(Visitor):
502 '''Visitor which rebuild types as it visits them.
504 By itself it is a no-op -- it is intended to be overwritten.
507 def visitVoid(self, void):
510 def visitLiteral(self, literal):
513 def visitString(self, string):
516 def visitConst(self, const):
517 return Const(const.type)
519 def visitStruct(self, struct):
520 members = [(self.visit(type), name) for type, name in struct.members]
521 return Struct(struct.name, members)
523 def visitArray(self, array):
524 type = self.visit(array.type)
525 return Array(type, array.length)
527 def visitBlob(self, blob):
528 type = self.visit(blob.type)
529 return Blob(type, blob.size)
531 def visitEnum(self, enum):
534 def visitBitmask(self, bitmask):
535 type = self.visit(bitmask.type)
536 return Bitmask(type, bitmask.values)
538 def visitPointer(self, pointer):
539 type = self.visit(pointer.type)
542 def visitIntPointer(self, pointer):
545 def visitLinearPointer(self, pointer):
546 type = self.visit(pointer.type)
547 return LinearPointer(type, pointer.size)
549 def visitHandle(self, handle):
550 type = self.visit(handle.type)
551 return Handle(handle.name, type, range=handle.range, key=handle.key)
553 def visitAlias(self, alias):
554 type = self.visit(alias.type)
555 return Alias(alias.expr, type)
557 def visitOpaque(self, opaque):
560 def visitInterface(self, interface, *args, **kwargs):
563 def visitPolymorphic(self, polymorphic):
564 defaultType = self.visit(polymorphic.defaultType)
565 switchExpr = polymorphic.switchExpr
566 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
567 return Polymorphic(defaultType, switchExpr, switchTypes)
570 class Collector(Visitor):
571 '''Visitor which collects all unique types as it traverses them.'''
574 self.__visited = set()
577 def visit(self, type):
578 if type in self.__visited:
580 self.__visited.add(type)
581 Visitor.visit(self, type)
582 self.types.append(type)
584 def visitVoid(self, literal):
587 def visitLiteral(self, literal):
590 def visitString(self, string):
593 def visitConst(self, const):
594 self.visit(const.type)
596 def visitStruct(self, struct):
597 for type, name in struct.members:
600 def visitArray(self, array):
601 self.visit(array.type)
603 def visitBlob(self, array):
606 def visitEnum(self, enum):
609 def visitBitmask(self, bitmask):
610 self.visit(bitmask.type)
612 def visitPointer(self, pointer):
613 self.visit(pointer.type)
615 def visitIntPointer(self, pointer):
618 def visitLinearPointer(self, pointer):
619 self.visit(pointer.type)
621 def visitHandle(self, handle):
622 self.visit(handle.type)
624 def visitAlias(self, alias):
625 self.visit(alias.type)
627 def visitOpaque(self, opaque):
630 def visitInterface(self, interface):
631 if interface.base is not None:
632 self.visit(interface.base)
633 for method in interface.iterMethods():
634 for arg in method.args:
636 self.visit(method.type)
638 def visitPolymorphic(self, polymorphic):
639 self.visit(polymorphic.defaultType)
640 for expr, type in polymorphic.switchTypes:
647 Essentially, a collection of types, functions, and interfaces.
650 def __init__(self, name = None):
656 def getAllTypes(self):
657 collector = Collector()
658 for function in self.functions:
659 for arg in function.args:
660 collector.visit(arg.type)
661 collector.visit(function.type)
662 for interface in self.interfaces:
663 collector.visit(interface)
664 for method in interface.iterMethods():
665 for arg in method.args:
666 collector.visit(arg.type)
667 collector.visit(method.type)
668 return collector.types
670 def getAllInterfaces(self):
671 types = self.getAllTypes()
672 interfaces = [type for type in types if isinstance(type, Interface)]
673 for interface in self.interfaces:
674 if interface not in interfaces:
675 interfaces.append(interface)
678 def addFunction(self, function):
679 self.functions.append(function)
681 def addFunctions(self, functions):
682 for function in functions:
683 self.addFunction(function)
685 def addInterface(self, interface):
686 self.interfaces.append(interface)
688 def addInterfaces(self, interfaces):
689 self.interfaces.extend(interfaces)
691 def addApi(self, api):
692 self.headers.extend(api.headers)
693 self.addFunctions(api.functions)
694 self.addInterfaces(api.interfaces)
696 def get_function_by_name(self, name):
697 for function in self.functions:
698 if function.name == name:
703 Bool = Literal("bool", "Bool")
704 SChar = Literal("signed char", "SInt")
705 UChar = Literal("unsigned char", "UInt")
706 Short = Literal("short", "SInt")
707 Int = Literal("int", "SInt")
708 Long = Literal("long", "SInt")
709 LongLong = Literal("long long", "SInt")
710 UShort = Literal("unsigned short", "UInt")
711 UInt = Literal("unsigned int", "UInt")
712 ULong = Literal("unsigned long", "UInt")
713 ULongLong = Literal("unsigned long long", "UInt")
714 Float = Literal("float", "Float")
715 Double = Literal("double", "Double")
716 SizeT = Literal("size_t", "UInt")
718 # C string (i.e., zero terminated)
720 WString = String("wchar_t *", kind="WString")
722 Int8 = Literal("int8_t", "SInt")
723 UInt8 = Literal("uint8_t", "UInt")
724 Int16 = Literal("int16_t", "SInt")
725 UInt16 = Literal("uint16_t", "UInt")
726 Int32 = Literal("int32_t", "SInt")
727 UInt32 = Literal("uint32_t", "UInt")
728 Int64 = Literal("int64_t", "SInt")
729 UInt64 = Literal("uint64_t", "UInt")