[Xcb] [PATCH libxcb 1/1] support switch case in the generator

Christian Linhart chris at demorecorder.com
Tue Aug 19 06:57:34 PDT 2014


The implementation is rather simple:
When a <case> is used instead of a <bitcase>
then operator "==" is used instead of "&" in the if-condition.

So it creates a series of "if" statements
(instead of a switch-case statement in C )

In practice this does not matter because a good
optimizing compiler will create the same code
as for a switch-case.

With this simple implementation we get additional
flexibility in the following forms:
* a case value may appear in multiple case branches.
  for example:
	case C1 will be selected by values 1, 4, or 5
	case C2 will be selected by values 3, 4, or 7

* mixing of bitcase and case is possible
	(this will usually make no sense but there may
	be protocol specs where this is needed)

details of the impl:
* replaced "is_bitcase" with "is_case_or_bitcase" in all places
  so that cases are treated like bitcases.

* In function "_c_serialize_helper_switch": write operator "=="
  instead of operator "&" if it is a case.
---
 src/c_client.py | 55 +++++++++++++++++++++++++++++++++----------------------
 1 file changed, 33 insertions(+), 22 deletions(-)

diff --git a/src/c_client.py b/src/c_client.py
index 54e56c4..87f268b 100644
--- a/src/c_client.py
+++ b/src/c_client.py
@@ -354,15 +354,15 @@ def _c_type_setup(self, name, postfix):
             if field.type.is_list and not field.type.member.fixed_size():
                 field.c_pointer = '*'
 
             if field.type.is_switch:
                 field.c_pointer = '*'
                 field.c_field_const_type = 'const ' + field.c_field_type
                 self.c_need_aux = True
-            elif not field.type.fixed_size() and not field.type.is_bitcase:
+            elif not field.type.fixed_size() and not field.type.is_case_or_bitcase:
                 self.c_need_sizeof = True
 
             field.c_iterator_type = _t(field.field_type + ('iterator',))      # xcb_fieldtype_iterator_t
             field.c_iterator_name = _n(name + (field.field_name, 'iterator')) # xcb_container_field_iterator
             field.c_accessor_name = _n(name + (field.field_name,))            # xcb_container_field
             field.c_length_name = _n(name + (field.field_name, 'length'))     # xcb_container_field_length
             field.c_end_name = _n(name + (field.field_name, 'end'))           # xcb_container_field_end
@@ -403,15 +403,15 @@ def _c_type_setup(self, name, postfix):
             _c_complex(self)
             for bitcase in self.bitcases:
                 bitcase_name = bitcase.type.name if bitcase.type.has_name else name
                 _c_accessors(bitcase.type, bitcase_name, bitcase_name)
                 # no list with switch as element, so no call to
                 # _c_iterator(field.type, field_name) necessary
 
-    if not self.is_bitcase:
+    if not self.is_case_or_bitcase:
         if self.c_need_serialize:
             if self.c_serialize_name not in finished_serializers:
                 finished_serializers.append(self.c_serialize_name)
                 _c_serialize('serialize', self)
 
                 # _unpack() and _unserialize() are only needed for special cases:
                 #   switch -> unpack
