]> git.cworth.org Git - apitrace/blob - base.py
Handle more pointers.
[apitrace] / base.py
1 ##########################################################################
2 #
3 # Copyright 2008-2009 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 all_types = {}
33
34
35 class Visitor:
36
37     def visit(self, type, *args, **kwargs):
38         return type.visit(self, *args, **kwargs)
39
40     __call__ = visit
41
42     def visit_void(self, type, *args, **kwargs):
43         raise NotImplementedError
44
45     def visit_literal(self, type, *args, **kwargs):
46         raise NotImplementedError
47
48     def visit_string(self, type, *args, **kwargs):
49         raise NotImplementedError
50
51     def visit_const(self, type, *args, **kwargs):
52         raise NotImplementedError
53
54     def visit_struct(self, type, *args, **kwargs):
55         raise NotImplementedError
56
57     def visit_array(self, type, *args, **kwargs):
58         raise NotImplementedError
59
60     def visit_blob(self, type, *args, **kwargs):
61         raise NotImplementedError
62
63     def visit_enum(self, type, *args, **kwargs):
64         raise NotImplementedError
65
66     def visit_bitmask(self, type, *args, **kwargs):
67         raise NotImplementedError
68
69     def visit_pointer(self, type, *args, **kwargs):
70         raise NotImplementedError
71
72     def visit_alias(self, type, *args, **kwargs):
73         raise NotImplementedError
74
75     def visit_opaque(self, type, *args, **kwargs):
76         raise NotImplementedError
77
78
79 class Rebuilder(Visitor):
80
81     def visit_void(self, void):
82         return void
83
84     def visit_literal(self, literal):
85         return literal
86
87     def visit_string(self, string):
88         return string
89
90     def visit_const(self, const):
91         return Const(const.type)
92
93     def visit_struct(self, struct):
94         members = [self.visit(member) for member in struct.members]
95         return Struct(struct.name, members)
96
97     def visit_array(self, array):
98         type = self.visit(array.type)
99         return Array(type, array.length)
100
101     def visit_blob(self, blob):
102         type = self.visit(blob.type)
103         return Blob(type, blob.size)
104
105     def visit_enum(self, enum):
106         return enum
107
108     def visit_bitmask(self, bitmask):
109         type = self.visit(bitmask.type)
110         return Bitmask(type, bitmask.values)
111
112     def visit_pointer(self, pointer):
113         type = self.visit(pointer.type)
114         return Pointer(type)
115
116     def visit_alias(self, alias):
117         type = self.visit(alias.type)
118         return Alias(alias.expr, type)
119
120     def visit_opaque(self, opaque):
121         return opaque
122
123
124 class Type:
125
126     __seq = 0
127
128     def __init__(self, expr, id = ''):
129         self.expr = expr
130         
131         for char in id:
132             assert char.isalnum() or char in '_ '
133
134         id = id.replace(' ', '_')
135         
136         if id in all_types:
137             Type.__seq += 1
138             id += str(Type.__seq)
139         
140         assert id not in all_types
141         all_types[id] = self
142
143         self.id = id
144
145     def __str__(self):
146         return self.expr
147
148     def visit(self, visitor, *args, **kwargs):
149         raise NotImplementedError
150
151     def decl(self):
152         pass
153
154     def impl(self):
155         pass
156
157     def dump(self, instance):
158         raise NotImplementedError
159     
160     def wrap_instance(self, instance):
161         pass 
162
163     def unwrap_instance(self, instance):
164         pass
165
166
167 class _Void(Type):
168
169     def __init__(self):
170         Type.__init__(self, "void")
171
172     def visit(self, visitor, *args, **kwargs):
173         return visitor.visit_void(self, *args, **kwargs)
174
175 Void = _Void()
176
177
178 class Concrete(Type):
179
180     def decl(self):
181         print 'static void Dump%s(const %s &value);' % (self.id, self.expr)
182     
183     def impl(self):
184         print 'static void Dump%s(const %s &value) {' % (self.id, self.expr)
185         self._dump("value");
186         print '}'
187         print
188     
189     def _dump(self, instance):
190         raise NotImplementedError
191     
192     def dump(self, instance):
193         print '    Dump%s(%s);' % (self.id, instance)
194     
195
196 class Literal(Concrete):
197
198     def __init__(self, expr, format, base=10):
199         Concrete.__init__(self, expr)
200         self.format = format
201
202     def visit(self, visitor, *args, **kwargs):
203         return visitor.visit_literal(self, *args, **kwargs)
204
205     def _dump(self, instance):
206         print '    Log::Literal%s(%s);' % (self.format, instance)
207
208
209 class Const(Type):
210
211     def __init__(self, type):
212
213         if type.expr.startswith("const "):
214             expr = type.expr + " const"
215         else:
216             expr = "const " + type.expr
217
218         Type.__init__(self, expr, 'C' + type.id)
219
220         self.type = type
221
222     def visit(self, visitor, *args, **kwargs):
223         return visitor.visit_const(self, *args, **kwargs)
224
225     def dump(self, instance):
226         self.type.dump(instance)
227
228
229 class Pointer(Type):
230
231     def __init__(self, type):
232         Type.__init__(self, type.expr + " *", 'P' + type.id)
233         self.type = type
234
235     def visit(self, visitor, *args, **kwargs):
236         return visitor.visit_pointer(self, *args, **kwargs)
237
238     def dump(self, instance):
239         print '    if(%s) {' % instance
240         print '        Log::BeginPointer("%s", (const void *)%s);' % (self.type, instance)
241         try:
242             self.type.dump("*" + instance)
243         except NotImplementedError:
244             pass
245         print '        Log::EndPointer();'
246         print '    }'
247         print '    else'
248         print '        Log::LiteralNull();'
249
250     def wrap_instance(self, instance):
251         self.type.wrap_instance("*" + instance)
252
253     def unwrap_instance(self, instance):
254         self.type.wrap_instance("*" + instance)
255
256
257 def ConstPointer(type):
258     return Pointer(Const(type))
259
260
261 class Enum(Concrete):
262
263     def __init__(self, name, values):
264         Concrete.__init__(self, name)
265         self.values = values
266     
267     def visit(self, visitor, *args, **kwargs):
268         return visitor.visit_enum(self, *args, **kwargs)
269
270     def _dump(self, instance):
271         print '    switch(%s) {' % instance
272         for value in self.values:
273             print '    case %s:' % value
274             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
275             print '        break;'
276         print '    default:'
277         print '        Log::LiteralSInt(%s);' % instance
278         print '        break;'
279         print '    }'
280
281
282 def FakeEnum(type, values):
283     return Enum(type.expr, values)
284
285
286 class Bitmask(Concrete):
287
288     def __init__(self, type, values):
289         Concrete.__init__(self, type.expr)
290         self.type = type
291         self.values = values
292
293     def visit(self, visitor, *args, **kwargs):
294         return visitor.visit_bitmask(self, *args, **kwargs)
295
296     def _dump(self, instance):
297         print '    %s l_Value = %s;' % (self.type, instance)
298         print '    Log::BeginBitmask("%s");' % (self.type,)
299         for value in self.values:
300             print '    if((l_Value & %s) == %s) {' % (value, value)
301             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
302             print '        l_Value &= ~%s;' % value
303             print '    }'
304         print '    if(l_Value) {'
305         self.type.dump("l_Value");
306         print '    }'
307         print '    Log::EndBitmask();'
308
309 Flags = Bitmask
310
311
312 class Array(Type):
313
314     def __init__(self, type, length):
315         Type.__init__(self, type.expr + " *")
316         self.type = type
317         self.length = length
318
319     def visit(self, visitor, *args, **kwargs):
320         return visitor.visit_array(self, *args, **kwargs)
321
322     def dump(self, instance):
323         print '    if(%s) {' % instance
324         index = '__i' + self.type.id
325         print '        Log::BeginArray("%s", %s);' % (self.type, self.length)
326         print '        for (int %s = 0; %s < %s; ++%s) {' % (index, index, self.length, index)
327         print '            Log::BeginElement("%s");' % (self.type,)
328         self.type.dump('(%s)[%s]' % (instance, index))
329         print '            Log::EndElement();'
330         print '        }'
331         print '        Log::EndArray();'
332         print '    }'
333         print '    else'
334         print '        Log::LiteralNull();'
335
336     def wrap_instance(self, instance):
337         self.type.wrap_instance("*" + instance)
338
339     def unwrap_instance(self, instance):
340         self.type.wrap_instance("*" + instance)
341
342
343 class Blob(Type):
344
345     def __init__(self, type, size):
346         Type.__init__(self, type.expr + ' *')
347         self.type = type
348         self.size = size
349
350     def visit(self, visitor, *args, **kwargs):
351         return visitor.visit_blob(self, *args, **kwargs)
352
353     def dump(self, instance):
354         print '    Log::LiteralBlob(%s, %s);' % (instance, self.size)
355
356
357 class Struct(Concrete):
358
359     def __init__(self, name, members):
360         Concrete.__init__(self, name)
361         self.name = name
362         self.members = members
363
364     def visit(self, visitor, *args, **kwargs):
365         return visitor.visit_struct(self, *args, **kwargs)
366
367     def _dump(self, instance):
368         print '    Log::BeginStruct("%s");' % (self.name,)
369         for type, name in self.members:
370             print '    Log::BeginMember("%s", "%s");' % (type, name)
371             type.dump('(%s).%s' % (instance, name))
372             print '    Log::EndMember();'
373         print '    Log::EndStruct();'
374
375
376 class Alias(Type):
377
378     def __init__(self, expr, type):
379         Type.__init__(self, expr)
380         self.type = type
381
382     def visit(self, visitor, *args, **kwargs):
383         return visitor.visit_alias(self, *args, **kwargs)
384
385     def dump(self, instance):
386         self.type.dump(instance)
387
388
389 def Out(type, name):
390     arg = Arg(type, name, output=True)
391     return arg
392
393
394 class Arg:
395
396     def __init__(self, type, name, output=False):
397         self.type = type
398         self.name = name
399         self.output = output
400
401     def __str__(self):
402         return '%s %s' % (self.type, self.name)
403
404
405 class Function:
406
407     def __init__(self, type, name, args, call = '__stdcall', fail = None, sideeffects=True):
408         self.type = type
409         self.name = name
410
411         self.args = []
412         for arg in args:
413             if isinstance(arg, tuple):
414                 arg_type, arg_name = arg
415                 arg = Arg(arg_type, arg_name)
416             self.args.append(arg)
417
418         self.call = call
419         self.fail = fail
420         self.sideeffects = sideeffects
421
422     def prototype(self, name=None):
423         if name is not None:
424             name = name.strip()
425         else:
426             name = self.name
427         s = name
428         if self.call:
429             s = self.call + ' ' + s
430         if name.startswith('*'):
431             s = '(' + s + ')'
432         s = self.type.expr + ' ' + s
433         s += "("
434         if self.args:
435             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
436         else:
437             s += "void"
438         s += ")"
439         return s
440
441     def pointer_type(self):
442         return 'P' + self.name
443
444     def pointer_value(self):
445         return 'p' + self.name
446
447     def wrap_decl(self):
448         ptype = self.pointer_type()
449         pvalue = self.pointer_value()
450         print 'typedef ' + self.prototype('* %s' % ptype) + ';'
451         print 'static %s %s = NULL;' % (ptype, pvalue)
452         print
453
454     def get_true_pointer(self):
455         raise NotImplementedError
456
457     def exit_impl(self):
458         print '            Log::Abort();'
459
460     def fail_impl(self):
461         if self.fail is not None:
462             if self.type is Void:
463                 assert self.fail == ''
464                 print '            return;' 
465             else:
466                 assert self.fail != ''
467                 print '            return %s;' % self.fail
468         else:
469             self.exit_impl()
470
471     def wrap_impl(self):
472         pvalue = self.pointer_value()
473         print self.prototype() + ' {'
474         if self.type is Void:
475             result = ''
476         else:
477             print '    %s result;' % self.type
478             result = 'result = '
479         self.get_true_pointer()
480         print '    Log::BeginCall("%s");' % (self.name)
481         for arg in self.args:
482             if not arg.output:
483                 arg.type.unwrap_instance(arg.name)
484                 print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
485                 arg.type.dump(arg.name)
486                 print '    Log::EndArg();'
487         print '    %s%s(%s);' % (result, pvalue, ', '.join([str(arg.name) for arg in self.args]))
488         for arg in self.args:
489             if arg.output:
490                 print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
491                 arg.type.dump(arg.name)
492                 print '    Log::EndArg();'
493                 arg.type.wrap_instance(arg.name)
494         if self.type is not Void:
495             print '    Log::BeginReturn("%s");' % self.type
496             self.type.dump("result")
497             print '    Log::EndReturn();'
498             self.type.wrap_instance('result')
499         print '    Log::EndCall();'
500         self.post_call_impl()
501         if self.type is not Void:
502             print '    return result;'
503         print '}'
504         print
505
506     def post_call_impl(self):
507         pass
508
509
510 class Interface(Type):
511
512     def __init__(self, name, base=None):
513         Type.__init__(self, name)
514         self.name = name
515         self.base = base
516         self.methods = []
517
518     def itermethods(self):
519         if self.base is not None:
520             for method in self.base.itermethods():
521                 yield method
522         for method in self.methods:
523             yield method
524         raise StopIteration
525
526     def wrap_name(self):
527         return "Wrap" + self.expr
528
529     def wrap_pre_decl(self):
530         print "class %s;" % self.wrap_name()
531
532     def wrap_decl(self):
533         print "class %s : public %s " % (self.wrap_name(), self.name)
534         print "{"
535         print "public:"
536         print "    %s(%s * pInstance);" % (self.wrap_name(), self.name)
537         print "    virtual ~%s();" % self.wrap_name()
538         print
539         for method in self.itermethods():
540             print "    " + method.prototype() + ";"
541         print
542         #print "private:"
543         print "    %s * m_pInstance;" % (self.name,)
544         print "};"
545         print
546
547     def wrap_impl(self):
548         print '%s::%s(%s * pInstance) {' % (self.wrap_name(), self.wrap_name(), self.name)
549         print '    m_pInstance = pInstance;'
550         print '}'
551         print
552         print '%s::~%s() {' % (self.wrap_name(), self.wrap_name())
553         print '}'
554         print
555         for method in self.itermethods():
556             print method.prototype(self.wrap_name() + '::' + method.name) + ' {'
557             if method.type is Void:
558                 result = ''
559             else:
560                 print '    %s result;' % method.type
561                 result = 'result = '
562             print '    Log::BeginCall("%s");' % (self.name + '::' + method.name)
563             print '    Log::BeginArg("%s *", "this");' % self.name
564             print '    Log::BeginPointer("%s", (const void *)m_pInstance);' % self.name
565             print '    Log::EndPointer();'
566             print '    Log::EndArg();'
567             for arg in method.args:
568                 if not arg.output:
569                     arg.type.unwrap_instance(arg.name)
570                     print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
571                     arg.type.dump(arg.name)
572                     print '    Log::EndArg();'
573             print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
574             for arg in method.args:
575                 if arg.output:
576                     print '    Log::BeginArg("%s", "%s");' % (arg.type, arg.name)
577                     arg.type.dump(arg.name)
578                     print '    Log::EndArg();'
579                     arg.type.wrap_instance(arg.name)
580             if method.type is not Void:
581                 print '    Log::BeginReturn("%s");' % method.type
582                 method.type.dump("result")
583                 print '    Log::EndReturn();'
584                 method.type.wrap_instance('result')
585             print '    Log::EndCall();'
586             if method.name == 'QueryInterface':
587                 print '    if(*ppvObj == m_pInstance)'
588                 print '        *ppvObj = this;'
589             if method.name == 'Release':
590                 assert method.type is not Void
591                 print '    if(!result)'
592                 print '        delete this;'
593             if method.type is not Void:
594                 print '    return result;'
595             print '}'
596             print
597         print
598
599
600 class Method(Function):
601
602     def __init__(self, type, name, args):
603         Function.__init__(self, type, name, args, call = '__stdcall')
604
605
606 towrap = []
607
608 class WrapPointer(Pointer):
609
610     def __init__(self, type):
611         Pointer.__init__(self, type)
612         if type not in towrap:
613             towrap.append(type)
614
615     def wrap_instance(self, instance):
616         print "    if(%s)" % instance
617         print "        %s = new %s(%s);" % (instance, self.type.wrap_name(), instance)
618
619     def unwrap_instance(self, instance):
620         print "    if(%s)" % instance
621         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, self.type.wrap_name(), instance)
622
623
624 class _String(Type):
625
626     def __init__(self):
627         Type.__init__(self, "char *")
628
629     def visit(self, visitor, *args, **kwargs):
630         return visitor.visit_string(self, *args, **kwargs)
631
632     def dump(self, instance):
633         print '    Log::LiteralString((const char *)%s);' % instance
634
635 String = _String()
636
637
638 class Opaque(Type):
639     '''Opaque pointer.'''
640
641     def __init__(self, expr):
642         Type.__init__(self, expr)
643
644     def visit(self, visitor, *args, **kwargs):
645         return visitor.visit_opaque(self, *args, **kwargs)
646
647     def dump(self, instance):
648         print '    Log::LiteralOpaque((const void *)%s);' % instance
649
650
651 def OpaquePointer(type):
652     return Opaque(type.expr + ' *')
653
654
655 Bool = Literal("bool", "Bool")
656 SChar = Literal("signed char", "SInt")
657 UChar = Literal("unsigned char", "UInt")
658 Short = Literal("short", "SInt")
659 Int = Literal("int", "SInt")
660 Long = Literal("long", "SInt")
661 LongLong = Literal("long long", "SInt")
662 UShort = Literal("unsigned short", "UInt")
663 UInt = Literal("unsigned int", "UInt")
664 ULong = Literal("unsigned long", "UInt")
665 ULongLong = Literal("unsigned long long", "UInt")
666 Float = Literal("float", "Float")
667 Double = Literal("double", "Float")
668 SizeT = Literal("size_t", "UInt")
669 WString = Literal("wchar_t *", "WString")
670
671
672 def wrap():
673     for type in all_types.itervalues():
674         type.decl()
675     print
676     for type in all_types.itervalues():
677         type.impl()
678     print
679     for type in towrap:
680         type.wrap_pre_decl()
681     print
682     for type in towrap:
683         type.wrap_decl()
684     print
685     for type in towrap:
686         type.wrap_impl()
687     print