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