]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
Describe C++ references accurately.
[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 LinearPointer(Type):
138     '''Integer encoded as a pointer.'''
139
140     def __init__(self, type, size = None):
141         Type.__init__(self, type.expr + " *", 'P' + type.tag)
142         self.type = type
143         self.size = size
144
145     def visit(self, visitor, *args, **kwargs):
146         return visitor.visitLinearPointer(self, *args, **kwargs)
147
148
149 class Reference(Type):
150     '''C++ references.'''
151
152     def __init__(self, type):
153         Type.__init__(self, type.expr + " &", 'R' + type.tag)
154         self.type = type
155
156     def visit(self, visitor, *args, **kwargs):
157         return visitor.visitReference(self, *args, **kwargs)
158
159
160 class Handle(Type):
161
162     def __init__(self, name, type, range=None, key=None):
163         Type.__init__(self, type.expr, 'P' + type.tag)
164         self.name = name
165         self.type = type
166         self.range = range
167         self.key = key
168
169     def visit(self, visitor, *args, **kwargs):
170         return visitor.visitHandle(self, *args, **kwargs)
171
172
173 def ConstPointer(type):
174     return Pointer(Const(type))
175
176
177 class Enum(Type):
178
179     __id = 0
180
181     def __init__(self, name, values):
182         Type.__init__(self, name)
183
184         self.id = Enum.__id
185         Enum.__id += 1
186
187         self.values = list(values)
188
189     def visit(self, visitor, *args, **kwargs):
190         return visitor.visitEnum(self, *args, **kwargs)
191
192
193 def FakeEnum(type, values):
194     return Enum(type.expr, values)
195
196
197 class Bitmask(Type):
198
199     __id = 0
200
201     def __init__(self, type, values):
202         Type.__init__(self, type.expr)
203
204         self.id = Bitmask.__id
205         Bitmask.__id += 1
206
207         self.type = type
208         self.values = values
209
210     def visit(self, visitor, *args, **kwargs):
211         return visitor.visitBitmask(self, *args, **kwargs)
212
213 Flags = Bitmask
214
215
216 class Array(Type):
217
218     def __init__(self, type, length):
219         Type.__init__(self, type.expr + " *")
220         self.type = type
221         self.length = length
222
223     def visit(self, visitor, *args, **kwargs):
224         return visitor.visitArray(self, *args, **kwargs)
225
226
227 class Blob(Type):
228
229     def __init__(self, type, size):
230         Type.__init__(self, type.expr + ' *')
231         self.type = type
232         self.size = size
233
234     def visit(self, visitor, *args, **kwargs):
235         return visitor.visitBlob(self, *args, **kwargs)
236
237
238 class Struct(Type):
239
240     __id = 0
241
242     def __init__(self, name, members):
243         Type.__init__(self, name)
244
245         self.id = Struct.__id
246         Struct.__id += 1
247
248         self.name = name
249         self.members = members
250
251     def visit(self, visitor, *args, **kwargs):
252         return visitor.visitStruct(self, *args, **kwargs)
253
254
255 class Alias(Type):
256
257     def __init__(self, expr, type):
258         Type.__init__(self, expr)
259         self.type = type
260
261     def visit(self, visitor, *args, **kwargs):
262         return visitor.visitAlias(self, *args, **kwargs)
263
264
265 def Out(type, name):
266     arg = Arg(type, name, output=True)
267     return arg
268
269
270 class Arg:
271
272     def __init__(self, type, name, output=False):
273         self.type = type
274         self.name = name
275         self.output = output
276         self.index = None
277
278     def __str__(self):
279         return '%s %s' % (self.type, self.name)
280
281
282 class Function:
283
284     # 0-3 are reserved to memcpy, malloc, free, and realloc
285     __id = 4
286
287     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
288         self.id = Function.__id
289         Function.__id += 1
290
291         self.type = type
292         self.name = name
293
294         self.args = []
295         index = 0
296         for arg in args:
297             if not isinstance(arg, Arg):
298                 if isinstance(arg, tuple):
299                     arg_type, arg_name = arg
300                 else:
301                     arg_type = arg
302                     arg_name = "arg%u" % index
303                 arg = Arg(arg_type, arg_name)
304             arg.index = index
305             index += 1
306             self.args.append(arg)
307
308         self.call = call
309         self.fail = fail
310         self.sideeffects = sideeffects
311
312     def prototype(self, name=None):
313         if name is not None:
314             name = name.strip()
315         else:
316             name = self.name
317         s = name
318         if self.call:
319             s = self.call + ' ' + s
320         if name.startswith('*'):
321             s = '(' + s + ')'
322         s = self.type.expr + ' ' + s
323         s += "("
324         if self.args:
325             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
326         else:
327             s += "void"
328         s += ")"
329         return s
330
331     def argNames(self):
332         return [arg.name for arg in self.args]
333
334
335 def StdFunction(*args, **kwargs):
336     kwargs.setdefault('call', '__stdcall')
337     return Function(*args, **kwargs)
338
339
340 def FunctionPointer(type, name, args, **kwargs):
341     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
342     return Opaque(name)
343
344
345 class Interface(Type):
346
347     def __init__(self, name, base=None):
348         Type.__init__(self, name)
349         self.name = name
350         self.base = base
351         self.methods = []
352
353     def visit(self, visitor, *args, **kwargs):
354         return visitor.visitInterface(self, *args, **kwargs)
355
356     def iterMethods(self):
357         if self.base is not None:
358             for method in self.base.iterMethods():
359                 yield method
360         for method in self.methods:
361             yield method
362         raise StopIteration
363
364     def iterBaseMethods(self):
365         if self.base is not None:
366             for iface, method in self.base.iterBaseMethods():
367                 yield iface, method
368         for method in self.methods:
369             yield self, method
370         raise StopIteration
371
372
373 class Method(Function):
374
375     def __init__(self, type, name, args, const=False, sideeffects=True):
376         Function.__init__(self, type, name, args, call = '__stdcall', sideeffects=sideeffects)
377         for index in range(len(self.args)):
378             self.args[index].index = index + 1
379         self.const = const
380
381     def prototype(self, name=None):
382         s = Function.prototype(self, name)
383         if self.const:
384             s += ' const'
385         return s
386
387
388 class String(Type):
389
390     def __init__(self, expr = "char *", length = None, kind = 'String'):
391         Type.__init__(self, expr)
392         self.length = length
393         self.kind = kind
394
395     def visit(self, visitor, *args, **kwargs):
396         return visitor.visitString(self, *args, **kwargs)
397
398
399 class Opaque(Type):
400     '''Opaque pointer.'''
401
402     def __init__(self, expr):
403         Type.__init__(self, expr)
404
405     def visit(self, visitor, *args, **kwargs):
406         return visitor.visitOpaque(self, *args, **kwargs)
407
408
409 def OpaquePointer(type, *args):
410     return Opaque(type.expr + ' *')
411
412 def OpaqueArray(type, size):
413     return Opaque(type.expr + ' *')
414
415 def OpaqueBlob(type, size):
416     return Opaque(type.expr + ' *')
417
418
419 class Polymorphic(Type):
420
421     def __init__(self, defaultType, switchExpr, switchTypes):
422         Type.__init__(self, defaultType.expr)
423         self.defaultType = defaultType
424         self.switchExpr = switchExpr
425         self.switchTypes = switchTypes
426
427     def visit(self, visitor, *args, **kwargs):
428         return visitor.visitPolymorphic(self, *args, **kwargs)
429
430     def iterSwitch(self):
431         cases = [['default']]
432         types = [self.defaultType]
433
434         for expr, type in self.switchTypes:
435             case = 'case %s' % expr
436             try:
437                 i = types.index(type)
438             except ValueError:
439                 cases.append([case])
440                 types.append(type)
441             else:
442                 cases[i].append(case)
443
444         return zip(cases, types)
445
446
447 class Visitor:
448     '''Abstract visitor for the type hierarchy.'''
449
450     def visit(self, type, *args, **kwargs):
451         return type.visit(self, *args, **kwargs)
452
453     def visitVoid(self, void, *args, **kwargs):
454         raise NotImplementedError
455
456     def visitLiteral(self, literal, *args, **kwargs):
457         raise NotImplementedError
458
459     def visitString(self, string, *args, **kwargs):
460         raise NotImplementedError
461
462     def visitConst(self, const, *args, **kwargs):
463         raise NotImplementedError
464
465     def visitStruct(self, struct, *args, **kwargs):
466         raise NotImplementedError
467
468     def visitArray(self, array, *args, **kwargs):
469         raise NotImplementedError
470
471     def visitBlob(self, blob, *args, **kwargs):
472         raise NotImplementedError
473
474     def visitEnum(self, enum, *args, **kwargs):
475         raise NotImplementedError
476
477     def visitBitmask(self, bitmask, *args, **kwargs):
478         raise NotImplementedError
479
480     def visitPointer(self, pointer, *args, **kwargs):
481         raise NotImplementedError
482
483     def visitIntPointer(self, pointer, *args, **kwargs):
484         raise NotImplementedError
485
486     def visitLinearPointer(self, pointer, *args, **kwargs):
487         raise NotImplementedError
488
489     def visitReference(self, reference, *args, **kwargs):
490         raise NotImplementedError
491
492     def visitHandle(self, handle, *args, **kwargs):
493         raise NotImplementedError
494
495     def visitAlias(self, alias, *args, **kwargs):
496         raise NotImplementedError
497
498     def visitOpaque(self, opaque, *args, **kwargs):
499         raise NotImplementedError
500
501     def visitInterface(self, interface, *args, **kwargs):
502         raise NotImplementedError
503
504     def visitPolymorphic(self, polymorphic, *args, **kwargs):
505         raise NotImplementedError
506         #return self.visit(polymorphic.defaultType, *args, **kwargs)
507
508
509 class OnceVisitor(Visitor):
510     '''Visitor that guarantees that each type is visited only once.'''
511
512     def __init__(self):
513         self.__visited = set()
514
515     def visit(self, type, *args, **kwargs):
516         if type not in self.__visited:
517             self.__visited.add(type)
518             return type.visit(self, *args, **kwargs)
519         return None
520
521
522 class Rebuilder(Visitor):
523     '''Visitor which rebuild types as it visits them.
524
525     By itself it is a no-op -- it is intended to be overwritten.
526     '''
527
528     def visitVoid(self, void):
529         return void
530
531     def visitLiteral(self, literal):
532         return literal
533
534     def visitString(self, string):
535         return string
536
537     def visitConst(self, const):
538         return Const(const.type)
539
540     def visitStruct(self, struct):
541         members = [(self.visit(type), name) for type, name in struct.members]
542         return Struct(struct.name, members)
543
544     def visitArray(self, array):
545         type = self.visit(array.type)
546         return Array(type, array.length)
547
548     def visitBlob(self, blob):
549         type = self.visit(blob.type)
550         return Blob(type, blob.size)
551
552     def visitEnum(self, enum):
553         return enum
554
555     def visitBitmask(self, bitmask):
556         type = self.visit(bitmask.type)
557         return Bitmask(type, bitmask.values)
558
559     def visitPointer(self, pointer):
560         type = self.visit(pointer.type)
561         return Pointer(type)
562
563     def visitIntPointer(self, pointer):
564         return pointer
565
566     def visitLinearPointer(self, pointer):
567         type = self.visit(pointer.type)
568         return LinearPointer(type, pointer.size)
569
570     def visitReference(self, reference):
571         type = self.visit(reference.type)
572         return Reference(type)
573
574     def visitHandle(self, handle):
575         type = self.visit(handle.type)
576         return Handle(handle.name, type, range=handle.range, key=handle.key)
577
578     def visitAlias(self, alias):
579         type = self.visit(alias.type)
580         return Alias(alias.expr, type)
581
582     def visitOpaque(self, opaque):
583         return opaque
584
585     def visitInterface(self, interface, *args, **kwargs):
586         return interface
587
588     def visitPolymorphic(self, polymorphic):
589         defaultType = self.visit(polymorphic.defaultType)
590         switchExpr = polymorphic.switchExpr
591         switchTypes = [(expr, self.visit(type)) for expr, type in polymorphic.switchTypes]
592         return Polymorphic(defaultType, switchExpr, switchTypes)
593
594
595 class Collector(Visitor):
596     '''Visitor which collects all unique types as it traverses them.'''
597
598     def __init__(self):
599         self.__visited = set()
600         self.types = []
601
602     def visit(self, type):
603         if type in self.__visited:
604             return
605         self.__visited.add(type)
606         Visitor.visit(self, type)
607         self.types.append(type)
608
609     def visitVoid(self, literal):
610         pass
611
612     def visitLiteral(self, literal):
613         pass
614
615     def visitString(self, string):
616         pass
617
618     def visitConst(self, const):
619         self.visit(const.type)
620
621     def visitStruct(self, struct):
622         for type, name in struct.members:
623             self.visit(type)
624
625     def visitArray(self, array):
626         self.visit(array.type)
627
628     def visitBlob(self, array):
629         pass
630
631     def visitEnum(self, enum):
632         pass
633
634     def visitBitmask(self, bitmask):
635         self.visit(bitmask.type)
636
637     def visitPointer(self, pointer):
638         self.visit(pointer.type)
639
640     def visitIntPointer(self, pointer):
641         pass
642
643     def visitLinearPointer(self, pointer):
644         self.visit(pointer.type)
645
646     def visitReference(self, reference):
647         self.visit(reference.type)
648
649     def visitHandle(self, handle):
650         self.visit(handle.type)
651
652     def visitAlias(self, alias):
653         self.visit(alias.type)
654
655     def visitOpaque(self, opaque):
656         pass
657
658     def visitInterface(self, interface):
659         if interface.base is not None:
660             self.visit(interface.base)
661         for method in interface.iterMethods():
662             for arg in method.args:
663                 self.visit(arg.type)
664             self.visit(method.type)
665
666     def visitPolymorphic(self, polymorphic):
667         self.visit(polymorphic.defaultType)
668         for expr, type in polymorphic.switchTypes:
669             self.visit(type)
670
671
672 class API:
673     '''API abstraction.
674
675     Essentially, a collection of types, functions, and interfaces.
676     '''
677
678     def __init__(self, name = None):
679         self.name = name
680         self.headers = []
681         self.functions = []
682         self.interfaces = []
683
684     def getAllTypes(self):
685         collector = Collector()
686         for function in self.functions:
687             for arg in function.args:
688                 collector.visit(arg.type)
689             collector.visit(function.type)
690         for interface in self.interfaces:
691             collector.visit(interface)
692             for method in interface.iterMethods():
693                 for arg in method.args:
694                     collector.visit(arg.type)
695                 collector.visit(method.type)
696         return collector.types
697
698     def getAllInterfaces(self):
699         types = self.getAllTypes()
700         interfaces = [type for type in types if isinstance(type, Interface)]
701         for interface in self.interfaces:
702             if interface not in interfaces:
703                 interfaces.append(interface)
704         return interfaces
705
706     def addFunction(self, function):
707         self.functions.append(function)
708
709     def addFunctions(self, functions):
710         for function in functions:
711             self.addFunction(function)
712
713     def addInterface(self, interface):
714         self.interfaces.append(interface)
715
716     def addInterfaces(self, interfaces):
717         self.interfaces.extend(interfaces)
718
719     def addApi(self, api):
720         self.headers.extend(api.headers)
721         self.addFunctions(api.functions)
722         self.addInterfaces(api.interfaces)
723
724     def get_function_by_name(self, name):
725         for function in self.functions:
726             if function.name == name:
727                 return function
728         return None
729
730
731 Bool = Literal("bool", "Bool")
732 SChar = Literal("signed char", "SInt")
733 UChar = Literal("unsigned char", "UInt")
734 Short = Literal("short", "SInt")
735 Int = Literal("int", "SInt")
736 Long = Literal("long", "SInt")
737 LongLong = Literal("long long", "SInt")
738 UShort = Literal("unsigned short", "UInt")
739 UInt = Literal("unsigned int", "UInt")
740 ULong = Literal("unsigned long", "UInt")
741 ULongLong = Literal("unsigned long long", "UInt")
742 Float = Literal("float", "Float")
743 Double = Literal("double", "Double")
744 SizeT = Literal("size_t", "UInt")
745
746 # C string (i.e., zero terminated)
747 CString = String()
748 WString = String("wchar_t *", kind="WString")
749
750 Int8 = Literal("int8_t", "SInt")
751 UInt8 = Literal("uint8_t", "UInt")
752 Int16 = Literal("int16_t", "SInt")
753 UInt16 = Literal("uint16_t", "UInt")
754 Int32 = Literal("int32_t", "SInt")
755 UInt32 = Literal("uint32_t", "UInt")
756 Int64 = Literal("int64_t", "SInt")
757 UInt64 = Literal("uint64_t", "UInt")