blob: b30869c7b7b5fa41ac12f4481d285d1adc6da56e [file] [log] [blame]
Tobin Ehlis5ade0692016-10-05 17:18:15 -06001#!/usr/bin/python3 -i
2
3import sys
4import xml.etree.ElementTree as etree
5import urllib2
Tobin Ehlis5ade0692016-10-05 17:18:15 -06006
7#############################
8# spec.py script
9#
10# Overview - this script is intended to generate validation error codes and message strings from the xhtml version of
11# the specification. In addition to generating the header file, it provides a number of corrollary services to aid in
12# generating/updating the header.
13#
14# Ideal flow - Not there currently, but the ideal flow for this script would be that you run the script, it pulls the
15# latest spec, compares it to the current set of generated error codes, and makes any updates as needed
16#
17# Current flow - the current flow acheives all of the ideal flow goals, but with more steps than are desired
18# 1. Get the spec - right now spec has to be manually generated or pulled from the web
19# 2. Generate header from spec - This is done in a single command line
20# 3. Generate database file from spec - Can be done along with step #2 above, the database file contains a list of
21# all error enums and message strings, along with some other info on if those errors are implemented/tested
22# 4. Update header using a given database file as the root and a new spec file as goal - This makes sure that existing
23# errors keep the same enum identifier while also making sure that new errors get a unique_id that continues on
24# from the end of the previous highest unique_id.
25#
26# TODO:
27# 1. Improve string matching to add more automation for figuring out which messages are changed vs. completely new
Tobin Ehlise7560e72016-10-19 15:59:38 -060028# Temp hack path:
29# 1. Read in spec w/ API info
30# 2. Read in database file
31# 3. Write out updated DB file w/ API/Notes columns
Tobin Ehlis5ade0692016-10-05 17:18:15 -060032#
33#############################
34
35
36spec_filename = "vkspec.html" # can override w/ '-spec <filename>' option
37out_filename = "vk_validation_error_messages.h" # can override w/ '-out <filename>' option
38db_filename = "vk_validation_error_database.txt" # can override w/ '-gendb <filename>' option
39gen_db = False # set to True when '-gendb <filename>' option provided
40spec_compare = False # set to True with '-compare <db_filename>' option
41# This is the root spec link that is used in error messages to point users to spec sections
Tobin Ehlisbd0a9c62016-10-14 18:06:16 -060042#old_spec_url = "https://www.khronos.org/registry/vulkan/specs/1.0/xhtml/vkspec.html"
43spec_url = "https://www.khronos.org/registry/vulkan/specs/1.0-extensions/xhtml/vkspec.html"
Tobin Ehlis5ade0692016-10-05 17:18:15 -060044# After the custom validation error message, this is the prefix for the standard message that includes the
45# spec valid usage language as well as the link to nearest section of spec to that language
46error_msg_prefix = "For more information refer to Vulkan Spec Section "
47ns = {'ns': 'http://www.w3.org/1999/xhtml'}
Mark Lobodzinski629d47b2016-10-18 13:34:58 -060048validation_error_enum_name = "VALIDATION_ERROR_"
Tobin Ehlis5ade0692016-10-05 17:18:15 -060049# Dict of new enum values that should be forced to remap to old handles, explicitly set by -remap option
50remap_dict = {}
51
52def printHelp():
53 print "Usage: python spec.py [-spec <specfile.html>] [-out <headerfile.h>] [-gendb <databasefile.txt>] [-compare <databasefile.txt>] [-update] [-remap <new_id-old_id,count>] [-help]"
54 print "\n Default script behavior is to parse the specfile and generate a header of unique error enums and corresponding error messages based on the specfile.\n"
55 print " Default specfile is from online at %s" % (spec_url)
56 print " Default headerfile is %s" % (out_filename)
57 print " Default databasefile is %s" % (db_filename)
58 print "\nIf '-gendb' option is specified then a database file is generated to default file or <databasefile.txt> if supplied. The database file stores"
59 print " the list of enums and their error messages."
60 print "\nIf '-compare' option is specified then the given database file will be read in as the baseline for generating the new specfile"
61 print "\nIf '-update' option is specified this triggers the master flow to automate updating header and database files using default db file as baseline"
62 print " and online spec file as the latest. The default header and database files will be updated in-place for review and commit to the git repo."
63 print "\nIf '-remap' option is specified it supplies forced remapping from new enum ids to old enum ids. This should only be specified along with -update"
64 print " option. Starting at newid and remapping to oldid, count ids will be remapped. Default count is '1' and use ':' to specify multiple remappings."
65
66class Specification:
67 def __init__(self):
68 self.tree = None
Tobin Ehlise7560e72016-10-19 15:59:38 -060069 self.val_error_dict = {} # string for enum is key that references 'error_msg' and 'api'
Tobin Ehlis5ade0692016-10-05 17:18:15 -060070 self.error_db_dict = {} # dict of previous error values read in from database file
71 self.delimiter = '~^~' # delimiter for db file
72 self.copyright = """/* THIS FILE IS GENERATED. DO NOT EDIT. */
73
74/*
75 * Vulkan
76 *
77 * Copyright (c) 2016 Google Inc.
Mark Lobodzinski629d47b2016-10-18 13:34:58 -060078 * Copyright (c) 2016 LunarG, Inc.
Tobin Ehlis5ade0692016-10-05 17:18:15 -060079 *
80 * Licensed under the Apache License, Version 2.0 (the "License");
81 * you may not use this file except in compliance with the License.
82 * You may obtain a copy of the License at
83 *
84 * http://www.apache.org/licenses/LICENSE-2.0
85 *
86 * Unless required by applicable law or agreed to in writing, software
87 * distributed under the License is distributed on an "AS IS" BASIS,
88 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
89 * See the License for the specific language governing permissions and
90 * limitations under the License.
91 *
92 * Author: Tobin Ehlis <tobine@google.com>
93 */"""
94 def _checkInternetSpec(self):
95 """Verify that we can access the spec online"""
96 try:
97 online = urllib2.urlopen(spec_url,timeout=1)
98 return True
99 except urllib2.URLError as err:
100 return False
101 return False
102 def loadFile(self, online=True, spec_file=spec_filename):
103 """Load an API registry XML file into a Registry object and parse it"""
104 # Check if spec URL is available
105 if (online and self._checkInternetSpec()):
106 print "Using spec from online at %s" % (spec_url)
107 self.tree = etree.parse(urllib2.urlopen(spec_url))
108 else:
109 print "Using local spec %s" % (spec_file)
110 self.tree = etree.parse(spec_file)
111 #self.tree.write("tree_output.xhtml")
112 #self.tree = etree.parse("tree_output.xhtml")
113 self.parseTree()
114 def updateDict(self, updated_dict):
115 """Assign internal dict to use updated_dict"""
116 self.val_error_dict = updated_dict
117 def parseTree(self):
118 """Parse the registry Element, once created"""
119 print "Parsing spec file..."
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600120 unique_enum_id = 0
121 self.root = self.tree.getroot()
122 #print "ROOT: %s" % self.root
123 prev_heading = '' # Last seen section heading or sub-heading
124 prev_link = '' # Last seen link id within the spec
Tobin Ehlise7560e72016-10-19 15:59:38 -0600125 api_function = '' # API call that a check appears under
Tobin Ehlis85008cd2016-10-19 15:32:35 -0600126 error_strings = set() # Flag any exact duplicate error strings and skip them
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600127 for tag in self.root.iter(): # iterate down tree
128 # Grab most recent section heading and link
129 if tag.tag in ['{http://www.w3.org/1999/xhtml}h2', '{http://www.w3.org/1999/xhtml}h3']:
130 if tag.get('class') != 'title':
131 continue
132 #print "Found heading %s" % (tag.tag)
133 prev_heading = "".join(tag.itertext())
134 # Insert a space between heading number & title
135 sh_list = prev_heading.rsplit('.', 1)
136 prev_heading = '. '.join(sh_list)
137 prev_link = tag[0].get('id')
138 #print "Set prev_heading %s to have link of %s" % (prev_heading.encode("ascii", "ignore"), prev_link.encode("ascii", "ignore"))
139 elif tag.tag == '{http://www.w3.org/1999/xhtml}a': # grab any intermediate links
140 if tag.get('id') != None:
141 prev_link = tag.get('id')
Tobin Ehlis16b159c2016-10-25 06:33:27 -0600142 #print "Updated prev link to %s" % (prev_link)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600143 elif tag.tag == '{http://www.w3.org/1999/xhtml}pre' and tag.get('class') == 'programlisting':
144 # Check and see if this is API function
145 code_text = "".join(tag.itertext()).replace('\n', '')
146 code_text_list = code_text.split()
147 if len(code_text_list) > 1 and code_text_list[1].startswith('vk'):
148 api_function = code_text_list[1].strip('(')
149 print "Found API function: %s" % (api_function)
Tobin Ehlis69ebddf2016-10-18 15:55:07 -0600150 elif tag.tag == '{http://www.w3.org/1999/xhtml}div' and tag.get('class') == 'sidebar':
151 # parse down sidebar to check for valid usage cases
152 valid_usage = False
153 for elem in tag.iter():
154 if elem.tag == '{http://www.w3.org/1999/xhtml}strong' and None != elem.text and 'Valid Usage' in elem.text:
155 valid_usage = True
156 elif valid_usage and elem.tag == '{http://www.w3.org/1999/xhtml}li': # grab actual valid usage requirements
157 error_msg_str = "%s '%s' which states '%s' (%s#%s)" % (error_msg_prefix, prev_heading, "".join(elem.itertext()).replace('\n', ''), spec_url, prev_link)
158 # Some txt has multiple spaces so split on whitespace and join w/ single space
159 error_msg_str = " ".join(error_msg_str.split())
Tobin Ehlis85008cd2016-10-19 15:32:35 -0600160 if error_msg_str in error_strings:
161 print "WARNING: SKIPPING adding repeat entry for string. Please review spec and file issue as appropriate. Repeat string is: %s" % (error_msg_str)
162 else:
163 error_strings.add(error_msg_str)
164 enum_str = "%s%05d" % (validation_error_enum_name, unique_enum_id)
165 # TODO : '\' chars in spec error messages are most likely bad spec txt that needs to be updated
Tobin Ehlise7560e72016-10-19 15:59:38 -0600166 self.val_error_dict[enum_str] = {}
167 self.val_error_dict[enum_str]['error_msg'] = error_msg_str.encode("ascii", "ignore").replace("\\", "/")
168 self.val_error_dict[enum_str]['api'] = api_function
Tobin Ehlis85008cd2016-10-19 15:32:35 -0600169 unique_enum_id = unique_enum_id + 1
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600170 #print "Validation Error Dict has a total of %d unique errors and contents are:\n%s" % (unique_enum_id, self.val_error_dict)
171 def genHeader(self, header_file):
172 """Generate a header file based on the contents of a parsed spec"""
173 print "Generating header %s..." % (header_file)
174 file_contents = []
175 file_contents.append(self.copyright)
176 file_contents.append('\n#pragma once')
Tobin Ehlisbf98b692016-10-06 12:58:06 -0600177 file_contents.append('#include <unordered_map>')
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600178 file_contents.append('\n// enum values for unique validation error codes')
179 file_contents.append('// Corresponding validation error message for each enum is given in the mapping table below')
180 file_contents.append('// When a given error occurs, these enum values should be passed to the as the messageCode')
181 file_contents.append('// parameter to the PFN_vkDebugReportCallbackEXT function')
182 enum_decl = ['enum UNIQUE_VALIDATION_ERROR_CODE {']
Tobin Ehlisbf98b692016-10-06 12:58:06 -0600183 error_string_map = ['static std::unordered_map<int, char const *const> validation_error_map{']
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600184 for enum in sorted(self.val_error_dict):
185 #print "Header enum is %s" % (enum)
186 enum_decl.append(' %s = %d,' % (enum, int(enum.split('_')[-1])))
Tobin Ehlise7560e72016-10-19 15:59:38 -0600187 error_string_map.append(' {%s, "%s"},' % (enum, self.val_error_dict[enum]['error_msg']))
Mark Lobodzinski629d47b2016-10-18 13:34:58 -0600188 enum_decl.append(' %sMAX_ENUM = %d,' % (validation_error_enum_name, int(enum.split('_')[-1]) + 1))
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600189 enum_decl.append('};')
Tobin Ehlise7560e72016-10-19 15:59:38 -0600190 error_string_map.append('};\n')
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600191 file_contents.extend(enum_decl)
192 file_contents.append('\n// Mapping from unique validation error enum to the corresponding error message')
193 file_contents.append('// The error message should be appended to the end of a custom error message that is passed')
194 file_contents.append('// as the pMessage parameter to the PFN_vkDebugReportCallbackEXT function')
195 file_contents.extend(error_string_map)
196 #print "File contents: %s" % (file_contents)
197 with open(header_file, "w") as outfile:
198 outfile.write("\n".join(file_contents))
199 def analyze(self):
200 """Print out some stats on the valid usage dict"""
201 # Create dict for # of occurences of identical strings
202 str_count_dict = {}
203 unique_id_count = 0
204 for enum in self.val_error_dict:
Tobin Ehlise7560e72016-10-19 15:59:38 -0600205 err_str = self.val_error_dict[enum]['error_msg']
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600206 if err_str in str_count_dict:
Tobin Ehlis69ebddf2016-10-18 15:55:07 -0600207 print "Found repeat error string"
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600208 str_count_dict[err_str] = str_count_dict[err_str] + 1
209 else:
210 str_count_dict[err_str] = 1
211 unique_id_count = unique_id_count + 1
212 print "Processed %d unique_ids" % (unique_id_count)
213 repeat_string = 0
214 for es in str_count_dict:
215 if str_count_dict[es] > 1:
216 repeat_string = repeat_string + 1
Tobin Ehlis69ebddf2016-10-18 15:55:07 -0600217 print "String '%s' repeated %d times" % (es, repeat_string)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600218 print "Found %d repeat strings" % (repeat_string)
219 def genDB(self, db_file):
220 """Generate a database of check_enum, check_coded?, testname, error_string"""
221 db_lines = []
222 # Write header for database file
223 db_lines.append("# This is a database file with validation error check information")
224 db_lines.append("# Comments are denoted with '#' char")
225 db_lines.append("# The format of the lines is:")
Tobin Ehlise7560e72016-10-19 15:59:38 -0600226 db_lines.append("# <error_enum>%s<check_implemented>%s<testname>%s<api>%s<errormsg>%s<note>" % (self.delimiter, self.delimiter, self.delimiter, self.delimiter, self.delimiter))
Mark Lobodzinski629d47b2016-10-18 13:34:58 -0600227 db_lines.append("# error_enum: Unique error enum for this check of format %s<uniqueid>" % validation_error_enum_name)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600228 db_lines.append("# check_implemented: 'Y' if check has been implemented in layers, 'U' for unknown, or 'N' for not implemented")
229 db_lines.append("# testname: Name of validation test for this check, 'Unknown' for unknown, or 'None' if not implmented")
Tobin Ehlise7560e72016-10-19 15:59:38 -0600230 db_lines.append("# api: Vulkan API function that this check is related to")
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600231 db_lines.append("# errormsg: The unique error message for this check that includes spec language and link")
Tobin Ehlise7560e72016-10-19 15:59:38 -0600232 db_lines.append("# note: Free txt field with any custom notes related to the check in question")
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600233 for enum in sorted(self.val_error_dict):
234 # Default to unknown if check or test are implemented, then update below if appropriate
235 implemented = 'U'
236 testname = 'Unknown'
237 # If we have an existing db entry for this enum, use its implemented/testname values
238 if enum in self.error_db_dict:
239 implemented = self.error_db_dict[enum]['check_implemented']
240 testname = self.error_db_dict[enum]['testname']
241 #print "delimiter: %s, id: %s, str: %s" % (self.delimiter, enum, self.val_error_dict[enum])
242 # No existing entry so default to N for implemented and None for testname
Tobin Ehlise7560e72016-10-19 15:59:38 -0600243 db_lines.append("%s%s%s%s%s%s%s%s%s%s" % (enum, self.delimiter, implemented, self.delimiter, testname, self.delimiter, self.val_error_dict[enum]['api'], self.delimiter, self.val_error_dict[enum]['error_msg'], self.delimiter))
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600244 print "Generating database file %s" % (db_file)
245 with open(db_file, "w") as outfile:
246 outfile.write("\n".join(db_lines))
Tobin Ehlise7560e72016-10-19 15:59:38 -0600247 outfile.write("\n")
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600248 def readDB(self, db_file):
249 """Read a db file into a dict, format of each line is <enum><implemented Y|N?><testname><errormsg>"""
250 db_dict = {} # This is a simple db of just enum->errormsg, the same as is created from spec
251 max_id = 0
252 with open(db_file, "r") as infile:
253 for line in infile:
254 if line.startswith('#'):
255 continue
256 line = line.strip()
257 db_line = line.split(self.delimiter)
Tobin Ehlis802b16e2016-10-11 09:37:19 -0600258 if len(db_line) != 4:
259 print "ERROR: Bad database line doesn't have 4 elements: %s" % (line)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600260 error_enum = db_line[0]
261 implemented = db_line[1]
262 testname = db_line[2]
263 error_str = db_line[3]
264 db_dict[error_enum] = error_str
265 # Also read complete database contents into our class var for later use
266 self.error_db_dict[error_enum] = {}
267 self.error_db_dict[error_enum]['check_implemented'] = implemented
268 self.error_db_dict[error_enum]['testname'] = testname
269 self.error_db_dict[error_enum]['error_string'] = error_str
270 unique_id = int(db_line[0].split('_')[-1])
271 if unique_id > max_id:
272 max_id = unique_id
273 return (db_dict, max_id)
274 # Compare unique ids from original database to data generated from updated spec
275 # 1. If a new id and error code exactly match original, great
276 # 2. If new id is not in original, but exact error code is, need to use original error code
277 # 3. If new id and new error are not in original, make sure new id picks up from end of original list
278 # 4. If new id in original, but error strings don't match then:
279 # 4a. If error string has exact match in original, update new to use original
280 # 4b. If error string not in original, may be updated error message, manually address
Tobin Ehlise7560e72016-10-19 15:59:38 -0600281 def compareDB(self, orig_error_msg_dict, max_id):
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600282 """Compare orig database dict to new dict, report out findings, and return potential new dict for parsed spec"""
283 # First create reverse dicts of err_strings to IDs
284 next_id = max_id + 1
285 orig_err_to_id_dict = {}
286 # Create an updated dict in-place that will be assigned to self.val_error_dict when done
287 updated_val_error_dict = {}
Tobin Ehlise7560e72016-10-19 15:59:38 -0600288 for enum in orig_error_msg_dict:
289 orig_err_to_id_dict[orig_error_msg_dict[enum]] = enum
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600290 new_err_to_id_dict = {}
291 for enum in self.val_error_dict:
Tobin Ehlise7560e72016-10-19 15:59:38 -0600292 new_err_to_id_dict[self.val_error_dict[enum]['error_msg']] = enum
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600293 ids_parsed = 0
Tobin Ehlise7560e72016-10-19 15:59:38 -0600294 # Values to be used for the update dict
295 update_enum = ''
296 update_msg = ''
297 update_api = ''
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600298 # Now parse through new dict and figure out what to do with non-matching things
299 for enum in sorted(self.val_error_dict):
300 ids_parsed = ids_parsed + 1
301 enum_list = enum.split('_') # grab sections of enum for use below
Tobin Ehlise7560e72016-10-19 15:59:38 -0600302 # Default update values to be the same
303 update_enum = enum
304 update_msg = self.val_error_dict[enum]['error_msg']
305 update_api = self.val_error_dict[enum]['api']
Tobin Ehlisbd0a9c62016-10-14 18:06:16 -0600306 # Any user-forced remap takes precendence
307 if enum_list[-1] in remap_dict:
308 enum_list[-1] = remap_dict[enum_list[-1]]
309 new_enum = "_".join(enum_list)
310 print "NOTE: Using user-supplied remap to force %s to be %s" % (enum, new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600311 update_enum = new_enum
312 elif enum in orig_error_msg_dict:
313 if self.val_error_dict[enum]['error_msg'] == orig_error_msg_dict[enum]:
Tobin Ehlisbd0a9c62016-10-14 18:06:16 -0600314 print "Exact match for enum %s" % (enum)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600315 # Nothing to see here
316 if enum in updated_val_error_dict:
317 print "ERROR: About to overwrite entry for %s" % (enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600318 elif self.val_error_dict[enum]['error_msg'] in orig_err_to_id_dict:
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600319 # Same value w/ different error id, need to anchor to original id
Tobin Ehlise7560e72016-10-19 15:59:38 -0600320 print "Need to switch new id %s to original id %s" % (enum, orig_err_to_id_dict[self.val_error_dict[enum]['error_msg']])
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600321 # Update id at end of new enum to be same id from original enum
Tobin Ehlise7560e72016-10-19 15:59:38 -0600322 enum_list[-1] = orig_err_to_id_dict[self.val_error_dict[enum]['error_msg']].split('_')[-1]
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600323 new_enum = "_".join(enum_list)
324 if new_enum in updated_val_error_dict:
325 print "ERROR: About to overwrite entry for %s" % (new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600326 update_enum = new_enum
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600327 else:
328 # No error match:
329 # First check if only link has changed, in which case keep ID but update message
Tobin Ehlise7560e72016-10-19 15:59:38 -0600330 orig_msg_list = orig_error_msg_dict[enum].split('(', 1)
331 new_msg_list = self.val_error_dict[enum]['error_msg'].split('(', 1)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600332 if orig_msg_list[0] == new_msg_list[0]: # Msg is same bug link has changed, keep enum & update msg
333 print "NOTE: Found that only spec link changed for %s so keeping same id w/ new link" % (enum)
Tobin Ehlisbd0a9c62016-10-14 18:06:16 -0600334 # This seems to be a new error so need to pick it up from end of original unique ids & flag for review
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600335 else:
336 enum_list[-1] = "%05d" % (next_id)
337 new_enum = "_".join(enum_list)
338 next_id = next_id + 1
339 print "MANUALLY VERIFY: Updated new enum %s to be unique %s. Make sure new error msg is actually unique and not just changed" % (enum, new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600340 print " New error string: %s" % (self.val_error_dict[enum]['error_msg'])
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600341 if new_enum in updated_val_error_dict:
342 print "ERROR: About to overwrite entry for %s" % (new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600343 update_enum = new_enum
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600344 else: # new enum is not in orig db
Tobin Ehlise7560e72016-10-19 15:59:38 -0600345 if self.val_error_dict[enum]['error_msg'] in orig_err_to_id_dict:
346 print "New enum %s not in orig dict, but exact error message matches original unique id %s" % (enum, orig_err_to_id_dict[self.val_error_dict[enum]['error_msg']])
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600347 # Update new unique_id to use original
Tobin Ehlise7560e72016-10-19 15:59:38 -0600348 enum_list[-1] = orig_err_to_id_dict[self.val_error_dict[enum]['error_msg']].split('_')[-1]
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600349 new_enum = "_".join(enum_list)
350 if new_enum in updated_val_error_dict:
351 print "ERROR: About to overwrite entry for %s" % (new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600352 update_enum = new_enum
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600353 else:
354 enum_list[-1] = "%05d" % (next_id)
355 new_enum = "_".join(enum_list)
356 next_id = next_id + 1
357 print "Completely new id and error code, update new id from %s to unique %s" % (enum, new_enum)
358 if new_enum in updated_val_error_dict:
359 print "ERROR: About to overwrite entry for %s" % (new_enum)
Tobin Ehlise7560e72016-10-19 15:59:38 -0600360 update_enum = new_enum
361 updated_val_error_dict[update_enum] = {}
362 updated_val_error_dict[update_enum]['error_msg'] = update_msg
363 updated_val_error_dict[update_enum]['api'] = update_api
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600364 # Assign parsed dict to be the udpated dict based on db compare
365 print "In compareDB parsed %d entries" % (ids_parsed)
366 return updated_val_error_dict
367 def validateUpdateDict(self, update_dict):
368 """Compare original dict vs. update dict and make sure that all of the checks are still there"""
369 # Currently just make sure that the same # of checks as the original checks are there
370 #orig_ids = {}
371 orig_id_count = len(self.val_error_dict)
372 #update_ids = {}
373 update_id_count = len(update_dict)
374 if orig_id_count != update_id_count:
375 print "Original dict had %d unique_ids, but updated dict has %d!" % (orig_id_count, update_id_count)
376 return False
377 print "Original dict and updated dict both have %d unique_ids. Great!" % (orig_id_count)
378 return True
379 # TODO : include some more analysis
380
381# User passes in arg of form <new_id1>-<old_id1>[,count1]:<new_id2>-<old_id2>[,count2]:...
382# new_id# = the new enum id that was assigned to an error
383# old_id# = the previous enum id that was assigned to the same error
384# [,count#] = The number of ids to remap starting at new_id#=old_id# and ending at new_id[#+count#-1]=old_id[#+count#-1]
385# If not supplied, then ,1 is assumed, which will only update a single id
386def updateRemapDict(remap_string):
387 """Set up global remap_dict based on user input"""
388 remap_list = remap_string.split(":")
389 for rmap in remap_list:
390 count = 1 # Default count if none supplied
391 id_count_list = rmap.split(',')
392 if len(id_count_list) > 1:
393 count = int(id_count_list[1])
394 new_old_id_list = id_count_list[0].split('-')
395 for offset in range(count):
396 remap_dict["%05d" % (int(new_old_id_list[0]) + offset)] = "%05d" % (int(new_old_id_list[1]) + offset)
397 for new_id in sorted(remap_dict):
398 print "Set to remap new id %s to old id %s" % (new_id, remap_dict[new_id])
399
400if __name__ == "__main__":
401 i = 1
402 use_online = True # Attempt to grab spec from online by default
403 update_option = False
404 while (i < len(sys.argv)):
405 arg = sys.argv[i]
406 i = i + 1
407 if (arg == '-spec'):
408 spec_filename = sys.argv[i]
409 # If user specifies local specfile, skip online
410 use_online = False
411 i = i + 1
412 elif (arg == '-out'):
413 out_filename = sys.argv[i]
414 i = i + 1
415 elif (arg == '-gendb'):
416 gen_db = True
417 # Set filename if supplied, else use default
418 if i < len(sys.argv) and not sys.argv[i].startswith('-'):
419 db_filename = sys.argv[i]
420 i = i + 1
421 elif (arg == '-compare'):
422 db_filename = sys.argv[i]
423 spec_compare = True
424 i = i + 1
425 elif (arg == '-update'):
426 update_option = True
427 spec_compare = True
428 gen_db = True
429 elif (arg == '-remap'):
430 updateRemapDict(sys.argv[i])
431 i = i + 1
432 elif (arg in ['-help', '-h']):
433 printHelp()
434 sys.exit()
435 if len(remap_dict) > 1 and not update_option:
436 print "ERROR: '-remap' option can only be used along with '-update' option. Exiting."
437 sys.exit()
438 spec = Specification()
439 spec.loadFile(use_online, spec_filename)
440 #spec.parseTree()
441 #spec.genHeader(out_filename)
442 spec.analyze()
443 if (spec_compare):
444 # Read in old spec info from db file
Tobin Ehlise7560e72016-10-19 15:59:38 -0600445 (orig_err_msg_dict, max_id) = spec.readDB(db_filename)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600446 # New spec data should already be read into self.val_error_dict
Tobin Ehlise7560e72016-10-19 15:59:38 -0600447 updated_dict = spec.compareDB(orig_err_msg_dict, max_id)
Tobin Ehlis5ade0692016-10-05 17:18:15 -0600448 update_valid = spec.validateUpdateDict(updated_dict)
449 if update_valid:
450 spec.updateDict(updated_dict)
451 else:
452 sys.exit()
453 if (gen_db):
454 spec.genDB(db_filename)
455 print "Writing out file (-out) to '%s'" % (out_filename)
456 spec.genHeader(out_filename)
457
458##### Example dataset
459# <div class="sidebar">
460# <div class="titlepage">
461# <div>
462# <div>
463# <p class="title">
464# <strong>Valid Usage</strong> # When we get to this guy, we know we're under interesting sidebar
465# </p>
466# </div>
467# </div>
468# </div>
469# <div class="itemizedlist">
470# <ul class="itemizedlist" style="list-style-type: disc; ">
471# <li class="listitem">
472# <em class="parameter">
473# <code>device</code>
474# </em>
475# <span class="normative">must</span> be a valid
476# <code class="code">VkDevice</code> handle
477# </li>
478# <li class="listitem">
479# <em class="parameter">
480# <code>commandPool</code>
481# </em>
482# <span class="normative">must</span> be a valid
483# <code class="code">VkCommandPool</code> handle
484# </li>
485# <li class="listitem">
486# <em class="parameter">
487# <code>flags</code>
488# </em>
489# <span class="normative">must</span> be a valid combination of
490# <code class="code">
491# <a class="link" href="#VkCommandPoolResetFlagBits">VkCommandPoolResetFlagBits</a>
492# </code> values
493# </li>
494# <li class="listitem">
495# <em class="parameter">
496# <code>commandPool</code>
497# </em>
498# <span class="normative">must</span> have been created, allocated, or retrieved from
499# <em class="parameter">
500# <code>device</code>
501# </em>
502# </li>
503# <li class="listitem">All
504# <code class="code">VkCommandBuffer</code>
505# objects allocated from
506# <em class="parameter">
507# <code>commandPool</code>
508# </em>
509# <span class="normative">must</span> not currently be pending execution
510# </li>
511# </ul>
512# </div>
513# </div>
514##### Second example dataset
515# <div class="sidebar">
516# <div class="titlepage">
517# <div>
518# <div>
519# <p class="title">
520# <strong>Valid Usage</strong>
521# </p>
522# </div>
523# </div>
524# </div>
525# <div class="itemizedlist">
526# <ul class="itemizedlist" style="list-style-type: disc; ">
527# <li class="listitem">The <em class="parameter"><code>queueFamilyIndex</code></em> member of any given element of <em class="parameter"><code>pQueueCreateInfos</code></em> <span class="normative">must</span> be unique within <em class="parameter"><code>pQueueCreateInfos</code></em>
528# </li>
529# </ul>
530# </div>
531# </div>
532# <div class="sidebar">
533# <div class="titlepage">
534# <div>
535# <div>
536# <p class="title">
537# <strong>Valid Usage (Implicit)</strong>
538# </p>
539# </div>
540# </div>
541# </div>
542# <div class="itemizedlist"><ul class="itemizedlist" style="list-style-type: disc; "><li class="listitem">
543#<em class="parameter"><code>sType</code></em> <span class="normative">must</span> be <code class="code">VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO</code>
544#</li><li class="listitem">
545#<em class="parameter"><code>pNext</code></em> <span class="normative">must</span> be <code class="literal">NULL</code>
546#</li><li class="listitem">
547#<em class="parameter"><code>flags</code></em> <span class="normative">must</span> be <code class="literal">0</code>
548#</li><li class="listitem">
549#<em class="parameter"><code>pQueueCreateInfos</code></em> <span class="normative">must</span> be a pointer to an array of <em class="parameter"><code>queueCreateInfoCount</code></em> valid <code class="code">VkDeviceQueueCreateInfo</code> structures
550#</li>