blob: 5c92d271b556a89240411f8e1c8bfe6e825a22a6 [file] [log] [blame]
Mike Stroyandee76ef2016-01-07 15:35:37 -07001#!/usr/bin/python3 -i
2#
Mark Lobodzinski36c33862017-02-13 10:15:53 -07003# Copyright (c) 2013-2017 The Khronos Group Inc.
Mike Stroyandee76ef2016-01-07 15:35:37 -07004#
Jon Ashburn3ebf1252016-04-19 11:30:31 -06005# 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
Mike Stroyandee76ef2016-01-07 15:35:37 -07008#
Jon Ashburn3ebf1252016-04-19 11:30:31 -06009# http://www.apache.org/licenses/LICENSE-2.0
Mike Stroyandee76ef2016-01-07 15:35:37 -070010#
Jon Ashburn3ebf1252016-04-19 11:30:31 -060011# 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.
Mike Stroyandee76ef2016-01-07 15:35:37 -070016
Mark Lobodzinskic97e2642016-10-13 08:58:38 -060017import io,os,re,string,sys,copy
Mike Stroyan3c5a6e22016-04-05 16:40:30 -060018import xml.etree.ElementTree as etree
Mike Stroyandee76ef2016-01-07 15:35:37 -070019
20# matchAPIProfile - returns whether an API and profile
21# being generated matches an element's profile
22# api - string naming the API to match
23# profile - string naming the profile to match
24# elem - Element which (may) have 'api' and 'profile'
25# attributes to match to.
26# If a tag is not present in the Element, the corresponding API
27# or profile always matches.
28# Otherwise, the tag must exactly match the API or profile.
29# Thus, if 'profile' = core:
30# <remove> with no attribute will match
31# <remove profile='core'> will match
32# <remove profile='compatibility'> will not match
33# Possible match conditions:
34# Requested Element
35# Profile Profile
36# --------- --------
37# None None Always matches
38# 'string' None Always matches
39# None 'string' Does not match. Can't generate multiple APIs
40# or profiles, so if an API/profile constraint
41# is present, it must be asked for explicitly.
42# 'string' 'string' Strings must match
43#
44# ** In the future, we will allow regexes for the attributes,
45# not just strings, so that api="^(gl|gles2)" will match. Even
46# this isn't really quite enough, we might prefer something
47# like "gl(core)|gles1(common-lite)".
48def matchAPIProfile(api, profile, elem):
49 """Match a requested API & profile name to a api & profile attributes of an Element"""
50 match = True
51 # Match 'api', if present
52 if ('api' in elem.attrib):
53 if (api == None):
54 raise UserWarning("No API requested, but 'api' attribute is present with value '" +
55 elem.get('api') + "'")
56 elif (api != elem.get('api')):
57 # Requested API doesn't match attribute
58 return False
59 if ('profile' in elem.attrib):
60 if (profile == None):
61 raise UserWarning("No profile requested, but 'profile' attribute is present with value '" +
62 elem.get('profile') + "'")
63 elif (profile != elem.get('profile')):
64 # Requested profile doesn't match attribute
65 return False
66 return True
67
68# BaseInfo - base class for information about a registry feature
69# (type/group/enum/command/API/extension).
70# required - should this feature be defined during header generation
71# (has it been removed by a profile or version)?
72# declared - has this feature been defined already?
Mike Stroyan3c5a6e22016-04-05 16:40:30 -060073# elem - etree Element for this feature
Mike Stroyandee76ef2016-01-07 15:35:37 -070074# resetState() - reset required/declared to initial values. Used
75# prior to generating a new API interface.
76class BaseInfo:
77 """Represents the state of a registry feature, used during API generation"""
78 def __init__(self, elem):
79 self.required = False
80 self.declared = False
81 self.elem = elem
82 def resetState(self):
83 self.required = False
84 self.declared = False
85
86# TypeInfo - registry information about a type. No additional state
87# beyond BaseInfo is required.
88class TypeInfo(BaseInfo):
89 """Represents the state of a registry type"""
90 def __init__(self, elem):
91 BaseInfo.__init__(self, elem)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -060092 self.additionalValidity = []
93 self.removedValidity = []
94 def resetState(self):
95 BaseInfo.resetState(self)
96 self.additionalValidity = []
97 self.removedValidity = []
Mike Stroyandee76ef2016-01-07 15:35:37 -070098
99# GroupInfo - registry information about a group of related enums
100# in an <enums> block, generally corresponding to a C "enum" type.
101class GroupInfo(BaseInfo):
102 """Represents the state of a registry <enums> group"""
103 def __init__(self, elem):
104 BaseInfo.__init__(self, elem)
105
106# EnumInfo - registry information about an enum
107# type - numeric type of the value of the <enum> tag
108# ( '' for GLint, 'u' for GLuint, 'ull' for GLuint64 )
109class EnumInfo(BaseInfo):
110 """Represents the state of a registry enum"""
111 def __init__(self, elem):
112 BaseInfo.__init__(self, elem)
113 self.type = elem.get('type')
114 if (self.type == None):
115 self.type = ''
116
117# CmdInfo - registry information about a command
118class CmdInfo(BaseInfo):
119 """Represents the state of a registry command"""
120 def __init__(self, elem):
121 BaseInfo.__init__(self, elem)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600122 self.additionalValidity = []
123 self.removedValidity = []
124 def resetState(self):
125 BaseInfo.resetState(self)
126 self.additionalValidity = []
127 self.removedValidity = []
Mike Stroyandee76ef2016-01-07 15:35:37 -0700128
129# FeatureInfo - registry information about an API <feature>
130# or <extension>
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600131# name - feature name string (e.g. 'VK_KHR_surface')
Mike Stroyandee76ef2016-01-07 15:35:37 -0700132# version - feature version number (e.g. 1.2). <extension>
133# features are unversioned and assigned version number 0.
134# ** This is confusingly taken from the 'number' attribute of <feature>.
135# Needs fixing.
136# number - extension number, used for ordering and for
137# assigning enumerant offsets. <feature> features do
138# not have extension numbers and are assigned number 0.
139# category - category, e.g. VERSION or khr/vendor tag
140# emit - has this feature been defined already?
141class FeatureInfo(BaseInfo):
142 """Represents the state of an API feature (version/extension)"""
143 def __init__(self, elem):
144 BaseInfo.__init__(self, elem)
145 self.name = elem.get('name')
146 # Determine element category (vendor). Only works
147 # for <extension> elements.
148 if (elem.tag == 'feature'):
149 self.category = 'VERSION'
150 self.version = elem.get('number')
151 self.number = "0"
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600152 self.supported = None
Mike Stroyandee76ef2016-01-07 15:35:37 -0700153 else:
154 self.category = self.name.split('_', 2)[1]
155 self.version = "0"
156 self.number = elem.get('number')
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600157 self.supported = elem.get('supported')
Mike Stroyandee76ef2016-01-07 15:35:37 -0700158 self.emit = False
159
160from generator import write, GeneratorOptions, OutputGenerator
161
162# Registry - object representing an API registry, loaded from an XML file
163# Members
164# tree - ElementTree containing the root <registry>
165# typedict - dictionary of TypeInfo objects keyed by type name
166# groupdict - dictionary of GroupInfo objects keyed by group name
167# enumdict - dictionary of EnumInfo objects keyed by enum name
168# cmddict - dictionary of CmdInfo objects keyed by command name
169# apidict - dictionary of <api> Elements keyed by API name
170# extensions - list of <extension> Elements
171# extdict - dictionary of <extension> Elements keyed by extension name
172# gen - OutputGenerator object used to write headers / messages
173# genOpts - GeneratorOptions object used to control which
174# fetures to write and how to format them
175# emitFeatures - True to actually emit features for a version / extension,
176# or False to just treat them as emitted
177# Public methods
178# loadElementTree(etree) - load registry from specified ElementTree
179# loadFile(filename) - load registry from XML file
180# setGenerator(gen) - OutputGenerator to use
181# parseTree() - parse the registry once loaded & create dictionaries
182# dumpReg(maxlen, filehandle) - diagnostic to dump the dictionaries
183# to specified file handle (default stdout). Truncates type /
184# enum / command elements to maxlen characters (default 80)
185# generator(g) - specify the output generator object
186# apiGen(apiname, genOpts) - generate API headers for the API type
187# and profile specified in genOpts, but only for the versions and
188# extensions specified there.
189# apiReset() - call between calls to apiGen() to reset internal state
190# Private methods
191# addElementInfo(elem,info,infoName,dictionary) - add feature info to dict
192# lookupElementInfo(fname,dictionary) - lookup feature info in dict
193class Registry:
194 """Represents an API registry loaded from XML"""
195 def __init__(self):
196 self.tree = None
197 self.typedict = {}
198 self.groupdict = {}
199 self.enumdict = {}
200 self.cmddict = {}
201 self.apidict = {}
202 self.extensions = []
Mark Lobodzinskie5b2b712017-06-28 14:58:27 -0600203 self.requiredextensions = [] # Hack - can remove it after validity generator goes away
Mike Stroyandee76ef2016-01-07 15:35:37 -0700204 self.extdict = {}
205 # A default output generator, so commands prior to apiGen can report
206 # errors via the generator object.
207 self.gen = OutputGenerator()
208 self.genOpts = None
209 self.emitFeatures = False
210 def loadElementTree(self, tree):
211 """Load ElementTree into a Registry object and parse it"""
212 self.tree = tree
213 self.parseTree()
214 def loadFile(self, file):
215 """Load an API registry XML file into a Registry object and parse it"""
216 self.tree = etree.parse(file)
217 self.parseTree()
218 def setGenerator(self, gen):
219 """Specify output generator object. None restores the default generator"""
220 self.gen = gen
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600221 self.gen.setRegistry(self)
Mike Stroyandee76ef2016-01-07 15:35:37 -0700222
223 # addElementInfo - add information about an element to the
224 # corresponding dictionary
225 # elem - <type>/<enums>/<enum>/<command>/<feature>/<extension> Element
226 # info - corresponding {Type|Group|Enum|Cmd|Feature}Info object
227 # infoName - 'type' / 'group' / 'enum' / 'command' / 'feature' / 'extension'
228 # dictionary - self.{type|group|enum|cmd|api|ext}dict
229 # If the Element has an 'api' attribute, the dictionary key is the
230 # tuple (name,api). If not, the key is the name. 'name' is an
231 # attribute of the Element
232 def addElementInfo(self, elem, info, infoName, dictionary):
233 if ('api' in elem.attrib):
234 key = (elem.get('name'),elem.get('api'))
235 else:
236 key = elem.get('name')
237 if key in dictionary:
238 self.gen.logMsg('warn', '*** Attempt to redefine',
239 infoName, 'with key:', key)
240 else:
241 dictionary[key] = info
242 #
243 # lookupElementInfo - find a {Type|Enum|Cmd}Info object by name.
244 # If an object qualified by API name exists, use that.
245 # fname - name of type / enum / command
246 # dictionary - self.{type|enum|cmd}dict
247 def lookupElementInfo(self, fname, dictionary):
248 key = (fname, self.genOpts.apiname)
249 if (key in dictionary):
250 # self.gen.logMsg('diag', 'Found API-specific element for feature', fname)
251 return dictionary[key]
252 elif (fname in dictionary):
253 # self.gen.logMsg('diag', 'Found generic element for feature', fname)
254 return dictionary[fname]
255 else:
256 return None
257 def parseTree(self):
258 """Parse the registry Element, once created"""
259 # This must be the Element for the root <registry>
260 self.reg = self.tree.getroot()
261 #
262 # Create dictionary of registry types from toplevel <types> tags
263 # and add 'name' attribute to each <type> tag (where missing)
264 # based on its <name> element.
265 #
266 # There's usually one <types> block; more are OK
267 # Required <type> attributes: 'name' or nested <name> tag contents
268 self.typedict = {}
269 for type in self.reg.findall('types/type'):
270 # If the <type> doesn't already have a 'name' attribute, set
271 # it from contents of its <name> tag.
272 if (type.get('name') == None):
273 type.attrib['name'] = type.find('name').text
274 self.addElementInfo(type, TypeInfo(type), 'type', self.typedict)
275 #
276 # Create dictionary of registry enum groups from <enums> tags.
277 #
278 # Required <enums> attributes: 'name'. If no name is given, one is
279 # generated, but that group can't be identified and turned into an
280 # enum type definition - it's just a container for <enum> tags.
281 self.groupdict = {}
282 for group in self.reg.findall('enums'):
283 self.addElementInfo(group, GroupInfo(group), 'group', self.groupdict)
284 #
285 # Create dictionary of registry enums from <enum> tags
286 #
287 # <enums> tags usually define different namespaces for the values
288 # defined in those tags, but the actual names all share the
289 # same dictionary.
290 # Required <enum> attributes: 'name', 'value'
291 # For containing <enums> which have type="enum" or type="bitmask",
292 # tag all contained <enum>s are required. This is a stopgap until
293 # a better scheme for tagging core and extension enums is created.
294 self.enumdict = {}
295 for enums in self.reg.findall('enums'):
296 required = (enums.get('type') != None)
297 for enum in enums.findall('enum'):
298 enumInfo = EnumInfo(enum)
299 enumInfo.required = required
300 self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
301 #
302 # Create dictionary of registry commands from <command> tags
303 # and add 'name' attribute to each <command> tag (where missing)
304 # based on its <proto><name> element.
305 #
306 # There's usually only one <commands> block; more are OK.
307 # Required <command> attributes: 'name' or <proto><name> tag contents
308 self.cmddict = {}
309 for cmd in self.reg.findall('commands/command'):
310 # If the <command> doesn't already have a 'name' attribute, set
311 # it from contents of its <proto><name> tag.
312 if (cmd.get('name') == None):
313 cmd.attrib['name'] = cmd.find('proto/name').text
314 ci = CmdInfo(cmd)
315 self.addElementInfo(cmd, ci, 'command', self.cmddict)
316 #
317 # Create dictionaries of API and extension interfaces
318 # from toplevel <api> and <extension> tags.
319 #
320 self.apidict = {}
321 for feature in self.reg.findall('feature'):
322 featureInfo = FeatureInfo(feature)
323 self.addElementInfo(feature, featureInfo, 'feature', self.apidict)
324 self.extensions = self.reg.findall('extensions/extension')
325 self.extdict = {}
326 for feature in self.extensions:
327 featureInfo = FeatureInfo(feature)
328 self.addElementInfo(feature, featureInfo, 'extension', self.extdict)
329
330 # Add additional enums defined only in <extension> tags
331 # to the corresponding core type.
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600332 # When seen here, the <enum> element, processed to contain the
333 # numeric enum value, is added to the corresponding <enums>
334 # element, as well as adding to the enum dictionary. It is
335 # *removed* from the <require> element it is introduced in.
336 # Not doing this will cause spurious genEnum()
337 # calls to be made in output generation, and it's easier
338 # to handle here than in genEnum().
339 #
340 # In lxml.etree, an Element can have only one parent, so the
341 # append() operation also removes the element. But in Python's
342 # ElementTree package, an Element can have multiple parents. So
343 # it must be explicitly removed from the <require> tag, leading
344 # to the nested loop traversal of <require>/<enum> elements
345 # below.
346 #
347 # This code also adds a 'extnumber' attribute containing the
348 # extension number, used for enumerant value calculation.
Mike Stroyandee76ef2016-01-07 15:35:37 -0700349 #
350 # For <enum> tags which are actually just constants, if there's
351 # no 'extends' tag but there is a 'value' or 'bitpos' tag, just
352 # add an EnumInfo record to the dictionary. That works because
353 # output generation of constants is purely dependency-based, and
354 # doesn't need to iterate through the XML tags.
355 #
356 # Something like this will need to be done for 'feature's up
357 # above, if we use the same mechanism for adding to the core
358 # API in 1.1.
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600359 #
360 for elem in feature.findall('require'):
361 for enum in elem.findall('enum'):
Mike Stroyandee76ef2016-01-07 15:35:37 -0700362 addEnumInfo = False
363 groupName = enum.get('extends')
364 if (groupName != None):
365 # self.gen.logMsg('diag', '*** Found extension enum',
366 # enum.get('name'))
367 # Add extension number attribute to the <enum> element
368 enum.attrib['extnumber'] = featureInfo.number
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600369 enum.attrib['extname'] = featureInfo.name
370 enum.attrib['supported'] = featureInfo.supported
Mike Stroyandee76ef2016-01-07 15:35:37 -0700371 # Look up the GroupInfo with matching groupName
372 if (groupName in self.groupdict.keys()):
373 # self.gen.logMsg('diag', '*** Matching group',
374 # groupName, 'found, adding element...')
375 gi = self.groupdict[groupName]
376 gi.elem.append(enum)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600377 # Remove element from parent <require> tag
378 # This should be a no-op in lxml.etree
379 elem.remove(enum)
Mike Stroyandee76ef2016-01-07 15:35:37 -0700380 else:
381 self.gen.logMsg('warn', '*** NO matching group',
382 groupName, 'for enum', enum.get('name'), 'found.')
383 addEnumInfo = True
384 elif (enum.get('value') or enum.get('bitpos')):
385 # self.gen.logMsg('diag', '*** Adding extension constant "enum"',
386 # enum.get('name'))
387 addEnumInfo = True
388 if (addEnumInfo):
389 enumInfo = EnumInfo(enum)
390 self.addElementInfo(enum, enumInfo, 'enum', self.enumdict)
391 def dumpReg(self, maxlen = 40, filehandle = sys.stdout):
392 """Dump all the dictionaries constructed from the Registry object"""
393 write('***************************************', file=filehandle)
394 write(' ** Dumping Registry contents **', file=filehandle)
395 write('***************************************', file=filehandle)
396 write('// Types', file=filehandle)
397 for name in self.typedict:
398 tobj = self.typedict[name]
399 write(' Type', name, '->', etree.tostring(tobj.elem)[0:maxlen], file=filehandle)
400 write('// Groups', file=filehandle)
401 for name in self.groupdict:
402 gobj = self.groupdict[name]
403 write(' Group', name, '->', etree.tostring(gobj.elem)[0:maxlen], file=filehandle)
404 write('// Enums', file=filehandle)
405 for name in self.enumdict:
406 eobj = self.enumdict[name]
407 write(' Enum', name, '->', etree.tostring(eobj.elem)[0:maxlen], file=filehandle)
408 write('// Commands', file=filehandle)
409 for name in self.cmddict:
410 cobj = self.cmddict[name]
411 write(' Command', name, '->', etree.tostring(cobj.elem)[0:maxlen], file=filehandle)
412 write('// APIs', file=filehandle)
413 for key in self.apidict:
414 write(' API Version ', key, '->',
415 etree.tostring(self.apidict[key].elem)[0:maxlen], file=filehandle)
416 write('// Extensions', file=filehandle)
417 for key in self.extdict:
418 write(' Extension', key, '->',
419 etree.tostring(self.extdict[key].elem)[0:maxlen], file=filehandle)
420 # write('***************************************', file=filehandle)
421 # write(' ** Dumping XML ElementTree **', file=filehandle)
422 # write('***************************************', file=filehandle)
423 # write(etree.tostring(self.tree.getroot(),pretty_print=True), file=filehandle)
424 #
425 # typename - name of type
426 # required - boolean (to tag features as required or not)
427 def markTypeRequired(self, typename, required):
428 """Require (along with its dependencies) or remove (but not its dependencies) a type"""
429 self.gen.logMsg('diag', '*** tagging type:', typename, '-> required =', required)
430 # Get TypeInfo object for <type> tag corresponding to typename
431 type = self.lookupElementInfo(typename, self.typedict)
432 if (type != None):
433 if (required):
434 # Tag type dependencies in 'required' attributes as
435 # required. This DOES NOT un-tag dependencies in a <remove>
436 # tag. See comments in markRequired() below for the reason.
437 if ('requires' in type.elem.attrib):
438 depType = type.elem.get('requires')
439 self.gen.logMsg('diag', '*** Generating dependent type',
440 depType, 'for type', typename)
441 self.markTypeRequired(depType, required)
442 # Tag types used in defining this type (e.g. in nested
443 # <type> tags)
444 # Look for <type> in entire <command> tree,
445 # not just immediate children
446 for subtype in type.elem.findall('.//type'):
447 self.gen.logMsg('diag', '*** markRequired: type requires dependent <type>', subtype.text)
448 self.markTypeRequired(subtype.text, required)
449 # Tag enums used in defining this type, for example in
450 # <member><name>member</name>[<enum>MEMBER_SIZE</enum>]</member>
451 for subenum in type.elem.findall('.//enum'):
452 self.gen.logMsg('diag', '*** markRequired: type requires dependent <enum>', subenum.text)
453 self.markEnumRequired(subenum.text, required)
454 type.required = required
455 else:
456 self.gen.logMsg('warn', '*** type:', typename , 'IS NOT DEFINED')
457 #
458 # enumname - name of enum
459 # required - boolean (to tag features as required or not)
460 def markEnumRequired(self, enumname, required):
461 self.gen.logMsg('diag', '*** tagging enum:', enumname, '-> required =', required)
462 enum = self.lookupElementInfo(enumname, self.enumdict)
463 if (enum != None):
464 enum.required = required
465 else:
466 self.gen.logMsg('warn', '*** enum:', enumname , 'IS NOT DEFINED')
467 #
468 # features - Element for <require> or <remove> tag
469 # required - boolean (to tag features as required or not)
470 def markRequired(self, features, required):
471 """Require or remove features specified in the Element"""
472 self.gen.logMsg('diag', '*** markRequired (features = <too long to print>, required =', required, ')')
473 # Loop over types, enums, and commands in the tag
474 # @@ It would be possible to respect 'api' and 'profile' attributes
475 # in individual features, but that's not done yet.
476 for typeElem in features.findall('type'):
477 self.markTypeRequired(typeElem.get('name'), required)
478 for enumElem in features.findall('enum'):
479 self.markEnumRequired(enumElem.get('name'), required)
480 for cmdElem in features.findall('command'):
481 name = cmdElem.get('name')
482 self.gen.logMsg('diag', '*** tagging command:', name, '-> required =', required)
483 cmd = self.lookupElementInfo(name, self.cmddict)
484 if (cmd != None):
485 cmd.required = required
486 # Tag all parameter types of this command as required.
487 # This DOES NOT remove types of commands in a <remove>
488 # tag, because many other commands may use the same type.
489 # We could be more clever and reference count types,
490 # instead of using a boolean.
491 if (required):
492 # Look for <type> in entire <command> tree,
493 # not just immediate children
494 for type in cmd.elem.findall('.//type'):
495 self.gen.logMsg('diag', '*** markRequired: command implicitly requires dependent type', type.text)
496 self.markTypeRequired(type.text, required)
497 else:
498 self.gen.logMsg('warn', '*** command:', name, 'IS NOT DEFINED')
499 #
500 # interface - Element for <version> or <extension>, containing
501 # <require> and <remove> tags
502 # api - string specifying API name being generated
503 # profile - string specifying API profile being generated
504 def requireAndRemoveFeatures(self, interface, api, profile):
505 """Process <recquire> and <remove> tags for a <version> or <extension>"""
506 # <require> marks things that are required by this version/profile
507 for feature in interface.findall('require'):
508 if (matchAPIProfile(api, profile, feature)):
509 self.markRequired(feature,True)
510 # <remove> marks things that are removed by this version/profile
511 for feature in interface.findall('remove'):
512 if (matchAPIProfile(api, profile, feature)):
513 self.markRequired(feature,False)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600514
515 def assignAdditionalValidity(self, interface, api, profile):
516 #
517 # Loop over all usage inside all <require> tags.
518 for feature in interface.findall('require'):
519 if (matchAPIProfile(api, profile, feature)):
520 for v in feature.findall('usage'):
521 if v.get('command'):
522 self.cmddict[v.get('command')].additionalValidity.append(copy.deepcopy(v))
523 if v.get('struct'):
524 self.typedict[v.get('struct')].additionalValidity.append(copy.deepcopy(v))
525
526 #
527 # Loop over all usage inside all <remove> tags.
528 for feature in interface.findall('remove'):
529 if (matchAPIProfile(api, profile, feature)):
530 for v in feature.findall('usage'):
531 if v.get('command'):
532 self.cmddict[v.get('command')].removedValidity.append(copy.deepcopy(v))
533 if v.get('struct'):
534 self.typedict[v.get('struct')].removedValidity.append(copy.deepcopy(v))
535
Mike Stroyandee76ef2016-01-07 15:35:37 -0700536 #
537 # generateFeature - generate a single type / enum group / enum / command,
538 # and all its dependencies as needed.
539 # fname - name of feature (<type>/<enum>/<command>)
540 # ftype - type of feature, 'type' | 'enum' | 'command'
541 # dictionary - of *Info objects - self.{type|enum|cmd}dict
542 def generateFeature(self, fname, ftype, dictionary):
543 f = self.lookupElementInfo(fname, dictionary)
544 if (f == None):
545 # No such feature. This is an error, but reported earlier
546 self.gen.logMsg('diag', '*** No entry found for feature', fname,
547 'returning!')
548 return
549 #
550 # If feature isn't required, or has already been declared, return
551 if (not f.required):
552 self.gen.logMsg('diag', '*** Skipping', ftype, fname, '(not required)')
553 return
554 if (f.declared):
555 self.gen.logMsg('diag', '*** Skipping', ftype, fname, '(already declared)')
556 return
557 # Always mark feature declared, as though actually emitted
558 f.declared = True
559 #
560 # Pull in dependent declaration(s) of the feature.
561 # For types, there may be one type in the 'required' attribute of
562 # the element, as well as many in imbedded <type> and <enum> tags
563 # within the element.
564 # For commands, there may be many in <type> tags within the element.
565 # For enums, no dependencies are allowed (though perhaps if you
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600566 # have a uint64 enum, it should require that type).
Mike Stroyandee76ef2016-01-07 15:35:37 -0700567 genProc = None
568 if (ftype == 'type'):
569 genProc = self.gen.genType
570 if ('requires' in f.elem.attrib):
571 depname = f.elem.get('requires')
572 self.gen.logMsg('diag', '*** Generating required dependent type',
573 depname)
574 self.generateFeature(depname, 'type', self.typedict)
575 for subtype in f.elem.findall('.//type'):
576 self.gen.logMsg('diag', '*** Generating required dependent <type>',
577 subtype.text)
578 self.generateFeature(subtype.text, 'type', self.typedict)
579 for subtype in f.elem.findall('.//enum'):
580 self.gen.logMsg('diag', '*** Generating required dependent <enum>',
581 subtype.text)
582 self.generateFeature(subtype.text, 'enum', self.enumdict)
583 # If the type is an enum group, look up the corresponding
584 # group in the group dictionary and generate that instead.
585 if (f.elem.get('category') == 'enum'):
586 self.gen.logMsg('diag', '*** Type', fname, 'is an enum group, so generate that instead')
587 group = self.lookupElementInfo(fname, self.groupdict)
588 if (group == None):
589 # Unless this is tested for, it's probably fatal to call below
590 genProc = None
591 self.logMsg('warn', '*** NO MATCHING ENUM GROUP FOUND!!!')
592 else:
593 genProc = self.gen.genGroup
594 f = group
595 elif (ftype == 'command'):
596 genProc = self.gen.genCmd
597 for type in f.elem.findall('.//type'):
598 depname = type.text
599 self.gen.logMsg('diag', '*** Generating required parameter type',
600 depname)
601 self.generateFeature(depname, 'type', self.typedict)
602 elif (ftype == 'enum'):
603 genProc = self.gen.genEnum
604 # Actually generate the type only if emitting declarations
605 if self.emitFeatures:
606 self.gen.logMsg('diag', '*** Emitting', ftype, 'decl for', fname)
607 genProc(f, fname)
608 else:
609 self.gen.logMsg('diag', '*** Skipping', ftype, fname,
610 '(not emitting this feature)')
611 #
612 # generateRequiredInterface - generate all interfaces required
613 # by an API version or extension
614 # interface - Element for <version> or <extension>
615 def generateRequiredInterface(self, interface):
616 """Generate required C interface for specified API version/extension"""
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600617
Mike Stroyandee76ef2016-01-07 15:35:37 -0700618 #
619 # Loop over all features inside all <require> tags.
Mike Stroyandee76ef2016-01-07 15:35:37 -0700620 for features in interface.findall('require'):
621 for t in features.findall('type'):
622 self.generateFeature(t.get('name'), 'type', self.typedict)
623 for e in features.findall('enum'):
624 self.generateFeature(e.get('name'), 'enum', self.enumdict)
625 for c in features.findall('command'):
626 self.generateFeature(c.get('name'), 'command', self.cmddict)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600627
Mike Stroyandee76ef2016-01-07 15:35:37 -0700628 #
629 # apiGen(genOpts) - generate interface for specified versions
630 # genOpts - GeneratorOptions object with parameters used
631 # by the Generator object.
632 def apiGen(self, genOpts):
633 """Generate interfaces for the specified API type and range of versions"""
634 #
635 self.gen.logMsg('diag', '*******************************************')
636 self.gen.logMsg('diag', ' Registry.apiGen file:', genOpts.filename,
637 'api:', genOpts.apiname,
638 'profile:', genOpts.profile)
639 self.gen.logMsg('diag', '*******************************************')
640 #
641 self.genOpts = genOpts
642 # Reset required/declared flags for all features
643 self.apiReset()
644 #
645 # Compile regexps used to select versions & extensions
646 regVersions = re.compile(self.genOpts.versions)
647 regEmitVersions = re.compile(self.genOpts.emitversions)
648 regAddExtensions = re.compile(self.genOpts.addExtensions)
649 regRemoveExtensions = re.compile(self.genOpts.removeExtensions)
650 #
651 # Get all matching API versions & add to list of FeatureInfo
652 features = []
653 apiMatch = False
654 for key in self.apidict:
655 fi = self.apidict[key]
656 api = fi.elem.get('api')
657 if (api == self.genOpts.apiname):
658 apiMatch = True
659 if (regVersions.match(fi.version)):
660 # Matches API & version #s being generated. Mark for
661 # emission and add to the features[] list .
662 # @@ Could use 'declared' instead of 'emit'?
663 fi.emit = (regEmitVersions.match(fi.version) != None)
664 features.append(fi)
665 if (not fi.emit):
666 self.gen.logMsg('diag', '*** NOT tagging feature api =', api,
667 'name =', fi.name, 'version =', fi.version,
668 'for emission (does not match emitversions pattern)')
669 else:
670 self.gen.logMsg('diag', '*** NOT including feature api =', api,
671 'name =', fi.name, 'version =', fi.version,
672 '(does not match requested versions)')
673 else:
674 self.gen.logMsg('diag', '*** NOT including feature api =', api,
675 'name =', fi.name,
676 '(does not match requested API)')
677 if (not apiMatch):
678 self.gen.logMsg('warn', '*** No matching API versions found!')
679 #
680 # Get all matching extensions, in order by their extension number,
681 # and add to the list of features.
682 # Start with extensions tagged with 'api' pattern matching the API
683 # being generated. Add extensions matching the pattern specified in
684 # regExtensions, then remove extensions matching the pattern
685 # specified in regRemoveExtensions
686 for (extName,ei) in sorted(self.extdict.items(),key = lambda x : x[1].number):
687 extName = ei.name
688 include = False
689 #
690 # Include extension if defaultExtensions is not None and if the
691 # 'supported' attribute matches defaultExtensions. The regexp in
692 # 'supported' must exactly match defaultExtensions, so bracket
693 # it with ^(pat)$.
694 pat = '^(' + ei.elem.get('supported') + ')$'
695 if (self.genOpts.defaultExtensions and
696 re.match(pat, self.genOpts.defaultExtensions)):
697 self.gen.logMsg('diag', '*** Including extension',
698 extName, "(defaultExtensions matches the 'supported' attribute)")
699 include = True
700 #
701 # Include additional extensions if the extension name matches
702 # the regexp specified in the generator options. This allows
703 # forcing extensions into an interface even if they're not
704 # tagged appropriately in the registry.
705 if (regAddExtensions.match(extName) != None):
706 self.gen.logMsg('diag', '*** Including extension',
707 extName, '(matches explicitly requested extensions to add)')
708 include = True
709 # Remove extensions if the name matches the regexp specified
710 # in generator options. This allows forcing removal of
711 # extensions from an interface even if they're tagged that
712 # way in the registry.
713 if (regRemoveExtensions.match(extName) != None):
714 self.gen.logMsg('diag', '*** Removing extension',
715 extName, '(matches explicitly requested extensions to remove)')
716 include = False
717 #
718 # If the extension is to be included, add it to the
719 # extension features list.
720 if (include):
721 ei.emit = True
722 features.append(ei)
Mark Lobodzinskie5b2b712017-06-28 14:58:27 -0600723
724 # Hack - can be removed when validity generator goes away
725 self.requiredextensions.append(extName)
Mike Stroyandee76ef2016-01-07 15:35:37 -0700726 else:
727 self.gen.logMsg('diag', '*** NOT including extension',
728 extName, '(does not match api attribute or explicitly requested extensions)')
729 #
730 # Sort the extension features list, if a sort procedure is defined
731 if (self.genOpts.sortProcedure):
732 self.genOpts.sortProcedure(features)
733 #
734 # Pass 1: loop over requested API versions and extensions tagging
735 # types/commands/features as required (in an <require> block) or no
736 # longer required (in an <remove> block). It is possible to remove
737 # a feature in one version and restore it later by requiring it in
738 # a later version.
739 # If a profile other than 'None' is being generated, it must
740 # match the profile attribute (if any) of the <require> and
741 # <remove> tags.
742 self.gen.logMsg('diag', '*** PASS 1: TAG FEATURES ********************************************')
743 for f in features:
744 self.gen.logMsg('diag', '*** PASS 1: Tagging required and removed features for',
745 f.name)
746 self.requireAndRemoveFeatures(f.elem, self.genOpts.apiname, self.genOpts.profile)
Mark Lobodzinskic97e2642016-10-13 08:58:38 -0600747 self.assignAdditionalValidity(f.elem, self.genOpts.apiname, self.genOpts.profile)
Mike Stroyandee76ef2016-01-07 15:35:37 -0700748 #
749 # Pass 2: loop over specified API versions and extensions printing
750 # declarations for required things which haven't already been
751 # generated.
752 self.gen.logMsg('diag', '*** PASS 2: GENERATE INTERFACES FOR FEATURES ************************')
753 self.gen.beginFile(self.genOpts)
754 for f in features:
755 self.gen.logMsg('diag', '*** PASS 2: Generating interface for',
756 f.name)
757 emit = self.emitFeatures = f.emit
758 if (not emit):
759 self.gen.logMsg('diag', '*** PASS 2: NOT declaring feature',
760 f.elem.get('name'), 'because it is not tagged for emission')
761 # Generate the interface (or just tag its elements as having been
762 # emitted, if they haven't been).
763 self.gen.beginFeature(f.elem, emit)
764 self.generateRequiredInterface(f.elem)
765 self.gen.endFeature()
766 self.gen.endFile()
767 #
768 # apiReset - use between apiGen() calls to reset internal state
769 #
770 def apiReset(self):
771 """Reset type/enum/command dictionaries before generating another API"""
772 for type in self.typedict:
773 self.typedict[type].resetState()
774 for enum in self.enumdict:
775 self.enumdict[enum].resetState()
776 for cmd in self.cmddict:
777 self.cmddict[cmd].resetState()
778 for cmd in self.apidict:
779 self.apidict[cmd].resetState()
780 #
781 # validateGroups - check that group= attributes match actual groups
782 #
783 def validateGroups(self):
784 """Validate group= attributes on <param> and <proto> tags"""
785 # Keep track of group names not in <group> tags
786 badGroup = {}
787 self.gen.logMsg('diag', '*** VALIDATING GROUP ATTRIBUTES ***')
788 for cmd in self.reg.findall('commands/command'):
789 proto = cmd.find('proto')
790 funcname = cmd.find('proto/name').text
791 if ('group' in proto.attrib.keys()):
792 group = proto.get('group')
793 # self.gen.logMsg('diag', '*** Command ', funcname, ' has return group ', group)
794 if (group not in self.groupdict.keys()):
795 # self.gen.logMsg('diag', '*** Command ', funcname, ' has UNKNOWN return group ', group)
796 if (group not in badGroup.keys()):
797 badGroup[group] = 1
798 else:
799 badGroup[group] = badGroup[group] + 1
800 for param in cmd.findall('param'):
801 pname = param.find('name')
802 if (pname != None):
803 pname = pname.text
804 else:
805 pname = type.get('name')
806 if ('group' in param.attrib.keys()):
807 group = param.get('group')
808 if (group not in self.groupdict.keys()):
809 # self.gen.logMsg('diag', '*** Command ', funcname, ' param ', pname, ' has UNKNOWN group ', group)
810 if (group not in badGroup.keys()):
811 badGroup[group] = 1
812 else:
813 badGroup[group] = badGroup[group] + 1
814 if (len(badGroup.keys()) > 0):
815 self.gen.logMsg('diag', '*** SUMMARY OF UNRECOGNIZED GROUPS ***')
816 for key in sorted(badGroup.keys()):
817 self.gen.logMsg('diag', ' ', key, ' occurred ', badGroup[key], ' times')