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, const=False, sideeffects=True):
365 Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
366 for index in range(len(self.args)):
367 self.args[index].index = index + 1
370 def prototype(self, name=None):
371 s = Function.prototype(self, name)
379 def __init__(self, expr = "char *", length = None, kind = 'String'):
380 Type.__init__(self, expr)
384 def visit(self, visitor, *args, **kwargs):
385 return visitor.visitString(self, *args, **kwargs)
389 '''Opaque pointer.'''
391 def __init__(self, expr):
392 Type.__init__(self, expr)
394 def visit(self, visitor, *args, **kwargs):
395 return visitor.visitOpaque(self, *args, **kwargs)
398 def OpaquePointer(type, *args):
399 return Opaque(type.expr + ' *')
401 def OpaqueArray(type, size):
402 return Opaque(type.expr + ' *')
404 def OpaqueBlob(type, size):
405 return Opaque(type.expr + ' *')
408 class Polymorphic(Type):
410 def __init__(self, defaultType, switchExpr, switchTypes):
411 Type.__init__(self, defaultType.expr)
412 self.defaultType = defaultType
413 self.switchExpr = switchExpr
414 self.switchTypes = switchTypes
416 def visit(self, visitor, *args, **kwargs):
417 return visitor.visitPolymorphic(self, *args, **kwargs)
419 def iterSwitch(self):
420 cases = [['default']]
421 types = [self.defaultType]
423 for expr, type in self.switchTypes:
424 case = 'case %s' % expr
426 i = types.index(type)
431 cases[i].append(case)
433 return zip(cases, types)
437 '''Abstract visitor for the type hierarchy.'''
439 def visit(self, type, *args, **kwargs):
440 return type.visit(self, *args, **kwargs)
442 def visitVoid(self, void, *args, **kwargs):
443 raise NotImplementedError
445 def visitLiteral(self, literal, *args, **kwargs):
446 raise NotImplementedError
448 def visitString(self, string, *args, **kwargs):
449 raise NotImplementedError
451 def visitConst(self, const, *args, **kwargs):
452 raise NotImplementedError
454 def visitStruct(self, struct, *args, **kwargs):
455 raise NotImplementedError
457 def visitArray(self, array, *args, **kwargs):
458 raise NotImplementedError
460 def visitBlob(self, blob, *args, **kwargs):
461 raise NotImplementedError
463 def visitEnum(self, enum, *args, **kwargs):
464 raise NotImplementedError
466 def visitBitmask(self, bitmask, *args, **kwargs):
467 raise NotImplementedError
469 def visitPointer(self, pointer, *args, **kwargs):
470 raise NotImplementedError
472 def visitIntPointer(self, pointer, *args, **kwargs):
473 raise NotImplementedError
475 def visitLinearPointer(self, pointer, *args, **kwargs):
476 raise NotImplementedError
478 def visitHandle(self, handle, *args, **kwargs):
479 raise NotImplementedError
481 def visitAlias(self, alias, *args, **kwargs):
482 raise NotImplementedError
484 def visitOpaque(self, opaque, *args, **kwargs):
485 raise NotImplementedError
487 def visitInterface(self, interface, *args, **kwargs):
488 raise NotImplementedError
490 def visitPolymorphic(self, polymorphic, *args, **kwargs):
491 raise NotImplementedError
492 #return self.visit(polymorphic.defaultType, *args, **kwargs)
495 class OnceVisitor(Visitor):
496 '''Visitor that guarantees that each type is visited only once.'''
499 self.__visited = set()
501 def visit(self, type, *args, **kwargs):
502 if type not in self.__visited:
503 self.__visited.add(type)
504 return type.visit(self, *args, **kwargs)
508 class Rebuilder(Visitor):
509 '''Visitor which rebuild types as it visits them.
511 By itself it is a no-op -- it is intended to be overwritten.
514 def visitVoid(self, void):
517 def visitLiteral(self, literal):
520 def visitString(self, string):
523 def visitConst(self, const):
524 return Const(const.type)
526 def visitStruct(self, struct):
527 members = [(self.visit(type), name) for type, name in struct.members]
528 return Struct(struct.name, members)
530 def visitArray(self, array):
531 type = self.visit(array.type)
532 return Array(type, array.length)
534 def visitBlob(self, blob):
535 type = self.visit(blob.type)
536 return Blob(type, blob.size)
538 def visitEnum(self, enum):
541 def visitBitmask(self, bitmask):
542 type = self.visit(bitmask.type)
543 return Bitmask(type, bitmask.values)
545 def visitPointer(self, pointer):
546 type = self.visit(pointer.type)
549 def visitIntPointer(self, pointer):
552 def visitLinearPointer(self, pointer):
553 type = self.visit(pointer.type)
554 return LinearPointer(type, pointer.size)
556 def visitHandle(self, handle):
557 type = self.visit(handle.type)
558 return Handle(handle.name, type, range=handle.range, key=handle.key)
560 def visitAlias(self, alias):
561 type = self.visit(alias.type)
562 return Alias(alias.expr, type)
564 def visitOpaque(self, opaque):
567 def visitInterface(self, interface, *args, **kwargs):
570 def visitPolymorphic(self, polymorphic):
571 defaultType = self.visit(polymorphic.defaultType)
572 switchExpr = polymorphic.switchExpr
573 switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
574 return Polymorphic(defaultType, switchExpr, switchTypes)
577 class Collector(Visitor):
578 '''Visitor which collects all unique types as it traverses them.'''
581 self.__visited = set()
584 def visit(self, type):
585 if type in self.__visited:
587 self.__visited.add(type)
588 Visitor.visit(self, type)
589 self.types.append(type)
591 def visitVoid(self, literal):
594 def visitLiteral(self, literal):
597 def visitString(self, string):
600 def visitConst(self, const):
601 self.visit(const.type)
603 def visitStruct(self, struct):
604 for type, name in struct.members:
607 def visitArray(self, array):
608 self.visit(array.type)
610 def visitBlob(self, array):
613 def visitEnum(self, enum):
616 def visitBitmask(self, bitmask):
617 self.visit(bitmask.type)
619 def visitPointer(self, pointer):
620 self.visit(pointer.type)
622 def visitIntPointer(self, pointer):
625 def visitLinearPointer(self, pointer):
626 self.visit(pointer.type)
628 def visitHandle(self, handle):
629 self.visit(handle.type)
631 def visitAlias(self, alias):
632 self.visit(alias.type)
634 def visitOpaque(self, opaque):
637 def visitInterface(self, interface):
638 if interface.base is not None:
639 self.visit(interface.base)
640 for method in interface.iterMethods():
641 for arg in method.args:
643 self.visit(method.type)
645 def visitPolymorphic(self, polymorphic):
646 self.visit(polymorphic.defaultType)
647 for expr, type in polymorphic.switchTypes:
654 Essentially, a collection of types, functions, and interfaces.
657 def __init__(self, name = None):
663 def getAllTypes(self):
664 collector = Collector()
665 for function in self.functions:
666 for arg in function.args:
667 collector.visit(arg.type)
668 collector.visit(function.type)
669 for interface in self.interfaces:
670 collector.visit(interface)
671 for method in interface.iterMethods():
672 for arg in method.args:
673 collector.visit(arg.type)
674 collector.visit(method.type)
675 return collector.types
677 def getAllInterfaces(self):
678 types = self.getAllTypes()
679 interfaces = [type for type in types if isinstance(type, Interface)]
680 for interface in self.interfaces:
681 if interface not in interfaces:
682 interfaces.append(interface)
685 def addFunction(self, function):
686 self.functions.append(function)
688 def addFunctions(self, functions):
689 for function in functions:
690 self.addFunction(function)
692 def addInterface(self, interface):
693 self.interfaces.append(interface)
695 def addInterfaces(self, interfaces):
696 self.interfaces.extend(interfaces)
698 def addApi(self, api):
699 self.headers.extend(api.headers)
700 self.addFunctions(api.functions)
701 self.addInterfaces(api.interfaces)
703 def get_function_by_name(self, name):
704 for function in self.functions:
705 if function.name == name:
710 Bool = Literal("bool", "Bool")
711 SChar = Literal("signed char", "SInt")
712 UChar = Literal("unsigned char", "UInt")
713 Short = Literal("short", "SInt")
714 Int = Literal("int", "SInt")
715 Long = Literal("long", "SInt")
716 LongLong = Literal("long long", "SInt")
717 UShort = Literal("unsigned short", "UInt")
718 UInt = Literal("unsigned int", "UInt")
719 ULong = Literal("unsigned long", "UInt")
720 ULongLong = Literal("unsigned long long", "UInt")
721 Float = Literal("float", "Float")
722 Double = Literal("double", "Double")
723 SizeT = Literal("size_t", "UInt")
725 # C string (i.e., zero terminated)
727 WString = String("wchar_t *", kind="WString")
729 Int8 = Literal("int8_t", "SInt")
730 UInt8 = Literal("uint8_t", "UInt")
731 Int16 = Literal("int16_t", "SInt")
732 UInt16 = Literal("uint16_t", "UInt")
733 Int32 = Literal("int32_t", "SInt")
734 UInt32 = Literal("uint32_t", "UInt")
735 Int64 = Literal("int64_t", "SInt")
736 UInt64 = Literal("uint64_t", "UInt")