• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python3 -i
2#
3# Copyright (c) 2013-2019 The Khronos Group Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9#     http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17import io,os,pdb,re,string,sys,copy
18import xml.etree.ElementTree as etree
19from collections import defaultdict
20
21# matchAPIProfile - returns whether an API and profile
22#   being generated matches an element's profile
23# api - string naming the API to match
24# profile - string naming the profile to match
25# elem - Element which (may) have 'api' and 'profile'
26#   attributes to match to.
27# If a tag is not present in the Element, the corresponding API
28#   or profile always matches.
29# Otherwise, the tag must exactly match the API or profile.
30# Thus, if 'profile' = core:
31#   <remove> with no attribute will match
32#   <remove profile='core'> will match
33#   <remove profile='compatibility'> will not match
34# Possible match conditions:
35#   Requested   Element
36#   Profile     Profile
37#   ---------   --------
38#   None        None        Always matches
39#   'string'    None        Always matches
40#   None        'string'    Does not match. Can't generate multiple APIs
41#                           or profiles, so if an API/profile constraint
42#                           is present, it must be asked for explicitly.
43#   'string'    'string'    Strings must match
44#
45#   ** In the future, we will allow regexes for the attributes,
46#   not just strings, so that api="^(gl|gles2)" will match. Even
47#   this isn't really quite enough, we might prefer something
48#   like "gl(core)|gles1(common-lite)".
49def matchAPIProfile(api, profile, elem):
50    """Match a requested API & profile name to a api & profile attributes of an Element"""
51    match = True
52    # Match 'api', if present
53    if ('api' in elem.attrib):
54        if (api == None):
55            raise UserWarning("No API requested, but 'api' attribute is present with value '" +
56                              elem.get('api') + "'")
57        elif (api != elem.get('api')):
58            # Requested API doesn't match attribute
59            return False
60    if ('profile' in elem.attrib):
61        if (profile == None):
62            raise UserWarning("No profile requested, but 'profile' attribute is present with value '" +
63                elem.get('profile') + "'")
64        elif (profile != elem.get('profile')):
65            # Requested profile doesn't match attribute
66            return False
67    return True
68
69# BaseInfo - base class for information about a registry feature
70# (type/group/enum/command/API/extension).
71#   required - should this feature be defined during header generation
72#     (has it been removed by a profile or version)?
73#   declared - has this feature been defined already?
74#   elem - etree Element for this feature
75#   resetState() - reset required/declared to initial values. Used
76#     prior to generating a new API interface.
77#   compareElem(info) - return True if self.elem and info.elem have the
78#     same definition.
79class BaseInfo:
80    """Represents the state of a registry feature, used during API generation"""
81    def __init__(self, elem):
82        self.required = False
83        self.declared = False
84        self.elem = elem
85    def resetState(self):
86        self.required = False
87        self.declared = False
88    def compareElem(self, info):
89        # Just compares the tag and attributes.
90        # @@ This should be virtualized. In particular, comparing <enum>
91        # tags requires special-casing on the attributes, as 'extnumber' is
92        # only relevant when 'offset' is present.
93        selfKeys = sorted(self.elem.keys())
94        infoKeys = sorted(info.elem.keys())
95
96        if selfKeys != infoKeys:
97            return False
98
99        # Ignore value of 'extname' and 'extnumber', as these will inherently
100        # be different when redefining the same interface in different feature
101        # and/or extension blocks.
102        for key in selfKeys:
103            if (key != 'extname' and key != 'extnumber' and
104                (self.elem.get(key) != info.elem.get(key))):
105                return False
106
107        return True
108
109# TypeInfo - registry information about a type. No additional state
110#   beyond BaseInfo is required.
111class TypeInfo(BaseInfo):
112    """Represents the state of a registry type"""
113    def __init__(self, elem):
114        BaseInfo.__init__(self, elem)
115        self.additionalValidity = []
116        self.removedValidity = []
117    def resetState(self):
118        BaseInfo.resetState(self)
119        self.additionalValidity = []
120        self.removedValidity = []
121
122# GroupInfo - registry information about a group of related enums
123# in an <enums> block, generally corresponding to a C "enum" type.
124class GroupInfo(BaseInfo):
125    """Represents the state of a registry <enums> group"""
126    def __init__(self, elem):
127        BaseInfo.__init__(self, elem)
128
129# EnumInfo - registry information about an enum
130#   type - numeric type of the value of the <enum> tag
131#     ( '' for GLint, 'u' for GLuint, 'ull' for GLuint64 )
132class EnumInfo(BaseInfo):
133    """Represents the state of a registry enum"""
134    def __init__(self, elem):
135        BaseInfo.__init__(self, elem)
136        self.type = elem.get('type')
137        if (self.type == None):
138            self.type = ''
139
140# CmdInfo - registry information about a command
141class CmdInfo(BaseInfo):
142    """Represents the state of a registry command"""
143    def __init__(self, elem):
144        BaseInfo.__init__(self, elem)
145        self.additionalValidity = []
146        self.removedValidity = []
147    def resetState(self):
148        BaseInfo.resetState(self)
149        self.additionalValidity = []
150        self.removedValidity = []
151
152# FeatureInfo - registry information about an API <feature>
153# or <extension>
154#   name - feature name string (e.g. 'VK_KHR_surface')
155#   version - feature version number (e.g. 1.2). <extension>
156#     features are unversioned and assigned version number 0.
157#     ** This is confusingly taken from the 'number' attribute of <feature>.
158#        Needs fixing.
159#   number - extension number, used for ordering and for
160#     assigning enumerant offsets. <feature> features do
161#     not have extension numbers and are assigned number 0.
162#   category - category, e.g. VERSION or khr/vendor tag
163#   emit - has this feature been defined already?
164class FeatureInfo(BaseInfo):
165    """Represents the state of an API feature (version/extension)"""
166    def __init__(self, elem):
167        BaseInfo.__init__(self, elem)
168        self.name = elem.get('name')
169        # Determine element category (vendor). Only works
170        # for <extension> elements.
171        if (elem.tag == 'feature'):
172            self.category = 'VERSION'
173            self.version = elem.get('name')
174            self.versionNumber = elem.get('number')
175            self.number = "0"
176            self.supported = None
177        else:
178            self.category = self.name.split('_', 2)[1]
179            self.version = "0"
180            self.versionNumber = "0"
181            self.number = elem.get('number')
182            self.supported = elem.get('supported')
183        self.emit = False
184
185from generator import write, GeneratorOptions, OutputGenerator
186
187# Registry - object representing an API registry, loaded from an XML file
188# Members
189#   tree - ElementTree containing the root <registry>
190#   typedict - dictionary of TypeInfo objects keyed by type name
191#   groupdict - dictionary of GroupInfo objects keyed by group name
192#   enumdict - dictionary of EnumInfo objects keyed by enum name
193#   cmddict - dictionary of CmdInfo objects keyed by command name
194#   apidict - dictionary of <api> Elements keyed by API name
195#   extensions - list of <extension> Elements
196#   extdict - dictionary of <extension> Elements keyed by extension name
197#   gen - OutputGenerator object used to write headers / messages
198#   genOpts - GeneratorOptions object used to control which
199#     fetures to write and how to format them
200#   emitFeatures - True to actually emit features for a version / extension,
201#     or False to just treat them as emitted
202#   breakPat - regexp pattern to break on when generatng names
203# Public methods
204#   loadElementTree(etree) - load registry from specified ElementTree
205#   loadFile(filename) - load registry from XML file
206#   setGenerator(gen) - OutputGenerator to use
207#   breakOnName() - specify a feature name regexp to break on when
208#     generating features.
209#   parseTree() - parse the registry once loaded & create dictionaries
210#   dumpReg(maxlen, filehandle) - diagnostic to dump the dictionaries
211#     to specified file handle (default stdout). Truncates type /
212#     enum / command elements to maxlen characters (default 80)
213#   generator(g) - specify the output generator object
214#   apiGen(apiname, genOpts) - generate API headers for the API type
215#     and profile specified in genOpts, but only for the versions and
216#     extensions specified there.
217#   apiReset() - call between calls to apiGen() to reset internal state
218# Private methods
219#   addElementInfo(elem,info,infoName,dictionary) - add feature info to dict
220#   lookupElementInfo(fname,dictionary) - lookup feature info in dict
221class Registry:
222    """Represents an API registry loaded from XML"""
223    def __init__(self):
224        self.tree         = None
225        self.typedict     = {}
226        self.groupdict    = {}
227        self.enumdict     = {}
228        self.cmddict      = {}
229        self.apidict      = {}
230        self.extensions   = []
231        self.requiredextensions = [] # Hack - can remove it after validity generator goes away
232        self.validextensionstructs = defaultdict(list)
233        self.extdict      = {}
234        # A default output generator, so commands prior to apiGen can report
235        # errors via the generator object.
236        self.gen          = OutputGenerator()
237        self.genOpts      = None
238        self.emitFeatures = False
239        self.breakPat     = None
240        # self.breakPat     = re.compile('VkFenceImportFlagBits.*')
241    def loadElementTree(self, tree):
242        """Load ElementTree into a Registry object and parse it"""
243        self.tree = tree
244        self.parseTree()
245    def loadFile(self, file):
246        """Load an API registry XML file into a Registry object and parse it"""
247        self.tree = etree.parse(file)
248        self.parseTree()
249    def setGenerator(self, gen):
250        """Specify output generator object. None restores the default generator"""
251        self.gen = gen
252        self.gen.setRegistry(self)
253
254    # addElementInfo - add information about an element to the
255    # corresponding dictionary
256    #   elem - <type>/<enums>/<enum>/<command>/<feature>/<extension> Element
257    #   info - corresponding {Type|Group|Enum|Cmd|Feature}Info object
258    #   infoName - 'type' / 'group' / 'enum' / 'command' / 'feature' / 'extension'
259    #   dictionary - self.{type|group|enum|cmd|api|ext}dict
260    # If the Element has an 'api' attribute, the dictionary key is the
261    # tuple (name,api). If not, the key is the name. 'name' is an
262    # attribute of the Element
263    def addElementInfo(self, elem, info, infoName, dictionary):
264        # self.gen.logMsg('diag', 'Adding ElementInfo.required =',
265        #     info.required, 'name =', elem.get('name'))
266
267        if ('api' in elem.attrib):
268            key = (elem.get('name'),elem.get('api'))
269        else:
270            key = elem.get('name')
271        if key in dictionary:
272            if not dictionary[key].compareElem(info):
273                self.gen.logMsg('warn', 'Attempt to redefine', key,
274                                'with different value (this may be benign)')
275            #else:
276            #    self.gen.logMsg('warn', 'Benign redefinition of', key,
277            #                    'with identical value')
278        else:
279            dictionary[key] = info
280    #
281    # lookupElementInfo - find a {Type|Enum|Cmd}Info object by name.
282    # If an object qualified by API name exists, use that.
283    #   fname - name of type / enum / command
284    #   dictionary - self.{type|enum|cmd}dict
285    def lookupElementInfo(self, fname, dictionary):
286        key = (fname, self.genOpts.apiname)
287        if (key in dictionary):
288            # self.gen.logMsg('diag', 'Found API-specific element for feature', fname)
289            return dictionary[key]
290        elif (fname in dictionary):
291            # self.gen.logMsg('diag', 'Found generic element for feature', fname)
292            return dictionary[fname]
293        else:
294            return None
295    def breakOnName(self, regexp):
296        self.breakPat = re.compile(regexp)
297    def parseTree(self):
298        """Parse the registry Element, once created"""
299        # This must be the Element for the root <registry>
300        self.reg = self.tree.getroot()
301        #
302        # Create dictionary of registry types from toplevel <types> tags
303        # and add 'name' attribute to each <type> tag (where missing)
304        # based on its <name> element.
305        #
306        # There's usually one <types> block; more are OK
307        # Required <type> attributes: 'name' or nested <name> tag contents
308        self.typedict = {}
309        for type in self.reg.findall('types/type'):
310            # If the <type> doesn't already have a 'name' attribute, set
311            # it from contents of its <name> tag.
312            if (type.get('name') == None):
313                type.attrib['name'] = type.find('name').text
314            self.addElementInfo(type, TypeInfo(type), 'type', self.typedict)
315        #
316        # Create dictionary of registry enum groups from <enums> tags.
317        #
318        # Required <enums> attributes: 'name'. If no name is given, one is
319        # generated, but that group can't be identified and turned into an
320        # enum type definition - it's just a container for <enum> tags.
321        self.groupdict = {}
322        for group in self.reg.findall('enums'):
323            self.addElementInfo(group, GroupInfo(group), 'group', self.groupdict)
324        #
325        # Create dictionary of registry enums from <enum> tags
326        #
327        # <enums> tags usually define different namespaces for the values
328        #   defined in those tags, but the actual names all share the
329        #   same dictionary.
330        # Required <enum> attributes: 'name', 'value'
331        # For containing <enums> which have type="enum" or type="bitmask",
332        # tag all contained <enum>s are required. This is a stopgap until
333        # a better scheme for tagging core and extension enums is created.
334        self.enumdict = {}
335        for enums in self.reg.findall('enums'):
336            required = (enums.get('type') != None)
337            for enum in enums.findall('enum'):
338                enumInfo = EnumInfo(enum)
339                enumInfo.required = required
340                self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
341                # self.gen.logMsg('diag', 'parseTree: marked req =',
342                #                 required, 'for', enum.get('name'))
343        #
344        # Create dictionary of registry commands from <command> tags
345        # and add 'name' attribute to each <command> tag (where missing)
346        # based on its <proto><name> element.
347        #
348        # There's usually only one <commands> block; more are OK.
349        # Required <command> attributes: 'name' or <proto><name> tag contents
350        self.cmddict = {}
351        # List of commands which alias others. Contains
352        #   [ aliasName, element ]
353        # for each alias
354        cmdAlias = []
355        for cmd in self.reg.findall('commands/command'):
356            # If the <command> doesn't already have a 'name' attribute, set
357            # it from contents of its <proto><name> tag.
358            name = cmd.get('name')
359            if name == None:
360                name = cmd.attrib['name'] = cmd.find('proto/name').text
361            ci = CmdInfo(cmd)
362            self.addElementInfo(cmd, ci, 'command', self.cmddict)
363            alias = cmd.get('alias')
364            if alias:
365                cmdAlias.append([name, alias, cmd])
366        # Now loop over aliases, injecting a copy of the aliased command's
367        # Element with the aliased prototype name replaced with the command
368        # name - if it exists.
369        for (name, alias, cmd) in cmdAlias:
370            if alias in self.cmddict:
371                #@ pdb.set_trace()
372                aliasInfo = self.cmddict[alias]
373                cmdElem = copy.deepcopy(aliasInfo.elem)
374                cmdElem.find('proto/name').text = name
375                cmdElem.attrib['name'] = name
376                cmdElem.attrib['alias'] = alias
377                ci = CmdInfo(cmdElem)
378                # Replace the dictionary entry for the CmdInfo element
379                self.cmddict[name] = ci
380
381                #@  newString = etree.tostring(base, encoding="unicode").replace(aliasValue, aliasName)
382                #@elem.append(etree.fromstring(replacement))
383            else:
384                self.gen.logMsg('warn', 'No matching <command> found for command',
385                    cmd.get('name'), 'alias', alias)
386
387        #
388        # Create dictionaries of API and extension interfaces
389        #   from toplevel <api> and <extension> tags.
390        #
391        self.apidict = {}
392        for feature in self.reg.findall('feature'):
393            featureInfo = FeatureInfo(feature)
394            self.addElementInfo(feature, featureInfo, 'feature', self.apidict)
395
396            # Add additional enums defined only in <feature> tags
397            # to the corresponding core type.
398            # When seen here, the <enum> element, processed to contain the
399            # numeric enum value, is added to the corresponding <enums>
400            # element, as well as adding to the enum dictionary. It is
401            # *removed* from the <require> element it is introduced in.
402            # Not doing this will cause spurious genEnum()
403            # calls to be made in output generation, and it's easier
404            # to handle here than in genEnum().
405            #
406            # In lxml.etree, an Element can have only one parent, so the
407            # append() operation also removes the element. But in Python's
408            # ElementTree package, an Element can have multiple parents. So
409            # it must be explicitly removed from the <require> tag, leading
410            # to the nested loop traversal of <require>/<enum> elements
411            # below.
412            #
413            # This code also adds a 'version' attribute containing the
414            # api version.
415            #
416            # For <enum> tags which are actually just constants, if there's
417            # no 'extends' tag but there is a 'value' or 'bitpos' tag, just
418            # add an EnumInfo record to the dictionary. That works because
419            # output generation of constants is purely dependency-based, and
420            # doesn't need to iterate through the XML tags.
421            #
422            for elem in feature.findall('require'):
423              for enum in elem.findall('enum'):
424                addEnumInfo = False
425                groupName = enum.get('extends')
426                if (groupName != None):
427                    # self.gen.logMsg('diag', 'Found extension enum',
428                    #     enum.get('name'))
429                    # Add version number attribute to the <enum> element
430                    enum.attrib['version'] = featureInfo.version
431                    # Look up the GroupInfo with matching groupName
432                    if (groupName in self.groupdict.keys()):
433                        # self.gen.logMsg('diag', 'Matching group',
434                        #     groupName, 'found, adding element...')
435                        gi = self.groupdict[groupName]
436                        gi.elem.append(enum)
437                        # Remove element from parent <require> tag
438                        # This should be a no-op in lxml.etree
439                        elem.remove(enum)
440                    else:
441                        self.gen.logMsg('warn', 'NO matching group',
442                            groupName, 'for enum', enum.get('name'), 'found.')
443                    addEnumInfo = True
444                elif (enum.get('value') or enum.get('bitpos') or enum.get('alias')):
445                    # self.gen.logMsg('diag', 'Adding extension constant "enum"',
446                    #     enum.get('name'))
447                    addEnumInfo = True
448                if (addEnumInfo):
449                    enumInfo = EnumInfo(enum)
450                    self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
451
452        self.extensions = self.reg.findall('extensions/extension')
453        self.extdict = {}
454        for feature in self.extensions:
455            featureInfo = FeatureInfo(feature)
456            self.addElementInfo(feature, featureInfo, 'extension', self.extdict)
457
458            # Add additional enums defined only in <extension> tags
459            # to the corresponding core type.
460            # Algorithm matches that of enums in a "feature" tag as above.
461            #
462            # This code also adds a 'extnumber' attribute containing the
463            # extension number, used for enumerant value calculation.
464            #
465            for elem in feature.findall('require'):
466              for enum in elem.findall('enum'):
467                addEnumInfo = False
468                groupName = enum.get('extends')
469                if (groupName != None):
470                    # self.gen.logMsg('diag', 'Found extension enum',
471                    #     enum.get('name'))
472
473                    # Add <extension> block's extension number attribute to
474                    # the <enum> element unless specified explicitly, such
475                    # as when redefining an enum in another extension.
476                    extnumber = enum.get('extnumber')
477                    if not extnumber:
478                        enum.attrib['extnumber'] = featureInfo.number
479
480                    enum.attrib['extname'] = featureInfo.name
481                    enum.attrib['supported'] = featureInfo.supported
482                    # Look up the GroupInfo with matching groupName
483                    if (groupName in self.groupdict.keys()):
484                        # self.gen.logMsg('diag', 'Matching group',
485                        #     groupName, 'found, adding element...')
486                        gi = self.groupdict[groupName]
487                        gi.elem.append(enum)
488                        # Remove element from parent <require> tag
489                        # This should be a no-op in lxml.etree
490                        elem.remove(enum)
491                    else:
492                        self.gen.logMsg('warn', 'NO matching group',
493                            groupName, 'for enum', enum.get('name'), 'found.')
494                    addEnumInfo = True
495                elif (enum.get('value') or enum.get('bitpos') or enum.get('alias')):
496                    # self.gen.logMsg('diag', 'Adding extension constant "enum"',
497                    #     enum.get('name'))
498                    addEnumInfo = True
499                if (addEnumInfo):
500                    enumInfo = EnumInfo(enum)
501                    self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
502
503        # Construct a "validextensionstructs" list for parent structures
504        # based on "structextends" tags in child structures
505        disabled_types = []
506        for disabled_ext in self.reg.findall('extensions/extension[@supported="disabled"]'):
507            for type in disabled_ext.findall("*/type"):
508                disabled_types.append(type.get('name'))
509        for type in self.reg.findall('types/type'):
510            if type.get('name') not in disabled_types:
511                parentStructs = type.get('structextends')
512                if (parentStructs != None):
513                    for parent in parentStructs.split(','):
514                        # self.gen.logMsg('diag', type.get('name'), 'extends', parent)
515                        self.validextensionstructs[parent].append(type.get('name'))
516        # Sort the lists so they don't depend on the XML order
517        for parent in self.validextensionstructs:
518            self.validextensionstructs[parent].sort()
519
520    def dumpReg(self, maxlen = 120, filehandle = sys.stdout):
521        """Dump all the dictionaries constructed from the Registry object"""
522        write('***************************************', file=filehandle)
523        write('    ** Dumping Registry contents **',     file=filehandle)
524        write('***************************************', file=filehandle)
525        write('// Types', file=filehandle)
526        for name in self.typedict:
527            tobj = self.typedict[name]
528            write('    Type', name, '->', etree.tostring(tobj.elem)[0:maxlen], file=filehandle)
529        write('// Groups', file=filehandle)
530        for name in self.groupdict:
531            gobj = self.groupdict[name]
532            write('    Group', name, '->', etree.tostring(gobj.elem)[0:maxlen], file=filehandle)
533        write('// Enums', file=filehandle)
534        for name in self.enumdict:
535            eobj = self.enumdict[name]
536            write('    Enum', name, '->', etree.tostring(eobj.elem)[0:maxlen], file=filehandle)
537        write('// Commands', file=filehandle)
538        for name in self.cmddict:
539            cobj = self.cmddict[name]
540            write('    Command', name, '->', etree.tostring(cobj.elem)[0:maxlen], file=filehandle)
541        write('// APIs', file=filehandle)
542        for key in self.apidict:
543            write('    API Version ', key, '->',
544                etree.tostring(self.apidict[key].elem)[0:maxlen], file=filehandle)
545        write('// Extensions', file=filehandle)
546        for key in self.extdict:
547            write('    Extension', key, '->',
548                etree.tostring(self.extdict[key].elem)[0:maxlen], file=filehandle)
549        # write('***************************************', file=filehandle)
550        # write('    ** Dumping XML ElementTree **', file=filehandle)
551        # write('***************************************', file=filehandle)
552        # write(etree.tostring(self.tree.getroot(),pretty_print=True), file=filehandle)
553    #
554    # typename - name of type
555    # required - boolean (to tag features as required or not)
556    def markTypeRequired(self, typename, required):
557        """Require (along with its dependencies) or remove (but not its dependencies) a type"""
558        self.gen.logMsg('diag', 'tagging type:', typename, '-> required =', required)
559        # Get TypeInfo object for <type> tag corresponding to typename
560        type = self.lookupElementInfo(typename, self.typedict)
561        if (type != None):
562            if (required):
563                # Tag type dependencies in 'alias' and 'required' attributes as
564                # required. This DOES NOT un-tag dependencies in a <remove>
565                # tag. See comments in markRequired() below for the reason.
566                for attrib in [ 'requires', 'alias' ]:
567                    depname = type.elem.get(attrib)
568                    if depname:
569                        self.gen.logMsg('diag', 'Generating dependent type',
570                            depname, 'for', attrib, 'type', typename)
571                        # Don't recurse on self-referential structures.
572                        if (typename != depname):
573                            self.markTypeRequired(depname, required)
574                        else:
575                            self.gen.logMsg('diag', 'type', typename, 'is self-referential')
576                # Tag types used in defining this type (e.g. in nested
577                # <type> tags)
578                # Look for <type> in entire <command> tree,
579                # not just immediate children
580                for subtype in type.elem.findall('.//type'):
581                    self.gen.logMsg('diag', 'markRequired: type requires dependent <type>', subtype.text)
582                    if (typename != subtype.text):
583                        self.markTypeRequired(subtype.text, required)
584                    else:
585                        self.gen.logMsg('diag', 'type', typename, 'is self-referential')
586                # Tag enums used in defining this type, for example in
587                #   <member><name>member</name>[<enum>MEMBER_SIZE</enum>]</member>
588                for subenum in type.elem.findall('.//enum'):
589                    self.gen.logMsg('diag', 'markRequired: type requires dependent <enum>', subenum.text)
590                    self.markEnumRequired(subenum.text, required)
591            type.required = required
592        else:
593            self.gen.logMsg('warn', 'type:', typename , 'IS NOT DEFINED')
594    #
595    # enumname - name of enum
596    # required - boolean (to tag features as required or not)
597    def markEnumRequired(self, enumname, required):
598        self.gen.logMsg('diag', 'tagging enum:', enumname, '-> required =', required)
599        enum = self.lookupElementInfo(enumname, self.enumdict)
600        if (enum != None):
601            enum.required = required
602            # Tag enum dependencies in 'alias' attribute as required
603            depname = enum.elem.get('alias')
604            if depname:
605                self.gen.logMsg('diag', 'Generating dependent enum',
606                    depname, 'for alias', enumname, 'required =', enum.required)
607                self.markEnumRequired(depname, required)
608        else:
609            self.gen.logMsg('warn', 'enum:', enumname , 'IS NOT DEFINED')
610    #
611    # cmdname - name of command
612    # required - boolean (to tag features as required or not)
613    def markCmdRequired(self, cmdname, required):
614        self.gen.logMsg('diag', 'tagging command:', cmdname, '-> required =', required)
615        cmd = self.lookupElementInfo(cmdname, self.cmddict)
616        if (cmd != None):
617            cmd.required = required
618            # Tag command dependencies in 'alias' attribute as required
619            depname = cmd.elem.get('alias')
620            if depname:
621                self.gen.logMsg('diag', 'Generating dependent command',
622                    depname, 'for alias', cmdname)
623                self.markCmdRequired(depname, required)
624            # Tag all parameter types of this command as required.
625            # This DOES NOT remove types of commands in a <remove>
626            # tag, because many other commands may use the same type.
627            # We could be more clever and reference count types,
628            # instead of using a boolean.
629            if (required):
630                # Look for <type> in entire <command> tree,
631                # not just immediate children
632                for type in cmd.elem.findall('.//type'):
633                    self.gen.logMsg('diag', 'markRequired: command implicitly requires dependent type', type.text)
634                    self.markTypeRequired(type.text, required)
635        else:
636            self.gen.logMsg('warn', 'command:', name, 'IS NOT DEFINED')
637    #
638    # features - Element for <require> or <remove> tag
639    # required - boolean (to tag features as required or not)
640    def markRequired(self, features, required):
641        """Require or remove features specified in the Element"""
642        self.gen.logMsg('diag', 'markRequired (features = <too long to print>, required =', required, ')')
643        # Loop over types, enums, and commands in the tag
644        # @@ It would be possible to respect 'api' and 'profile' attributes
645        #  in individual features, but that's not done yet.
646        for typeElem in features.findall('type'):
647            self.markTypeRequired(typeElem.get('name'), required)
648        for enumElem in features.findall('enum'):
649            self.markEnumRequired(enumElem.get('name'), required)
650        for cmdElem in features.findall('command'):
651            self.markCmdRequired(cmdElem.get('name'), required)
652    #
653    # interface - Element for <version> or <extension>, containing
654    #   <require> and <remove> tags
655    # api - string specifying API name being generated
656    # profile - string specifying API profile being generated
657    def requireAndRemoveFeatures(self, interface, api, profile):
658        """Process <recquire> and <remove> tags for a <version> or <extension>"""
659        # <require> marks things that are required by this version/profile
660        for feature in interface.findall('require'):
661            if (matchAPIProfile(api, profile, feature)):
662                self.markRequired(feature,True)
663        # <remove> marks things that are removed by this version/profile
664        for feature in interface.findall('remove'):
665            if (matchAPIProfile(api, profile, feature)):
666                self.markRequired(feature,False)
667
668    def assignAdditionalValidity(self, interface, api, profile):
669        #
670        # Loop over all usage inside all <require> tags.
671        for feature in interface.findall('require'):
672            if (matchAPIProfile(api, profile, feature)):
673                for v in feature.findall('usage'):
674                    if v.get('command'):
675                        self.cmddict[v.get('command')].additionalValidity.append(copy.deepcopy(v))
676                    if v.get('struct'):
677                        self.typedict[v.get('struct')].additionalValidity.append(copy.deepcopy(v))
678
679        #
680        # Loop over all usage inside all <remove> tags.
681        for feature in interface.findall('remove'):
682            if (matchAPIProfile(api, profile, feature)):
683                for v in feature.findall('usage'):
684                    if v.get('command'):
685                        self.cmddict[v.get('command')].removedValidity.append(copy.deepcopy(v))
686                    if v.get('struct'):
687                        self.typedict[v.get('struct')].removedValidity.append(copy.deepcopy(v))
688
689    #
690    # generateFeature - generate a single type / enum group / enum / command,
691    # and all its dependencies as needed.
692    #   fname - name of feature (<type>/<enum>/<command>)
693    #   ftype - type of feature, 'type' | 'enum' | 'command'
694    #   dictionary - of *Info objects - self.{type|enum|cmd}dict
695    def generateFeature(self, fname, ftype, dictionary):
696        #@ # Break to debugger on matching name pattern
697        #@ if self.breakPat and re.match(self.breakPat, fname):
698        #@    pdb.set_trace()
699
700        self.gen.logMsg('diag', 'generateFeature: generating', ftype, fname)
701        f = self.lookupElementInfo(fname, dictionary)
702        if (f == None):
703            # No such feature. This is an error, but reported earlier
704            self.gen.logMsg('diag', 'No entry found for feature', fname,
705                            'returning!')
706            return
707        #
708        # If feature isn't required, or has already been declared, return
709        if (not f.required):
710            self.gen.logMsg('diag', 'Skipping', ftype, fname, '(not required)')
711            return
712        if (f.declared):
713            self.gen.logMsg('diag', 'Skipping', ftype, fname, '(already declared)')
714            return
715        # Always mark feature declared, as though actually emitted
716        f.declared = True
717
718        # Determine if this is an alias, and of what, if so
719        alias = f.elem.get('alias')
720        if alias:
721            self.gen.logMsg('diag', fname, 'is an alias of', alias)
722
723        #
724        # Pull in dependent declaration(s) of the feature.
725        # For types, there may be one type in the 'required' attribute of
726        #   the element, one in the 'alias' attribute, and many in
727        #   imbedded <type> and <enum> tags within the element.
728        # For commands, there may be many in <type> tags within the element.
729        # For enums, no dependencies are allowed (though perhaps if you
730        #   have a uint64 enum, it should require that type).
731        genProc = None
732        if (ftype == 'type'):
733            genProc = self.gen.genType
734
735            # Generate type dependencies in 'alias' and 'required' attributes
736            if alias:
737                self.generateFeature(alias, 'type', self.typedict)
738            requires = f.elem.get('requires')
739            if requires:
740                self.generateFeature(requires, 'type', self.typedict)
741
742            # Generate types used in defining this type (e.g. in nested
743            # <type> tags)
744            # Look for <type> in entire <command> tree,
745            # not just immediate children
746            for subtype in f.elem.findall('.//type'):
747                self.gen.logMsg('diag', 'Generating required dependent <type>',
748                    subtype.text)
749                self.generateFeature(subtype.text, 'type', self.typedict)
750
751            # Generate enums used in defining this type, for example in
752            #   <member><name>member</name>[<enum>MEMBER_SIZE</enum>]</member>
753            for subtype in f.elem.findall('.//enum'):
754                self.gen.logMsg('diag', 'Generating required dependent <enum>',
755                    subtype.text)
756                self.generateFeature(subtype.text, 'enum', self.enumdict)
757
758            # If the type is an enum group, look up the corresponding
759            # group in the group dictionary and generate that instead.
760            if (f.elem.get('category') == 'enum'):
761                self.gen.logMsg('diag', 'Type', fname, 'is an enum group, so generate that instead')
762                group = self.lookupElementInfo(fname, self.groupdict)
763                if alias != None:
764                    # An alias of another group name.
765                    # Pass to genGroup with 'alias' parameter = aliased name
766                    self.gen.logMsg('diag', 'Generating alias', fname,
767                                    'for enumerated type', alias)
768                    # Now, pass the *aliased* GroupInfo to the genGroup, but
769                    # with an additional parameter which is the alias name.
770                    genProc = self.gen.genGroup
771                    f = self.lookupElementInfo(alias, self.groupdict)
772                elif group == None:
773                    self.gen.logMsg('warn', 'Skipping enum type', fname,
774                        ': No matching enumerant group')
775                    return
776                else:
777                    genProc = self.gen.genGroup
778                    f = group
779
780                    #@ The enum group is not ready for generation. At this
781                    #@   point, it contains all <enum> tags injected by
782                    #@   <extension> tags without any verification of whether
783                    #@   they're required or not. It may also contain
784                    #@   duplicates injected by multiple consistent
785                    #@   definitions of an <enum>.
786
787                    #@ Pass over each enum, marking its enumdict[] entry as
788                    #@ required or not. Mark aliases of enums as required,
789                    #@ too.
790
791                    enums = group.elem.findall('enum')
792
793                    self.gen.logMsg('diag', 'generateFeature: checking enums for group', fname)
794
795                    # Check for required enums, including aliases
796                    # LATER - Check for, report, and remove duplicates?
797                    enumAliases = []
798                    for elem in enums:
799                        name = elem.get('name')
800
801                        required = False
802
803                        extname = elem.get('extname')
804                        version = elem.get('version')
805                        if extname is not None:
806                            # 'supported' attribute was injected when the <enum> element was
807                            # moved into the <enums> group in Registry.parseTree()
808                            if self.genOpts.defaultExtensions == elem.get('supported'):
809                                required = True
810                            elif re.match(self.genOpts.addExtensions, extname) is not None:
811                                required = True
812                        elif version is not None:
813                            required = re.match(self.genOpts.emitversions, version) is not None
814                        else:
815                            required = True
816
817                        self.gen.logMsg('diag', '* required =', required, 'for', name)
818                        if required:
819                            # Mark this element as required (in the element, not the EnumInfo)
820                            elem.attrib['required'] = 'true'
821                            # If it's an alias, track that for later use
822                            enumAlias = elem.get('alias')
823                            if enumAlias:
824                                enumAliases.append(enumAlias)
825                    for elem in enums:
826                        name = elem.get('name')
827                        if name in enumAliases:
828                            elem.attrib['required'] = 'true'
829                            self.gen.logMsg('diag', '* also need to require alias', name)
830        elif (ftype == 'command'):
831            # Generate command dependencies in 'alias' attribute
832            if alias:
833                self.generateFeature(alias, 'command', self.cmddict)
834
835            genProc = self.gen.genCmd
836            for type in f.elem.findall('.//type'):
837                depname = type.text
838                self.gen.logMsg('diag', 'Generating required parameter type',
839                                depname)
840                self.generateFeature(depname, 'type', self.typedict)
841        elif (ftype == 'enum'):
842            # Generate enum dependencies in 'alias' attribute
843            if alias:
844                self.generateFeature(alias, 'enum', self.enumdict)
845            genProc = self.gen.genEnum
846
847        # Actually generate the type only if emitting declarations
848        if self.emitFeatures:
849            self.gen.logMsg('diag', 'Emitting', ftype, fname, 'declaration')
850            genProc(f, fname, alias)
851        else:
852            self.gen.logMsg('diag', 'Skipping', ftype, fname,
853                            '(should not be emitted)')
854    #
855    # generateRequiredInterface - generate all interfaces required
856    # by an API version or extension
857    #   interface - Element for <version> or <extension>
858    def generateRequiredInterface(self, interface):
859        """Generate required C interface for specified API version/extension"""
860
861        #
862        # Loop over all features inside all <require> tags.
863        for features in interface.findall('require'):
864            for t in features.findall('type'):
865                self.generateFeature(t.get('name'), 'type', self.typedict)
866            for e in features.findall('enum'):
867                self.generateFeature(e.get('name'), 'enum', self.enumdict)
868            for c in features.findall('command'):
869                self.generateFeature(c.get('name'), 'command', self.cmddict)
870
871    #
872    # apiGen(genOpts) - generate interface for specified versions
873    #   genOpts - GeneratorOptions object with parameters used
874    #   by the Generator object.
875    def apiGen(self, genOpts):
876        """Generate interfaces for the specified API type and range of versions"""
877        #
878        self.gen.logMsg('diag', '*******************************************')
879        self.gen.logMsg('diag', '  Registry.apiGen file:', genOpts.filename,
880                        'api:', genOpts.apiname,
881                        'profile:', genOpts.profile)
882        self.gen.logMsg('diag', '*******************************************')
883        #
884        self.genOpts = genOpts
885        # Reset required/declared flags for all features
886        self.apiReset()
887        #
888        # Compile regexps used to select versions & extensions
889        regVersions = re.compile(self.genOpts.versions)
890        regEmitVersions = re.compile(self.genOpts.emitversions)
891        regAddExtensions = re.compile(self.genOpts.addExtensions)
892        regRemoveExtensions = re.compile(self.genOpts.removeExtensions)
893        regEmitExtensions = re.compile(self.genOpts.emitExtensions)
894        #
895        # Get all matching API feature names & add to list of FeatureInfo
896        # Note we used to select on feature version attributes, not names.
897        features = []
898        apiMatch = False
899        for key in self.apidict:
900            fi = self.apidict[key]
901            api = fi.elem.get('api')
902            if (api == self.genOpts.apiname):
903                apiMatch = True
904                if (regVersions.match(fi.name)):
905                    # Matches API & version #s being generated. Mark for
906                    # emission and add to the features[] list .
907                    # @@ Could use 'declared' instead of 'emit'?
908                    fi.emit = (regEmitVersions.match(fi.name) != None)
909                    features.append(fi)
910                    if (not fi.emit):
911                        self.gen.logMsg('diag', 'NOT tagging feature api =', api,
912                            'name =', fi.name, 'version =', fi.version,
913                            'for emission (does not match emitversions pattern)')
914                    else:
915                        self.gen.logMsg('diag', 'Including feature api =', api,
916                            'name =', fi.name, 'version =', fi.version,
917                            'for emission (matches emitversions pattern)')
918                else:
919                    self.gen.logMsg('diag', 'NOT including feature api =', api,
920                        'name =', fi.name, 'version =', fi.version,
921                        '(does not match requested versions)')
922            else:
923                self.gen.logMsg('diag', 'NOT including feature api =', api,
924                    'name =', fi.name,
925                    '(does not match requested API)')
926        if (not apiMatch):
927            self.gen.logMsg('warn', 'No matching API versions found!')
928        #
929        # Get all matching extensions, in order by their extension number,
930        # and add to the list of features.
931        # Start with extensions tagged with 'api' pattern matching the API
932        # being generated. Add extensions matching the pattern specified in
933        # regExtensions, then remove extensions matching the pattern
934        # specified in regRemoveExtensions
935        for (extName,ei) in sorted(self.extdict.items(),key = lambda x : x[1].number):
936            extName = ei.name
937            include = False
938            #
939            # Include extension if defaultExtensions is not None and if the
940            # 'supported' attribute matches defaultExtensions. The regexp in
941            # 'supported' must exactly match defaultExtensions, so bracket
942            # it with ^(pat)$.
943            pat = '^(' + ei.elem.get('supported') + ')$'
944            if (self.genOpts.defaultExtensions and
945                     re.match(pat, self.genOpts.defaultExtensions)):
946                self.gen.logMsg('diag', 'Including extension',
947                    extName, "(defaultExtensions matches the 'supported' attribute)")
948                include = True
949            #
950            # Include additional extensions if the extension name matches
951            # the regexp specified in the generator options. This allows
952            # forcing extensions into an interface even if they're not
953            # tagged appropriately in the registry.
954            if (regAddExtensions.match(extName) != None):
955                self.gen.logMsg('diag', 'Including extension',
956                    extName, '(matches explicitly requested extensions to add)')
957                include = True
958            # Remove extensions if the name matches the regexp specified
959            # in generator options. This allows forcing removal of
960            # extensions from an interface even if they're tagged that
961            # way in the registry.
962            if (regRemoveExtensions.match(extName) != None):
963                self.gen.logMsg('diag', 'Removing extension',
964                    extName, '(matches explicitly requested extensions to remove)')
965                include = False
966            #
967            # If the extension is to be included, add it to the
968            # extension features list.
969            if (include):
970                ei.emit = (regEmitExtensions.match(extName) != None)
971                features.append(ei)
972                if (not ei.emit):
973                    self.gen.logMsg('diag', 'NOT tagging extension',
974                        extName,
975                        'for emission (does not match emitextensions pattern)')
976                # Hack - can be removed when validity generator goes away
977                # (Jon) I'm not sure what this does, or if it should respect
978                # the ei.emit flag above.
979                self.requiredextensions.append(extName)
980            else:
981                self.gen.logMsg('diag', 'NOT including extension',
982                    extName, '(does not match api attribute or explicitly requested extensions)')
983        #
984        # Sort the extension features list, if a sort procedure is defined
985        if (self.genOpts.sortProcedure):
986            self.genOpts.sortProcedure(features)
987        #
988        # Pass 1: loop over requested API versions and extensions tagging
989        #   types/commands/features as required (in an <require> block) or no
990        #   longer required (in an <remove> block). It is possible to remove
991        #   a feature in one version and restore it later by requiring it in
992        #   a later version.
993        # If a profile other than 'None' is being generated, it must
994        #   match the profile attribute (if any) of the <require> and
995        #   <remove> tags.
996        self.gen.logMsg('diag', '*******PASS 1: TAG FEATURES **********')
997        for f in features:
998            self.gen.logMsg('diag', 'PASS 1: Tagging required and removed features for',
999                f.name)
1000            self.requireAndRemoveFeatures(f.elem, self.genOpts.apiname, self.genOpts.profile)
1001            self.assignAdditionalValidity(f.elem, self.genOpts.apiname, self.genOpts.profile)
1002        #
1003        # Pass 2: loop over specified API versions and extensions printing
1004        #   declarations for required things which haven't already been
1005        #   generated.
1006        self.gen.logMsg('diag', '*******PASS 2: GENERATE INTERFACES FOR FEATURES **********')
1007        self.gen.beginFile(self.genOpts)
1008        for f in features:
1009            self.gen.logMsg('diag', 'PASS 2: Generating interface for',
1010                f.name)
1011            emit = self.emitFeatures = f.emit
1012            if (not emit):
1013                self.gen.logMsg('diag', 'PASS 2: NOT declaring feature',
1014                    f.elem.get('name'), 'because it is not tagged for emission')
1015            # Generate the interface (or just tag its elements as having been
1016            # emitted, if they haven't been).
1017            self.gen.beginFeature(f.elem, emit)
1018            self.generateRequiredInterface(f.elem)
1019            self.gen.endFeature()
1020        self.gen.endFile()
1021    #
1022    # apiReset - use between apiGen() calls to reset internal state
1023    #
1024    def apiReset(self):
1025        """Reset type/enum/command dictionaries before generating another API"""
1026        for type in self.typedict:
1027            self.typedict[type].resetState()
1028        for enum in self.enumdict:
1029            self.enumdict[enum].resetState()
1030        for cmd in self.cmddict:
1031            self.cmddict[cmd].resetState()
1032        for cmd in self.apidict:
1033            self.apidict[cmd].resetState()
1034    #
1035    # validateGroups - check that group= attributes match actual groups
1036    #
1037    def validateGroups(self):
1038        """Validate group= attributes on <param> and <proto> tags"""
1039        # Keep track of group names not in <group> tags
1040        badGroup = {}
1041        self.gen.logMsg('diag', 'VALIDATING GROUP ATTRIBUTES ***')
1042        for cmd in self.reg.findall('commands/command'):
1043            proto = cmd.find('proto')
1044            funcname = cmd.find('proto/name').text
1045            if ('group' in proto.attrib.keys()):
1046                group = proto.get('group')
1047                # self.gen.logMsg('diag', 'Command ', funcname, ' has return group ', group)
1048                if (group not in self.groupdict.keys()):
1049                    # self.gen.logMsg('diag', 'Command ', funcname, ' has UNKNOWN return group ', group)
1050                    if (group not in badGroup.keys()):
1051                        badGroup[group] = 1
1052                    else:
1053                        badGroup[group] = badGroup[group] +  1
1054            for param in cmd.findall('param'):
1055                pname = param.find('name')
1056                if (pname != None):
1057                    pname = pname.text
1058                else:
1059                    pname = type.get('name')
1060                if ('group' in param.attrib.keys()):
1061                    group = param.get('group')
1062                    if (group not in self.groupdict.keys()):
1063                        # self.gen.logMsg('diag', 'Command ', funcname, ' param ', pname, ' has UNKNOWN group ', group)
1064                        if (group not in badGroup.keys()):
1065                            badGroup[group] = 1
1066                        else:
1067                            badGroup[group] = badGroup[group] +  1
1068        if (len(badGroup.keys()) > 0):
1069            self.gen.logMsg('diag', 'SUMMARY OF UNRECOGNIZED GROUPS ***')
1070            for key in sorted(badGroup.keys()):
1071                self.gen.logMsg('diag', '    ', key, ' occurred ', badGroup[key], ' times')
1072