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)
132 def __init__(self, name, type, range=None, key=None):
133 Type.__init__(self, type.expr, 'P' + type.tag)
139 def visit(self, visitor, *args, **kwargs):
140 return visitor.visitHandle(self, *args, **kwargs)
143 def ConstPointer(type):
144 return Pointer(Const(type))
151 def __init__(self, name, values):
152 Type.__init__(self, name)
157 self.values = list(values)
159 def visit(self, visitor, *args, **kwargs):
160 return visitor.visitEnum(self, *args, **kwargs)
163 def FakeEnum(type, values):
164 return Enum(type.expr, values)
171 def __init__(self, type, values):
172 Type.__init__(self, type.expr)
174 self.id = Bitmask.__id
180 def visit(self, visitor, *args, **kwargs):
181 return visitor.visitBitmask(self, *args, **kwargs)
188 def __init__(self, type, length):
189 Type.__init__(self, type.expr + " *")
193 def visit(self, visitor, *args, **kwargs):
194 return visitor.visitArray(self, *args, **kwargs)
199 def __init__(self, type, size):
200 Type.__init__(self, type.expr + ' *')
204 def visit(self, visitor, *args, **kwargs):
205 return visitor.visitBlob(self, *args, **kwargs)
212 def __init__(self, name, members):
213 Type.__init__(self, name)
215 self.id = Struct.__id
219 self.members = members
221 def visit(self, visitor, *args, **kwargs):
222 return visitor.visitStruct(self, *args, **kwargs)
227 def __init__(self, expr, type):
228 Type.__init__(self, expr)
231 def visit(self, visitor, *args, **kwargs):
232 return visitor.visitAlias(self, *args, **kwargs)
236 arg = Arg(type, name, output=True)
242 def __init__(self, type, name, output=False):
249 return '%s %s' % (self.type, self.name)
254 # 0-3 are reserved to memcpy, malloc, free, and realloc
257 def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
258 self.id = Function.__id
267 if not isinstance(arg, Arg):
268 if isinstance(arg, tuple):
269 arg_type, arg_name = arg
272 arg_name = "arg%u" % index
273 arg = Arg(arg_type, arg_name)
276 self.args.append(arg)
280 self.sideeffects = sideeffects
282 def prototype(self, name=None):
289 s = self.call + ' ' + s
290 if name.startswith('*'):
292 s = self.type.expr + ' ' + s
295 s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
302 def StdFunction(*args, **kwargs):
303 kwargs.setdefault('call', '__stdcall')
304 return Function(*args, **kwargs)
307 def FunctionPointer(type, name, args, **kwargs):
308 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
312 class Interface(Type):
314 def __init__(self, name, base=None):
315 Type.__init__(self, name)
320 def visit(self, visitor, *args, **kwargs):
321 return visitor.visitInterface(self, *args, **kwargs)
323 def iterMethods(self):
324 if self.base is not None:
325 for method in self.base.iterMethods():
327 for method in self.methods:
332 class Method(Function):
334 def __init__(self, type, name, args):
335 Function.__init__(self, type, name, args, call = '__stdcall')
336 for index in range(len(self.args)):
337 self.args[index].index = index + 1
342 def __init__(self, expr = "char *", length = None):
343 Type.__init__(self, expr)
346 def visit(self, visitor, *args, **kwargs):
347 return visitor.visitString(self, *args, **kwargs)
349 # C string (i.e., zero terminated)
354 '''Opaque pointer.'''
356 def __init__(self, expr):
357 Type.__init__(self, expr)
359 def visit(self, visitor, *args, **kwargs):
360 return visitor.visitOpaque(self, *args, **kwargs)
363 def OpaquePointer(type, *args):
364 return Opaque(type.expr + ' *')
366 def OpaqueArray(type, size):
367 return Opaque(type.expr + ' *')
369 def OpaqueBlob(type, size):
370 return Opaque(type.expr + ' *')
373 class Polymorphic(Type):
375 def __init__(self, defaultType, switchExpr, switchTypes):
376 Type.__init__(self, defaultType.expr)
377 self.defaultType = defaultType
378 self.switchExpr = switchExpr
379 self.switchTypes = switchTypes
381 def visit(self, visitor, *args, **kwargs):
382 return visitor.visitPolymorphic(self, *args, **kwargs)
384 def iterSwitch(self):
385 cases = [['default']]
386 types = [self.defaultType]
388 for expr, type in self.switchTypes:
389 case = 'case %s' % expr
391 i = types.index(type)
396 cases[i].append(case)
398 return zip(cases, types)
402 '''Abstract visitor for the type hierarchy.'''
404 def visit(self, type, *args, **kwargs):
405 return type.visit(self, *args, **kwargs)
407 def visitVoid(self, void, *args, **kwargs):
408 raise NotImplementedError
410 def visitLiteral(self, literal, *args, **kwargs):
411 raise NotImplementedError
413 def visitString(self, string, *args, **kwargs):
414 raise NotImplementedError
416 def visitConst(self, const, *args, **kwargs):
417 raise NotImplementedError
419 def visitStruct(self, struct, *args, **kwargs):
420 raise NotImplementedError
422 def visitArray(self, array, *args, **kwargs):
423 raise NotImplementedError
425 def visitBlob(self, blob, *args, **kwargs):
426 raise NotImplementedError
428 def visitEnum(self, enum, *args, **kwargs):
429 raise NotImplementedError
431 def visitBitmask(self, bitmask, *args, **kwargs):
432 raise NotImplementedError
434 def visitPointer(self, pointer, *args, **kwargs):
435 raise NotImplementedError
437 def visitHandle(self, handle, *args, **kwargs):
438 raise NotImplementedError
440 def visitAlias(self, alias, *args, **kwargs):
441 raise NotImplementedError
443 def visitOpaque(self, opaque, *args, **kwargs):
444 raise NotImplementedError
446 def visitInterface(self, interface, *args, **kwargs):
447 raise NotImplementedError
449 def visitPolymorphic(self, polymorphic, *args, **kwargs):
450 raise NotImplementedError
451 #return self.visit(polymorphic.defaultType, *args, **kwargs)
454 class OnceVisitor(Visitor):
455 '''Visitor that guarantees that each type is visited only once.'''
458 self.__visited = set()
460 def visit(self, type, *args, **kwargs):
461 if type not in self.__visited:
462 self.__visited.add(type)
463 return type.visit(self, *args, **kwargs)
467 class Rebuilder(Visitor):
468 '''Visitor which rebuild types as it visits them.
470 By itself it is a no-op -- it is intended to be overwritten.
473 def visitVoid(self, void):
476 def visitLiteral(self, literal):
479 def visitString(self, string):
482 def visitConst(self, const):
483 return Const(const.type)
485 def visitStruct(self, struct):
486 members = [(self.visit(type), name) for type, name in struct.members]
487 return Struct(struct.name, members)
489 def visitArray(self, array):
490 type = self.visit(array.type)
491 return Array(type, array.length)
493 def visitBlob(self, blob):
494 type = self.visit(blob.type)
495 return Blob(type, blob.size)
497 def visitEnum(self, enum):
500 def visitBitmask(self, bitmask):
501 type = self.visit(bitmask.type)
502 return Bitmask(type, bitmask.values)
504 def visitPointer(self, pointer):
505 type = self.visit(pointer.type)
508 def visitHandle(self, handle):
509 type = self.visit(handle.type)
510 return Handle(handle.name, type, range=handle.range, key=handle.key)
512 def visitAlias(self, alias):
513 type = self.visit(alias.type)
514 return Alias(alias.expr, type)
516 def visitOpaque(self, opaque):
519 def visitPolymorphic(self, polymorphic):
520 defaultType = self.visit(polymorphic.defaultType)
521 switchExpr = polymorphic.switchExpr
522 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
523 return Polymorphic(defaultType, switchExpr, switchTypes)
526 class Collector(Visitor):
527 '''Visitor which collects all unique types as it traverses them.'''
530 self.__visited = set()
533 def visit(self, type):
534 if type in self.__visited:
536 self.__visited.add(type)
537 Visitor.visit(self, type)
538 self.types.append(type)
540 def visitVoid(self, literal):
543 def visitLiteral(self, literal):
546 def visitString(self, string):
549 def visitConst(self, const):
550 self.visit(const.type)
552 def visitStruct(self, struct):
553 for type, name in struct.members:
556 def visitArray(self, array):
557 self.visit(array.type)
559 def visitBlob(self, array):
562 def visitEnum(self, enum):
565 def visitBitmask(self, bitmask):
566 self.visit(bitmask.type)
568 def visitPointer(self, pointer):
569 self.visit(pointer.type)
571 def visitHandle(self, handle):
572 self.visit(handle.type)
574 def visitAlias(self, alias):
575 self.visit(alias.type)
577 def visitOpaque(self, opaque):
580 def visitInterface(self, interface):
581 if interface.base is not None:
582 self.visit(interface.base)
583 for method in interface.iterMethods():
584 for arg in method.args:
586 self.visit(method.type)
588 def visitPolymorphic(self, polymorphic):
589 self.visit(polymorphic.defaultType)
590 for expr, type in polymorphic.switchTypes:
597 Essentially, a collection of types, functions, and interfaces.
600 def __init__(self, name = None):
607 collector = Collector()
608 for function in self.functions:
609 for arg in function.args:
610 collector.visit(arg.type)
611 collector.visit(function.type)
612 for interface in self.interfaces:
613 collector.visit(interface)
614 for method in interface.iterMethods():
615 for arg in method.args:
616 collector.visit(arg.type)
617 collector.visit(method.type)
618 return collector.types
620 def addFunction(self, function):
621 self.functions.append(function)
623 def addFunctions(self, functions):
624 for function in functions:
625 self.addFunction(function)
627 def addInterface(self, interface):
628 self.interfaces.append(interface)
630 def addInterfaces(self, interfaces):
631 self.interfaces.extend(interfaces)
633 def addApi(self, api):
634 self.headers.extend(api.headers)
635 self.addFunctions(api.functions)
636 self.addInterfaces(api.interfaces)
638 def get_function_by_name(self, name):
639 for function in self.functions:
640 if function.name == name:
645 Bool = Literal("bool", "Bool")
646 SChar = Literal("signed char", "SInt")
647 UChar = Literal("unsigned char", "UInt")
648 Short = Literal("short", "SInt")
649 Int = Literal("int", "SInt")
650 Long = Literal("long", "SInt")
651 LongLong = Literal("long long", "SInt")
652 UShort = Literal("unsigned short", "UInt")
653 UInt = Literal("unsigned int", "UInt")
654 ULong = Literal("unsigned long", "UInt")
655 ULongLong = Literal("unsigned long long", "UInt")
656 Float = Literal("float", "Float")
657 Double = Literal("double", "Double")
658 SizeT = Literal("size_t", "UInt")
659 WString = Literal("wchar_t *", "WString")
661 Int8 = Literal("int8_t", "SInt")
662 UInt8 = Literal("uint8_t", "UInt")
663 Int16 = Literal("int16_t", "SInt")
664 UInt16 = Literal("uint16_t", "UInt")
665 Int32 = Literal("int32_t", "SInt")
666 UInt32 = Literal("uint32_t", "UInt")
667 Int64 = Literal("int64_t", "SInt")
668 UInt64 = Literal("uint64_t", "UInt")