blob: dcd4ce6b0f07d6ac368cf8e95e8f26dc593e11f2 [file] [log] [blame]
Tobin Ehlis236717c2015-08-31 12:42:38 -06001#!/usr/bin/env python3
Karl Schultzc85a02f2016-02-02 19:32:33 -07002# 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.
Tobin Ehlis236717c2015-08-31 12:42:38 -06006#
Karl Schultzc85a02f2016-02-02 19:32:33 -07007# Permission is hereby granted, free of charge, to any person obtaining a copy
8# of this software and/or associated documentation files (the "Materials"), to
9# deal in the Materials without restriction, including without limitation the
10# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11# sell copies of the Materials, and to permit persons to whom the Materials
12# are furnished to do so, subject to the following conditions:
Tobin Ehlis236717c2015-08-31 12:42:38 -060013#
Karl Schultzc85a02f2016-02-02 19:32:33 -070014# The above copyright notice(s) and this permission notice shall be included
15# in all copies or substantial portions of the Materials.
Tobin Ehlis236717c2015-08-31 12:42:38 -060016#
Karl Schultzc85a02f2016-02-02 19:32:33 -070017# The Materials are Confidential Information as defined by the Khronos
18# Membership Agreement until designated non-confidential by Khronos, at which
19# point this condition clause shall be removed.
Tobin Ehlis236717c2015-08-31 12:42:38 -060020#
Karl Schultzc85a02f2016-02-02 19:32:33 -070021# THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
Tobin Ehlis236717c2015-08-31 12:42:38 -060022# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
Karl Schultzc85a02f2016-02-02 19:32:33 -070023# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
24#
25# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE
28# USE OR OTHER DEALINGS IN THE MATERIALS
Courtney Goeltzenleuchter96cd7952015-10-30 11:14:30 -060029#
30# Author: Tobin Ehlis <tobin@lunarg.com>
Tobin Ehlis236717c2015-08-31 12:42:38 -060031
32import argparse
33import os
34import sys
35import vulkan
36import platform
37
38# vk_layer_documentation_generate.py overview
39# This script is intended to generate documentation based on vulkan layers
40# It parses known validation layer headers for details of the validation checks
41# It parses validation layer source files for specific code where checks are implemented
42# structs in a human-readable txt format, as well as utility functions
43# to print enum values as strings
44
45# NOTE : Initially the script is performing validation of a hand-written document
46# Right now it does 3 checks:
47# 1. Verify ENUM codes declared in source are documented
48# 2. Verify ENUM codes in document are declared in source
49# 3. Verify API function names in document are in the actual API header (vulkan.py)
50# Currently script will flag errors in all of these cases
51
52# TODO : Need a formal specification of the syntax for doc generation
53# Initially, these are the basics:
54# 1. Validation checks have unique ENUM values defined in validation layer header
55# 2. ENUM includes comments for 1-line overview of check and more detailed description
56# 3. Actual code implementing checks includes ENUM value in callback
57# 4. Code to test checks should include reference to ENUM
58
59
60# TODO : Need list of known validation layers to use as default input
61# Just a couple of flat lists right now, but may need to make this input file
62# or at least a more dynamic data structure
63layer_inputs = { 'draw_state' : {'header' : 'layers/draw_state.h',
64 'source' : 'layers/draw_state.cpp',
65 'generated' : False,
66 'error_enum' : 'DRAW_STATE_ERROR'},
Mark Lobodzinski5e5b98b2015-12-04 10:11:56 -070067 'shader_checker' : {'header' : 'layers/draw_state.h',
68 'source' : 'layers/draw_state.cpp',
69 'generated' : False,
70 'error_enum' : 'SHADER_CHECKER_ERROR'},
Tobin Ehlis236717c2015-08-31 12:42:38 -060071 'mem_tracker' : {'header' : 'layers/mem_tracker.h',
72 'source' : 'layers/mem_tracker.cpp',
73 'generated' : False,
74 'error_enum' : 'MEM_TRACK_ERROR'},
Tobin Ehlis236717c2015-08-31 12:42:38 -060075 'threading' : {'header' : 'layers/threading.h',
76 'source' : 'dbuild/layers/threading.cpp',
77 'generated' : True,
78 'error_enum' : 'THREADING_CHECKER_ERROR'},
Jon Ashburn6e277322015-12-31 09:44:26 -070079 'object_tracker' : {'header' : 'layers/object_tracker.h',
80 'source' : 'dbuild/layers/object_tracker.cpp',
Tobin Ehlis236717c2015-08-31 12:42:38 -060081 'generated' : True,
82 'error_enum' : 'OBJECT_TRACK_ERROR',},
Tobin Ehlisc345b8b2015-09-03 09:50:06 -060083 'device_limits' : {'header' : 'layers/device_limits.h',
Tobin Ehlis65380532015-09-21 15:20:28 -060084 'source' : 'layers/device_limits.cpp',
85 'generated' : False,
86 'error_enum' : 'DEV_LIMITS_ERROR',},
87 'image' : {'header' : 'layers/image.h',
88 'source' : 'layers/image.cpp',
89 'generated' : False,
90 'error_enum' : 'IMAGE_ERROR',},
Ian Elliottf81c2562015-09-25 15:50:55 -060091 'swapchain' : {'header' : 'layers/swapchain.h',
92 'source' : 'layers/swapchain.cpp',
93 'generated' : False,
94 'error_enum' : 'SWAPCHAIN_ERROR',},
Tobin Ehlis236717c2015-08-31 12:42:38 -060095 }
96
97builtin_headers = [layer_inputs[ln]['header'] for ln in layer_inputs]
98builtin_source = [layer_inputs[ln]['source'] for ln in layer_inputs]
99
100# List of extensions in layers that are included in documentation, but not in vulkan.py API set
101layer_extension_functions = ['objTrackGetObjects', 'objTrackGetObjectsOfType']
102
103def handle_args():
104 parser = argparse.ArgumentParser(description='Generate layer documenation from source.')
105 parser.add_argument('--in_headers', required=False, default=builtin_headers, help='The input layer header files from which code will be generated.')
106 parser.add_argument('--in_source', required=False, default=builtin_source, help='The input layer source files from which code will be generated.')
107 parser.add_argument('--layer_doc', required=False, default='layers/vk_validation_layer_details.md', help='Existing layer document to be validated against actual layers.')
108 parser.add_argument('--validate', action='store_true', default=False, help='Validate that there are no mismatches between layer documentation and source. This includes cross-checking the validation checks, and making sure documented Vulkan API calls exist.')
109 parser.add_argument('--print_structs', action='store_true', default=False, help='Primarily a debug option that prints out internal data structs used to generate layer docs.')
110 parser.add_argument('--print_doc_checks', action='store_true', default=False, help='Primarily a debug option that prints out all of the checks that are documented.')
111 return parser.parse_args()
112
113# Little helper class for coloring cmd line output
114class bcolors:
115
116 def __init__(self):
117 self.GREEN = '\033[0;32m'
118 self.RED = '\033[0;31m'
119 self.ENDC = '\033[0m'
120 if 'Linux' != platform.system():
121 self.GREEN = ''
122 self.RED = ''
123 self.ENDC = ''
124
125 def green(self):
126 return self.GREEN
127
128 def red(self):
129 return self.RED
130
131 def endc(self):
132 return self.ENDC
133
134# Class to parse the layer source code and store details in internal data structs
135class LayerParser:
136 def __init__(self, header_file_list, source_file_list):
137 self.header_files = header_file_list
138 self.source_files = source_file_list
139 self.layer_dict = {}
140 self.api_dict = {}
141
142 # Parse layer header files into internal dict data structs
143 def parse(self):
144 # For each header file, parse details into dicts
145 # TODO : Should have a global dict element to track overall list of checks
146 store_enum = False
Tobin Ehlis32479352015-12-01 09:48:58 -0700147 for layer_name in layer_inputs:
148 hf = layer_inputs[layer_name]['header']
Tobin Ehlis236717c2015-08-31 12:42:38 -0600149 self.layer_dict[layer_name] = {} # initialize a new dict for this layer
150 self.layer_dict[layer_name]['CHECKS'] = [] # enum of checks is stored in a list
151 #print('Parsing header file %s as layer name %s' % (hf, layer_name))
152 with open(hf) as f:
153 for line in f:
154 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
155 #print("Skipping comment line: %s" % line)
156 # For now skipping lines starting w/ comment, may use these to capture
157 # documentation in the future
158 continue
159
160 # Find enums
161 if store_enum:
162 if '}' in line: # we're done with enum definition
163 store_enum = False
164 continue
165 # grab the enum name as a unique check
166 if ',' in line:
167 # TODO : When documentation for a check is contained in the source,
168 # this is where we should also capture that documentation so that
169 # it can then be transformed into desired doc format
170 enum_name = line.split(',')[0].strip()
171 # Flag an error if we have already seen this enum
172 if enum_name in self.layer_dict[layer_name]['CHECKS']:
173 print('ERROR : % layer has duplicate error enum: %s' % (layer_name, enum_name))
174 self.layer_dict[layer_name]['CHECKS'].append(enum_name)
175 # If the line includes 'typedef', 'enum', and the expected enum name, start capturing enums
176 if False not in [ex in line for ex in ['typedef', 'enum', layer_inputs[layer_name]['error_enum']]]:
177 store_enum = True
178
179 # For each source file, parse into dicts
180 for sf in self.source_files:
181 #print('Parsing source file %s' % sf)
182 pass
183 # TODO : In the source file we want to see where checks actually occur
184 # Need to build function tree of checks so that we know all of the
185 # checks that occur under a top-level Vulkan API call
186 # Eventually in the validation we can flag ENUMs that aren't being
187 # used in the source, and we can document source code lines as well
188 # as Vulkan API calls where each specific ENUM check is made
189
190 def print_structs(self):
191 print('This is where I print the data structs')
192 for layer in self.layer_dict:
193 print('Layer %s has %i checks:\n%s' % (layer, len(self.layer_dict[layer]['CHECKS'])-1, "\n\t".join(self.layer_dict[layer]['CHECKS'])))
194
195# Class to parse hand-written md layer documentation into a dict and then validate its contents
196class LayerDoc:
197 def __init__(self, source_file):
198 self.layer_doc_filename = source_file
199 self.txt_color = bcolors()
200 # Main data struct to store info from layer doc
201 self.layer_doc_dict = {}
202 # Comprehensive list of all validation checks recorded in doc
203 self.enum_list = []
204
205 # Parse the contents of doc into data struct
206 def parse(self):
207 layer_name = 'INIT'
208 parse_layer_details = False
209 detail_trigger = '| Check | '
210 parse_pending_work = False
211 pending_trigger = ' Pending Work'
212 parse_overview = False
213 overview_trigger = ' Overview'
214 enum_prefix = ''
215
216 with open(self.layer_doc_filename) as f:
217 for line in f:
218 if parse_pending_work:
219 if '.' in line and line.strip()[0].isdigit():
220 todo_item = line.split('.')[1].strip()
221 self.layer_doc_dict[layer_name]['pending'].append(todo_item)
222 if pending_trigger in line and '##' in line:
223 parse_layer_details = False
224 parse_pending_work = True
225 parse_overview = False
226 self.layer_doc_dict[layer_name]['pending'] = []
227 if parse_layer_details:
228 # Grab details but skip the fomat line with a bunch of '-' chars
229 if '|' in line and line.count('-') < 20:
230 detail_sections = line.split('|')
231 #print("Details elements from line %s: %s" % (line, detail_sections))
232 check_name = '%s%s' % (enum_prefix, detail_sections[3].strip())
233 if '_NA' in check_name:
234 # TODO : Should clean up these NA checks in the doc, skipping them for now
235 continue
236 self.enum_list.append(check_name)
237 self.layer_doc_dict[layer_name][check_name] = {}
238 self.layer_doc_dict[layer_name][check_name]['summary_txt'] = detail_sections[1].strip()
239 self.layer_doc_dict[layer_name][check_name]['details_txt'] = detail_sections[2].strip()
240 self.layer_doc_dict[layer_name][check_name]['api_list'] = detail_sections[4].split()
241 self.layer_doc_dict[layer_name][check_name]['tests'] = detail_sections[5].split()
242 self.layer_doc_dict[layer_name][check_name]['notes'] = detail_sections[6].strip()
243 # strip any unwanted commas from api and test names
244 self.layer_doc_dict[layer_name][check_name]['api_list'] = [a.strip(',') for a in self.layer_doc_dict[layer_name][check_name]['api_list']]
245 self.layer_doc_dict[layer_name][check_name]['tests'] = [a.strip(',') for a in self.layer_doc_dict[layer_name][check_name]['tests']]
246 # Trigger details parsing when we have table header
247 if detail_trigger in line:
248 parse_layer_details = True
249 parse_pending_work = False
250 parse_overview = False
251 enum_txt = line.split('|')[3]
252 if '*' in enum_txt:
253 enum_prefix = enum_txt.split()[-1].strip('*').strip()
254 #print('prefix: %s' % enum_prefix)
255 if parse_overview:
256 self.layer_doc_dict[layer_name]['overview'] += line
257 if overview_trigger in line and '##' in line:
258 parse_layer_details = False
259 parse_pending_work = False
260 parse_overview = True
261 layer_name = line.split()[1]
262 self.layer_doc_dict[layer_name] = {}
263 self.layer_doc_dict[layer_name]['overview'] = ''
264
265 # Verify that checks and api references in layer doc match reality
266 # Report API calls from doc that are not found in API
267 # Report checks from doc that are not in actual layers
268 # Report checks from layers that are not captured in doc
269 def validate(self, layer_dict):
270 # Count number of errors found and return it
271 errors_found = 0
272 # First we'll go through the doc datastructures and flag any issues
273 for chk in self.enum_list:
274 doc_layer_found = False
275 for real_layer in layer_dict:
276 if chk in layer_dict[real_layer]['CHECKS']:
277 #print('Found actual layer check %s in doc' % (chk))
278 doc_layer_found = True
279 continue
280 if not doc_layer_found:
281 print(self.txt_color.red() + 'Actual layers do not contain documented check: %s' % (chk) + self.txt_color.endc())
282 errors_found += 1
283 # Now go through API names in doc and verify they're real
284 # First we're going to transform proto names from vulkan.py into single list
285 core_api_names = [p.name for p in vulkan.core.protos]
Jon Ashburn37155e32015-11-24 16:40:36 -0700286 wsi_s_names = [p.name for p in vulkan.ext_khr_surface.protos]
Ian Elliott338dedb2015-08-21 15:09:33 -0600287 wsi_ds_names = [p.name for p in vulkan.ext_khr_device_swapchain.protos]
David Pinedoa31fe0b2015-11-24 09:00:24 -0700288 dbg_rpt_names = [p.name for p in vulkan.lunarg_debug_report.protos]
289 dbg_mrk_names = [p.name for p in vulkan.lunarg_debug_marker.protos]
Tobin Ehlis236717c2015-08-31 12:42:38 -0600290 api_names = core_api_names + wsi_s_names + wsi_ds_names + dbg_rpt_names + dbg_mrk_names
291 for ln in self.layer_doc_dict:
292 for chk in self.layer_doc_dict[ln]:
293 if chk in ['overview', 'pending']:
294 continue
295 for api in self.layer_doc_dict[ln][chk]['api_list']:
296 if api[2:] not in api_names and api not in layer_extension_functions:
297 print(self.txt_color.red() + 'Doc references invalid function: %s' % (api) + self.txt_color.endc())
298 errors_found += 1
299 # Now go through all of the actual checks in the layers and make sure they're covered in the doc
300 for ln in layer_dict:
301 for chk in layer_dict[ln]['CHECKS']:
302 if chk not in self.enum_list:
303 print(self.txt_color.red() + 'Doc is missing check: %s' % (chk) + self.txt_color.endc())
304 errors_found += 1
305
306 return errors_found
307
308 # Print all of the checks captured in the doc
309 def print_checks(self):
310 print('Checks captured in doc:\n%s' % ('\n\t'.join(self.enum_list)))
311
312def main(argv=None):
313 # Parse args
314 opts = handle_args()
315 # Create parser for layer files
316 layer_parser = LayerParser(opts.in_headers, opts.in_source)
317 # Parse files into internal data structs
318 layer_parser.parse()
319
320 # Generate requested types of output
321 if opts.print_structs: # Print details of internal data structs
322 layer_parser.print_structs()
323
324 layer_doc = LayerDoc(opts.layer_doc)
325 layer_doc.parse()
326 if opts.print_doc_checks:
327 layer_doc.print_checks()
328
329 if opts.validate:
330 num_errors = layer_doc.validate(layer_parser.layer_dict)
331 if (0 == num_errors):
332 txt_color = bcolors()
333 print(txt_color.green() + 'No mismatches found between %s and implementation' % (os.path.basename(opts.layer_doc)) + txt_color.endc())
334 else:
335 return num_errors
336 return 0
337
338if __name__ == "__main__":
339 sys.exit(main())
340