summaryrefslogtreecommitdiffhomepage
path: root/registry/cgenerator.py
diff options
context:
space:
mode:
Diffstat (limited to 'registry/cgenerator.py')
-rw-r--r--registry/cgenerator.py318
1 files changed, 163 insertions, 155 deletions
diff --git a/registry/cgenerator.py b/registry/cgenerator.py
index ab0c779..7f2d9bc 100644
--- a/registry/cgenerator.py
+++ b/registry/cgenerator.py
@@ -14,8 +14,11 @@
# See the License for the specific language governing permissions and
# limitations under the License.
-import os,re,sys,pdb
-from generator import *
+import os
+import re
+import sys
+from generator import (GeneratorOptions, OutputGenerator, noneStr,
+ regSortFeatures, write)
# CGeneratorOptions - subclass of GeneratorOptions.
#
@@ -51,9 +54,16 @@ from generator import *
# parameter on a separate line
# alignFuncParam - if nonzero and parameters are being put on a
# separate line, align parameter names at the specified column
+# genEnumBeginEndRange - True if BEGIN_RANGE / END_RANGE macros should
+# be generated for enumerated types
+# genAliasMacro - True if the OpenXR alias macro should be generated
+# for aliased types (unclear what other circumstances this is useful)
+# aliasMacro - alias macro to inject when genAliasMacro is True
class CGeneratorOptions(GeneratorOptions):
"""Represents options during C interface generation for headers"""
+
def __init__(self,
+ conventions = None,
filename = None,
directory = '.',
apiname = None,
@@ -76,8 +86,12 @@ class CGeneratorOptions(GeneratorOptions):
apientryp = '',
indentFuncProto = True,
indentFuncPointer = False,
- alignFuncParam = 0):
- GeneratorOptions.__init__(self, filename, directory, apiname, profile,
+ alignFuncParam = 0,
+ genEnumBeginEndRange = False,
+ genAliasMacro = False,
+ aliasMacro = ''
+ ):
+ GeneratorOptions.__init__(self, conventions, filename, directory, apiname, profile,
versions, emitversions, defaultExtensions,
addExtensions, removeExtensions,
emitExtensions, sortProcedure)
@@ -93,6 +107,9 @@ class CGeneratorOptions(GeneratorOptions):
self.indentFuncProto = indentFuncProto
self.indentFuncPointer = indentFuncPointer
self.alignFuncParam = alignFuncParam
+ self.genEnumBeginEndRange = genEnumBeginEndRange
+ self.genAliasMacro = genAliasMacro
+ self.aliasMacro = aliasMacro
# COutputGenerator - subclass of OutputGenerator.
# Generates C-language API interfaces.
@@ -116,21 +133,25 @@ class COutputGenerator(OutputGenerator):
TYPE_SECTIONS = ['include', 'define', 'basetype', 'handle', 'enum',
'group', 'bitmask', 'funcpointer', 'struct']
ALL_SECTIONS = TYPE_SECTIONS + ['commandPointer', 'command']
+
def __init__(self,
errFile = sys.stderr,
warnFile = sys.stderr,
diagFile = sys.stdout):
OutputGenerator.__init__(self, errFile, warnFile, diagFile)
# Internal state - accumulators for different inner block text
- self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
- #
+ self.sections = {section: [] for section in self.ALL_SECTIONS}
+ self.feature_not_empty = False
+ self.need_platform_include = False
+ self.may_alias = None
+
def beginFile(self, genOpts):
OutputGenerator.beginFile(self, genOpts)
# C-specific
#
# Multiple inclusion protection & C++ wrappers.
- if (genOpts.protectFile and self.genOpts.filename):
- headerSym = re.sub('\.h', '_h_',
+ if genOpts.protectFile and self.genOpts.filename:
+ headerSym = re.sub(r'\.h', '_h_',
os.path.basename(self.genOpts.filename)).upper()
write('#ifndef', headerSym, file=self.outFile)
write('#define', headerSym, '1', file=self.outFile)
@@ -139,26 +160,12 @@ class COutputGenerator(OutputGenerator):
write('extern "C" {', file=self.outFile)
write('#endif', file=self.outFile)
self.newline()
- #
+
# User-supplied prefix text, if any (list of strings)
- if (genOpts.prefixText):
+ if genOpts.prefixText:
for s in genOpts.prefixText:
write(s, file=self.outFile)
- #
- # Some boilerplate describing what was generated - this
- # will probably be removed later since the extensions
- # pattern may be very long.
- # write('/* Generated C header for:', file=self.outFile)
- # write(' * API:', genOpts.apiname, file=self.outFile)
- # if (genOpts.profile):
- # write(' * Profile:', genOpts.profile, file=self.outFile)
- # write(' * Versions considered:', genOpts.versions, file=self.outFile)
- # write(' * Versions emitted:', genOpts.emitversions, file=self.outFile)
- # write(' * Default extensions included:', genOpts.defaultExtensions, file=self.outFile)
- # write(' * Additional extensions included:', genOpts.addExtensions, file=self.outFile)
- # write(' * Extensions removed:', genOpts.removeExtensions, file=self.outFile)
- # write(' * Extensions emitted:', genOpts.emitExtensions, file=self.outFile)
- # write(' */', file=self.outFile)
+
def endFile(self):
# C-specific
# Finish C++ wrapper and multiple inclusion protection
@@ -166,11 +173,12 @@ class COutputGenerator(OutputGenerator):
write('#ifdef __cplusplus', file=self.outFile)
write('}', file=self.outFile)
write('#endif', file=self.outFile)
- if (self.genOpts.protectFile and self.genOpts.filename):
+ if self.genOpts.protectFile and self.genOpts.filename:
self.newline()
write('#endif', file=self.outFile)
# Finish processing in superclass
OutputGenerator.endFile(self)
+
def beginFeature(self, interface, emit):
# Start processing in superclass
OutputGenerator.beginFeature(self, interface, emit)
@@ -178,55 +186,68 @@ class COutputGenerator(OutputGenerator):
# Accumulate includes, defines, types, enums, function pointer typedefs,
# end function prototypes separately for this feature. They're only
# printed in endFeature().
- self.sections = dict([(section, []) for section in self.ALL_SECTIONS])
+ self.sections = {section: [] for section in self.ALL_SECTIONS}
+ self.feature_not_empty = False
+
def endFeature(self):
# C-specific
# Actually write the interface to the output file.
- if (self.emit):
- self.newline()
- if (self.genOpts.protectFeature):
- write('#ifndef', self.featureName, file=self.outFile)
- # If type declarations are needed by other features based on
- # this one, it may be necessary to suppress the ExtraProtect,
- # or move it below the 'for section...' loop.
- if (self.featureExtraProtect != None):
- write('#ifdef', self.featureExtraProtect, file=self.outFile)
- write('#define', self.featureName, '1', file=self.outFile)
- for section in self.TYPE_SECTIONS:
- contents = self.sections[section]
- if contents:
- write('\n'.join(contents), file=self.outFile)
+ if self.emit:
+ if self.feature_not_empty:
+ if self.genOpts.conventions.writeFeature(self.featureExtraProtect, self.genOpts.filename):
self.newline()
- if (self.genOpts.genFuncPointers and self.sections['commandPointer']):
- write('\n'.join(self.sections['commandPointer']), file=self.outFile)
- self.newline()
- if (self.sections['command']):
- if (self.genOpts.protectProto):
- write(self.genOpts.protectProto,
- self.genOpts.protectProtoStr, file=self.outFile)
- write('\n'.join(self.sections['command']), end='', file=self.outFile)
- if (self.genOpts.protectProto):
- write('#endif', file=self.outFile)
- else:
+ if self.genOpts.protectFeature:
+ write('#ifndef', self.featureName, file=self.outFile)
+ # If type declarations are needed by other features based on
+ # this one, it may be necessary to suppress the ExtraProtect,
+ # or move it below the 'for section...' loop.
+ if self.featureExtraProtect is not None:
+ write('#ifdef', self.featureExtraProtect, file=self.outFile)
self.newline()
- if (self.featureExtraProtect != None):
- write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile)
- if (self.genOpts.protectFeature):
- write('#endif /*', self.featureName, '*/', file=self.outFile)
+ write('#define', self.featureName, '1', file=self.outFile)
+ for section in self.TYPE_SECTIONS:
+ # OpenXR:
+ # If we need the explicit include of the external platform header,
+ # put it right before the function pointer definitions
+ if section == "funcpointer" and self.need_platform_include:
+ write('// Include for OpenXR Platform-Specific Types', file=self.outFile)
+ write('#include "openxr_platform.h"', file=self.outFile)
+ self.newline()
+ self.need_platform_include = False
+ contents = self.sections[section]
+ if contents:
+ write('\n'.join(contents), file=self.outFile)
+ if self.genOpts.genFuncPointers and self.sections['commandPointer']:
+ write('\n'.join(self.sections['commandPointer']), file=self.outFile)
+ self.newline()
+ if self.sections['command']:
+ if self.genOpts.protectProto:
+ write(self.genOpts.protectProto,
+ self.genOpts.protectProtoStr, file=self.outFile)
+ write('\n'.join(self.sections['command']), end='', file=self.outFile)
+ if self.genOpts.protectProto:
+ write('#endif', file=self.outFile)
+ else:
+ self.newline()
+ if self.featureExtraProtect is not None:
+ write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile)
+ if self.genOpts.protectFeature:
+ write('#endif /*', self.featureName, '*/', file=self.outFile)
# Finish processing in superclass
OutputGenerator.endFeature(self)
- #
+
# Append a definition to the specified section
def appendSection(self, section, text):
# self.sections[section].append('SECTION: ' + section + '\n')
self.sections[section].append(text)
- # self.logMsg('diag', 'appendSection(section =', section, 'text =', text)
- #
+ self.feature_not_empty = True
+
# Type generation
def genType(self, typeinfo, name, alias):
OutputGenerator.genType(self, typeinfo, name, alias)
typeElem = typeinfo.elem
+ # Vulkan:
# Determine the category of the type, and the type section to add
# its definition to.
# 'funcpointer' is added to the 'struct' section as a workaround for
@@ -238,11 +259,12 @@ class COutputGenerator(OutputGenerator):
else:
section = category
- if category == 'struct' or category == 'union':
+ if category in ('struct', 'union'):
# If the type is a struct type, generate it using the
# special-purpose generator.
self.genStruct(typeinfo, name, alias)
else:
+ # OpenXR: this section was not under 'else:' previously, just fell through
if alias:
# If the type is an alias, just emit a typedef declaration
body = 'typedef ' + alias + ' ' + name + ';\n'
@@ -252,17 +274,65 @@ class COutputGenerator(OutputGenerator):
# If the resulting text is an empty string, don't emit it.
body = noneStr(typeElem.text)
for elem in typeElem:
- if (elem.tag == 'apientry'):
+ if elem.tag == 'apientry':
body += self.genOpts.apientry + noneStr(elem.tail)
else:
body += noneStr(elem.text) + noneStr(elem.tail)
-
if body:
# Add extra newline after multi-line entries.
if '\n' in body[0:-1]:
body += '\n'
self.appendSection(section, body)
- #
+
+ # Protection string generation
+ # Protection strings are the strings defining the OS/Platform/Graphics
+ # requirements for a given OpenXR command. When generating the
+ # language header files, we need to make sure the items specific to a
+ # graphics API or OS platform are properly wrapped in #ifs.
+ def genProtectString(self, protect_str):
+ protect_if_str = ''
+ protect_end_str = ''
+ protect_list = []
+ if protect_str:
+ if ',' in protect_str:
+ protect_list.extend(protect_str.split(","))
+ protect_def_str = ''
+ count = 0
+ for protect_define in protect_list:
+ if count > 0:
+ protect_def_str += ' &&'
+ protect_def_str += ' defined(%s)' % protect_define
+ count = count + 1
+ count = count + 1
+ protect_if_str = '#if'
+ protect_if_str += protect_def_str
+ protect_if_str += '\n'
+ protect_end_str = '#endif //'
+ protect_end_str += protect_def_str
+ protect_end_str += '\n'
+ else:
+ protect_if_str += '#ifdef %s\n' % protect_str
+ protect_end_str += '#endif // %s\n' % protect_str
+ return (protect_if_str, protect_end_str)
+
+ def typeMayAlias(self, typeName):
+ if not self.may_alias:
+ # First time we've asked if a type may alias.
+ # So, let's populate the set of all names of types that may.
+
+ # Everyone with an explicit mayalias="true"
+ self.may_alias = set(typeName
+ for typeName, data in self.registry.typedict.items()
+ if data.elem.get('mayalias') == 'true')
+
+ # Every type mentioned in some other type's parentstruct attribute.
+ self.may_alias.update(set(x for x in
+ [otherType.elem.get('parentstruct')
+ for _, otherType in self.registry.typedict.items()]
+ if x is not None
+ ))
+ return typeName in self.may_alias
+
# Struct (e.g. C "struct" type) generation.
# This is a special case of the <type> tag where the contents are
# interpreted as a set of <member> tags instead of freeform C
@@ -270,7 +340,7 @@ class COutputGenerator(OutputGenerator):
# tags - they are a declaration of a struct or union member.
# Only simple member declarations are supported (no nested
# structs etc.)
- # If alias != None, then this struct aliases another; just
+ # If alias is not None, then this struct aliases another; just
# generate a typedef of that alias.
def genStruct(self, typeinfo, typeName, alias):
OutputGenerator.genStruct(self, typeinfo, typeName, alias)
@@ -280,127 +350,65 @@ class COutputGenerator(OutputGenerator):
if alias:
body = 'typedef ' + alias + ' ' + typeName + ';\n'
else:
- body = 'typedef ' + typeElem.get('category') + ' ' + typeName + ' {\n'
+ body = ''
+ (protect_begin, protect_end) = self.genProtectString(typeElem.get('protect'))
+ if protect_begin:
+ body += protect_begin
+ body += 'typedef ' + typeElem.get('category')
+
+ # This is an OpenXR-specific alternative where aliasing refers
+ # to an inheritance hierarchy of types rather than C-level type
+ # aliases.
+ if self.genOpts.genAliasMacro and self.typeMayAlias(typeName):
+ body += ' ' + self.genOpts.aliasMacro
+
+ body += ' ' + typeName + ' {\n'
- targetLen = 0;
+ targetLen = 0
for member in typeElem.findall('.//member'):
targetLen = max(targetLen, self.getCParamTypeLength(member))
for member in typeElem.findall('.//member'):
body += self.makeCParamDecl(member, targetLen + 4)
body += ';\n'
body += '} ' + typeName + ';\n'
+ if protect_end:
+ body += protect_end
self.appendSection('struct', body)
- #
+
# Group (e.g. C "enum" type) generation.
# These are concatenated together with other types.
- # If alias != None, it is the name of another group type
+ # If alias is not None, it is the name of another group type
# which aliases this type; just generate that alias.
def genGroup(self, groupinfo, groupName, alias = None):
OutputGenerator.genGroup(self, groupinfo, groupName, alias)
groupElem = groupinfo.elem
- if alias:
- # If the group name is aliased, just emit a typedef declaration
- # for the alias.
- body = 'typedef ' + alias + ' ' + groupName + ';\n'
- else:
- self.logMsg('diag', 'CGenerator.genGroup group =', groupName, 'alias =', alias)
-
- # Otherwise, emit an actual enumerated type declaration
- expandName = re.sub(r'([0-9a-z_])([A-Z0-9])',r'\1_\2',groupName).upper()
-
- expandPrefix = expandName
- expandSuffix = ''
- expandSuffixMatch = re.search(r'[A-Z][A-Z]+$',groupName)
- if expandSuffixMatch:
- expandSuffix = '_' + expandSuffixMatch.group()
- # Strip off the suffix from the prefix
- expandPrefix = expandName.rsplit(expandSuffix, 1)[0]
-
- # Prefix
- body = "\ntypedef enum " + groupName + " {\n"
-
- # @@ Should use the type="bitmask" attribute instead
- isEnum = ('FLAG_BITS' not in expandPrefix)
-
- # Get a list of nested 'enum' tags.
- enums = groupElem.findall('enum')
-
- # Check for and report duplicates, and return a list with them
- # removed.
- enums = self.checkDuplicateEnums(enums)
-
- # Loop over the nested 'enum' tags. Keep track of the minimum and
- # maximum numeric values, if they can be determined; but only for
- # core API enumerants, not extension enumerants. This is inferred
- # by looking for 'extends' attributes.
- minName = None
-
- # Accumulate non-numeric enumerant values separately and append
- # them following the numeric values, to allow for aliases.
- # NOTE: this doesn't do a topological sort yet, so aliases of
- # aliases can still get in the wrong order.
- aliasText = ""
-
- for elem in enums:
- # Convert the value to an integer and use that to track min/max.
- (numVal,strVal) = self.enumToValue(elem, True)
- name = elem.get('name')
-
- # Extension enumerants are only included if they are required
- if self.isEnumRequired(elem):
- decl = " " + name + " = " + strVal + ",\n"
- if numVal != None:
- body += decl
- else:
- aliasText += decl
-
- # Don't track min/max for non-numbers (numVal == None)
- if isEnum and numVal != None and elem.get('extends') is None:
- if minName == None:
- minName = maxName = name
- minValue = maxValue = numVal
- elif numVal < minValue:
- minName = name
- minValue = numVal
- elif numVal > maxValue:
- maxName = name
- maxValue = numVal
-
- # Now append the non-numeric enumerant values
- body += aliasText
-
- # Generate min/max value tokens and a range-padding enum. Need some
- # additional padding to generate correct names...
- if isEnum:
- body += " " + expandPrefix + "_BEGIN_RANGE" + expandSuffix + " = " + minName + ",\n"
- body += " " + expandPrefix + "_END_RANGE" + expandSuffix + " = " + maxName + ",\n"
- body += " " + expandPrefix + "_RANGE_SIZE" + expandSuffix + " = (" + maxName + " - " + minName + " + 1),\n"
-
- body += " " + expandPrefix + "_MAX_ENUM" + expandSuffix + " = 0x7FFFFFFF\n"
-
- # Postfix
- body += "} " + groupName + ";"
-
# After either enumerated type or alias paths, add the declaration
# to the appropriate section for the group being defined.
if groupElem.get('type') == 'bitmask':
section = 'bitmask'
else:
section = 'group'
- self.appendSection(section, body)
+
+ if alias:
+ # If the group name is aliased, just emit a typedef declaration
+ # for the alias.
+ body = 'typedef ' + alias + ' ' + groupName + ';\n'
+ self.appendSection(section, body)
+ else:
+ (section, body) = self.buildEnumCDecl(self.genOpts.genEnumBeginEndRange, groupinfo, groupName)
+ self.appendSection(section, "\n" + body)
# Enumerant generation
# <enum> tags may specify their values in several ways, but are usually
# just integers.
def genEnum(self, enuminfo, name, alias):
OutputGenerator.genEnum(self, enuminfo, name, alias)
- (numVal,strVal) = self.enumToValue(enuminfo.elem, False)
+ (_, strVal) = self.enumToValue(enuminfo.elem, False)
body = '#define ' + name.ljust(33) + ' ' + strVal
self.appendSection('enum', body)
- #
# Command generation
def genCmd(self, cmdinfo, name, alias):
OutputGenerator.genCmd(self, cmdinfo, name, alias)
@@ -413,5 +421,5 @@ class COutputGenerator(OutputGenerator):
prefix = ''
decls = self.makeCDecls(cmdinfo.elem)
self.appendSection('command', prefix + decls[0] + '\n')
- if (self.genOpts.genFuncPointers):
+ if self.genOpts.genFuncPointers:
self.appendSection('commandPointer', decls[1])