blob: fa3819d7b942d1042c149a6acbc2ef26ba3ae504 [file] [log] [blame]
Tobin Ehlis35308dd2016-10-31 13:27:36 -06001#!/usr/bin/env python3
2# Copyright (c) 2015-2016 The Khronos Group Inc.
3# Copyright (c) 2015-2016 Valve Corporation
4# Copyright (c) 2015-2016 LunarG, Inc.
5# Copyright (c) 2015-2016 Google Inc.
6#
7# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# Author: Tobin Ehlis <tobine@google.com>
20
21import argparse
22import os
23import sys
24import platform
25
26# vk_validation_stats.py overview
27# This script is intended to generate statistics on the state of validation code
28# based on information parsed from the source files and the database file
29# Here's what it currently does:
30# 1. Parse vk_validation_error_database.txt to store claimed state of validation checks
31# 2. Parse vk_validation_error_messages.h to verify the actual checks in header vs. the
32# claimed state of the checks
33# 3. Parse source files to identify which checks are implemented and verify that this
34# exactly matches the list of checks claimed to be implemented in the database
35# 4. Parse test file(s) and verify that reported tests exist
36# 5. Report out stats on number of checks, implemented checks, and duplicated checks
37#
38# TODO:
39# 1. Would also like to report out number of existing checks that don't yet use new, unique enum
40# 2. Could use notes to store custom fields (like TODO) and print those out here
41# 3. Update test code to check if tests use new, unique enums to check for errors instead of strings
42
43db_file = 'vk_validation_error_database.txt'
44layer_source_files = [
45'core_validation.cpp',
46'descriptor_sets.cpp',
47'parameter_validation.cpp',
48'object_tracker.cpp',
Tobin Ehlis3f0b2772016-11-18 16:56:15 -070049'image.cpp'
Tobin Ehlis35308dd2016-10-31 13:27:36 -060050]
51header_file = 'vk_validation_error_messages.h'
52# TODO : Don't hardcode linux path format if we want this to run on windows
53test_file = '../tests/layer_validation_tests.cpp'
54
55
56class ValidationDatabase:
57 def __init__(self, filename=db_file):
58 self.db_file = filename
59 self.delimiter = '~^~'
60 self.db_dict = {} # complete dict of all db values per error enum
61 # specialized data structs with slices of complete dict
62 self.db_implemented_enums = [] # list of all error enums claiming to be implemented in database file
63 self.db_enum_to_tests = {} # dict where enum is key to lookup list of tests implementing the enum
64 #self.src_implemented_enums
65 def read(self):
66 """Read a database file into internal data structures, format of each line is <enum><implemented Y|N?><testname><api><errormsg><notes>"""
67 #db_dict = {} # This is a simple db of just enum->errormsg, the same as is created from spec
68 #max_id = 0
69 with open(self.db_file, "r") as infile:
70 for line in infile:
71 line = line.strip()
72 if line.startswith('#') or '' == line:
73 continue
74 db_line = line.split(self.delimiter)
75 if len(db_line) != 6:
76 print "ERROR: Bad database line doesn't have 6 elements: %s" % (line)
77 error_enum = db_line[0]
78 implemented = db_line[1]
79 testname = db_line[2]
80 api = db_line[3]
81 error_str = db_line[4]
82 note = db_line[5]
83 # Read complete database contents into our class var for later use
84 self.db_dict[error_enum] = {}
85 self.db_dict[error_enum]['check_implemented'] = implemented
86 self.db_dict[error_enum]['testname'] = testname
87 self.db_dict[error_enum]['api'] = api
88 self.db_dict[error_enum]['error_string'] = error_str
89 self.db_dict[error_enum]['note'] = note
90 # Now build custom data structs
91 if 'Y' == implemented:
92 self.db_implemented_enums.append(error_enum)
93 if testname.lower() not in ['unknown', 'none']:
94 self.db_enum_to_tests[error_enum] = testname.split(',')
95 #if len(self.db_enum_to_tests[error_enum]) > 1:
96 # print "Found check %s that has multiple tests: %s" % (error_enum, self.db_enum_to_tests[error_enum])
97 #else:
98 # print "Check %s has single test: %s" % (error_enum, self.db_enum_to_tests[error_enum])
99 #unique_id = int(db_line[0].split('_')[-1])
100 #if unique_id > max_id:
101 # max_id = unique_id
102 #print "Found %d total enums in database" % (len(self.db_dict.keys()))
103 #print "Found %d enums claiming to be implemented in source" % (len(self.db_implemented_enums))
104 #print "Found %d enums claiming to have tests implemented" % (len(self.db_enum_to_tests.keys()))
105
106class ValidationHeader:
107 def __init__(self, filename=header_file):
108 self.filename = header_file
109 self.enums = []
110 def read(self):
111 """Read unique error enum header file into internal data structures"""
112 grab_enums = False
113 with open(self.filename, "r") as infile:
114 for line in infile:
115 line = line.strip()
116 if 'enum UNIQUE_VALIDATION_ERROR_CODE {' in line:
117 grab_enums = True
118 continue
119 if grab_enums:
120 if 'VALIDATION_ERROR_MAX_ENUM' in line:
121 grab_enums = False
122 break # done
123 if 'VALIDATION_ERROR_' in line:
124 enum = line.split(' = ')[0]
125 self.enums.append(enum)
126 #print "Found %d error enums. First is %s and last is %s." % (len(self.enums), self.enums[0], self.enums[-1])
127
128class ValidationSource:
129 def __init__(self, source_file_list):
130 self.source_files = source_file_list
131 self.enum_count_dict = {} # dict of enum values to the count of how much they're used
Tobin Ehlis3d9dd942016-11-23 13:08:01 -0700132 # 1790 is a special case that provides an exception when an extension is enabled. No specific error is flagged, but the exception is handled so add it here
133 self.enum_count_dict['VALIDATION_ERROR_01790'] = 1
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600134 def parse(self):
135 duplicate_checks = 0
136 for sf in self.source_files:
137 with open(sf) as f:
138 for line in f:
139 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
140 continue
141 # Find enums
142 #if 'VALIDATION_ERROR_' in line and True not in [ignore in line for ignore in ['[VALIDATION_ERROR_', 'UNIQUE_VALIDATION_ERROR_CODE']]:
143 if 'VALIDATION_ERROR_' in line and 'UNIQUE_VALIDATION_ERROR_CODE' not in line:
144 # Need to isolate the validation error enum
145 #print("Line has check:%s" % (line))
146 line_list = line.split()
147 enum = ''
148 for str in line_list:
149 if 'VALIDATION_ERROR_' in str and '[VALIDATION_ERROR_' not in str:
150 enum = str.strip(',);')
151 break
152 if enum != '':
153 if enum not in self.enum_count_dict:
154 self.enum_count_dict[enum] = 1
155 #print "Found enum %s implemented for first time in file %s" % (enum, sf)
156 else:
157 self.enum_count_dict[enum] = self.enum_count_dict[enum] + 1
158 #print "Found enum %s implemented for %d time in file %s" % (enum, self.enum_count_dict[enum], sf)
159 duplicate_checks = duplicate_checks + 1
160 #else:
161 #print("Didn't find actual check in line:%s" % (line))
162 #print "Found %d unique implemented checks and %d are duplicated at least once" % (len(self.enum_count_dict.keys()), duplicate_checks)
163
164# Class to parse the validation layer test source and store testnames
165# TODO: Enhance class to detect use of unique error enums in the test
166class TestParser:
167 def __init__(self, test_file_list, test_group_name=['VkLayerTest', 'VkPositiveLayerTest', 'VkWsiEnabledLayerTest']):
168 self.test_files = test_file_list
169 self.tests_set = set()
170 self.test_trigger_txt_list = []
171 for tg in test_group_name:
172 self.test_trigger_txt_list.append('TEST_F(%s' % tg)
173 #print('Test trigger test list: %s' % (self.test_trigger_txt_list))
174
175 # Parse test files into internal data struct
176 def parse(self):
177 # For each test file, parse test names into set
178 grab_next_line = False # handle testname on separate line than wildcard
179 for test_file in self.test_files:
180 with open(test_file) as tf:
181 for line in tf:
182 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
183 continue
184
185 if True in [ttt in line for ttt in self.test_trigger_txt_list]:
186 #print('Test wildcard in line: %s' % (line))
187 testname = line.split(',')[-1]
188 testname = testname.strip().strip(' {)')
189 #print('Inserting test: "%s"' % (testname))
190 if ('' == testname):
191 grab_next_line = True
192 continue
193 self.tests_set.add(testname)
194 if grab_next_line: # test name on its own line
195 grab_next_line = False
196 testname = testname.strip().strip(' {)')
197 self.tests_set.add(testname)
198
199# Little helper class for coloring cmd line output
200class bcolors:
201
202 def __init__(self):
203 self.GREEN = '\033[0;32m'
204 self.RED = '\033[0;31m'
205 self.YELLOW = '\033[1;33m'
206 self.ENDC = '\033[0m'
207 if 'Linux' != platform.system():
208 self.GREEN = ''
209 self.RED = ''
210 self.YELLOW = ''
211 self.ENDC = ''
212
213 def green(self):
214 return self.GREEN
215
216 def red(self):
217 return self.RED
218
219 def yellow(self):
220 return self.YELLOW
221
222 def endc(self):
223 return self.ENDC
224
225# Class to parse the validation layer test source and store testnames
226class TestParser:
227 def __init__(self, test_file_list, test_group_name=['VkLayerTest', 'VkPositiveLayerTest', 'VkWsiEnabledLayerTest']):
228 self.test_files = test_file_list
229 self.tests_set = set()
230 self.test_trigger_txt_list = []
231 for tg in test_group_name:
232 self.test_trigger_txt_list.append('TEST_F(%s' % tg)
233 #print('Test trigger test list: %s' % (self.test_trigger_txt_list))
234
235 # Parse test files into internal data struct
236 def parse(self):
237 # For each test file, parse test names into set
238 grab_next_line = False # handle testname on separate line than wildcard
239 for test_file in self.test_files:
240 with open(test_file) as tf:
241 for line in tf:
242 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
243 continue
244
245 if True in [ttt in line for ttt in self.test_trigger_txt_list]:
246 #print('Test wildcard in line: %s' % (line))
247 testname = line.split(',')[-1]
248 testname = testname.strip().strip(' {)')
249 #print('Inserting test: "%s"' % (testname))
250 if ('' == testname):
251 grab_next_line = True
252 continue
253 self.tests_set.add(testname)
254 if grab_next_line: # test name on its own line
255 grab_next_line = False
256 testname = testname.strip().strip(' {)')
257 self.tests_set.add(testname)
258
259def main(argv=None):
260 # parse db
261 val_db = ValidationDatabase()
262 val_db.read()
263 # parse header
264 val_header = ValidationHeader()
265 val_header.read()
266 # Create parser for layer files
267 val_source = ValidationSource(layer_source_files)
268 val_source.parse()
269 # Parse test files
270 test_parser = TestParser([test_file, ])
271 test_parser.parse()
272
273 # Process stats - Just doing this inline in main, could make a fancy class to handle
274 # all the processing of data and then get results from that
275 txt_color = bcolors()
276 print("Validation Statistics")
277 # First give number of checks in db & header and report any discrepancies
278 db_enums = len(val_db.db_dict.keys())
279 hdr_enums = len(val_header.enums)
280 print(" Database file includes %d unique checks" % (db_enums))
281 print(" Header file declares %d unique checks" % (hdr_enums))
282 tmp_db_dict = val_db.db_dict
283 db_missing = []
284 for enum in val_header.enums:
285 if not tmp_db_dict.pop(enum, False):
286 db_missing.append(enum)
287 if db_enums == hdr_enums and len(db_missing) == 0 and len(tmp_db_dict.keys()) == 0:
288 print(txt_color.green() + " Database and Header match, GREAT!" + txt_color.endc())
289 else:
290 print(txt_color.red() + " Uh oh, Database doesn't match Header :(" + txt_color.endc())
291 if len(db_missing) != 0:
292 print(txt_color.red() + " The following checks are in header but missing from database:" + txt_color.endc())
293 for missing_enum in db_missing:
294 print(txt_color.red() + " %s" % (missing_enum) + txt_color.endc())
295 if len(tmp_db_dict.keys()) != 0:
296 print(txt_color.red() + " The following checks are in database but haven't been declared in the header:" + txt_color.endc())
297 for extra_enum in tmp_db_dict:
298 print(txt_color.red() + " %s" % (extra_enum) + txt_color.endc())
299 # Report out claimed implemented checks vs. found actual implemented checks
300 imp_not_found = [] # Checks claimed to implemented in DB file but no source found
301 imp_not_claimed = [] # Checks found implemented but not claimed to be in DB
302 multiple_uses = False # Flag if any enums are used multiple times
303 for db_imp in val_db.db_implemented_enums:
304 if db_imp not in val_source.enum_count_dict:
305 imp_not_found.append(db_imp)
306 for src_enum in val_source.enum_count_dict:
307 if val_source.enum_count_dict[src_enum] > 1:
308 multiple_uses = True
309 if src_enum not in val_db.db_implemented_enums:
310 imp_not_claimed.append(src_enum)
311 print(" Database file claims that %d checks (%s) are implemented in source." % (len(val_db.db_implemented_enums), "{0:.0f}%".format(float(len(val_db.db_implemented_enums))/db_enums * 100)))
312 if len(imp_not_found) == 0 and len(imp_not_claimed) == 0:
313 print(txt_color.green() + " All claimed Database implemented checks have been found in source, and no source checks aren't claimed in Database, GREAT!" + txt_color.endc())
314 else:
315 print(txt_color.red() + " Uh oh, Database claimed implemented don't match Source :(" + txt_color.endc())
316 if len(imp_not_found) != 0:
Tobin Ehlis3f0b2772016-11-18 16:56:15 -0700317 print(txt_color.red() + " The following %d checks are claimed to be implemented in Database, but weren't found in source:" % (len(imp_not_found)) + txt_color.endc())
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600318 for not_imp_enum in imp_not_found:
319 print(txt_color.red() + " %s" % (not_imp_enum) + txt_color.endc())
320 if len(imp_not_claimed) != 0:
321 print(txt_color.red() + " The following checks are implemented in source, but not claimed to be in Database:" + txt_color.endc())
322 for imp_enum in imp_not_claimed:
323 print(txt_color.red() + " %s" % (imp_enum) + txt_color.endc())
324 if multiple_uses:
325 print(txt_color.yellow() + " Note that some checks are used multiple times. These may be good candidates for new valid usage spec language." + txt_color.endc())
326 print(txt_color.yellow() + " Here is a list of each check used multiple times with its number of uses:" + txt_color.endc())
327 for enum in val_source.enum_count_dict:
328 if val_source.enum_count_dict[enum] > 1:
329 print(txt_color.yellow() + " %s: %d" % (enum, val_source.enum_count_dict[enum]) + txt_color.endc())
330 # Now check that tests claimed to be implemented are actual test names
331 bad_testnames = []
332 for enum in val_db.db_enum_to_tests:
333 for testname in val_db.db_enum_to_tests[enum]:
334 if testname not in test_parser.tests_set:
335 bad_testnames.append(testname)
336 print(" Database file claims that %d checks have tests written." % len(val_db.db_enum_to_tests))
337 if len(bad_testnames) == 0:
338 print(txt_color.green() + " All claimed tests have valid names. That's good!" + txt_color.endc())
339 else:
340 print(txt_color.red() + " The following testnames in Database appear to be invalid:")
341 for bt in bad_testnames:
Tobin Ehlisb04c2c62016-11-21 15:51:45 -0700342 print(txt_color.red() + " %s" % (bt) + txt_color.endc())
Tobin Ehlis35308dd2016-10-31 13:27:36 -0600343
344 return 0
345
346if __name__ == "__main__":
347 sys.exit(main())
348