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