]> git.cworth.org Git - apitrace/blob - base.py
Cleanup generated log code.
[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(Type):
197
198     def __init__(self, expr, format, base=10):
199         Type.__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((const void *)%s);' % (instance,)
241         self.type.dump("*" + instance)
242         print '        Log::EndPointer();'
243         print '    }'
244         print '    else'
245         print '        Log::LiteralNull();'
246
247     def wrap_instance(self, instance):
248         self.type.wrap_instance("*" + instance)
249
250     def unwrap_instance(self, instance):
251         self.type.wrap_instance("*" + instance)
252
253
254 def ConstPointer(type):
255     return Pointer(Const(type))
256
257
258 class Enum(Concrete):
259
260     def __init__(self, name, values):
261         Concrete.__init__(self, name)
262         self.values = values
263     
264     def visit(self, visitor, *args, **kwargs):
265         return visitor.visit_enum(self, *args, **kwargs)
266
267     def _dump(self, instance):
268         print '    switch(%s) {' % instance
269         for value in self.values:
270             print '    case %s:' % value
271             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
272             print '        break;'
273         print '    default:'
274         print '        Log::LiteralSInt(%s);' % instance
275         print '        break;'
276         print '    }'
277
278
279 def FakeEnum(type, values):
280     return Enum(type.expr, values)
281
282
283 class Bitmask(Concrete):
284
285     def __init__(self, type, values):
286         Concrete.__init__(self, type.expr)
287         self.type = type
288         self.values = values
289
290     def visit(self, visitor, *args, **kwargs):
291         return visitor.visit_bitmask(self, *args, **kwargs)
292
293     def _dump(self, instance):
294         print '    %s l_Value = %s;' % (self.type, instance)
295         print '    Log::BeginBitmask();'
296         for value in self.values:
297             print '    if((l_Value & %s) == %s) {' % (value, value)
298             print '        Log::LiteralNamedConstant("%s", %s);' % (value, value)
299             print '        l_Value &= ~%s;' % value
300             print '    }'
301         print '    if(l_Value) {'
302         self.type.dump("l_Value");
303         print '    }'
304         print '    Log::EndBitmask();'
305
306 Flags = Bitmask
307
308
309 class Array(Type):
310
311     def __init__(self, type, length):
312         Type.__init__(self, type.expr + " *")
313         self.type = type
314         self.length = length
315
316     def visit(self, visitor, *args, **kwargs):
317         return visitor.visit_array(self, *args, **kwargs)
318
319     def dump(self, instance):
320         print '    if(%s) {' % instance
321         index = '__i' + self.type.id
322         print '        Log::BeginArray(%s);' % (self.length,)
323         print '        for (int %s = 0; %s < %s; ++%s) {' % (index, index, self.length, index)
324         print '            Log::BeginElement();'
325         self.type.dump('(%s)[%s]' % (instance, index))
326         print '            Log::EndElement();'
327         print '        }'
328         print '        Log::EndArray();'
329         print '    }'
330         print '    else'
331         print '        Log::LiteralNull();'
332
333     def wrap_instance(self, instance):
334         self.type.wrap_instance("*" + instance)
335
336     def unwrap_instance(self, instance):
337         self.type.wrap_instance("*" + instance)
338
339
340 class Blob(Type):
341
342     def __init__(self, type, size):
343         Type.__init__(self, type.expr + ' *')
344         self.type = type
345         self.size = size
346
347     def visit(self, visitor, *args, **kwargs):
348         return visitor.visit_blob(self, *args, **kwargs)
349
350     def dump(self, instance):
351         print '    Log::LiteralBlob(%s, %s);' % (instance, self.size)
352
353
354 class Struct(Concrete):
355
356     def __init__(self, name, members):
357         Concrete.__init__(self, name)
358         self.name = name
359         self.members = members
360
361     def visit(self, visitor, *args, **kwargs):
362         return visitor.visit_struct(self, *args, **kwargs)
363
364     def _dump(self, instance):
365         print '    Log::BeginStruct("%s");' % self.name
366         for type, name in self.members:
367             print '    Log::BeginMember("%s");' % (name,)
368             type.dump('(%s).%s' % (instance, name))
369             print '    Log::EndMember();'
370         print '    Log::EndStruct();'
371
372
373 class Alias(Type):
374
375     def __init__(self, expr, type):
376         Type.__init__(self, expr)
377         self.type = type
378
379     def visit(self, visitor, *args, **kwargs):
380         return visitor.visit_alias(self, *args, **kwargs)
381
382     def dump(self, instance):
383         self.type.dump(instance)
384
385
386 def Out(type, name):
387     arg = Arg(type, name, output=True)
388     return arg
389
390
391 class Arg:
392
393     def __init__(self, type, name, output=False):
394         self.type = type
395         self.name = name
396         self.output = output
397
398     def __str__(self):
399         return '%s %s' % (self.type, self.name)
400
401
402 class Function:
403
404     def __init__(self, type, name, args, call = '__stdcall', fail = None, sideeffects=True):
405         self.type = type
406         self.name = name
407
408         self.args = []
409         for arg in args:
410             if isinstance(arg, tuple):
411                 arg_type, arg_name = arg
412                 arg = Arg(arg_type, arg_name)
413             self.args.append(arg)
414
415         self.call = call
416         self.fail = fail
417         self.sideeffects = sideeffects
418
419     def prototype(self, name=None):
420         if name is not None:
421             name = name.strip()
422         else:
423             name = self.name
424         s = name
425         if self.call:
426             s = self.call + ' ' + s
427         if name.startswith('*'):
428             s = '(' + s + ')'
429         s = self.type.expr + ' ' + s
430         s += "("
431         if self.args:
432             s += ", ".join(["%s %s" % (arg.type, arg.name) for arg in self.args])
433         else:
434             s += "void"
435         s += ")"
436         return s
437
438     def pointer_type(self):
439         return 'P' + self.name
440
441     def pointer_value(self):
442         return 'p' + self.name
443
444     def wrap_decl(self):
445         ptype = self.pointer_type()
446         pvalue = self.pointer_value()
447         print 'typedef ' + self.prototype('* %s' % ptype) + ';'
448         print 'static %s %s = NULL;' % (ptype, pvalue)
449         print
450
451     def get_true_pointer(self):
452         raise NotImplementedError
453
454     def exit_impl(self):
455         print '            Log::Abort();'
456
457     def fail_impl(self):
458         if self.fail is not None:
459             if self.type is Void:
460                 assert self.fail == ''
461                 print '            return;' 
462             else:
463                 assert self.fail != ''
464                 print '            return %s;' % self.fail
465         else:
466             self.exit_impl()
467
468     def wrap_impl(self):
469         pvalue = self.pointer_value()
470         print self.prototype() + ' {'
471         if self.type is Void:
472             result = ''
473         else:
474             print '    %s result;' % self.type
475             result = 'result = '
476         self.get_true_pointer()
477         print '    Log::BeginCall("%s");' % (self.name)
478         for arg in self.args:
479             if not arg.output:
480                 arg.type.unwrap_instance(arg.name)
481                 print '    Log::BeginArg("%s");' % (arg.name,)
482                 arg.type.dump(arg.name)
483                 print '    Log::EndArg();'
484         print '    %s%s(%s);' % (result, pvalue, ', '.join([str(arg.name) for arg in self.args]))
485         for arg in self.args:
486             if arg.output:
487                 print '    Log::BeginArg("%s");' % (arg.name,)
488                 arg.type.dump(arg.name)
489                 print '    Log::EndArg();'
490                 arg.type.wrap_instance(arg.name)
491         if self.type is not Void:
492             print '    Log::BeginReturn();'
493             self.type.dump("result")
494             print '    Log::EndReturn();'
495             self.type.wrap_instance('result')
496         print '    Log::EndCall();'
497         self.post_call_impl()
498         if self.type is not Void:
499             print '    return result;'
500         print '}'
501         print
502
503     def post_call_impl(self):
504         pass
505
506
507 def FunctionPointer(type, name, args, **kwargs):
508     # XXX
509     return Opaque(name)
510
511
512 class Interface(Type):
513
514     def __init__(self, name, base=None):
515         Type.__init__(self, name)
516         self.name = name
517         self.base = base
518         self.methods = []
519
520     def dump(self, instance):
521         print '    Log::LiteralOpaque((const void *)%s);' % instance
522
523     def itermethods(self):
524         if self.base is not None:
525             for method in self.base.itermethods():
526                 yield method
527         for method in self.methods:
528             yield method
529         raise StopIteration
530
531     def wrap_name(self):
532         return "Wrap" + self.expr
533
534     def wrap_pre_decl(self):
535         print "class %s;" % self.wrap_name()
536
537     def wrap_decl(self):
538         print "class %s : public %s " % (self.wrap_name(), self.name)
539         print "{"
540         print "public:"
541         print "    %s(%s * pInstance);" % (self.wrap_name(), self.name)
542         print "    virtual ~%s();" % self.wrap_name()
543         print
544         for method in self.itermethods():
545             print "    " + method.prototype() + ";"
546         print
547         #print "private:"
548         print "    %s * m_pInstance;" % (self.name,)
549         print "};"
550         print
551
552     def wrap_impl(self):
553         print '%s::%s(%s * pInstance) {' % (self.wrap_name(), self.wrap_name(), self.name)
554         print '    m_pInstance = pInstance;'
555         print '}'
556         print
557         print '%s::~%s() {' % (self.wrap_name(), self.wrap_name())
558         print '}'
559         print
560         for method in self.itermethods():
561             print method.prototype(self.wrap_name() + '::' + method.name) + ' {'
562             if method.type is Void:
563                 result = ''
564             else:
565                 print '    %s result;' % method.type
566                 result = 'result = '
567             print '    Log::BeginCall("%s");' % (self.name + '::' + method.name)
568             print '    Log::BeginArg("this");'
569             print '    Log::LiteralOpaque((const void *)m_pInstance);'
570             print '    Log::EndArg();'
571             for arg in method.args:
572                 if not arg.output:
573                     arg.type.unwrap_instance(arg.name)
574                     print '    Log::BeginArg("%s");' % (arg.name,)
575                     arg.type.dump(arg.name)
576                     print '    Log::EndArg();'
577             print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(arg.name) for arg in method.args]))
578             for arg in method.args:
579                 if arg.output:
580                     print '    Log::BeginArg("%s");' % (arg.name,)
581                     arg.type.dump(arg.name)
582                     print '    Log::EndArg();'
583                     arg.type.wrap_instance(arg.name)
584             if method.type is not Void:
585                 print '    Log::BeginReturn("%s");' % method.type
586                 method.type.dump("result")
587                 print '    Log::EndReturn();'
588                 method.type.wrap_instance('result')
589             print '    Log::EndCall();'
590             if method.name == 'QueryInterface':
591                 print '    if(*ppvObj == m_pInstance)'
592                 print '        *ppvObj = this;'
593             if method.name == 'Release':
594                 assert method.type is not Void
595                 print '    if(!result)'
596                 print '        delete this;'
597             if method.type is not Void:
598                 print '    return result;'
599             print '}'
600             print
601         print
602
603
604 class Method(Function):
605
606     def __init__(self, type, name, args):
607         Function.__init__(self, type, name, args, call = '__stdcall')
608
609
610 towrap = []
611
612 class WrapPointer(Pointer):
613
614     def __init__(self, type):
615         Pointer.__init__(self, type)
616         if type not in towrap:
617             towrap.append(type)
618
619     def wrap_instance(self, instance):
620         print "    if(%s)" % instance
621         print "        %s = new %s(%s);" % (instance, self.type.wrap_name(), instance)
622
623     def unwrap_instance(self, instance):
624         print "    if(%s)" % instance
625         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, self.type.wrap_name(), instance)
626
627
628 class _String(Type):
629
630     def __init__(self):
631         Type.__init__(self, "char *")
632
633     def visit(self, visitor, *args, **kwargs):
634         return visitor.visit_string(self, *args, **kwargs)
635
636     def dump(self, instance):
637         print '    Log::LiteralString((const char *)%s);' % instance
638
639 String = _String()
640
641
642 class Opaque(Type):
643     '''Opaque pointer.'''
644
645     def __init__(self, expr):
646         Type.__init__(self, expr)
647
648     def visit(self, visitor, *args, **kwargs):
649         return visitor.visit_opaque(self, *args, **kwargs)
650
651     def dump(self, instance):
652         print '    Log::LiteralOpaque((const void *)%s);' % instance
653
654
655 def OpaquePointer(type):
656     return Opaque(type.expr + ' *')
657
658
659 Bool = Literal("bool", "Bool")
660 SChar = Literal("signed char", "SInt")
661 UChar = Literal("unsigned char", "UInt")
662 Short = Literal("short", "SInt")
663 Int = Literal("int", "SInt")
664 Long = Literal("long", "SInt")
665 LongLong = Literal("long long", "SInt")
666 UShort = Literal("unsigned short", "UInt")
667 UInt = Literal("unsigned int", "UInt")
668 ULong = Literal("unsigned long", "UInt")
669 ULongLong = Literal("unsigned long long", "UInt")
670 Float = Literal("float", "Float")
671 Double = Literal("double", "Float")
672 SizeT = Literal("size_t", "UInt")
673 WString = Literal("wchar_t *", "WString")
674
675
676 def wrap():
677     for type in all_types.itervalues():
678         type.decl()
679     print
680     for type in all_types.itervalues():
681         type.impl()
682     print
683     for type in towrap:
684         type.wrap_pre_decl()
685     print
686     for type in towrap:
687         type.wrap_decl()
688     print
689     for type in towrap:
690         type.wrap_impl()
691     print