mapi/glapi: Generate sizeof() helpers instead of fixed sizes.
[mesa.git] / src / mapi / glapi / gen / gl_XML.py
index 67aba81a74e69e188c29663b5a46aefd7f4e45ab..5b5f6e23b0a9159cedd6cad1a66f7b0f8c21463e 100644 (file)
@@ -1,4 +1,3 @@
-#!/usr/bin/env python
 
 # (C) Copyright IBM Corporation 2004, 2005
 # All Rights Reserved.
 # Authors:
 #    Ian Romanick <idr@us.ibm.com>
 
+from __future__ import print_function
+
+from collections import OrderedDict
 from decimal import Decimal
 import xml.etree.ElementTree as ET
-import re, sys, string
+import re, sys
 import os.path
 import typeexpr
 import static_data
@@ -47,7 +49,7 @@ def parse_GL_API( file_name, factory = None ):
     # that are not part of the ABI.
 
     for func in api.functionIterateByCategory():
-        if func.assign_offset:
+        if func.assign_offset and func.offset < 0:
             func.offset = api.next_offset;
             api.next_offset += 1
 
@@ -126,17 +128,17 @@ class gl_print_base(object):
     def printHeader(self):
         """Print the header associated with all files and call the printRealHeader method."""
 
-        print '/* DO NOT EDIT - This file generated automatically by %s script */' \
-                % (self.name)
-        print ''
-        print '/*'
-        print ' * ' + self.license.replace('\n', '\n * ')
-        print ' */'
-        print ''
+        print('/* DO NOT EDIT - This file generated automatically by %s script */' \
+                % (self.name))
+        print('')
+        print('/*')
+        print((' * ' + self.license.replace('\n', '\n * ')).replace(' \n', '\n'))
+        print(' */')
+        print('')
         if self.header_tag:
-            print '#if !defined( %s )' % (self.header_tag)
-            print '#  define %s' % (self.header_tag)
-            print ''
+            print('#if !defined( %s )' % (self.header_tag))
+            print('#  define %s' % (self.header_tag))
+            print('')
         self.printRealHeader();
         return
 
@@ -147,13 +149,13 @@ class gl_print_base(object):
         self.printRealFooter()
 
         if self.undef_list:
-            print ''
+            print('')
             for u in self.undef_list:
-                print "#  undef %s" % (u)
+                print("#  undef %s" % (u))
 
         if self.header_tag:
-            print ''
-            print '#endif /* !defined( %s ) */' % (self.header_tag)
+            print('')
+            print('#endif /* !defined( %s ) */' % (self.header_tag))
 
 
     def printRealHeader(self):
