e9596a9491127d6b01185c54a5667c3a975540c6
[free-sw/xcb/proto] / xcbgen / xtypes.py
1 '''
2 This module contains the classes which represent XCB data types.
3 '''
4 from xcbgen.expr import Field, Expression
5 import __main__
6
7 class Type(object):
8     '''
9     Abstract base class for all XCB data types.
10     Contains default fields, and some abstract methods.
11     '''
12     def __init__(self, name):
13         '''
14         Default structure initializer.  Sets up default fields.
15
16         Public fields:
17         name is a tuple of strings specifying the full type name.
18         size is the size of the datatype in bytes, or None if variable-sized.
19         nmemb is 1 for non-list types, None for variable-sized lists, otherwise number of elts.
20         booleans for identifying subclasses, because I can't figure out isinstance().
21         '''
22         self.name = name
23         self.size = None
24         self.nmemb = None
25         self.resolved = False
26
27         # Screw isinstance().
28         self.is_simple = False
29         self.is_list = False
30         self.is_expr = False
31         self.is_container = False
32         self.is_reply = False
33         self.is_union = False
34         self.is_pad = False
35         self.is_switch = False
36         self.is_bitcase = False
37
38     def resolve(self, module):
39         '''
40         Abstract method for resolving a type.
41         This should make sure any referenced types are already declared.
42         '''
43         raise Exception('abstract resolve method not overridden!')
44
45     def out(self, name):
46         '''
47         Abstract method for outputting code.
48         These are declared in the language-specific modules, and
49         there must be a dictionary containing them declared when this module is imported!
50         '''
51         raise Exception('abstract out method not overridden!')
52
53     def fixed_size(self):
54         '''
55         Abstract method for determining if the data type is fixed-size.
56         '''
57         raise Exception('abstract fixed_size method not overridden!')
58
59     def make_member_of(self, module, complex_type, field_type, field_name, visible, wire, auto, enum=None):
60         '''
61         Default method for making a data type a member of a structure.
62         Extend this if the data type needs to add an additional length field or something.
63
64         module is the global module object.
65         complex_type is the structure object.
66         see Field for the meaning of the other parameters.
67         '''
68         new_field = Field(self, field_type, field_name, visible, wire, auto, enum)
69
70         # We dump the _placeholder_byte if any fields are added.
71         for (idx, field) in enumerate(complex_type.fields):
72             if field == _placeholder_byte:
73                 complex_type.fields[idx] = new_field
74                 return
75
76         complex_type.fields.append(new_field)
77
78     def make_fd_of(self, module, complex_type, fd_name):
79         '''
80         Method for making a fd member of a structure.
81         '''
82         new_fd = Field(self, module.get_type_name('INT32'), fd_name, True, False, False, None, True)
83         # We dump the _placeholder_byte if any fields are added.
84         for (idx, field) in enumerate(complex_type.fields):
85             if field == _placeholder_byte:
86                 complex_type.fields[idx] = new_fd
87                 return
88
89         complex_type.fields.append(new_fd)
90
91 class SimpleType(Type):
92     '''
93     Derived class which represents a cardinal type like CARD32 or char.
94     Any type which is typedef'ed to cardinal will be one of these.
95
96     Public fields added:
97     none
98     '''
99     def __init__(self, name, size):
100         Type.__init__(self, name)
101         self.is_simple = True
102         self.size = size
103         self.nmemb = 1
104
105     def resolve(self, module):
106         self.resolved = True
107
108     def fixed_size(self):
109         return True
110
111     out = __main__.output['simple']
112
113
114 # Cardinal datatype globals.  See module __init__ method.
115 tcard8 = SimpleType(('uint8_t',), 1)
116 tcard16 = SimpleType(('uint16_t',), 2)
117 tcard32 = SimpleType(('uint32_t',), 4)
118 tcard64 = SimpleType(('uint64_t',), 8)
119 tint8 =  SimpleType(('int8_t',), 1)
120 tint16 = SimpleType(('int16_t',), 2)
121 tint32 = SimpleType(('int32_t',), 4)
122 tint64 = SimpleType(('int64_t',), 8)
123 tchar =  SimpleType(('char',), 1)
124 tfloat = SimpleType(('float',), 4)
125 tdouble = SimpleType(('double',), 8)
126
127
128 class Enum(SimpleType):
129     '''
130     Derived class which represents an enum.  Fixed-size.
131
132     Public fields added:
133     values contains a list of (name, value) tuples.  value is empty, or a number.
134     bits contains a list of (name, bitnum) tuples.  items only appear if specified as a bit. bitnum is a number.
135     '''
136     def __init__(self, name, elt):
137         SimpleType.__init__(self, name, 4)
138         self.values = []
139         self.bits = []
140         self.doc = None
141         for item in list(elt):
142             if item.tag == 'doc':
143                 self.doc = Doc(name, item)
144
145             # First check if we're using a default value
146             if len(list(item)) == 0:
147                 self.values.append((item.get('name'), ''))
148                 continue
149
150             # An explicit value or bit was specified.
151             value = list(item)[0]
152             if value.tag == 'value':
153                 self.values.append((item.get('name'), value.text))
154             elif value.tag == 'bit':
155                 self.values.append((item.get('name'), '%u' % (1 << int(value.text, 0))))
156                 self.bits.append((item.get('name'), value.text))
157
158     def resolve(self, module):
159         self.resolved = True
160
161     def fixed_size(self):
162         return True
163
164     out = __main__.output['enum']
165
166
167 class ListType(Type):
168     '''
169     Derived class which represents a list of some other datatype.  Fixed- or variable-sized.
170
171     Public fields added:
172     member is the datatype of the list elements.
173     parent is the structure type containing the list.
174     expr is an Expression object containing the length information, for variable-sized lists.
175     '''
176     def __init__(self, elt, member, *parent):
177         Type.__init__(self, member.name)
178         self.is_list = True
179         self.member = member
180         self.parents = list(parent)
181
182         if elt.tag == 'list':
183             elts = list(elt)
184             self.expr = Expression(elts[0] if len(elts) else elt, self)
185         elif elt.tag == 'valueparam':
186             self.expr = Expression(elt, self)
187
188         self.size = member.size if member.fixed_size() else None
189         self.nmemb = self.expr.nmemb if self.expr.fixed_size() else None
190
191     def make_member_of(self, module, complex_type, field_type, field_name, visible, wire, auto, enum=None):
192         if not self.fixed_size():
193             # We need a length field.
194             # Ask our Expression object for it's name, type, and whether it's on the wire.
195             lenfid = self.expr.lenfield_type
196             lenfield_name = self.expr.lenfield_name
197             lenwire = self.expr.lenwire
198             needlen = True
199
200             # See if the length field is already in the structure.
201             for parent in self.parents:
202                 for field in parent.fields:
203                     if field.field_name == lenfield_name:
204                         needlen = False
205
206             # It isn't, so we need to add it to the structure ourself.
207             if needlen:
208                 type = module.get_type(lenfid)
209                 lenfield_type = module.get_type_name(lenfid)
210                 type.make_member_of(module, complex_type, lenfield_type, lenfield_name, True, lenwire, False, enum)
211
212         # Add ourself to the structure by calling our original method.
213         Type.make_member_of(self, module, complex_type, field_type, field_name, visible, wire, auto, enum)
214
215     def resolve(self, module):
216         if self.resolved:
217             return
218         self.member.resolve(module)
219         self.expr.resolve(module, self.parents)
220
221         # Find my length field again.  We need the actual Field object in the expr.
222         # This is needed because we might have added it ourself above.
223         if not self.fixed_size():
224             for parent in self.parents:
225                 for field in parent.fields:
226                     if field.field_name == self.expr.lenfield_name and field.wire:
227                         self.expr.lenfield = field
228                         break
229
230         self.resolved = True
231
232     def fixed_size(self):
233         return self.member.fixed_size() and self.expr.fixed_size()
234
235 class ExprType(Type):
236     '''
237     Derived class which represents an exprfield.  Fixed size.
238
239     Public fields added:
240     expr is an Expression object containing the value of the field.
241     '''
242     def __init__(self, elt, member, *parents):
243         Type.__init__(self, member.name)
244         self.is_expr = True
245         self.member = member
246         self.parents = parents
247
248         self.expr = Expression(list(elt)[0], self)
249
250         self.size = member.size
251         self.nmemb = 1
252
253     def resolve(self, module):
254         if self.resolved:
255             return
256         self.member.resolve(module)
257         self.resolved = True
258
259     def fixed_size(self):
260         return True
261
262 class PadType(Type):
263     '''
264     Derived class which represents a padding field.
265     '''
266     def __init__(self, elt):
267         Type.__init__(self, tcard8.name)
268         self.is_pad = True
269         self.size = 1
270         self.nmemb = 1 if (elt == None) else int(elt.get('bytes'), 0)
271
272     def resolve(self, module):
273         self.resolved = True
274
275     def fixed_size(self):
276         return True
277
278     
279 class ComplexType(Type):
280     '''
281     Derived class which represents a structure.  Base type for all structure types.
282
283     Public fields added:
284     fields is an array of Field objects describing the structure fields.
285     '''
286     def __init__(self, name, elt):
287         Type.__init__(self, name)
288         self.is_container = True
289         self.elt = elt
290         self.fields = []
291         self.nmemb = 1
292         self.size = 0
293         self.lenfield_parent = [self]
294         self.fds = []
295
296     def resolve(self, module):
297         if self.resolved:
298             return
299         enum = None
300
301         # Resolve all of our field datatypes.
302         for child in list(self.elt):
303             if child.tag == 'pad':
304                 field_name = 'pad' + str(module.pads)
305                 fkey = 'CARD8'
306                 type = PadType(child)
307                 module.pads = module.pads + 1
308                 visible = False
309             elif child.tag == 'field':
310                 field_name = child.get('name')
311                 enum = child.get('enum')
312                 fkey = child.get('type')
313                 type = module.get_type(fkey)
314                 visible = True
315             elif child.tag == 'exprfield':
316                 field_name = child.get('name')
317                 fkey = child.get('type')
318                 type = ExprType(child, module.get_type(fkey), *self.lenfield_parent)
319                 visible = False
320             elif child.tag == 'list':
321                 field_name = child.get('name')
322                 fkey = child.get('type')
323                 type = ListType(child, module.get_type(fkey), *self.lenfield_parent)
324                 visible = True
325             elif child.tag == 'valueparam':
326                 field_name = child.get('value-list-name')
327                 fkey = 'CARD32'
328                 type = ListType(child, module.get_type(fkey), *self.lenfield_parent)
329                 visible = True
330             elif child.tag == 'switch':
331                 field_name = child.get('name')
332                 # construct the switch type name from the parent type and the field name
333                 field_type = self.name + (field_name,)
334                 type = SwitchType(field_type, child, *self.lenfield_parent)
335                 visible = True
336                 type.make_member_of(module, self, field_type, field_name, visible, True, False)
337                 type.resolve(module)
338                 continue
339             elif child.tag == 'fd':
340                 fd_name = child.get('name')
341                 type = module.get_type('INT32')
342                 type.make_fd_of(module, self, fd_name)
343                 continue
344             else:
345                 # Hit this on Reply
346                 continue
347
348             # Get the full type name for the field
349             field_type = module.get_type_name(fkey)
350             # Add the field to ourself
351             type.make_member_of(module, self, field_type, field_name, visible, True, False, enum)
352             # Recursively resolve the type (could be another structure, list)
353             type.resolve(module)
354
355         self.calc_size() # Figure out how big we are
356         self.resolved = True
357
358     def calc_size(self):
359         self.size = 0
360         for m in self.fields:
361             if not m.wire:
362                 continue
363             if m.type.fixed_size():
364                 self.size = self.size + (m.type.size * m.type.nmemb)
365             else:
366                 self.size = None
367                 break
368
369     def fixed_size(self):
370         for m in self.fields:
371             if not m.type.fixed_size():
372                 return False
373         return True
374
375 class SwitchType(ComplexType):
376     '''
377     Derived class which represents a List of Items.  
378
379     Public fields added:
380     bitcases is an array of Bitcase objects describing the list items
381     '''
382
383     def __init__(self, name, elt, *parents):
384         ComplexType.__init__(self, name, elt)
385         self.parents = parents
386         # FIXME: switch cannot store lenfields, so it should just delegate the parents
387         self.lenfield_parent = list(parents) + [self]
388         # self.fields contains all possible fields collected from the Bitcase objects, 
389         # whereas self.items contains the Bitcase objects themselves
390         self.bitcases = []
391
392         self.is_switch = True
393         elts = list(elt)
394         self.expr = Expression(elts[0] if len(elts) else elt, self)
395
396     def resolve(self, module):
397         if self.resolved:
398             return
399
400         parents = list(self.parents) + [self]
401
402         # Resolve all of our field datatypes.
403         for index, child in enumerate(list(self.elt)):
404             if child.tag == 'bitcase':
405                 field_name = child.get('name')
406                 if field_name is None:
407                     field_type = self.name + ('bitcase%d' % index,)
408                 else:
409                     field_type = self.name + (field_name,)
410
411                 # use self.parent to indicate anchestor, 
412                 # as switch does not contain named fields itself
413                 type = BitcaseType(index, field_type, child, *parents)
414                 # construct the switch type name from the parent type and the field name
415                 if field_name is None:
416                     type.has_name = False
417                     # Get the full type name for the field
418                     field_type = type.name               
419                 visible = True
420
421                 # add the field to ourself
422                 type.make_member_of(module, self, field_type, field_name, visible, True, False)
423
424                 # recursively resolve the type (could be another structure, list)
425                 type.resolve(module)
426                 inserted = False
427                 for new_field in type.fields:
428                     # We dump the _placeholder_byte if any fields are added.
429                     for (idx, field) in enumerate(self.fields):
430                         if field == _placeholder_byte:
431                             self.fields[idx] = new_field
432                             inserted = True
433                             break
434                     if False == inserted:
435                         self.fields.append(new_field)
436
437         self.calc_size() # Figure out how big we are
438         self.resolved = True
439
440     def make_member_of(self, module, complex_type, field_type, field_name, visible, wire, auto, enum=None):
441         if not self.fixed_size():
442             # We need a length field.
443             # Ask our Expression object for it's name, type, and whether it's on the wire.
444             lenfid = self.expr.lenfield_type
445             lenfield_name = self.expr.lenfield_name
446             lenwire = self.expr.lenwire
447             needlen = True
448
449             # See if the length field is already in the structure.
450             for parent in self.parents:
451                 for field in parent.fields:
452                     if field.field_name == lenfield_name:
453                         needlen = False
454
455             # It isn't, so we need to add it to the structure ourself.
456             if needlen:
457                 type = module.get_type(lenfid)
458                 lenfield_type = module.get_type_name(lenfid)
459                 type.make_member_of(module, complex_type, lenfield_type, lenfield_name, True, lenwire, False, enum)
460
461         # Add ourself to the structure by calling our original method.
462         Type.make_member_of(self, module, complex_type, field_type, field_name, visible, wire, auto, enum)
463
464     # size for switch can only be calculated at runtime
465     def calc_size(self):
466         pass
467
468     # note: switch is _always_ of variable size, but we indicate here wether 
469     # it contains elements that are variable-sized themselves
470     def fixed_size(self):
471         return False
472 #        for m in self.fields:
473 #            if not m.type.fixed_size():
474 #                return False
475 #        return True
476
477
478 class Struct(ComplexType):
479     '''
480     Derived class representing a struct data type.
481     '''
482     out = __main__.output['struct']
483
484
485 class Union(ComplexType):
486     '''
487     Derived class representing a union data type.
488     '''
489     def __init__(self, name, elt):
490         ComplexType.__init__(self, name, elt)
491         self.is_union = True
492
493     out = __main__.output['union']
494
495
496 class BitcaseType(ComplexType):
497     '''
498     Derived class representing a struct data type.
499     '''
500     def __init__(self, index, name, elt, *parent):
501         elts = list(elt)
502         self.expr = []
503         fields = []
504         for elt in elts:
505             if elt.tag == 'enumref':
506                 self.expr.append(Expression(elt, self))
507             else:
508                 fields.append(elt)
509         ComplexType.__init__(self, name, fields)
510         self.has_name = True
511         self.index = 1
512         self.lenfield_parent = list(parent) + [self]
513         self.parents = list(parent)
514         self.is_bitcase = True
515
516     def make_member_of(self, module, switch_type, field_type, field_name, visible, wire, auto, enum=None):
517         '''
518         register BitcaseType with the corresponding SwitchType
519
520         module is the global module object.
521         complex_type is the structure object.
522         see Field for the meaning of the other parameters.
523         '''
524         new_field = Field(self, field_type, field_name, visible, wire, auto, enum)
525
526         # We dump the _placeholder_byte if any bitcases are added.
527         for (idx, field) in enumerate(switch_type.bitcases):
528             if field == _placeholder_byte:
529                 switch_type.bitcases[idx] = new_field
530                 return
531
532         switch_type.bitcases.append(new_field)
533
534     def resolve(self, module):
535         if self.resolved:
536             return
537
538         for e in self.expr:
539             e.resolve(module, self.parents+[self])
540
541         # Resolve the bitcase expression
542         ComplexType.resolve(self, module)
543
544
545 class Reply(ComplexType):
546     '''
547     Derived class representing a reply.  Only found as a field of Request.
548     '''
549     def __init__(self, name, elt):
550         ComplexType.__init__(self, name, elt)
551         self.is_reply = True
552         self.doc = None
553
554         for child in list(elt):
555             if child.tag == 'doc':
556                 self.doc = Doc(name, child)
557
558     def resolve(self, module):
559         if self.resolved:
560             return
561         # Reset pads count
562         module.pads = 0
563         # Add the automatic protocol fields
564         self.fields.append(Field(tcard8, tcard8.name, 'response_type', False, True, True))
565         self.fields.append(_placeholder_byte)
566         self.fields.append(Field(tcard16, tcard16.name, 'sequence', False, True, True))
567         self.fields.append(Field(tcard32, tcard32.name, 'length', False, True, True))
568         ComplexType.resolve(self, module)
569         
570
571 class Request(ComplexType):
572     '''
573     Derived class representing a request.
574
575     Public fields added:
576     reply contains the reply datatype or None for void requests.
577     opcode contains the request number.
578     '''
579     def __init__(self, name, elt):
580         ComplexType.__init__(self, name, elt)
581         self.reply = None
582         self.doc = None
583         self.opcode = elt.get('opcode')
584
585         for child in list(elt):
586             if child.tag == 'reply':
587                 self.reply = Reply(name, child)
588             if child.tag == 'doc':
589                 self.doc = Doc(name, child)
590
591     def resolve(self, module):
592         if self.resolved:
593             return
594         # Add the automatic protocol fields
595         if module.namespace.is_ext:
596             self.fields.append(Field(tcard8, tcard8.name, 'major_opcode', False, True, True))
597             self.fields.append(Field(tcard8, tcard8.name, 'minor_opcode', False, True, True))
598             self.fields.append(Field(tcard16, tcard16.name, 'length', False, True, True))
599             ComplexType.resolve(self, module)
600         else:
601             self.fields.append(Field(tcard8, tcard8.name, 'major_opcode', False, True, True))
602             self.fields.append(_placeholder_byte)
603             self.fields.append(Field(tcard16, tcard16.name, 'length', False, True, True))
604             ComplexType.resolve(self, module)
605
606         if self.reply:
607             self.reply.resolve(module)
608
609     out = __main__.output['request']
610
611
612 class Event(ComplexType):
613     '''
614     Derived class representing an event data type.
615
616     Public fields added:
617     opcodes is a dictionary of name -> opcode number, for eventcopies.
618     '''
619     def __init__(self, name, elt):
620         ComplexType.__init__(self, name, elt)
621         self.opcodes = {}
622
623         self.has_seq = not bool(elt.get('no-sequence-number'))
624
625         self.is_ge_event = bool(elt.get('xge'))
626
627         self.doc = None
628         for item in list(elt):
629             if item.tag == 'doc':
630                 self.doc = Doc(name, item)
631
632     def add_opcode(self, opcode, name, main):
633         self.opcodes[name] = opcode
634         if main:
635             self.name = name
636
637     def resolve(self, module):
638         def add_event_header():
639             self.fields.append(Field(tcard8, tcard8.name, 'response_type', False, True, True))
640             if self.has_seq:
641                 self.fields.append(_placeholder_byte)
642                 self.fields.append(Field(tcard16, tcard16.name, 'sequence', False, True, True))
643
644         def add_ge_event_header():
645             self.fields.append(Field(tcard8,  tcard8.name,  'response_type', False, True, True))
646             self.fields.append(Field(tcard8,  tcard8.name,  'extension', False, True, True))
647             self.fields.append(Field(tcard16, tcard16.name, 'sequence', False, True, True))
648             self.fields.append(Field(tcard32, tcard32.name, 'length', False, True, True))
649             self.fields.append(Field(tcard16, tcard16.name, 'event_type', False, True, True))
650
651         if self.resolved:
652             return
653
654         # Add the automatic protocol fields
655         if self.is_ge_event:
656             add_ge_event_header()
657         else:
658             add_event_header()
659
660         ComplexType.resolve(self, module)
661
662     out = __main__.output['event']
663
664
665 class Error(ComplexType):
666     '''
667     Derived class representing an error data type.
668
669     Public fields added:
670     opcodes is a dictionary of name -> opcode number, for errorcopies.
671     '''
672     def __init__(self, name, elt):
673         ComplexType.__init__(self, name, elt)
674         self.opcodes = {}
675
676     def add_opcode(self, opcode, name, main):
677         self.opcodes[name] = opcode
678         if main:
679             self.name = name
680
681     def resolve(self, module):
682         if self.resolved:
683             return
684
685         # Add the automatic protocol fields
686         self.fields.append(Field(tcard8, tcard8.name, 'response_type', False, True, True))
687         self.fields.append(Field(tcard8, tcard8.name, 'error_code', False, True, True))
688         self.fields.append(Field(tcard16, tcard16.name, 'sequence', False, True, True))
689         ComplexType.resolve(self, module)
690
691     out = __main__.output['error']
692
693
694 class Doc(object):
695     '''
696     Class representing a <doc> tag.
697     '''
698     def __init__(self, name, elt):
699         self.name = name
700         self.description = None
701         self.brief = 'BRIEF DESCRIPTION MISSING'
702         self.fields = {}
703         self.errors = {}
704         self.see = {}
705         self.example = None
706
707         for child in list(elt):
708             text = child.text if child.text else ''
709             if child.tag == 'description':
710                 self.description = text.strip()
711             if child.tag == 'brief':
712                 self.brief = text.strip()
713             if child.tag == 'field':
714                 self.fields[child.get('name')] = text.strip()
715             if child.tag == 'error':
716                 self.errors[child.get('type')] = text.strip()
717             if child.tag == 'see':
718                 self.see[child.get('name')] = child.get('type')
719             if child.tag == 'example':
720                 self.example = text.strip()
721
722
723
724 _placeholder_byte = Field(PadType(None), tcard8.name, 'pad0', False, True, False)