blob: 48eba171c22579182ab40f27637400a2a3a730e5 [file] [log] [blame]
Tobin Ehlis236717c2015-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',},
76 }
77
78builtin_headers = [layer_inputs[ln]['header'] for ln in layer_inputs]
79builtin_source = [layer_inputs[ln]['source'] for ln in layer_inputs]
80
81# List of extensions in layers that are included in documentation, but not in vulkan.py API set
82layer_extension_functions = ['objTrackGetObjects', 'objTrackGetObjectsOfType']
83
84def handle_args():
85 parser = argparse.ArgumentParser(description='Generate layer documenation from source.')
86 parser.add_argument('--in_headers', required=False, default=builtin_headers, help='The input layer header files from which code will be generated.')
87 parser.add_argument('--in_source', required=False, default=builtin_source, help='The input layer source files from which code will be generated.')
88 parser.add_argument('--layer_doc', required=False, default='layers/vk_validation_layer_details.md', help='Existing layer document to be validated against actual layers.')
89 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.')
90 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.')
91 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.')
92 return parser.parse_args()
93
94# Little helper class for coloring cmd line output
95class bcolors:
96
97 def __init__(self):
98 self.GREEN = '\033[0;32m'
99 self.RED = '\033[0;31m'
100 self.ENDC = '\033[0m'
101 if 'Linux' != platform.system():
102 self.GREEN = ''
103 self.RED = ''
104 self.ENDC = ''
105
106 def green(self):
107 return self.GREEN
108
109 def red(self):
110 return self.RED
111
112 def endc(self):
113 return self.ENDC
114
115# Class to parse the layer source code and store details in internal data structs
116class LayerParser:
117 def __init__(self, header_file_list, source_file_list):
118 self.header_files = header_file_list
119 self.source_files = source_file_list
120 self.layer_dict = {}
121 self.api_dict = {}
122
123 # Parse layer header files into internal dict data structs
124 def parse(self):
125 # For each header file, parse details into dicts
126 # TODO : Should have a global dict element to track overall list of checks
127 store_enum = False
128 for hf in self.header_files:
129 layer_name = os.path.basename(hf).split('.')[0]
130 self.layer_dict[layer_name] = {} # initialize a new dict for this layer
131 self.layer_dict[layer_name]['CHECKS'] = [] # enum of checks is stored in a list
132 #print('Parsing header file %s as layer name %s' % (hf, layer_name))
133 with open(hf) as f:
134 for line in f:
135 if True in [line.strip().startswith(comment) for comment in ['//', '/*']]:
136 #print("Skipping comment line: %s" % line)
137 # For now skipping lines starting w/ comment, may use these to capture
138 # documentation in the future
139 continue
140
141 # Find enums
142 if store_enum:
143 if '}' in line: # we're done with enum definition
144 store_enum = False
145 continue
146 # grab the enum name as a unique check
147 if ',' in line:
148 # TODO : When documentation for a check is contained in the source,
149 # this is where we should also capture that documentation so that
150 # it can then be transformed into desired doc format
151 enum_name = line.split(',')[0].strip()
152 # Flag an error if we have already seen this enum
153 if enum_name in self.layer_dict[layer_name]['CHECKS']:
154 print('ERROR : % layer has duplicate error enum: %s' % (layer_name, enum_name))
155 self.layer_dict[layer_name]['CHECKS'].append(enum_name)
156 # If the line includes 'typedef', 'enum', and the expected enum name, start capturing enums
157 if False not in [ex in line for ex in ['typedef', 'enum', layer_inputs[layer_name]['error_enum']]]:
158 store_enum = True
159
160 # For each source file, parse into dicts
161 for sf in self.source_files:
162 #print('Parsing source file %s' % sf)
163 pass
164 # TODO : In the source file we want to see where checks actually occur
165 # Need to build function tree of checks so that we know all of the
166 # checks that occur under a top-level Vulkan API call
167 # Eventually in the validation we can flag ENUMs that aren't being
168 # used in the source, and we can document source code lines as well
169 # as Vulkan API calls where each specific ENUM check is made
170
171 def print_structs(self):
172 print('This is where I print the data structs')
173 for layer in self.layer_dict:
174 print('Layer %s has %i checks:\n%s' % (layer, len(self.layer_dict[layer]['CHECKS'])-1, "\n\t".join(self.layer_dict[layer]['CHECKS'])))
175
176# Class to parse hand-written md layer documentation into a dict and then validate its contents
177class LayerDoc:
178 def __init__(self, source_file):
179 self.layer_doc_filename = source_file
180 self.txt_color = bcolors()
181 # Main data struct to store info from layer doc
182 self.layer_doc_dict = {}
183 # Comprehensive list of all validation checks recorded in doc
184 self.enum_list = []
185
186 # Parse the contents of doc into data struct
187 def parse(self):
188 layer_name = 'INIT'
189 parse_layer_details = False
190 detail_trigger = '| Check | '
191 parse_pending_work = False
192 pending_trigger = ' Pending Work'
193 parse_overview = False
194 overview_trigger = ' Overview'
195 enum_prefix = ''
196
197 with open(self.layer_doc_filename) as f:
198 for line in f:
199 if parse_pending_work:
200 if '.' in line and line.strip()[0].isdigit():
201 todo_item = line.split('.')[1].strip()
202 self.layer_doc_dict[layer_name]['pending'].append(todo_item)
203 if pending_trigger in line and '##' in line:
204 parse_layer_details = False
205 parse_pending_work = True
206 parse_overview = False
207 self.layer_doc_dict[layer_name]['pending'] = []
208 if parse_layer_details:
209 # Grab details but skip the fomat line with a bunch of '-' chars
210 if '|' in line and line.count('-') < 20:
211 detail_sections = line.split('|')
212 #print("Details elements from line %s: %s" % (line, detail_sections))
213 check_name = '%s%s' % (enum_prefix, detail_sections[3].strip())
214 if '_NA' in check_name:
215 # TODO : Should clean up these NA checks in the doc, skipping them for now
216 continue
217 self.enum_list.append(check_name)
218 self.layer_doc_dict[layer_name][check_name] = {}
219 self.layer_doc_dict[layer_name][check_name]['summary_txt'] = detail_sections[1].strip()
220 self.layer_doc_dict[layer_name][check_name]['details_txt'] = detail_sections[2].strip()
221 self.layer_doc_dict[layer_name][check_name]['api_list'] = detail_sections[4].split()
222 self.layer_doc_dict[layer_name][check_name]['tests'] = detail_sections[5].split()
223 self.layer_doc_dict[layer_name][check_name]['notes'] = detail_sections[6].strip()
224 # strip any unwanted commas from api and test names
225 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']]
226 self.layer_doc_dict[layer_name][check_name]['tests'] = [a.strip(',') for a in self.layer_doc_dict[layer_name][check_name]['tests']]
227 # Trigger details parsing when we have table header
228 if detail_trigger in line:
229 parse_layer_details = True
230 parse_pending_work = False
231 parse_overview = False
232 enum_txt = line.split('|')[3]
233 if '*' in enum_txt:
234 enum_prefix = enum_txt.split()[-1].strip('*').strip()
235 #print('prefix: %s' % enum_prefix)
236 if parse_overview:
237 self.layer_doc_dict[layer_name]['overview'] += line
238 if overview_trigger in line and '##' in line:
239 parse_layer_details = False
240 parse_pending_work = False
241 parse_overview = True
242 layer_name = line.split()[1]
243 self.layer_doc_dict[layer_name] = {}
244 self.layer_doc_dict[layer_name]['overview'] = ''
245
246 # Verify that checks and api references in layer doc match reality
247 # Report API calls from doc that are not found in API
248 # Report checks from doc that are not in actual layers
249 # Report checks from layers that are not captured in doc
250 def validate(self, layer_dict):
251 # Count number of errors found and return it
252 errors_found = 0
253 # First we'll go through the doc datastructures and flag any issues
254 for chk in self.enum_list:
255 doc_layer_found = False
256 for real_layer in layer_dict:
257 if chk in layer_dict[real_layer]['CHECKS']:
258 #print('Found actual layer check %s in doc' % (chk))
259 doc_layer_found = True
260 continue
261 if not doc_layer_found:
262 print(self.txt_color.red() + 'Actual layers do not contain documented check: %s' % (chk) + self.txt_color.endc())
263 errors_found += 1
264 # Now go through API names in doc and verify they're real
265 # First we're going to transform proto names from vulkan.py into single list
266 core_api_names = [p.name for p in vulkan.core.protos]
Ian Elliott338dedb2015-08-21 15:09:33 -0600267 wsi_s_names = [p.name for p in vulkan.ext_khr_swapchain.protos]
268 wsi_ds_names = [p.name for p in vulkan.ext_khr_device_swapchain.protos]
Tobin Ehlis236717c2015-08-31 12:42:38 -0600269 dbg_rpt_names = [p.name for p in vulkan.debug_report_lunarg.protos]
270 dbg_mrk_names = [p.name for p in vulkan.debug_marker_lunarg.protos]
271 api_names = core_api_names + wsi_s_names + wsi_ds_names + dbg_rpt_names + dbg_mrk_names
272 for ln in self.layer_doc_dict:
273 for chk in self.layer_doc_dict[ln]:
274 if chk in ['overview', 'pending']:
275 continue
276 for api in self.layer_doc_dict[ln][chk]['api_list']:
277 if api[2:] not in api_names and api not in layer_extension_functions:
278 print(self.txt_color.red() + 'Doc references invalid function: %s' % (api) + self.txt_color.endc())
279 errors_found += 1
280 # Now go through all of the actual checks in the layers and make sure they're covered in the doc
281 for ln in layer_dict:
282 for chk in layer_dict[ln]['CHECKS']:
283 if chk not in self.enum_list:
284 print(self.txt_color.red() + 'Doc is missing check: %s' % (chk) + self.txt_color.endc())
285 errors_found += 1
286
287 return errors_found
288
289 # Print all of the checks captured in the doc
290 def print_checks(self):
291 print('Checks captured in doc:\n%s' % ('\n\t'.join(self.enum_list)))
292
293def main(argv=None):
294 # Parse args
295 opts = handle_args()
296 # Create parser for layer files
297 layer_parser = LayerParser(opts.in_headers, opts.in_source)
298 # Parse files into internal data structs
299 layer_parser.parse()
300
301 # Generate requested types of output
302 if opts.print_structs: # Print details of internal data structs
303 layer_parser.print_structs()
304
305 layer_doc = LayerDoc(opts.layer_doc)
306 layer_doc.parse()
307 if opts.print_doc_checks:
308 layer_doc.print_checks()
309
310 if opts.validate:
311 num_errors = layer_doc.validate(layer_parser.layer_dict)
312 if (0 == num_errors):
313 txt_color = bcolors()
314 print(txt_color.green() + 'No mismatches found between %s and implementation' % (os.path.basename(opts.layer_doc)) + txt_color.endc())
315 else:
316 return num_errors
317 return 0
318
319if __name__ == "__main__":
320 sys.exit(main())
321