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