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 return [arg.name for arg in self.args]
305 def StdFunction(*args, **kwargs):
306 kwargs.setdefault('call', '__stdcall')
307 return Function(*args, **kwargs)
310 def FunctionPointer(type, name, args, **kwargs):
311 # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
315 class Interface(Type):
317 def __init__(self, name, base=None):
318 Type.__init__(self, name)
323 def visit(self, visitor, *args, **kwargs):
324 return visitor.visitInterface(self, *args, **kwargs)
326 def iterMethods(self):
327 if self.base is not None:
328 for method in self.base.iterMethods():
330 for method in self.methods:
335 class Method(Function):
337 def __init__(self, type, name, args):
338 Function.__init__(self, type, name, args, call = '__stdcall')
339 for index in range(len(self.args)):
340 self.args[index].index = index + 1
345 def __init__(self, expr = "char *", length = None):
346 Type.__init__(self, expr)
349 def visit(self, visitor, *args, **kwargs):
350 return visitor.visitString(self, *args, **kwargs)
352 # C string (i.e., zero terminated)
357 '''Opaque pointer.'''
359 def __init__(self, expr):
360 Type.__init__(self, expr)
362 def visit(self, visitor, *args, **kwargs):
363 return visitor.visitOpaque(self, *args, **kwargs)
366 def OpaquePointer(type, *args):
367 return Opaque(type.expr + ' *')
369 def OpaqueArray(type, size):
370 return Opaque(type.expr + ' *')
372 def OpaqueBlob(type, size):
373 return Opaque(type.expr + ' *')
376 class Polymorphic(Type):
378 def __init__(self, defaultType, switchExpr, switchTypes):
379 Type.__init__(self, defaultType.expr)
380 self.defaultType = defaultType
381 self.switchExpr = switchExpr
382 self.switchTypes = switchTypes
384 def visit(self, visitor, *args, **kwargs):
385 return visitor.visitPolymorphic(self, *args, **kwargs)
387 def iterSwitch(self):
388 cases = [['default']]
389 types = [self.defaultType]
391 for expr, type in self.switchTypes:
392 case = 'case %s' % expr
394 i = types.index(type)
399 cases[i].append(case)
401 return zip(cases, types)
405 '''Abstract visitor for the type hierarchy.'''
407 def visit(self, type, *args, **kwargs):
408 return type.visit(self, *args, **kwargs)
410 def visitVoid(self, void, *args, **kwargs):
411 raise NotImplementedError
413 def visitLiteral(self, literal, *args, **kwargs):
414 raise NotImplementedError
416 def visitString(self, string, *args, **kwargs):
417 raise NotImplementedError
419 def visitConst(self, const, *args, **kwargs):
420 raise NotImplementedError
422 def visitStruct(self, struct, *args, **kwargs):
423 raise NotImplementedError
425 def visitArray(self, array, *args, **kwargs):
426 raise NotImplementedError
428 def visitBlob(self, blob, *args, **kwargs):
429 raise NotImplementedError
431 def visitEnum(self, enum, *args, **kwargs):
432 raise NotImplementedError
434 def visitBitmask(self, bitmask, *args, **kwargs):
435 raise NotImplementedError
437 def visitPointer(self, pointer, *args, **kwargs):
438 raise NotImplementedError
440 def visitHandle(self, handle, *args, **kwargs):
441 raise NotImplementedError
443 def visitAlias(self, alias, *args, **kwargs):
444 raise NotImplementedError
446 def visitOpaque(self, opaque, *args, **kwargs):
447 raise NotImplementedError
449 def visitInterface(self, interface, *args, **kwargs):
450 raise NotImplementedError
452 def visitPolymorphic(self, polymorphic, *args, **kwargs):
453 raise NotImplementedError
454 #return self.visit(polymorphic.defaultType, *args, **kwargs)
457 class OnceVisitor(Visitor):
458 '''Visitor that guarantees that each type is visited only once.'''
461 self.__visited = set()
463 def visit(self, type, *args, **kwargs):
464 if type not in self.__visited:
465 self.__visited.add(type)
466 return type.visit(self, *args, **kwargs)
470 class Rebuilder(Visitor):
471 '''Visitor which rebuild types as it visits them.
473 By itself it is a no-op -- it is intended to be overwritten.
476 def visitVoid(self, void):
479 def visitLiteral(self, literal):
482 def visitString(self, string):
485 def visitConst(self, const):
486 return Const(const.type)
488 def visitStruct(self, struct):
489 members = [(self.visit(type), name) for type, name in struct.members]
490 return Struct(struct.name, members)
492 def visitArray(self, array):
493 type = self.visit(array.type)
494 return Array(type, array.length)
496 def visitBlob(self, blob):
497 type = self.visit(blob.type)
498 return Blob(type, blob.size)
500 def visitEnum(self, enum):
503 def visitBitmask(self, bitmask):
504 type = self.visit(bitmask.type)
505 return Bitmask(type, bitmask.values)
507 def visitPointer(self, pointer):
508 type = self.visit(pointer.type)
511 def visitHandle(self, handle):
512 type = self.visit(handle.type)
513 return Handle(handle.name, type, range=handle.range, key=handle.key)
515 def visitAlias(self, alias):
516 type = self.visit(alias.type)
517 return Alias(alias.expr, type)
519 def visitOpaque(self, opaque):
522 def visitPolymorphic(self, polymorphic):
523 defaultType = self.visit(polymorphic.defaultType)
524 switchExpr = polymorphic.switchExpr
525 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
526 return Polymorphic(defaultType, switchExpr, switchTypes)
529 class Collector(Visitor):
530 '''Visitor which collects all unique types as it traverses them.'''
533 self.__visited = set()
536 def visit(self, type):
537 if type in self.__visited:
539 self.__visited.add(type)
540 Visitor.visit(self, type)
541 self.types.append(type)
543 def visitVoid(self, literal):
546 def visitLiteral(self, literal):
549 def visitString(self, string):
552 def visitConst(self, const):
553 self.visit(const.type)
555 def visitStruct(self, struct):
556 for type, name in struct.members:
559 def visitArray(self, array):
560 self.visit(array.type)
562 def visitBlob(self, array):
565 def visitEnum(self, enum):
568 def visitBitmask(self, bitmask):
569 self.visit(bitmask.type)
571 def visitPointer(self, pointer):
572 self.visit(pointer.type)
574 def visitHandle(self, handle):
575 self.visit(handle.type)
577 def visitAlias(self, alias):
578 self.visit(alias.type)
580 def visitOpaque(self, opaque):
583 def visitInterface(self, interface):
584 if interface.base is not None:
585 self.visit(interface.base)
586 for method in interface.iterMethods():
587 for arg in method.args:
589 self.visit(method.type)
591 def visitPolymorphic(self, polymorphic):
592 self.visit(polymorphic.defaultType)
593 for expr, type in polymorphic.switchTypes:
600 Essentially, a collection of types, functions, and interfaces.
603 def __init__(self, name = None):
610 collector = Collector()
611 for function in self.functions:
612 for arg in function.args:
613 collector.visit(arg.type)
614 collector.visit(function.type)
615 for interface in self.interfaces:
616 collector.visit(interface)
617 for method in interface.iterMethods():
618 for arg in method.args:
619 collector.visit(arg.type)
620 collector.visit(method.type)
621 return collector.types
623 def addFunction(self, function):
624 self.functions.append(function)
626 def addFunctions(self, functions):
627 for function in functions:
628 self.addFunction(function)
630 def addInterface(self, interface):
631 self.interfaces.append(interface)
633 def addInterfaces(self, interfaces):
634 self.interfaces.extend(interfaces)
636 def addApi(self, api):
637 self.headers.extend(api.headers)
638 self.addFunctions(api.functions)
639 self.addInterfaces(api.interfaces)
641 def get_function_by_name(self, name):
642 for function in self.functions:
643 if function.name == name:
648 Bool = Literal("bool", "Bool")
649 SChar = Literal("signed char", "SInt")
650 UChar = Literal("unsigned char", "UInt")
651 Short = Literal("short", "SInt")
652 Int = Literal("int", "SInt")
653 Long = Literal("long", "SInt")
654 LongLong = Literal("long long", "SInt")
655 UShort = Literal("unsigned short", "UInt")
656 UInt = Literal("unsigned int", "UInt")
657 ULong = Literal("unsigned long", "UInt")
658 ULongLong = Literal("unsigned long long", "UInt")
659 Float = Literal("float", "Float")
660 Double = Literal("double", "Double")
661 SizeT = Literal("size_t", "UInt")
662 WString = Literal("wchar_t *", "WString")
664 Int8 = Literal("int8_t", "SInt")
665 UInt8 = Literal("uint8_t", "UInt")
666 Int16 = Literal("int16_t", "SInt")
667 UInt16 = Literal("uint16_t", "UInt")
668 Int32 = Literal("int32_t", "SInt")
669 UInt32 = Literal("uint32_t", "UInt")
670 Int64 = Literal("int64_t", "SInt")
671 UInt64 = Literal("uint64_t", "UInt")