@@ -433,15 +433,15 @@ def _c_helper_absolute_name(prefix, field=None):
     if field is not None, append the field name as well
     """
     prefix_str = ''
     for name, sep, obj in prefix:
         prefix_str += name
         if '' == sep:
             sep = '->'
-            if ((obj.is_bitcase and obj.has_name) or     # named bitcase
+            if ((obj.is_case_or_bitcase and obj.has_name) or     # named bitcase
                 (obj.is_switch and len(obj.parents)>1)):
                 sep = '.'
         prefix_str += sep
     if field is not None:
         prefix_str += _cpp(field.field_name)
     return prefix_str
 # _c_absolute_name
@@ -466,15 +466,15 @@ def _c_helper_field_mapping(complex_type, prefix, flat=False):
         for f in complex_type.fields:
             fname = _c_helper_absolute_name(prefix, f)
             if f.field_name in all_fields:
                 raise Exception("field name %s has been registered before" % f.field_name)
 
             all_fields[f.field_name] = (fname, f)
             if f.type.is_container and flat==False:
-                if f.type.is_bitcase and not f.type.has_name:
+                if f.type.is_case_or_bitcase and not f.type.has_name:
                     new_prefix = prefix
                 elif f.type.is_switch and len(f.type.parents)>1:
                     # nested switch gets another separator
                     new_prefix = prefix+[(f.c_field_name, '.', f.type)]
                 else:
                     new_prefix = prefix+[(f.c_field_name, '->', f.type)]
                 all_fields.update(_c_helper_field_mapping(f.type, new_prefix, flat))
@@ -489,18 +489,18 @@ def _c_helper_resolve_field_names (prefix):
     all_fields = {}
     tmp_prefix = []
     # look for fields in the remaining containers
     for idx, p in enumerate(prefix):
         name, sep, obj = p
         if ''==sep:
             # sep can be preset in prefix, if not, make a sensible guess
-            sep = '.' if (obj.is_switch or obj.is_bitcase) else '->'
+            sep = '.' if (obj.is_switch or obj.is_case_or_bitcase) else '->'
             # exception: 'toplevel' object (switch as well!) always have sep '->'
             sep = '->' if idx<1 else sep
-        if not obj.is_bitcase or (obj.is_bitcase and obj.has_name):
+        if not obj.is_case_or_bitcase or (obj.is_case_or_bitcase and obj.has_name):
             tmp_prefix.append((name, sep, obj))
         all_fields.update(_c_helper_field_mapping(obj, tmp_prefix, flat=True))
 
     return all_fields
 # _c_helper_resolve_field_names
 
 def get_expr_fields(self):
@@ -685,36 +685,47 @@ def _c_serialize_helper_switch(context, self, complex_name,
                                code_lines, temp_vars,
                                space, prefix):
     count = 0
     switch_expr = _c_accessor_get_expr(self.expr, None)
 
     for b in self.bitcases:
         len_expr = len(b.type.expr)
+
+        compare_operator = '&'
+        if b.type.is_case:
+            compare_operator = '=='
+        else:
+            compare_operator = '&'
+
         for n, expr in enumerate(b.type.expr):
             bitcase_expr = _c_accessor_get_expr(expr, None)
             # only one <enumref> in the <bitcase>
             if len_expr == 1:
-                code_lines.append('    if(%s & %s) {' % (switch_expr, bitcase_expr))
+                code_lines.append(
+                    '    if(%s %s %s) {' % (switch_expr, compare_operator, bitcase_expr))
             # multiple <enumref> in the <bitcase>
             elif n == 0: # first
-                code_lines.append('    if((%s & %s) ||' % (switch_expr, bitcase_expr))
+                code_lines.append(
+                    '    if((%s %s %s) ||' % (switch_expr, compare_operator, bitcase_expr))
             elif len_expr == (n + 1): # last
-                code_lines.append('       (%s & %s)) {' % (switch_expr, bitcase_expr))
+                code_lines.append(
+                    '       (%s %s %s)) {' % (switch_expr, compare_operator, bitcase_expr))
             else: # between first and last
-                code_lines.append('       (%s & %s) ||' % (switch_expr, bitcase_expr))
+                code_lines.append(
+                    '       (%s %s %s) ||' % (switch_expr, compare_operator, bitcase_expr))
 
         b_prefix = prefix
         if b.type.has_name:
             b_prefix = prefix + [(b.c_field_name, '.', b.type)]
 
         count += _c_serialize_helper_fields(context, b.type,
                                             code_lines, temp_vars,
                                             "%s    " % space,
                                             b_prefix,
-                                            is_bitcase = True)
+                                            is_case_or_bitcase = True)
         code_lines.append('    }')
 
 #    if 'serialize' == context:
 #        count += _c_serialize_helper_insert_padding(context, code_lines, space, False)
 #    elif context in ('unserialize', 'unpack', 'sizeof'):
 #        # padding
 #        code_lines.append('%s    xcb_pad = -xcb_block_len & 3;' % space)
@@ -830,15 +841,15 @@ def _c_serialize_helper_list_field(context, self, field,
     return length
 # _c_serialize_helper_list_field()
 
 def _c_serialize_helper_fields_fixed_size(context, self, field,
                                           code_lines, temp_vars,
                                           space, prefix):
     # keep the C code a bit more readable by giving the field name
-    if not self.is_bitcase:
+    if not self.is_case_or_bitcase:
         code_lines.append('%s    /* %s.%s */' % (space, self.c_type, field.c_field_name))
     else:
         scoped_name = [p[2].c_type if idx==0 else p[0] for idx, p in enumerate(prefix)]
         typename = reduce(lambda x,y: "%s.%s" % (x, y), scoped_name)
         code_lines.append('%s    /* %s.%s */' % (space, typename, field.c_field_name))
 
     abs_field_name = _c_helper_absolute_name(prefix, field)
@@ -947,27 +958,27 @@ def _c_serialize_helper_fields_variable_size(context, self, field,
         length = "%s(%s)" % (field.type.c_sizeof_name, var_field_name)
 
     return (value, length)
 # _c_serialize_helper_fields_variable_size
 
 def _c_serialize_helper_fields(context, self,
                                code_lines, temp_vars,
-                               space, prefix, is_bitcase):
+                               space, prefix, is_case_or_bitcase):
     count = 0
     need_padding = False
     prev_field_was_variable = False
 
     for field in self.fields:
         if not field.visible:
             if not ((field.wire and not field.auto) or 'unserialize' == context):
                 continue
 
         # switch/bitcase: fixed size fields must be considered explicitly
         if field.type.fixed_size():
-            if self.is_bitcase or self.c_var_followed_by_fixed_fields:
+            if self.is_case_or_bitcase or self.c_var_followed_by_fixed_fields:
                 if prev_field_was_variable and need_padding:
                     # insert padding
 #                    count += _c_serialize_helper_insert_padding(context, code_lines, space,
 #                                                                self.c_var_followed_by_fixed_fields)
                     prev_field_was_variable = False
 
                 # prefix for fixed size fields
@@ -985,29 +996,29 @@ def _c_serialize_helper_fields(context, self,
                 # Variable length pad is <pad align= />
                 code_lines.append('%s    xcb_align_to = %d;' % (space, field.type.align))
                 count += _c_serialize_helper_insert_padding(context, code_lines, space,
                                                         self.c_var_followed_by_fixed_fields)
                 continue
             else:
                 # switch/bitcase: always calculate padding before and after variable sized fields
-                if need_padding or is_bitcase:
+                if need_padding or is_case_or_bitcase:
                     count += _c_serialize_helper_insert_padding(context, code_lines, space,
                                                             self.c_var_followed_by_fixed_fields)
 
                 value, length = _c_serialize_helper_fields_variable_size(context, self, field,
                                                                          code_lines, temp_vars,
                                                                          space, prefix)
                 prev_field_was_variable = True
 
         # save (un)serialization C code
         if '' != value:
             code_lines.append('%s%s' % (space, value))
 
         if field.type.fixed_size():
-            if is_bitcase or self.c_var_followed_by_fixed_fields:
+            if is_case_or_bitcase or self.c_var_followed_by_fixed_fields:
                 # keep track of (un)serialized object's size
                 code_lines.append('%s    xcb_block_len += %s;' % (space, length))
                 if context in ('unserialize', 'unpack', 'sizeof'):
                     code_lines.append('%s    xcb_tmp += %s;' % (space, length))
         else:
             # variable size objects or bitcase:
             #   value & length might have been inserted earlier for special cases
@@ -1457,15 +1468,15 @@ def _c_accessors_field(self, field):
     '''
     Declares the accessor functions for a non-list field that follows a variable-length field.
     '''
     c_type = self.c_type
 
     # special case: switch
     switch_obj = self if self.is_switch else None
-    if self.is_bitcase:
+    if self.is_case_or_bitcase:
         switch_obj = self.parents[-1]
     if switch_obj is not None:
         c_type = switch_obj.c_type
 
     if field.type.is_simple:
         _hc('')
         _hc('%s', field.c_field_type)
@@ -1525,15 +1536,15 @@ def _c_accessors_list(self, field):
     # special case: switch
     # in case of switch, 2 params have to be supplied to certain accessor functions:
     #   1. the anchestor object (request or reply)
     #   2. the (anchestor) switch object
     # the reason is that switch is either a child of a request/reply or nested in another switch,
     # so whenever we need to access a length field, we might need to refer to some anchestor type
     switch_obj = self if self.is_switch else None
-    if self.is_bitcase:
+    if self.is_case_or_bitcase:
         switch_obj = self.parents[-1]
     if switch_obj is not None:
         c_type = switch_obj.c_type
 
     params = []
     fields = {}
     parents = self.parents if hasattr(self, 'parents') else [self]
@@ -1557,15 +1568,15 @@ def _c_accessors_list(self, field):
         prefix_str = '/* %s */ S' % toplevel_switch.name[-1]
         prefix = [(prefix_str, '->', toplevel_switch)]
 
         # look for fields in the remaining containers
         for p in parents[2:] + [self]:
             # the separator between parent and child is always '.' here,
             # because of nested switch statements
-            if not p.is_bitcase or (p.is_bitcase and p.has_name):
+            if not p.is_case_or_bitcase or (p.is_case_or_bitcase and p.has_name):
                 prefix.append((p.name[-1], '.', p))
             fields.update(_c_helper_field_mapping(p, prefix, flat=True))
 
         # auxiliary object for 'S' parameter
         S_obj = parents[1]
 
     _h_setlevel(1)
@@ -2360,15 +2371,15 @@ def _man_request(self, name, cookie_type, void, aux):
             '''
             Declares the accessor functions for a non-list field that follows a variable-length field.
             '''
             c_type = self.c_type
 
             # special case: switch
             switch_obj = self if self.is_switch else None
-            if self.is_bitcase:
+            if self.is_case_or_bitcase:
                 switch_obj = self.parents[-1]
             if switch_obj is not None:
                 c_type = switch_obj.c_type
 
             if field.type.is_simple:
                 f.write('%s %s (const %s *reply)\n' % (field.c_field_type, field.c_accessor_name, c_type))
                 create_link('%s' % field.c_accessor_name)
@@ -2388,15 +2399,15 @@ def _man_request(self, name, cookie_type, void, aux):
             # special case: switch
             # in case of switch, 2 params have to be supplied to certain accessor functions:
             #   1. the anchestor object (request or reply)
             #   2. the (anchestor) switch object
             # the reason is that switch is either a child of a request/reply or nested in another switch,
             # so whenever we need to access a length field, we might need to refer to some anchestor type
             switch_obj = self if self.is_switch else None
-            if self.is_bitcase:
+            if self.is_case_or_bitcase:
                 switch_obj = self.parents[-1]
             if switch_obj is not None:
                 c_type = switch_obj.c_type
 
             params = []
             fields = {}
             parents = self.parents if hasattr(self, 'parents') else [self]
@@ -2420,15 +2431,15 @@ def _man_request(self, name, cookie_type, void, aux):
                 prefix_str = '/* %s */ S' % toplevel_switch.name[-1]
                 prefix = [(prefix_str, '->', toplevel_switch)]
 
                 # look for fields in the remaining containers
                 for p in parents[2:] + [self]:
                     # the separator between parent and child is always '.' here,
                     # because of nested switch statements
-                    if not p.is_bitcase or (p.is_bitcase and p.has_name):
+                    if not p.is_case_or_bitcase or (p.is_case_or_bitcase and p.has_name):
                         prefix.append((p.name[-1], '.', p))
                     fields.update(_c_helper_field_mapping(p, prefix, flat=True))
 
                 # auxiliary object for 'S' parameter
                 S_obj = parents[1]
 
             if list.member.fixed_size():
-- 
2.0.1



More information about the Xcb mailing list