• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python3 -i
2#
3# Copyright 2013-2022 The Khronos Group Inc.
4#
5# SPDX-License-Identifier: Apache-2.0
6
7# Working-group-specific style conventions,
8# used in generation.
9
10import re
11import os
12
13from spec_tools.conventions import ConventionsBase
14
15# Modified from default implementation - see category_requires_validation() below
16CATEGORIES_REQUIRING_VALIDATION = set(('handle', 'enum', 'bitmask'))
17
18# Tokenize into "words" for structure types, approximately per spec "Implicit Valid Usage" section 2.7.2
19# This first set is for things we recognize explicitly as words,
20# as exceptions to the general regex.
21# Ideally these would be listed in the spec as exceptions, as OpenXR does.
22SPECIAL_WORDS = set((
23    '16Bit',  # VkPhysicalDevice16BitStorageFeatures
24    '2D',     # VkPhysicalDeviceImage2DViewOf3DFeaturesEXT
25    '3D',     # VkPhysicalDeviceImage2DViewOf3DFeaturesEXT
26    '8Bit',  # VkPhysicalDevice8BitStorageFeaturesKHR
27    'AABB',  # VkGeometryAABBNV
28    'ASTC',  # VkPhysicalDeviceTextureCompressionASTCHDRFeaturesEXT
29    'D3D12',  # VkD3D12FenceSubmitInfoKHR
30    'Float16',  # VkPhysicalDeviceShaderFloat16Int8FeaturesKHR
31    'ImagePipe',  # VkImagePipeSurfaceCreateInfoFUCHSIA
32    'Int64',  # VkPhysicalDeviceShaderAtomicInt64FeaturesKHR
33    'Int8',  # VkPhysicalDeviceShaderFloat16Int8FeaturesKHR
34    'MacOS',  # VkMacOSSurfaceCreateInfoMVK
35    'RGBA10X6', # VkPhysicalDeviceRGBA10X6FormatsFeaturesEXT
36    'Uint8',  # VkPhysicalDeviceIndexTypeUint8FeaturesEXT
37    'Win32',  # VkWin32SurfaceCreateInfoKHR
38))
39# A regex to match any of the SPECIAL_WORDS
40EXCEPTION_PATTERN = r'(?P<exception>{})'.format(
41    '|'.join('(%s)' % re.escape(w) for w in SPECIAL_WORDS))
42MAIN_RE = re.compile(
43    # the negative lookahead is to prevent the all-caps pattern from being too greedy.
44    r'({}|([0-9]+)|([A-Z][a-z]+)|([A-Z][A-Z]*(?![a-z])))'.format(EXCEPTION_PATTERN))
45
46
47class VulkanConventions(ConventionsBase):
48    @property
49    def null(self):
50        """Preferred spelling of NULL."""
51        return '`NULL`'
52
53    def formatExtension(self, name):
54        """Mark up an extension name as a link the spec."""
55        return '`apiext:{}`'.format(name)
56
57    @property
58    def struct_macro(self):
59        """Get the appropriate format macro for a structure.
60
61        Primarily affects generated valid usage statements.
62        """
63
64        return 'slink:'
65
66    @property
67    def constFlagBits(self):
68        """Returns True if static const flag bits should be generated, False if an enumerated type should be generated."""
69        return False
70
71    @property
72    def structtype_member_name(self):
73        """Return name of the structure type member"""
74        return 'sType'
75
76    @property
77    def nextpointer_member_name(self):
78        """Return name of the structure pointer chain member"""
79        return 'pNext'
80
81    @property
82    def valid_pointer_prefix(self):
83        """Return prefix to pointers which must themselves be valid"""
84        return 'valid'
85
86    def is_structure_type_member(self, paramtype, paramname):
87        """Determine if member type and name match the structure type member."""
88        return paramtype == 'VkStructureType' and paramname == self.structtype_member_name
89
90    def is_nextpointer_member(self, paramtype, paramname):
91        """Determine if member type and name match the next pointer chain member."""
92        return paramtype == 'void' and paramname == self.nextpointer_member_name
93
94    def generate_structure_type_from_name(self, structname):
95        """Generate a structure type name, like VK_STRUCTURE_TYPE_CREATE_INSTANCE_INFO"""
96
97        structure_type_parts = []
98        # Tokenize into "words"
99        for elem in MAIN_RE.findall(structname):
100            word = elem[0]
101            if word == 'Vk':
102                structure_type_parts.append('VK_STRUCTURE_TYPE')
103            else:
104                structure_type_parts.append(word.upper())
105        name = '_'.join(structure_type_parts)
106
107        # The simple-minded rules need modification for some structure names
108        subpats = [
109            [ r'_H_(26[45])_',              r'_H\1_' ],
110            [ r'_VULKAN_([0-9])([0-9])_',   r'_VULKAN_\1_\2_' ],
111            [ r'_DIRECT_FB_',               r'_DIRECTFB_' ],
112        ]
113
114        for subpat in subpats:
115            name = re.sub(subpat[0], subpat[1], name)
116        return name
117
118    @property
119    def warning_comment(self):
120        """Return warning comment to be placed in header of generated Asciidoctor files"""
121        return '// WARNING: DO NOT MODIFY! This file is automatically generated from the vk.xml registry'
122
123    @property
124    def file_suffix(self):
125        """Return suffix of generated Asciidoctor files"""
126        return '.adoc'
127
128    def api_name(self, spectype='api'):
129        """Return API or specification name for citations in ref pages.ref
130           pages should link to for
131
132           spectype is the spec this refpage is for: 'api' is the Vulkan API
133           Specification. Defaults to 'api'. If an unrecognized spectype is
134           given, returns None.
135        """
136        if spectype == 'api' or spectype is None:
137            return 'Vulkan'
138        else:
139            return None
140
141    @property
142    def api_prefix(self):
143        """Return API token prefix"""
144        return 'VK_'
145
146    @property
147    def write_contacts(self):
148        """Return whether contact list should be written to extension appendices"""
149        return True
150
151    @property
152    def write_refpage_include(self):
153        """Return whether refpage include should be written to extension appendices"""
154        return True
155
156    @property
157    def member_used_for_unique_vuid(self):
158        """Return the member name used in the VUID-...-...-unique ID."""
159        return self.structtype_member_name
160
161    def is_externsync_command(self, protoname):
162        """Returns True if the protoname element is an API command requiring
163           external synchronization
164        """
165        return protoname is not None and 'vkCmd' in protoname
166
167    def is_api_name(self, name):
168        """Returns True if name is in the reserved API namespace.
169        For Vulkan, these are names with a case-insensitive 'vk' prefix, or
170        a 'PFN_vk' function pointer type prefix.
171        """
172        return name[0:2].lower() == 'vk' or name[0:6] == 'PFN_vk'
173
174    def specURL(self, spectype='api'):
175        """Return public registry URL which ref pages should link to for the
176           current all-extensions HTML specification, so xrefs in the
177           asciidoc source that are not to ref pages can link into it
178           instead. N.b. this may need to change on a per-refpage basis if
179           there are multiple documents involved.
180        """
181        return 'https://registry.khronos.org/vulkan/specs/1.3-extensions/html/vkspec.html'
182
183    @property
184    def xml_api_name(self):
185        """Return the name used in the default API XML registry for the default API"""
186        return 'vulkan'
187
188    @property
189    def registry_path(self):
190        """Return relpath to the default API XML registry in this project."""
191        return 'xml/vk.xml'
192
193    @property
194    def specification_path(self):
195        """Return relpath to the Asciidoctor specification sources in this project."""
196        return '{generated}/meta'
197
198    @property
199    def special_use_section_anchor(self):
200        """Return asciidoctor anchor name in the API Specification of the
201        section describing extension special uses in detail."""
202        return 'extendingvulkan-compatibility-specialuse'
203
204    @property
205    def extension_index_prefixes(self):
206        """Return a list of extension prefixes used to group extension refpages."""
207        return ['VK_KHR', 'VK_EXT', 'VK']
208
209    @property
210    def unified_flag_refpages(self):
211        """Return True if Flags/FlagBits refpages are unified, False if
212           they are separate.
213        """
214        return False
215
216    @property
217    def spec_reflow_path(self):
218        """Return the path to the spec source folder to reflow"""
219        return os.getcwd()
220
221    @property
222    def spec_no_reflow_dirs(self):
223        """Return a set of directories not to automatically descend into
224           when reflowing spec text
225        """
226        return ('scripts', 'style')
227
228    @property
229    def zero(self):
230        return '`0`'
231
232    def category_requires_validation(self, category):
233        """Return True if the given type 'category' always requires validation.
234
235        Overridden because Vulkan does not require "valid" text for basetype
236        in the spec right now."""
237        return category in CATEGORIES_REQUIRING_VALIDATION
238
239    @property
240    def should_skip_checking_codes(self):
241        """Return True if more than the basic validation of return codes should
242        be skipped for a command.
243
244        Vulkan mostly relies on the validation layers rather than API
245        builtin error checking, so these checks are not appropriate.
246
247        For example, passing in a VkFormat parameter will not potentially
248        generate a VK_ERROR_FORMAT_NOT_SUPPORTED code."""
249
250        return True
251
252    def extension_file_path(self, name):
253        """Return file path to an extension appendix relative to a directory
254           containing all such appendices.
255           - name - extension name"""
256
257        return f'{name}{self.file_suffix}'
258
259    def valid_flag_bit(self, bitpos):
260        """Return True if bitpos is an allowed numeric bit position for
261           an API flag bit.
262
263           Vulkan uses 32 bit Vk*Flags types, and assumes C compilers may
264           cause Vk*FlagBits values with bit 31 set to result in a 64 bit
265           enumerated type, so disallows such flags."""
266        return bitpos >= 0 and bitpos < 31
267
268    @property
269    def extra_refpage_headers(self):
270        """Return any extra text to add to refpage headers."""
271        return 'include::{config}/attribs.adoc[]'
272
273    @property
274    def extra_refpage_body(self):
275        """Return any extra text (following the title) for generated
276           reference pages."""
277        return 'include::{generated}/specattribs.adoc[]'
278