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