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