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