blob: c0d00f843492406d8fda3ade842601bb915aa94a [file] [edit]
#!/usr/bin/env python3
#
# Copyright (c) 2026 Valve Corporation
# Copyright (c) 2026 LunarG, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Take the JSON with our settings and generates the other setting related files
# See docs/settings.md
import common_ci
import glob
import json
import os
import re
import subprocess
import sys
# We store the schema in VUL, which should be in some external folder somewhere
def FindSchema():
for pattern in ['*/Vulkan-Utility-Libraries/docs/layers_settings_schema.json',
'*/*/Vulkan-Utility-Libraries/docs/layers_settings_schema.json',
'*/*/*/Vulkan-Utility-Libraries/docs/layers_settings_schema.json']:
found = glob.glob(common_ci.RepoRelative(pattern))
if found:
return found[0]
return None
def LeafErrors(error):
if not error.context:
return [error]
branches = {}
for sub_error in error.context:
branches.setdefault(sub_error.schema_path[0], []).append(sub_error)
def WrongBranch(error):
return error.validator in ['enum', 'const'] and 'type' in error.absolute_schema_path
def Rank(branch):
return (any(WrongBranch(error) for error in branch), len(branch))
leaves = []
for sub_error in min(branches.values(), key=Rank):
leaves += LeafErrors(sub_error)
return leaves
def FormatPath(error):
path = ''
for part in error.absolute_path:
path += f'[{part}]' if isinstance(part, int) else f'.{part}'
return path if path else '<root>'
# json.load drops error positions, so build it
# Useful to be able to jump to error in an IDE
def FindLocation(text, path):
decoder = json.JSONDecoder()
separators = re.compile(r'[\s,:]*')
# Start of the value after the one at pos
def Next(pos):
return separators.match(text, decoder.raw_decode(text, pos)[1]).end()
pos = separators.match(text).end()
for part in path:
# Step into '{' or '['
pos = separators.match(text, pos + 1).end()
if isinstance(part, int):
for _ in range(part):
pos = Next(pos)
else:
# Step over key/value pairs, then over the matching key
while decoder.raw_decode(text, pos)[0] != part:
pos = Next(Next(pos))
pos = Next(pos)
return text.count('\n', 0, pos) + 1, pos - text.rfind('\n', 0, pos)
# Uncommitted git changes. No git or no repo (e.g. package builds) means unmodified
# "git status" fails outside a repo, "git diff" would wrongly report a change
def IsModified(*paths):
try:
result = subprocess.run(['git', 'status', '--porcelain', '--untracked-files=no', '--', *paths],
cwd=os.path.dirname(paths[0]), stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
except FileNotFoundError:
return False
return result.returncode == 0 and result.stdout != b''
# Keep the timestamp of identical files, otherwise every build recompiles layer_options.cpp and relinks
def WriteIfChanged(path, content):
with open(path, 'r') as file:
if file.read() == content:
return
with open(path, 'w') as file:
file.write(content)
def ValidateSchema(manifest, json_input):
try:
import jsonschema
except ImportError:
# Also reached when only this script changed, json.in then needs no validation
if not IsModified(json_input):
return
sys.exit(f'{json_input}: error: modified file but the python "jsonschema" module is not installed '
'to validate it (pip install jsonschema)')
schema_input = FindSchema()
if schema_input is None:
print('WARNING: layers_settings_schema.json was not found in the Vulkan-Utility-Libraries '
f'source, skipping validation of {os.path.basename(json_input)}')
return
with open(schema_input, 'r') as file:
schema = json.load(file)
# The layer name is still a configure_file placeholder here, but the schema requires the real prefixed form
manifest['layer']['name'] = 'VK_LAYER_KHRONOS_validation'
reported = []
for error in jsonschema.Draft7Validator(schema).iter_errors(manifest):
for leaf in LeafErrors(error):
entry = (FormatPath(leaf), leaf.message, list(leaf.absolute_path))
if entry not in reported:
reported.append(entry)
if not reported:
return
with open(json_input, 'r') as file:
text = file.read()
for path, message, parts in sorted(reported, key=lambda entry: FindLocation(text, entry[2])):
line, column = FindLocation(text, parts)
print(f'{json_input}({line},{column}): error: {path}: {message}', file=sys.stderr)
sys.exit(f'{len(reported)} error(s) validating against {schema_input}')
def IsDebugSetting(setting):
if setting['key'] == 'debug_action':
return False
return 'debug' in setting['key']
def GenerateTextFile(all_settings):
out = []
out.append(f'''# The settings in this file can be used to configure the behavior of layers in this repository.
# This file doesn't display the dependencies on the various settings
#
# This file is generated by {os.path.basename(__file__)}
# VK_LAYER_KHRONOS_validation
''')
for setting in all_settings:
if IsDebugSetting(setting):
continue
if 'view' in setting and setting['view'] == 'HIDDEN':
continue
default = setting['default']
type = setting['type']
if type == 'BOOL':
default = 'true' if setting['default'] is True else 'false'
if type == 'FLAGS' or type == 'LIST':
default = ','.join(default)
default = str(default)
if default:
default = " " + default
out.append(f'# {setting["label"]}')
out.append('# =====================')
out.append(f'# {setting["description"]}')
out.append(f'khronos_validation.{setting["key"]} ={default}\n')
WriteIfChanged(common_ci.RepoRelative('layers/vk_layer_settings.txt'), '\n'.join(out))
def GenerateValidation(all_settings):
out = []
out.append(f'''// *** THIS FILE IS GENERATED - DO NOT EDIT ***
// See {os.path.basename(__file__)} for modifications
/***************************************************************************
*
* Copyright (c) 2026 Valve Corporation
* Copyright (c) 2026 LunarG, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/''')
out.append('''
#pragma once
// clang-format off
// This function is generated from scripts/generate_settings.py
static void ValidateLayerSettingsProvided(const VkLayerSettingsCreateInfoEXT &layer_setting_create_info,
std::vector<std::string> &setting_warnings) {
// Found that a set of <const char*> doesn't detect duplicates on all compilers
vvl::unordered_set<std::string> used_settings;
for (uint32_t i = 0; i < layer_setting_create_info.settingCount; i++) {
const VkLayerSettingEXT &setting = layer_setting_create_info.pSettings[i];
if (strcmp(OBJECT_LAYER_NAME, setting.pLayerName) != 0) {
continue;
}
// used as a backup for settings not listed below
VkLayerSettingTypeEXT required_type = VK_LAYER_SETTING_TYPE_MAX_ENUM_EXT;
// Debugging settings are not added here as those are for internal development
// and not designed for an app to use via VkLayerSettings API
const char* name = setting.pSettingName;
if (strcmp(VK_LAYER_ENABLES, name) == 0) { required_type = VK_LAYER_SETTING_TYPE_STRING_EXT; }
else if (strcmp(VK_LAYER_DISABLES, name) == 0) { required_type = VK_LAYER_SETTING_TYPE_STRING_EXT; }''')
for setting in all_settings:
type = setting['type']
layer_type = None
if type == 'BOOL':
layer_type = 'VK_LAYER_SETTING_TYPE_BOOL32_EXT'
elif type == 'INT':
layer_type = 'VK_LAYER_SETTING_TYPE_UINT32_EXT'
elif type in ['SAVE_FILE', 'LIST', 'FLAGS', 'LOAD_FILE', 'ENUM']:
layer_type = 'VK_LAYER_SETTING_TYPE_STRING_EXT'
else:
print(f'Warning, not type handled for {type} ({setting["key"]})')
continue
out.append(f' else if (strcmp(VK_LAYER_{setting["key"].upper()}, name) == 0) {{ required_type = {layer_type}; }}')
out.append(''' else {
setting_warnings.emplace_back("The setting \\"" + std::string(name) +
"\\" in VkLayerSettingsCreateInfoEXT was not recognized by the Validation Layers. Please "
"view the VkLayer_khronos_validation.json for a list of all settings.");
}
if (required_type != VK_LAYER_SETTING_TYPE_MAX_ENUM_EXT && setting.type != required_type) {
setting_warnings.emplace_back(
"The setting \\"" + std::string(name) + "\\" in VkLayerSettingsCreateInfoEXT was set to type " +
std::string(string_VkLayerSettingTypeEXT(setting.type)) + " but requires type " +
std::string(string_VkLayerSettingTypeEXT(required_type)) + " and the value may be parsed incorrectly.");
}
if (used_settings.count(name)) {
setting_warnings.emplace_back(
"The setting \\"" + std::string(name) +
"\\" in VkLayerSettingsCreateInfoEXT was listed twice and only the first one listed will be recognized.");
}
used_settings.insert(name);
}
}
// clang-format on
''')
WriteIfChanged(common_ci.RepoRelative('layers/layer_options_validation.h'), '\n'.join(out))
if __name__ == '__main__':
json_input = common_ci.RepoRelative('layers/VkLayer_khronos_validation.json.in')
# Checked-in outputs already match the committed inputs. Package builds stop here: no write to their
# read-only source tree, no jsonschema needed
if not IsModified(json_input, os.path.abspath(__file__)):
sys.exit(0)
with open(json_input, 'r') as file:
try:
manifest = json.load(file)
except json.JSONDecodeError as error:
# Same "file(line): error:" format as compilers, so IDEs can jump to it
sys.exit(f'{json_input}({error.lineno},{error.colno}): error: {error.msg}')
json_settings = manifest['layer']['features']['settings']
ValidateSchema(manifest, json_input)
# Build up the list all at once into a flat list
all_settings = []
def Parse(setting):
type = setting['type']
if type == 'GROUP':
for s in setting['settings']:
Parse(s)
return
if type == 'FLAGS':
for flags in setting['flags']:
if 'settings' in flags:
for s in flags['settings']:
Parse(s)
if 'settings' in setting:
for s in setting['settings']:
Parse(s)
all_settings.append(setting)
for setting in json_settings:
Parse(setting)
# Same on all OS (and easy to find setting in large generated list)
all_settings = sorted(all_settings, key=lambda obj: obj['key'])
GenerateTextFile(all_settings)
GenerateValidation(all_settings)