@@ -183,11 +185,11 @@ class gl_print_base(object):
         The name is also added to the file's undef_list.
         """
         self.undef_list.append("PURE")
-        print """#  if defined(__GNUC__) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590))
+        print("""#  if defined(__GNUC__) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590))
 #    define PURE __attribute__((pure))
 #  else
 #    define PURE
-#  endif"""
+#  endif""")
         return
 
 
@@ -203,11 +205,11 @@ class gl_print_base(object):
         """
 
         self.undef_list.append("FASTCALL")
-        print """#  if defined(__i386__) && defined(__GNUC__) && !defined(__CYGWIN__) && !defined(__MINGW32__)
+        print("""#  if defined(__i386__) && defined(__GNUC__) && !defined(__CYGWIN__) && !defined(__MINGW32__)
 #    define FASTCALL __attribute__((fastcall))
 #  else
 #    define FASTCALL
-#  endif"""
+#  endif""")
         return
 
 
@@ -223,11 +225,11 @@ class gl_print_base(object):
         """
 
         self.undef_list.append(S)
-        print """#  if (defined(__GNUC__) && !defined(__CYGWIN__) && !defined(__MINGW32__)) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590) && defined(__ELF__))
+        print("""#  if defined(__GNUC__) && !defined(__CYGWIN__) && !defined(__MINGW32__)
 #    define %s  __attribute__((visibility("%s")))
 #  else
 #    define %s
-#  endif""" % (S, s, S)
+#  endif""" % (S, s, S))
         return
 
 
@@ -243,11 +245,11 @@ class gl_print_base(object):
         """
 
         self.undef_list.append("NOINLINE")
-        print """#  if defined(__GNUC__) || (defined(__SUNPRO_C) && (__SUNPRO_C >= 0x590))
+        print("""#  if defined(__GNUC__)
 #    define NOINLINE __attribute__((noinline))
 #  else
 #    define NOINLINE
-#  endif"""
+#  endif""")
         return
 
 
@@ -282,7 +284,7 @@ def classify_category(name, number):
 
     try:
         core_version = float(name)
-    except Exception,e:
+    except Exception:
         core_version = 0.0
 
     if core_version > 0.0:
@@ -318,7 +320,7 @@ def create_parameter_string(parameters, include_names):
 
     if len(list) == 0: list = ["void"]
 
-    return string.join(list, ", ")
+    return ", ".join(list)
 
 
 class gl_item(object):
@@ -363,7 +365,7 @@ class gl_enum( gl_item ):
         else:
             try:
                 c = int(temp)
-            except Exception,e:
+            except Exception:
                 raise RuntimeError('Invalid count value "%s" for enum "%s" in function "%s" when an integer was expected.' % (temp, self.name, n))
 
             self.default_count = c
@@ -424,7 +426,7 @@ class gl_parameter(object):
             count = int(c)
             self.count = count
             self.counter = None
-        except Exception,e:
+        except Exception:
             count = 1
             self.count = 0
             self.counter = c
@@ -563,7 +565,14 @@ class gl_parameter(object):
 
 
     def size_string(self, use_parens = 1):
-        s = self.size()
+        base_size_str = ""
+
+        count = self.get_element_count()
+        if count:
+            base_size_str = "%d * " % count
+
+        base_size_str += "sizeof(%s)" % ( self.get_base_type_string() )
+
         if self.counter or self.count_parameter_list:
             list = [ "compsize" ]
 
@@ -572,18 +581,18 @@ class gl_parameter(object):
             elif self.counter:
                 list = [ self.counter ]
 
-            if s > 1:
-                list.append( str(s) )
+            if self.size() > 1:
+                list.append( base_size_str )
 
             if len(list) > 1 and use_parens :
-                return "(%s)" % (string.join(list, " * "))
+                return "safe_mul(%s)" % ", ".join(list)
             else:
-                return string.join(list, " * ")
+                return " * ".join(list)
 
         elif self.is_image():
             return "compsize"
         else:
-            return str(s)
+            return base_size_str
 
 
     def format_string(self):
@@ -607,22 +616,13 @@ class gl_function( gl_item ):
         self.exec_flavor = 'mesa'
         self.desktop = True
         self.deprecated = None
-
-        # self.entry_point_api_map[name][api] is a decimal value
-        # indicating the earliest version of the given API in which
-        # each entry point exists.  Every entry point is included in
-        # the first level of the map; the second level of the map only
-        # lists APIs which contain the entry point in at least one
-        # version.  For example,
-        # self.entry_point_api_map['ClipPlanex'] == { 'es1':
-        # Decimal('1.1') }.
-        self.entry_point_api_map = {}
+        self.has_no_error_variant = False
 
         # self.api_map[api] is a decimal value indicating the earliest
         # version of the given API in which ANY alias for the function
         # exists.  The map only lists APIs which contain the function
         # in at least one version.  For example, for the ClipPlanex
-        # function, self.entry_point_api_map == { 'es1':
+        # function, self.api_map == { 'es1':
         # Decimal('1.1') }.
         self.api_map = {}
 
@@ -655,13 +655,11 @@ class gl_function( gl_item ):
 
         self.entry_points.append( name )
 
-        self.entry_point_api_map[name] = {}
         for api in ('es1', 'es2'):
             version_str = element.get(api, 'none')
             assert version_str is not None
             if version_str != 'none':
                 version_decimal = Decimal(version_str)
-                self.entry_point_api_map[name][api] = version_decimal
                 if api not in self.api_map or \
                         version_decimal < self.api_map[api]:
                     self.api_map[api] = version_decimal
@@ -677,6 +675,11 @@ class gl_function( gl_item ):
         if not is_attr_true(element, 'desktop', 'true'):
             self.desktop = False
 
+        if self.has_no_error_variant or is_attr_true(element, 'no_error'):
+            self.has_no_error_variant = True
+        else:
+            self.has_no_error_variant = False
+
         if alias:
             true_name = alias
         else:
@@ -685,10 +688,14 @@ class gl_function( gl_item ):
             # Only try to set the offset when a non-alias entry-point
             # is being processed.
 
-            if name in static_data.offsets:
+            if name in static_data.offsets and static_data.offsets[name] <= static_data.MAX_OFFSETS:
                 self.offset = static_data.offsets[name]
+            elif name in static_data.offsets and static_data.offsets[name] > static_data.MAX_OFFSETS:
+                self.offset = static_data.offsets[name]
+                self.assign_offset = True
             else:
-                self.offset = -1
+                if self.exec_flavor != "skip":
+                    raise RuntimeError("Entry-point %s is missing offset in static_data.py. Add one at the bottom of the list." % (name))
                 self.assign_offset = self.exec_flavor != "skip" or name in static_data.unused_functions
 
         if not self.name:
@@ -774,9 +781,9 @@ class gl_function( gl_item ):
 
     def parameterIterator(self, name = None):
         if name is not None:
-            return self.entry_point_parameters[name].__iter__();
+            return iter(self.entry_point_parameters[name]);
         else:
-            return self.parameters.__iter__();
+            return iter(self.parameters);
 
 
     def get_parameter_string(self, entrypoint = None):
@@ -818,23 +825,6 @@ class gl_function( gl_item ):
         else:
             return "_dispatch_stub_%u" % (self.offset)
 
-    def entry_points_for_api_version(self, api, version = None):
-        """Return a list of the entry point names for this function
-        which are supported in the given API (and optionally, version).
-
-        Use the decimal.Decimal type to precisely express non-integer
-        versions.
-        """
-        result = []
-        for entry_point, api_to_ver in self.entry_point_api_map.iteritems():
-            if api not in api_to_ver:
-                continue
-            if version is not None and version < api_to_ver[api]:
-                continue
-            result.append(entry_point)
-        return result
-
-
 class gl_item_factory(object):
     """Factory to create objects derived from gl_item."""
 
@@ -856,7 +846,7 @@ class gl_item_factory(object):
 
 class gl_api(object):
     def __init__(self, factory):
-        self.functions_by_name = {}
+        self.functions_by_name = OrderedDict()
         self.enums_by_name = {}
         self.types_by_name = {}
 
@@ -870,31 +860,6 @@ class gl_api(object):
         typeexpr.create_initial_types()
         return
 
-    def filter_functions(self, entry_point_list):
-        """Filter out entry points not in entry_point_list."""
-        functions_by_name = {}
-        for func in self.functions_by_name.itervalues():
-            entry_points = [ent for ent in func.entry_points if ent in entry_point_list]
-            if entry_points:
-                func.filter_entry_points(entry_points)
-                functions_by_name[func.name] = func
-
-        self.functions_by_name = functions_by_name
-
-    def filter_functions_by_api(self, api, version = None):
-        """Filter out entry points not in the given API (or
-        optionally, not in the given version of the given API).
-        """
-        functions_by_name = {}
-        for func in self.functions_by_name.itervalues():
-            entry_points = func.entry_points_for_api_version(api, version)
-            if entry_points:
-                func.filter_entry_points(entry_points)
-                functions_by_name[func.name] = func
-
-        self.functions_by_name = functions_by_name
-
-
     def parse_file(self, file_name):
         doc = ET.parse( file_name )
         self.process_element(file_name, doc)
@@ -935,7 +900,7 @@ class gl_api(object):
                 temp_name = child.get( "name" )
                 self.category_dict[ temp_name ] = [cat_name, cat_number]
 
-                if self.functions_by_name.has_key( func_name ):
+                if func_name in self.functions_by_name:
                     func = self.functions_by_name[ func_name ]
                     func.process_element( child )
                 else:
@@ -972,7 +937,7 @@ class gl_api(object):
             if (cat == None) or (cat == cat_name):
                 [func_cat_type, key] = classify_category(cat_name, cat_number)
 
-                if not lists[func_cat_type].has_key(key):
+                if key not in lists[func_cat_type]:
                     lists[func_cat_type][key] = {}
 
                 lists[func_cat_type][key][func.name] = func
@@ -980,28 +945,26 @@ class gl_api(object):
 
         functions = []
         for func_cat_type in range(0,4):
-            keys = lists[func_cat_type].keys()
-            keys.sort()
+            keys = sorted(lists[func_cat_type].keys())
 
             for key in keys:
-                names = lists[func_cat_type][key].keys()
-                names.sort()
+                names = sorted(lists[func_cat_type][key].keys())
 
                 for name in names:
                     functions.append(lists[func_cat_type][key][name])
 
-        return functions.__iter__()
+        return iter(functions)
 
 
     def functionIterateByOffset(self):
         max_offset = -1
-        for func in self.functions_by_name.itervalues():
+        for func in self.functions_by_name.values():
             if func.offset > max_offset:
                 max_offset = func.offset
 
 
         temp = [None for i in range(0, max_offset + 1)]
-        for func in self.functions_by_name.itervalues():
+        for func in self.functions_by_name.values():
             if func.offset != -1:
                 temp[ func.offset ] = func
 
@@ -1011,22 +974,21 @@ class gl_api(object):
             if temp[i]:
                 list.append(temp[i])
 
-        return list.__iter__();
+        return iter(list);
 
 
     def functionIterateAll(self):
-        return self.functions_by_name.itervalues()
+        return self.functions_by_name.values()
 
 
     def enumIterateByName(self):
-        keys = self.enums_by_name.keys()
-        keys.sort()
+        keys = sorted(self.enums_by_name.keys())
 
         list = []
         for enum in keys:
             list.append( self.enums_by_name[ enum ] )
 
-        return list.__iter__()
+        return iter(list)
 
 
     def categoryIterate(self):
@@ -1039,29 +1001,28 @@ class gl_api(object):
 
         list = []
         for cat_type in range(0,4):
-            keys = self.categories[cat_type].keys()
-            keys.sort()
+            keys = sorted(self.categories[cat_type].keys())
 
             for key in keys:
                 list.append(self.categories[cat_type][key])
 
-        return list.__iter__()
+        return iter(list)
 
 
     def get_category_for_name( self, name ):
-        if self.category_dict.has_key(name):
+        if name in self.category_dict:
             return self.category_dict[name]
         else:
             return ["<unknown category>", None]
 
 
     def typeIterate(self):
-        return self.types_by_name.itervalues()
+        return self.types_by_name.values()
 
 
     def find_type( self, type_name ):
         if type_name in self.types_by_name:
             return self.types_by_name[ type_name ].type_expr
         else:
-            print "Unable to find base type matching \"%s\"." % (type_name)
+            print("Unable to find base type matching \"%s\"." % (type_name))
             return None