]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
Allow InOut arguments.
[apitrace] / specs / stdapi.py
1 ##########################################################################
2 #
3 # Copyright 2008-2010 VMware, Inc.
4 # All Rights Reserved.
5 #
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:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
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
22 # THE SOFTWARE.
23 #
24 ##########################################################################/
25
26 """C basic types"""
27
28
29 import debug
30
31
32 class Type:
33     """Base class for all types."""
34
35     __tags = set()
36
37     def __init__(self, expr, tag = None):
38         self.expr = expr
39
40         # Generate a default tag, used when naming functions that will operate
41         # on this type, so it should preferrably be something representative of
42         # the type.
43         if tag is None:
44             tag = ''.join([c for c in expr if c.isalnum() or c in '_'])
45         else:
46             for c in tag:
47                 assert c.isalnum() or c in '_'
48
49         # Ensure it is unique.
50         if tag in Type.__tags:
51             suffix = 1
52             while tag + str(suffix) in Type.__tags:
53                 suffix += 1
54             tag += str(suffix)
55
56         assert tag not in Type.__tags
57         Type.__tags.add(tag)
58
59         self.tag = tag
60
61     def __str__(self):
62         """Return the C/C++ type expression for this type."""
63         return self.expr
64
65     def visit(self, visitor, *args, **kwargs):
66         raise NotImplementedError
67
68
69
70 class _Void(Type):
71     """Singleton void type."""
72
73     def __init__(self):
74         Type.__init__(self, "void")
75
76     def visit(self, visitor, *args, **kwargs):
77         return visitor.visitVoid(self, *args, **kwargs)
78
79 Void = _Void()
80
81
82 class Literal(Type):
83     """Class to describe literal types.
84
85     Types which are not defined in terms of other types, such as integers and
86     floats."""
87
88     def __init__(self, expr, kind):
89         Type.__init__(self, expr)
90         self.kind = kind
91
92     def visit(self, visitor, *args, **kwargs):
93         return visitor.visitLiteral(self, *args, **kwargs)
94
95
96 class Const(Type):
97
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"
108         else:
109             # The most legible
110             expr = "const " + type.expr
111
112         Type.__init__(self, expr, 'C' + type.tag)
113
114         self.type = type
115
116     def visit(self, visitor, *args, **kwargs):
117         return visitor.visitConst(self, *args, **kwargs)
118
119
120 class Pointer(Type):
121
122     def __init__(self, type):
123         Type.__init__(self, type.expr + " *", 'P' + type.tag)
124         self.type = type
125
126     def visit(self, visitor, *args, **kwargs):
127         return visitor.visitPointer(self, *args, **kwargs)
128
129
130 class IntPointer(Type):
131     '''Integer encoded as a pointer.'''
132
133     def visit(self, visitor, *args, **kwargs):
134         return visitor.visitIntPointer(self, *args, **kwargs)
135
136
137 class ObjPointer(Type):
138     '''Pointer to an object.'''
139
140     def __init__(self, type):
141         Type.__init__(self, type.expr + " *", 'P' + type.tag)
142         self.type = type
143
144     def visit(self, visitor, *args, **kwargs):
145         return visitor.visitObjPointer(self, *args, **kwargs)
146
147
148 class LinearPointer(Type):
149     '''Pointer to a linear range of memory.'''
150
151     def __init__(self, type, size = None):
152         Type.__init__(self, type.expr + " *", 'P' + type.tag)
153         self.type = type
154         self.size = size
155
156     def visit(self, visitor, *args, **kwargs):
157         return visitor.visitLinearPointer(self, *args, **kwargs)
158
159
160 class Reference(Type):
161     '''C++ references.'''
162
163     def __init__(self, type):
164         Type.__init__(self, type.expr + " &", 'R' + type.tag)
165         self.type = type
166
167     def visit(self, visitor, *args, **kwargs):
168         return visitor.visitReference(self, *args, **kwargs)
169
170
171 class Handle(Type):
172
173     def __init__(self, name, type, range=None, key=None):
174         Type.__init__(self, type.expr, 'P' + type.tag)
175         self.name = name
176         self.type = type
177         self.range = range
178         self.key = key
179
180     def visit(self, visitor, *args, **kwargs):
181         return visitor.visitHandle(self, *args, **kwargs)
182
183
184 def ConstPointer(type):
185     return Pointer(Const(type))
186
187
188 class Enum(Type):
189
190     __id = 0
191
192     def __init__(self, name, values):
193         Type.__init__(self, name)
194
195         self.id = Enum.__id
196         Enum.__id += 1
197
198         self.values = list(values)
199
200     def visit(self, visitor, *args, **kwargs):
201         return visitor.visitEnum(self, *args, **kwargs)
202
203
204 def FakeEnum(type, values):
205     return Enum(type.expr, values)
206
207
208 class Bitmask(Type):
209
210     __id = 0
211
212     def __init__(self, type, values):
213         Type.__init__(self, type.expr)
214
215         self.id = Bitmask.__id
216         Bitmask.__id += 1
217
218         self.type = type
219         self.values = values
220
221     def visit(self, visitor, *args, **kwargs):
222         return visitor.visitBitmask(self, *args, **kwargs)
223
224 Flags = Bitmask
225
226
227 class Array(Type):
228
229     def __init__(self, type, length):
230         Type.__init__(self, type.expr + " *")
231         self.type = type
232         self.length = length
233
234     def visit(self, visitor, *args, **kwargs):
235         return visitor.visitArray(self, *args, **kwargs)
236
237
238 class Blob(Type):
239
240     def __init__(self, type, size):
241         Type.__init__(self, type.expr + ' *')
242         self.type = type
243         self.size = size
244
245     def visit(self, visitor, *args, **kwargs):
246         return visitor.visitBlob(self, *args, **kwargs)
247
248
249 class Struct(Type):
250
251     __id = 0
252
253     def __init__(self, name, members):
254         Type.__init__(self, name)
255
256         self.id = Struct.__id
257         Struct.__id += 1
258
259         self.name = name
260         self.members = members
261
262     def visit(self, visitor, *args, **kwargs):
263         return visitor.visitStruct(self, *args, **kwargs)
264
265
266 class Alias(Type):
267
268     def __init__(self, expr, type):
269         Type.__init__(self, expr)
270         self.type = type
271
272     def visit(self, visitor, *args, **kwargs):
273         return visitor.visitAlias(self, *args, **kwargs)
274
275 class Arg:
276
277     def __init__(self, type, name, input=True, output=False):
278         self.type = type
279         self.name = name
280         self.input = input
281         self.output = output
282         self.index = None
283
284     def __str__(self):
285         return '%s %s' % (self.type, self.name)
286
287
288 def In(type, name):
289     return Arg(type, name, input=True, output=False)
290
291 def Out(type, name):
292     return Arg(type, name, input=False, output=True)
293
294 def InOut(type, name):
295     return Arg(type, name, input=True, output=True)
296
297
298 class Function:
299
300     # 0-3 are reserved to memcpy, malloc, free, and realloc
301     __id = 4
302
303     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
304         self.id = Function.__id
305         Function.__id += 1
306
307         self.type = type
308         self.name = name
309
310         self.args = []
311         index = 0
312         for arg in args:
313             if not isinstance(arg, Arg):
314                 if isinstance(arg, tuple):
315                     arg_type, arg_name = arg
316                 else:
317                     arg_type = arg
318                     arg_name = "arg%u" % index
319                 arg = Arg(arg_type, arg_name)
320             arg.index = index
321             index += 1
322             self.args.append(arg)
323
324         self.call = call
325         self.fail = fail
326         self.sideeffects = sideeffects
327
328     def prototype(self, name=None):
329         if name is not None:
330             name = name.strip()
331         else:
332             name = self.name
333         s = name
334         if self.call:
335             s = self.call + ' ' + s
336         if name.startswith('*'):
337             s = '(' + s + ')'
338         s = self.type.expr + ' ' + s
339         s += "("
340         if self.args:
341             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
342         else:
343             s += "void"
344         s += ")"
345         return s
346
347     def argNames(self):
348         return [arg.name for arg in self.args]
349
350
351 def StdFunction(*args, **kwargs):
352     kwargs.setdefault('call', '__stdcall')
353     return Function(*args, **kwargs)
354
355
356 def FunctionPointer(type, name, args, **kwargs):
357     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
358     return Opaque(name)
359
360
361 class Interface(Type):
362
363     def __init__(self, name, base=None):
364         Type.__init__(self, name)
365         self.name = name
366         self.base = base
367         self.methods = []
368
369     def visit(self, visitor, *args, **kwargs):
370         return visitor.visitInterface(self, *args, **kwargs)
371
372     def iterMethods(self):
373         if self.base is not None:
374             for method in self.base.iterMethods():
375                 yield method
376         for method in self.methods:
377             yield method
378         raise StopIteration
379
380     def iterBaseMethods(self):
381         if self.base is not None:
382             for iface, method in self.base.iterBaseMethods():
383                 yield iface, method
384         for method in self.methods:
385             yield self, method
386         raise StopIteration
387
388
389 class Method(Function):
390
391     def __init__(self, type, name, args, const=False, sideeffects=True):
392         Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
393         for index in range(len(self.args)):
394             self.args[index].index = index + 1
395         self.const = const
396
397     def prototype(self, name=None):
398         s = Function.prototype(self, name)
399         if self.const:
400             s += ' const'
401         return s
402
403
404 class String(Type):
405
406     def __init__(self, expr = "char *", length = None, kind = 'String'):
407         Type.__init__(self, expr)
408         self.length = length
409         self.kind = kind
410
411     def visit(self, visitor, *args, **kwargs):
412         return visitor.visitString(self, *args, **kwargs)
413
414
415 class Opaque(Type):
416     '''Opaque pointer.'''
417
418     def __init__(self, expr):
419         Type.__init__(self, expr)
420
421     def visit(self, visitor, *args, **kwargs):
422         return visitor.visitOpaque(self, *args, **kwargs)
423
424
425 def OpaquePointer(type, *args):
426     return Opaque(type.expr + ' *')
427
428 def OpaqueArray(type, size):
429     return Opaque(type.expr + ' *')
430
431 def OpaqueBlob(type, size):
432     return Opaque(type.expr + ' *')
433
434
435 class Polymorphic(Type):
436
437     def __init__(self, defaultType, switchExpr, switchTypes):
438         Type.__init__(self, defaultType.expr)
439         self.defaultType = defaultType
440         self.switchExpr = switchExpr
441         self.switchTypes = switchTypes
442
443     def visit(self, visitor, *args, **kwargs):
444         return visitor.visitPolymorphic(self, *args, **kwargs)
445
446     def iterSwitch(self):
447         cases = [['default']]
448         types = [self.defaultType]
449
450         for expr, type in self.switchTypes:
451             case = 'case %s' % expr
452             try:
453                 i = types.index(type)
454             except ValueError:
455                 cases.append([case])
456                 types.append(type)
457             else:
458                 cases[i].append(case)
459
460         return zip(cases, types)
461
462
463 class Visitor:
464     '''Abstract visitor for the type hierarchy.'''
465
466     def visit(self, type, *args, **kwargs):
467         return type.visit(self, *args, **kwargs)
468
469     def visitVoid(self, void, *args, **kwargs):
470         raise NotImplementedError
471
472     def visitLiteral(self, literal, *args, **kwargs):
473         raise NotImplementedError
474
475     def visitString(self, string, *args, **kwargs):
476         raise NotImplementedError
477
478     def visitConst(self, const, *args, **kwargs):
479         raise NotImplementedError
480
481     def visitStruct(self, struct, *args, **kwargs):
482         raise NotImplementedError
483
484     def visitArray(self, array, *args, **kwargs):
485         raise NotImplementedError
486
487     def visitBlob(self, blob, *args, **kwargs):
488         raise NotImplementedError
489
490     def visitEnum(self, enum, *args, **kwargs):
491         raise NotImplementedError
492
493     def visitBitmask(self, bitmask, *args, **kwargs):
494         raise NotImplementedError
495
496     def visitPointer(self, pointer, *args, **kwargs):
497         raise NotImplementedError
498
499     def visitIntPointer(self, pointer, *args, **kwargs):
500         raise NotImplementedError
501
502     def visitObjPointer(self, pointer, *args, **kwargs):
503         raise NotImplementedError
504
505     def visitLinearPointer(self, pointer, *args, **kwargs):
506         raise NotImplementedError
507
508     def visitReference(self, reference, *args, **kwargs):
509         raise NotImplementedError
510
511     def visitHandle(self, handle, *args, **kwargs):
512         raise NotImplementedError
513
514     def visitAlias(self, alias, *args, **kwargs):
515         raise NotImplementedError
516
517     def visitOpaque(self, opaque, *args, **kwargs):
518         raise NotImplementedError
519
520     def visitInterface(self, interface, *args, **kwargs):
521         raise NotImplementedError
522
523     def visitPolymorphic(self, polymorphic, *args, **kwargs):
524         raise NotImplementedError
525         #return self.visit(polymorphic.defaultType, *args, **kwargs)
526
527
528 class OnceVisitor(Visitor):
529     '''Visitor that guarantees that each type is visited only once.'''
530
531     def __init__(self):
532         self.__visited = set()
533
534     def visit(self, type, *args, **kwargs):
535         if type not in self.__visited:
536             self.__visited.add(type)
537             return type.visit(self, *args, **kwargs)
538         return None
539
540
541 class Rebuilder(Visitor):
542     '''Visitor which rebuild types as it visits them.
543
544     By itself it is a no-op -- it is intended to be overwritten.
545     '''
546
547     def visitVoid(self, void):
548         return void
549
550     def visitLiteral(self, literal):
551         return literal
552
553     def visitString(self, string):
554         return string
555
556     def visitConst(self, const):
557         const_type = self.visit(const.type)
558         if const_type is const.type:
559             return const
560         else:
561             return Const(const_type)
562
563     def visitStruct(self, struct):
564         members = [(self.visit(type), name) for type, name in struct.members]
565         return Struct(struct.name, members)
566
567     def visitArray(self, array):
568         type = self.visit(array.type)
569         return Array(type, array.length)
570
571     def visitBlob(self, blob):
572         type = self.visit(blob.type)
573         return Blob(type, blob.size)
574
575     def visitEnum(self, enum):
576         return enum
577
578     def visitBitmask(self, bitmask):
579         type = self.visit(bitmask.type)
580         return Bitmask(type, bitmask.values)
581
582     def visitPointer(self, pointer):
583         pointer_type = self.visit(pointer.type)
584         if pointer_type is pointer.type:
585             return pointer
586         else:
587             return Pointer(pointer_type)
588
589     def visitIntPointer(self, pointer):
590         return pointer
591
592     def visitObjPointer(self, pointer):
593         pointer_type = self.visit(pointer.type)
594         if pointer_type is pointer.type:
595             return pointer
596         else:
597             return ObjPointer(pointer_type)
598
599     def visitLinearPointer(self, pointer):
600         pointer_type = self.visit(pointer.type)
601         if pointer_type is pointer.type:
602             return pointer
603         else:
604             return LinearPointer(pointer_type)
605
606     def visitReference(self, reference):
607         reference_type = self.visit(reference.type)
608         if reference_type is reference.type:
609             return reference
610         else:
611             return Reference(reference_type)
612
613     def visitHandle(self, handle):
614         handle_type = self.visit(handle.type)
615         if handle_type is handle.type:
616             return handle
617         else:
618             return Handle(handle.name, handle_type, range=handle.range, key=handle.key)
619
620     def visitAlias(self, alias):
621         alias_type = self.visit(alias.type)
622         if alias_type is alias.type:
623             return alias
624         else:
625             return Alias(alias.expr, alias_type)
626
627     def visitOpaque(self, opaque):
628         return opaque
629
630     def visitInterface(self, interface, *args, **kwargs):
631         return interface
632
633     def visitPolymorphic(self, polymorphic):
634         defaultType = self.visit(polymorphic.defaultType)
635         switchExpr = polymorphic.switchExpr
636         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
637         return Polymorphic(defaultType, switchExpr, switchTypes)
638
639
640 class Collector(Visitor):
641     '''Visitor which collects all unique types as it traverses them.'''
642
643     def __init__(self):
644         self.__visited = set()
645         self.types = []
646
647     def visit(self, type):
648         if type in self.__visited:
649             return
650         self.__visited.add(type)
651         Visitor.visit(self, type)
652         self.types.append(type)
653
654     def visitVoid(self, literal):
655         pass
656
657     def visitLiteral(self, literal):
658         pass
659
660     def visitString(self, string):
661         pass
662
663     def visitConst(self, const):
664         self.visit(const.type)
665
666     def visitStruct(self, struct):
667         for type, name in struct.members:
668             self.visit(type)
669
670     def visitArray(self, array):
671         self.visit(array.type)
672
673     def visitBlob(self, array):
674         pass
675
676     def visitEnum(self, enum):
677         pass
678
679     def visitBitmask(self, bitmask):
680         self.visit(bitmask.type)
681
682     def visitPointer(self, pointer):
683         self.visit(pointer.type)
684
685     def visitIntPointer(self, pointer):
686         pass
687
688     def visitObjPointer(self, pointer):
689         self.visit(pointer.type)
690
691     def visitLinearPointer(self, pointer):
692         self.visit(pointer.type)
693
694     def visitReference(self, reference):
695         self.visit(reference.type)
696
697     def visitHandle(self, handle):
698         self.visit(handle.type)
699
700     def visitAlias(self, alias):
701         self.visit(alias.type)
702
703     def visitOpaque(self, opaque):
704         pass
705
706     def visitInterface(self, interface):
707         if interface.base is not None:
708             self.visit(interface.base)
709         for method in interface.iterMethods():
710             for arg in method.args:
711                 self.visit(arg.type)
712             self.visit(method.type)
713
714     def visitPolymorphic(self, polymorphic):
715         self.visit(polymorphic.defaultType)
716         for expr, type in polymorphic.switchTypes:
717             self.visit(type)
718
719
720 class API:
721     '''API abstraction.
722
723     Essentially, a collection of types, functions, and interfaces.
724     '''
725
726     def __init__(self, name = None):
727         self.name = name
728         self.headers = []
729         self.functions = []
730         self.interfaces = []
731
732     def getAllTypes(self):
733         collector = Collector()
734         for function in self.functions:
735             for arg in function.args:
736                 collector.visit(arg.type)
737             collector.visit(function.type)
738         for interface in self.interfaces:
739             collector.visit(interface)
740             for method in interface.iterMethods():
741                 for arg in method.args:
742                     collector.visit(arg.type)
743                 collector.visit(method.type)
744         return collector.types
745
746     def getAllInterfaces(self):
747         types = self.getAllTypes()
748         interfaces = [type for type in types if isinstance(type, Interface)]
749         for interface in self.interfaces:
750             if interface not in interfaces:
751                 interfaces.append(interface)
752         return interfaces
753
754     def addFunction(self, function):
755         self.functions.append(function)
756
757     def addFunctions(self, functions):
758         for function in functions:
759             self.addFunction(function)
760
761     def addInterface(self, interface):
762         self.interfaces.append(interface)
763
764     def addInterfaces(self, interfaces):
765         self.interfaces.extend(interfaces)
766
767     def addApi(self, api):
768         self.headers.extend(api.headers)
769         self.addFunctions(api.functions)
770         self.addInterfaces(api.interfaces)
771
772     def get_function_by_name(self, name):
773         for function in self.functions:
774             if function.name == name:
775                 return function
776         return None
777
778
779 Bool = Literal("bool", "Bool")
780 SChar = Literal("signed char", "SInt")
781 UChar = Literal("unsigned char", "UInt")
782 Short = Literal("short", "SInt")
783 Int = Literal("int", "SInt")
784 Long = Literal("long", "SInt")
785 LongLong = Literal("long long", "SInt")
786 UShort = Literal("unsigned short", "UInt")
787 UInt = Literal("unsigned int", "UInt")
788 ULong = Literal("unsigned long", "UInt")
789 ULongLong = Literal("unsigned long long", "UInt")
790 Float = Literal("float", "Float")
791 Double = Literal("double", "Double")
792 SizeT = Literal("size_t", "UInt")
793
794 # C string (i.e., zero terminated)
795 CString = String()
796 WString = String("wchar_t *", kind="WString")
797
798 Int8 = Literal("int8_t", "SInt")
799 UInt8 = Literal("uint8_t", "UInt")
800 Int16 = Literal("int16_t", "SInt")
801 UInt16 = Literal("uint16_t", "UInt")
802 Int32 = Literal("int32_t", "SInt")
803 UInt32 = Literal("uint32_t", "UInt")
804 Int64 = Literal("int64_t", "SInt")
805 UInt64 = Literal("uint64_t", "UInt")