]> git.cworth.org Git - apitrace/blob - specs/stdapi.py
Distinguish between tags and ids.
[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.visit_void(self, *args, **kwargs)
78
79 Void = _Void()
80
81
82 class Literal(Type):
83
84     def __init__(self, expr, format):
85         Type.__init__(self, expr)
86         self.format = format
87
88     def visit(self, visitor, *args, **kwargs):
89         return visitor.visit_literal(self, *args, **kwargs)
90
91
92 class Const(Type):
93
94     def __init__(self, type):
95         # While "const foo" and "foo const" are synonymous, "const foo *" and
96         # "foo * const" are not quite the same, and some compilers do enforce
97         # strict const correctness.
98         if isinstance(type, String) or type is WString:
99             # For strings we never intend to say a const pointer to chars, but
100             # rather a point to const chars.
101             expr = "const " + type.expr
102         elif type.expr.startswith("const ") or '*' in type.expr:
103             expr = type.expr + " const"
104         else:
105             # The most legible
106             expr = "const " + type.expr
107
108         Type.__init__(self, expr, 'C' + type.tag)
109
110         self.type = type
111
112     def visit(self, visitor, *args, **kwargs):
113         return visitor.visit_const(self, *args, **kwargs)
114
115
116 class Pointer(Type):
117
118     def __init__(self, type):
119         Type.__init__(self, type.expr + " *", 'P' + type.tag)
120         self.type = type
121
122     def visit(self, visitor, *args, **kwargs):
123         return visitor.visit_pointer(self, *args, **kwargs)
124
125
126 class Handle(Type):
127
128     def __init__(self, name, type, range=None, key=None):
129         Type.__init__(self, type.expr, 'P' + type.tag)
130         self.name = name
131         self.type = type
132         self.range = range
133         self.key = key
134
135     def visit(self, visitor, *args, **kwargs):
136         return visitor.visit_handle(self, *args, **kwargs)
137
138
139 def ConstPointer(type):
140     return Pointer(Const(type))
141
142
143 class Enum(Type):
144
145     __id = 0
146
147     def __init__(self, name, values):
148         Type.__init__(self, name)
149
150         self.id = Enum.__id
151         Enum.__id += 1
152
153         self.values = list(values)
154
155     def visit(self, visitor, *args, **kwargs):
156         return visitor.visit_enum(self, *args, **kwargs)
157
158
159 def FakeEnum(type, values):
160     return Enum(type.expr, values)
161
162
163 class Bitmask(Type):
164
165     __id = 0
166
167     def __init__(self, type, values):
168         Type.__init__(self, type.expr)
169
170         self.id = Bitmask.__id
171         Bitmask.__id += 1
172
173         self.type = type
174         self.values = values
175
176     def visit(self, visitor, *args, **kwargs):
177         return visitor.visit_bitmask(self, *args, **kwargs)
178
179 Flags = Bitmask
180
181
182 class Array(Type):
183
184     def __init__(self, type, length):
185         Type.__init__(self, type.expr + " *")
186         self.type = type
187         self.length = length
188
189     def visit(self, visitor, *args, **kwargs):
190         return visitor.visit_array(self, *args, **kwargs)
191
192
193 class Blob(Type):
194
195     def __init__(self, type, size):
196         Type.__init__(self, type.expr + ' *')
197         self.type = type
198         self.size = size
199
200     def visit(self, visitor, *args, **kwargs):
201         return visitor.visit_blob(self, *args, **kwargs)
202
203
204 class Struct(Type):
205
206     __id = 0
207
208     def __init__(self, name, members):
209         Type.__init__(self, name)
210
211         self.id = Struct.__id
212         Struct.__id += 1
213
214         self.name = name
215         self.members = members
216
217     def visit(self, visitor, *args, **kwargs):
218         return visitor.visit_struct(self, *args, **kwargs)
219
220
221 class Alias(Type):
222
223     def __init__(self, expr, type):
224         Type.__init__(self, expr)
225         self.type = type
226
227     def visit(self, visitor, *args, **kwargs):
228         return visitor.visit_alias(self, *args, **kwargs)
229
230
231 def Out(type, name):
232     arg = Arg(type, name, output=True)
233     return arg
234
235
236 class Arg:
237
238     def __init__(self, type, name, output=False):
239         self.type = type
240         self.name = name
241         self.output = output
242         self.index = None
243
244     def __str__(self):
245         return '%s %s' % (self.type, self.name)
246
247
248 class Function:
249
250     # 0-3 are reserved to memcpy, malloc, free, and realloc
251     __id = 4
252
253     def __init__(self, type, name, args, call = '', fail = None, sideeffects=True):
254         self.id = Function.__id
255         Function.__id += 1
256
257         self.type = type
258         self.name = name
259
260         self.args = []
261         index = 0
262         for arg in args:
263             if not isinstance(arg, Arg):
264                 if isinstance(arg, tuple):
265                     arg_type, arg_name = arg
266                 else:
267                     arg_type = arg
268                     arg_name = "arg%u" % index
269                 arg = Arg(arg_type, arg_name)
270             arg.index = index
271             index += 1
272             self.args.append(arg)
273
274         self.call = call
275         self.fail = fail
276         self.sideeffects = sideeffects
277
278     def prototype(self, name=None):
279         if name is not None:
280             name = name.strip()
281         else:
282             name = self.name
283         s = name
284         if self.call:
285             s = self.call + ' ' + s
286         if name.startswith('*'):
287             s = '(' + s + ')'
288         s = self.type.expr + ' ' + s
289         s += "("
290         if self.args:
291             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
292         else:
293             s += "void"
294         s += ")"
295         return s
296
297
298 def StdFunction(*args, **kwargs):
299     kwargs.setdefault('call', '__stdcall')
300     return Function(*args, **kwargs)
301
302
303 def FunctionPointer(type, name, args, **kwargs):
304     # XXX: We should probably treat function pointers (callbacks or not) in a generic fashion
305     return Opaque(name)
306
307
308 class Interface(Type):
309
310     def __init__(self, name, base=None):
311         Type.__init__(self, name)
312         self.name = name
313         self.base = base
314         self.methods = []
315
316     def visit(self, visitor, *args, **kwargs):
317         return visitor.visit_interface(self, *args, **kwargs)
318
319     def itermethods(self):
320         if self.base is not None:
321             for method in self.base.itermethods():
322                 yield method
323         for method in self.methods:
324             yield method
325         raise StopIteration
326
327
328 class Method(Function):
329
330     def __init__(self, type, name, args):
331         Function.__init__(self, type, name, args, call = '__stdcall')
332         for index in range(len(self.args)):
333             self.args[index].index = index + 1
334
335
336 class String(Type):
337
338     def __init__(self, expr = "char *", length = None):
339         Type.__init__(self, expr)
340         self.length = length
341
342     def visit(self, visitor, *args, **kwargs):
343         return visitor.visit_string(self, *args, **kwargs)
344
345 # C string (i.e., zero terminated)
346 CString = String()
347
348
349 class Opaque(Type):
350     '''Opaque pointer.'''
351
352     def __init__(self, expr):
353         Type.__init__(self, expr)
354
355     def visit(self, visitor, *args, **kwargs):
356         return visitor.visit_opaque(self, *args, **kwargs)
357
358
359 def OpaquePointer(type, *args):
360     return Opaque(type.expr + ' *')
361
362 def OpaqueArray(type, size):
363     return Opaque(type.expr + ' *')
364
365 def OpaqueBlob(type, size):
366     return Opaque(type.expr + ' *')
367
368
369 class Polymorphic(Type):
370
371     def __init__(self, default_type, switch_expr, switch_types):
372         Type.__init__(self, default_type.expr)
373         self.default_type = default_type
374         self.switch_expr = switch_expr
375         self.switch_types = switch_types
376
377     def visit(self, visitor, *args, **kwargs):
378         return visitor.visit_polymorphic(self, *args, **kwargs)
379
380     def iterswitch(self):
381         cases = [['default']]
382         types = [self.default_type]
383
384         for expr, type in self.switch_types:
385             case = 'case %s' % expr
386             try:
387                 i = types.index(type)
388             except ValueError:
389                 cases.append([case])
390                 types.append(type)
391             else:
392                 cases[i].append(case)
393
394         return zip(cases, types)
395
396
397 class Visitor:
398
399     def visit(self, type, *args, **kwargs):
400         return type.visit(self, *args, **kwargs)
401
402     def visit_void(self, void, *args, **kwargs):
403         raise NotImplementedError
404
405     def visit_literal(self, literal, *args, **kwargs):
406         raise NotImplementedError
407
408     def visit_string(self, string, *args, **kwargs):
409         raise NotImplementedError
410
411     def visit_const(self, const, *args, **kwargs):
412         raise NotImplementedError
413
414     def visit_struct(self, struct, *args, **kwargs):
415         raise NotImplementedError
416
417     def visit_array(self, array, *args, **kwargs):
418         raise NotImplementedError
419
420     def visit_blob(self, blob, *args, **kwargs):
421         raise NotImplementedError
422
423     def visit_enum(self, enum, *args, **kwargs):
424         raise NotImplementedError
425
426     def visit_bitmask(self, bitmask, *args, **kwargs):
427         raise NotImplementedError
428
429     def visit_pointer(self, pointer, *args, **kwargs):
430         raise NotImplementedError
431
432     def visit_handle(self, handle, *args, **kwargs):
433         raise NotImplementedError
434
435     def visit_alias(self, alias, *args, **kwargs):
436         raise NotImplementedError
437
438     def visit_opaque(self, opaque, *args, **kwargs):
439         raise NotImplementedError
440
441     def visit_interface(self, interface, *args, **kwargs):
442         raise NotImplementedError
443
444     def visit_polymorphic(self, polymorphic, *args, **kwargs):
445         raise NotImplementedError
446         #return self.visit(polymorphic.default_type, *args, **kwargs)
447
448
449 class OnceVisitor(Visitor):
450
451     def __init__(self):
452         self.__visited = set()
453
454     def visit(self, type, *args, **kwargs):
455         if type not in self.__visited:
456             self.__visited.add(type)
457             return type.visit(self, *args, **kwargs)
458         return None
459
460
461 class Rebuilder(Visitor):
462
463     def visit_void(self, void):
464         return void
465
466     def visit_literal(self, literal):
467         return literal
468
469     def visit_string(self, string):
470         return string
471
472     def visit_const(self, const):
473         return Const(const.type)
474
475     def visit_struct(self, struct):
476         members = [(self.visit(type), name) for type, name in struct.members]
477         return Struct(struct.name, members)
478
479     def visit_array(self, array):
480         type = self.visit(array.type)
481         return Array(type, array.length)
482
483     def visit_blob(self, blob):
484         type = self.visit(blob.type)
485         return Blob(type, blob.size)
486
487     def visit_enum(self, enum):
488         return enum
489
490     def visit_bitmask(self, bitmask):
491         type = self.visit(bitmask.type)
492         return Bitmask(type, bitmask.values)
493
494     def visit_pointer(self, pointer):
495         type = self.visit(pointer.type)
496         return Pointer(type)
497
498     def visit_handle(self, handle):
499         type = self.visit(handle.type)
500         return Handle(handle.name, type, range=handle.range, key=handle.key)
501
502     def visit_alias(self, alias):
503         type = self.visit(alias.type)
504         return Alias(alias.expr, type)
505
506     def visit_opaque(self, opaque):
507         return opaque
508
509     def visit_polymorphic(self, polymorphic):
510         default_type = self.visit(polymorphic.default_type)
511         switch_expr = polymorphic.switch_expr
512         switch_types = [(expr, self.visit(type)) for expr, type in polymorphic.switch_types]
513         return Polymorphic(default_type, switch_expr, switch_types)
514
515
516 class Collector(Visitor):
517     '''Collect.'''
518
519     def __init__(self):
520         self.__visited = set()
521         self.types = []
522
523     def visit(self, type):
524         if type in self.__visited:
525             return
526         self.__visited.add(type)
527         Visitor.visit(self, type)
528         self.types.append(type)
529
530     def visit_void(self, literal):
531         pass
532
533     def visit_literal(self, literal):
534         pass
535
536     def visit_string(self, string):
537         pass
538
539     def visit_const(self, const):
540         self.visit(const.type)
541
542     def visit_struct(self, struct):
543         for type, name in struct.members:
544             self.visit(type)
545
546     def visit_array(self, array):
547         self.visit(array.type)
548
549     def visit_blob(self, array):
550         pass
551
552     def visit_enum(self, enum):
553         pass
554
555     def visit_bitmask(self, bitmask):
556         self.visit(bitmask.type)
557
558     def visit_pointer(self, pointer):
559         self.visit(pointer.type)
560
561     def visit_handle(self, handle):
562         self.visit(handle.type)
563
564     def visit_alias(self, alias):
565         self.visit(alias.type)
566
567     def visit_opaque(self, opaque):
568         pass
569
570     def visit_interface(self, interface):
571         if interface.base is not None:
572             self.visit(interface.base)
573         for method in interface.itermethods():
574             for arg in method.args:
575                 self.visit(arg.type)
576             self.visit(method.type)
577
578     def visit_polymorphic(self, polymorphic):
579         self.visit(polymorphic.default_type)
580         for expr, type in polymorphic.switch_types:
581             self.visit(type)
582
583
584 class API:
585
586     def __init__(self, name = None):
587         self.name = name
588         self.headers = []
589         self.functions = []
590         self.interfaces = []
591
592     def all_types(self):
593         collector = Collector()
594         for function in self.functions:
595             for arg in function.args:
596                 collector.visit(arg.type)
597             collector.visit(function.type)
598         for interface in self.interfaces:
599             collector.visit(interface)
600             for method in interface.itermethods():
601                 for arg in method.args:
602                     collector.visit(arg.type)
603                 collector.visit(method.type)
604         return collector.types
605
606     def add_function(self, function):
607         self.functions.append(function)
608
609     def add_functions(self, functions):
610         for function in functions:
611             self.add_function(function)
612
613     def add_interface(self, interface):
614         self.interfaces.append(interface)
615
616     def add_interfaces(self, interfaces):
617         self.interfaces.extend(interfaces)
618
619     def add_api(self, api):
620         self.headers.extend(api.headers)
621         self.add_functions(api.functions)
622         self.add_interfaces(api.interfaces)
623
624     def get_function_by_name(self, name):
625         for function in self.functions:
626             if function.name == name:
627                 return function
628         return None
629
630
631 Bool = Literal("bool", "Bool")
632 SChar = Literal("signed char", "SInt")
633 UChar = Literal("unsigned char", "UInt")
634 Short = Literal("short", "SInt")
635 Int = Literal("int", "SInt")
636 Long = Literal("long", "SInt")
637 LongLong = Literal("long long", "SInt")
638 UShort = Literal("unsigned short", "UInt")
639 UInt = Literal("unsigned int", "UInt")
640 ULong = Literal("unsigned long", "UInt")
641 ULongLong = Literal("unsigned long long", "UInt")
642 Float = Literal("float", "Float")
643 Double = Literal("double", "Double")
644 SizeT = Literal("size_t", "UInt")
645 WString = Literal("wchar_t *", "WString")
646
647 Int8 = Literal("int8_t", "SInt")
648 UInt8 = Literal("uint8_t", "UInt")
649 Int16 = Literal("int16_t", "SInt")
650 UInt16 = Literal("uint16_t", "UInt")
651 Int32 = Literal("int32_t", "SInt")
652 UInt32 = Literal("uint32_t", "UInt")
653 Int64 = Literal("int64_t", "SInt")
654 UInt64 = Literal("uint64_t", "UInt")