]> git.cworth.org Git - apitrace/blob - base.py
Use more standard names on FindDirectX.cmake
[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     isoutput = False
146
147     def decl(self):
148         pass
149
150     def impl(self):
151         pass
152
153     def dump(self, instance):
154         raise NotImplementedError
155     
156     def wrap_instance(self, instance):
157         pass 
158
159     def unwrap_instance(self, instance):
160         pass
161
162
163 class _Void(Type):
164
165     def __init__(self):
166         Type.__init__(self, "void")
167
168     def visit(self, visitor, *args, **kwargs):
169         return visitor.visit_void(self, *args, **kwargs)
170
171 Void = _Void()
172
173
174 class Concrete(Type):
175
176     def decl(self):
177         print 'static void Dump%s(const %s &value);' % (self.id, self.expr)
178     
179     def impl(self):
180         print 'static void Dump%s(const %s &value) {' % (self.id, self.expr)
181         self._dump("value");
182         print '}'
183         print
184     
185     def _dump(self, instance):
186         raise NotImplementedError
187     
188     def dump(self, instance):
189         print '    Dump%s(%s);' % (self.id, instance)
190     
191
192 class Literal(Concrete):
193
194     def __init__(self, expr, format, base=10):
195         Concrete.__init__(self, expr)
196         self.format = format
197
198     def visit(self, visitor, *args, **kwargs):
199         return visitor.visit_literal(self, *args, **kwargs)
200
201     def _dump(self, instance):
202         print '    Log::Literal%s(%s);' % (self.format, instance)
203
204
205 class Const(Type):
206
207     def __init__(self, type):
208
209         if type.expr.startswith("const "):
210             expr = type.expr + " const"
211         else:
212             expr = "const " + type.expr
213
214         Type.__init__(self, expr, 'C' + type.id)
215
216         self.type = type
217
218     def visit(self, visitor, *args, **kwargs):
219         return visitor.visit_const(self, *args, **kwargs)
220
221     def dump(self, instance):
222         self.type.dump(instance)
223
224
225 class Pointer(Type):
226
227     def __init__(self, type):
228         Type.__init__(self, type.expr + " *", 'P' + type.id)
229         self.type = type
230
231     def visit(self, visitor, *args, **kwargs):
232         return visitor.visit_pointer(self, *args, **kwargs)
233
234     def dump(self, instance):
235         print '    if(%s) {' % instance
236         print '        Log::BeginPointer("%s", (const void *)%s);' % (self.type, instance)
237         try:
238             self.type.dump("*" + instance)
239         except NotImplementedError:
240             pass
241         print '        Log::EndPointer();'
242         print '    }'
243         print '    else'
244         print '        Log::LiteralNull();'
245
246     def wrap_instance(self, instance):
247         self.type.wrap_instance("*" + instance)
248
249     def unwrap_instance(self, instance):
250         self.type.wrap_instance("*" + instance)
251
252
253 def ConstPointer(type):
254     return Pointer(Const(type))
255
256
257 def OutPointer(type):
258     return Out(Pointer(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         index = '__i' + self.type.id
324         print '    Log::BeginArray("%s", %s);' % (self.type, self.length)
325         print '    for (int %s = 0; %s < %s; ++%s) {' % (index, index, self.length, index)
326         print '        Log::BeginElement("%s");' % (self.type,)
327         self.type.dump('(%s)[%s]' % (instance, index))
328         print '        Log::EndElement();'
329         print '    }'
330         print '    Log::EndArray();'
331
332     def wrap_instance(self, instance):
333         self.type.wrap_instance("*" + instance)
334
335     def unwrap_instance(self, instance):
336         self.type.wrap_instance("*" + instance)
337
338
339 def OutArray(type, length):
340     return Out(Array(type, length))
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):
390     type.isoutput = True
391     return type
392
393
394 class Function:
395
396     def __init__(self, type, name, args, call = '__stdcall', fail = None):
397         self.type = type
398         self.name = name
399         self.args = args
400         self.call = call
401         self.fail = fail
402
403     def prototype(self, name=None):
404         if name is not None:
405             name = name.strip()
406         else:
407             name = self.name
408         s = name
409         if self.call:
410             s = self.call + ' ' + s
411         if name.startswith('*'):
412             s = '(' + s + ')'
413         s = self.type.expr + ' ' + s
414         s += "("
415         if self.args:
416             s += ", ".join(["%s %s" % (type, name) for type, name in self.args])
417         else:
418             s += "void"
419         s += ")"
420         return s
421
422     def pointer_type(self):
423         return 'P' + self.name
424
425     def pointer_value(self):
426         return 'p' + self.name
427
428     def wrap_decl(self):
429         ptype = self.pointer_type()
430         pvalue = self.pointer_value()
431         print 'typedef ' + self.prototype('* %s' % ptype) + ';'
432         print 'static %s %s = NULL;' % (ptype, pvalue)
433         print
434
435     def get_true_pointer(self):
436         raise NotImplementedError
437
438     def exit_impl(self):
439         print '            ExitProcess(0);'
440
441     def fail_impl(self):
442         if self.fail is not None:
443             if self.type is Void:
444                 assert self.fail == ''
445                 print '            return;' 
446             else:
447                 assert self.fail != ''
448                 print '            return %s;' % self.fail
449         else:
450             self.exit_impl()
451
452     def wrap_impl(self):
453         pvalue = self.pointer_value()
454         print self.prototype() + ' {'
455         if self.type is Void:
456             result = ''
457         else:
458             print '    %s result;' % self.type
459             result = 'result = '
460         self.get_true_pointer()
461         print '    Log::BeginCall("%s");' % (self.name)
462         for type, name in self.args:
463             if not type.isoutput:
464                 type.unwrap_instance(name)
465                 print '    Log::BeginArg("%s", "%s");' % (type, name)
466                 type.dump(name)
467                 print '    Log::EndArg();'
468         print '    %s%s(%s);' % (result, pvalue, ', '.join([str(name) for type, name in self.args]))
469         for type, name in self.args:
470             if type.isoutput:
471                 print '    Log::BeginArg("%s", "%s");' % (type, name)
472                 type.dump(name)
473                 print '    Log::EndArg();'
474                 type.wrap_instance(name)
475         if self.type is not Void:
476             print '    Log::BeginReturn("%s");' % self.type
477             self.type.dump("result")
478             print '    Log::EndReturn();'
479             self.type.wrap_instance('result')
480         print '    Log::EndCall();'
481         self.post_call_impl()
482         if self.type is not Void:
483             print '    return result;'
484         print '}'
485         print
486
487     def post_call_impl(self):
488         pass
489
490
491 class Interface(Type):
492
493     def __init__(self, name, base=None):
494         Type.__init__(self, name)
495         self.name = name
496         self.base = base
497         self.methods = []
498
499     def itermethods(self):
500         if self.base is not None:
501             for method in self.base.itermethods():
502                 yield method
503         for method in self.methods:
504             yield method
505         raise StopIteration
506
507     def wrap_name(self):
508         return "Wrap" + self.expr
509
510     def wrap_pre_decl(self):
511         print "class %s;" % self.wrap_name()
512
513     def wrap_decl(self):
514         print "class %s : public %s " % (self.wrap_name(), self.name)
515         print "{"
516         print "public:"
517         print "    %s(%s * pInstance);" % (self.wrap_name(), self.name)
518         print "    virtual ~%s();" % self.wrap_name()
519         print
520         for method in self.itermethods():
521             print "    " + method.prototype() + ";"
522         print
523         #print "private:"
524         print "    %s * m_pInstance;" % (self.name,)
525         print "};"
526         print
527
528     def wrap_impl(self):
529         print '%s::%s(%s * pInstance) {' % (self.wrap_name(), self.wrap_name(), self.name)
530         print '    m_pInstance = pInstance;'
531         print '}'
532         print
533         print '%s::~%s() {' % (self.wrap_name(), self.wrap_name())
534         print '}'
535         print
536         for method in self.itermethods():
537             print method.prototype(self.wrap_name() + '::' + method.name) + ' {'
538             if method.type is Void:
539                 result = ''
540             else:
541                 print '    %s result;' % method.type
542                 result = 'result = '
543             print '    Log::BeginCall("%s");' % (self.name + '::' + method.name)
544             print '    Log::BeginArg("%s *", "this");' % self.name
545             print '    Log::BeginPointer("%s", (const void *)m_pInstance);' % self.name
546             print '    Log::EndPointer();'
547             print '    Log::EndArg();'
548             for type, name in method.args:
549                 if not type.isoutput:
550                     type.unwrap_instance(name)
551                     print '    Log::BeginArg("%s", "%s");' % (type, name)
552                     type.dump(name)
553                     print '    Log::EndArg();'
554             print '    %sm_pInstance->%s(%s);' % (result, method.name, ', '.join([str(name) for type, name in method.args]))
555             for type, name in method.args:
556                 if type.isoutput:
557                     print '    Log::BeginArg("%s", "%s");' % (type, name)
558                     type.dump(name)
559                     print '    Log::EndArg();'
560                     type.wrap_instance(name)
561             if method.type is not Void:
562                 print '    Log::BeginReturn("%s");' % method.type
563                 method.type.dump("result")
564                 print '    Log::EndReturn();'
565                 method.type.wrap_instance('result')
566             print '    Log::EndCall();'
567             if method.name == 'QueryInterface':
568                 print '    if(*ppvObj == m_pInstance)'
569                 print '        *ppvObj = this;'
570             if method.name == 'Release':
571                 assert method.type is not Void
572                 print '    if(!result)'
573                 print '        delete this;'
574             if method.type is not Void:
575                 print '    return result;'
576             print '}'
577             print
578         print
579
580
581 class Method(Function):
582
583     def __init__(self, type, name, args):
584         Function.__init__(self, type, name, args, call = '__stdcall')
585
586
587 towrap = []
588
589 class WrapPointer(Pointer):
590
591     def __init__(self, type):
592         Pointer.__init__(self, type)
593         if type not in towrap:
594             towrap.append(type)
595
596     def wrap_instance(self, instance):
597         print "    if(%s)" % instance
598         print "        %s = new %s(%s);" % (instance, self.type.wrap_name(), instance)
599
600     def unwrap_instance(self, instance):
601         print "    if(%s)" % instance
602         print "        %s = static_cast<%s *>(%s)->m_pInstance;" % (instance, self.type.wrap_name(), instance)
603
604
605 class _String(Type):
606
607     def __init__(self):
608         Type.__init__(self, "char *")
609
610     def visit(self, visitor, *args, **kwargs):
611         return visitor.visit_literal(self, *args, **kwargs)
612
613     def dump(self, instance):
614         print '    Log::LiteralString((const char *)%s);' % instance
615
616 String = _String()
617
618
619 class Opaque(Type):
620     '''Opaque pointer.'''
621
622     def __init__(self, expr):
623         Type.__init__(self, expr)
624
625     def visit(self, visitor, *args, **kwargs):
626         return visitor.visit_opaque(self, *args, **kwargs)
627
628     def dump(self, instance):
629         print '    Log::LiteralOpaque((const void *)%s);' % instance
630
631
632 def OpaquePointer(type):
633     return Opaque(type.expr + ' *')
634
635
636 Bool = Literal("bool", "Bool")
637 SChar = Literal("signed char", "SInt")
638 UChar = Literal("unsigned char", "UInt")
639 Short = Literal("short", "SInt")
640 Int = Literal("int", "SInt")
641 Long = Literal("long", "SInt")
642 LongLong = Literal("long long", "SInt")
643 UShort = Literal("unsigned short", "UInt")
644 UInt = Literal("unsigned int", "UInt")
645 ULong = Literal("unsigned long", "UInt")
646 Float = Literal("float", "Float")
647 Double = Literal("double", "Float")
648 SizeT = Literal("size_t", "UInt")
649 WString = Literal("wchar_t *", "WString")
650
651
652 def wrap():
653     for type in all_types.itervalues():
654         type.decl()
655     print
656     for type in all_types.itervalues():
657         type.impl()
658     print
659     for type in towrap:
660         type.wrap_pre_decl()
661     print
662     for type in towrap:
663         type.wrap_decl()
664     print
665     for type in towrap:
666         type.wrap_impl()
667     print