1#!/usr/bin/python3 -i 2# 3# Copyright 2013-2021 The Khronos Group Inc. 4# 5# SPDX-License-Identifier: Apache-2.0 6 7import os 8import re 9from generator import (GeneratorOptions, OutputGenerator, noneStr, 10 regSortFeatures, write) 11 12 13class CGeneratorOptions(GeneratorOptions): 14 """CGeneratorOptions - subclass of GeneratorOptions. 15 16 Adds options used by COutputGenerator objects during C language header 17 generation.""" 18 19 def __init__(self, 20 prefixText="", 21 genFuncPointers=True, 22 protectFile=True, 23 protectFeature=True, 24 protectProto=None, 25 protectProtoStr=None, 26 apicall='', 27 apientry='', 28 apientryp='', 29 indentFuncProto=True, 30 indentFuncPointer=False, 31 alignFuncParam=0, 32 genEnumBeginEndRange=False, 33 genAliasMacro=False, 34 aliasMacro='', 35 misracstyle=False, 36 misracppstyle=False, 37 **kwargs 38 ): 39 """Constructor. 40 Additional parameters beyond parent class: 41 42 - prefixText - list of strings to prefix generated header with 43 (usually a copyright statement + calling convention macros). 44 - protectFile - True if multiple inclusion protection should be 45 generated (based on the filename) around the entire header. 46 - protectFeature - True if #ifndef..#endif protection should be 47 generated around a feature interface in the header file. 48 - genFuncPointers - True if function pointer typedefs should be 49 generated 50 - protectProto - If conditional protection should be generated 51 around prototype declarations, set to either '#ifdef' 52 to require opt-in (#ifdef protectProtoStr) or '#ifndef' 53 to require opt-out (#ifndef protectProtoStr). Otherwise 54 set to None. 55 - protectProtoStr - #ifdef/#ifndef symbol to use around prototype 56 declarations, if protectProto is set 57 - apicall - string to use for the function declaration prefix, 58 such as APICALL on Windows. 59 - apientry - string to use for the calling convention macro, 60 in typedefs, such as APIENTRY. 61 - apientryp - string to use for the calling convention macro 62 in function pointer typedefs, such as APIENTRYP. 63 - indentFuncProto - True if prototype declarations should put each 64 parameter on a separate line 65 - indentFuncPointer - True if typedefed function pointers should put each 66 parameter on a separate line 67 - alignFuncParam - if nonzero and parameters are being put on a 68 separate line, align parameter names at the specified column 69 - genEnumBeginEndRange - True if BEGIN_RANGE / END_RANGE macros should 70 be generated for enumerated types 71 - genAliasMacro - True if the OpenXR alias macro should be generated 72 for aliased types (unclear what other circumstances this is useful) 73 - aliasMacro - alias macro to inject when genAliasMacro is True 74 - misracstyle - generate MISRA C-friendly headers 75 - misracppstyle - generate MISRA C++-friendly headers""" 76 77 GeneratorOptions.__init__(self, **kwargs) 78 79 self.prefixText = prefixText 80 """list of strings to prefix generated header with (usually a copyright statement + calling convention macros).""" 81 82 self.genFuncPointers = genFuncPointers 83 """True if function pointer typedefs should be generated""" 84 85 self.protectFile = protectFile 86 """True if multiple inclusion protection should be generated (based on the filename) around the entire header.""" 87 88 self.protectFeature = protectFeature 89 """True if #ifndef..#endif protection should be generated around a feature interface in the header file.""" 90 91 self.protectProto = protectProto 92 """If conditional protection should be generated around prototype declarations, set to either '#ifdef' to require opt-in (#ifdef protectProtoStr) or '#ifndef' to require opt-out (#ifndef protectProtoStr). Otherwise set to None.""" 93 94 self.protectProtoStr = protectProtoStr 95 """#ifdef/#ifndef symbol to use around prototype declarations, if protectProto is set""" 96 97 self.apicall = apicall 98 """string to use for the function declaration prefix, such as APICALL on Windows.""" 99 100 self.apientry = apientry 101 """string to use for the calling convention macro, in typedefs, such as APIENTRY.""" 102 103 self.apientryp = apientryp 104 """string to use for the calling convention macro in function pointer typedefs, such as APIENTRYP.""" 105 106 self.indentFuncProto = indentFuncProto 107 """True if prototype declarations should put each parameter on a separate line""" 108 109 self.indentFuncPointer = indentFuncPointer 110 """True if typedefed function pointers should put each parameter on a separate line""" 111 112 self.alignFuncParam = alignFuncParam 113 """if nonzero and parameters are being put on a separate line, align parameter names at the specified column""" 114 115 self.genEnumBeginEndRange = genEnumBeginEndRange 116 """True if BEGIN_RANGE / END_RANGE macros should be generated for enumerated types""" 117 118 self.genAliasMacro = genAliasMacro 119 """True if the OpenXR alias macro should be generated for aliased types (unclear what other circumstances this is useful)""" 120 121 self.aliasMacro = aliasMacro 122 """alias macro to inject when genAliasMacro is True""" 123 124 self.misracstyle = misracstyle 125 """generate MISRA C-friendly headers""" 126 127 self.misracppstyle = misracppstyle 128 """generate MISRA C++-friendly headers""" 129 130 self.codeGenerator = True 131 """True if this generator makes compilable code""" 132 133 134class COutputGenerator(OutputGenerator): 135 """Generates C-language API interfaces.""" 136 137 # This is an ordered list of sections in the header file. 138 TYPE_SECTIONS = ['include', 'define', 'basetype', 'handle', 'enum', 139 'group', 'bitmask', 'funcpointer', 'struct'] 140 ALL_SECTIONS = TYPE_SECTIONS + ['commandPointer', 'command'] 141 142 def __init__(self, *args, **kwargs): 143 super().__init__(*args, **kwargs) 144 # Internal state - accumulators for different inner block text 145 self.sections = {section: [] for section in self.ALL_SECTIONS} 146 self.feature_not_empty = False 147 self.may_alias = None 148 149 def beginFile(self, genOpts): 150 OutputGenerator.beginFile(self, genOpts) 151 # C-specific 152 # 153 # Multiple inclusion protection & C++ wrappers. 154 if genOpts.protectFile and self.genOpts.filename: 155 headerSym = re.sub(r'\.h', '_h_', 156 os.path.basename(self.genOpts.filename)).upper() 157 write('#ifndef', headerSym, file=self.outFile) 158 write('#define', headerSym, '1', file=self.outFile) 159 self.newline() 160 161 # User-supplied prefix text, if any (list of strings) 162 if genOpts.prefixText: 163 for s in genOpts.prefixText: 164 write(s, file=self.outFile) 165 166 # C++ extern wrapper - after prefix lines so they can add includes. 167 self.newline() 168 write('#ifdef __cplusplus', file=self.outFile) 169 write('extern "C" {', file=self.outFile) 170 write('#endif', file=self.outFile) 171 self.newline() 172 173 def endFile(self): 174 # C-specific 175 # Finish C++ wrapper and multiple inclusion protection 176 self.newline() 177 write('#ifdef __cplusplus', file=self.outFile) 178 write('}', file=self.outFile) 179 write('#endif', file=self.outFile) 180 if self.genOpts.protectFile and self.genOpts.filename: 181 self.newline() 182 write('#endif', file=self.outFile) 183 # Finish processing in superclass 184 OutputGenerator.endFile(self) 185 186 def beginFeature(self, interface, emit): 187 # Start processing in superclass 188 OutputGenerator.beginFeature(self, interface, emit) 189 # C-specific 190 # Accumulate includes, defines, types, enums, function pointer typedefs, 191 # end function prototypes separately for this feature. They are only 192 # printed in endFeature(). 193 self.sections = {section: [] for section in self.ALL_SECTIONS} 194 self.feature_not_empty = False 195 196 def endFeature(self): 197 "Actually write the interface to the output file." 198 # C-specific 199 if self.emit: 200 if self.feature_not_empty: 201 if self.genOpts.conventions.writeFeature(self.featureExtraProtect, self.genOpts.filename): 202 self.newline() 203 if self.genOpts.protectFeature: 204 write('#ifndef', self.featureName, file=self.outFile) 205 # If type declarations are needed by other features based on 206 # this one, it may be necessary to suppress the ExtraProtect, 207 # or move it below the 'for section...' loop. 208 if self.featureExtraProtect is not None: 209 write('#ifdef', self.featureExtraProtect, file=self.outFile) 210 self.newline() 211 write('#define', self.featureName, '1', file=self.outFile) 212 for section in self.TYPE_SECTIONS: 213 contents = self.sections[section] 214 if contents: 215 write('\n'.join(contents), file=self.outFile) 216 if self.genOpts.genFuncPointers and self.sections['commandPointer']: 217 write('\n'.join(self.sections['commandPointer']), file=self.outFile) 218 self.newline() 219 if self.sections['command']: 220 if self.genOpts.protectProto: 221 write(self.genOpts.protectProto, 222 self.genOpts.protectProtoStr, file=self.outFile) 223 write('\n'.join(self.sections['command']), end='', file=self.outFile) 224 if self.genOpts.protectProto: 225 write('#endif', file=self.outFile) 226 else: 227 self.newline() 228 if self.featureExtraProtect is not None: 229 write('#endif /*', self.featureExtraProtect, '*/', file=self.outFile) 230 if self.genOpts.protectFeature: 231 write('#endif /*', self.featureName, '*/', file=self.outFile) 232 # Finish processing in superclass 233 OutputGenerator.endFeature(self) 234 235 def appendSection(self, section, text): 236 "Append a definition to the specified section" 237 # self.sections[section].append('SECTION: ' + section + '\n') 238 self.sections[section].append(text) 239 self.feature_not_empty = True 240 241 def genType(self, typeinfo, name, alias): 242 "Generate type." 243 OutputGenerator.genType(self, typeinfo, name, alias) 244 typeElem = typeinfo.elem 245 246 # Vulkan: 247 # Determine the category of the type, and the type section to add 248 # its definition to. 249 # 'funcpointer' is added to the 'struct' section as a workaround for 250 # internal issue #877, since structures and function pointer types 251 # can have cross-dependencies. 252 category = typeElem.get('category') 253 if category == 'funcpointer': 254 section = 'struct' 255 else: 256 section = category 257 258 if category in ('struct', 'union'): 259 # If the type is a struct type, generate it using the 260 # special-purpose generator. 261 self.genStruct(typeinfo, name, alias) 262 else: 263 # OpenXR: this section was not under 'else:' previously, just fell through 264 if alias: 265 # If the type is an alias, just emit a typedef declaration 266 body = 'typedef ' + alias + ' ' + name + ';\n' 267 else: 268 # Replace <apientry /> tags with an APIENTRY-style string 269 # (from self.genOpts). Copy other text through unchanged. 270 # If the resulting text is an empty string, do not emit it. 271 body = noneStr(typeElem.text) 272 for elem in typeElem: 273 if elem.tag == 'apientry': 274 body += self.genOpts.apientry + noneStr(elem.tail) 275 else: 276 body += noneStr(elem.text) + noneStr(elem.tail) 277 if body: 278 # Add extra newline after multi-line entries. 279 if '\n' in body[0:-1]: 280 body += '\n' 281 self.appendSection(section, body) 282 283 def genProtectString(self, protect_str): 284 """Generate protection string. 285 286 Protection strings are the strings defining the OS/Platform/Graphics 287 requirements for a given OpenXR command. When generating the 288 language header files, we need to make sure the items specific to a 289 graphics API or OS platform are properly wrapped in #ifs.""" 290 protect_if_str = '' 291 protect_end_str = '' 292 if not protect_str: 293 return (protect_if_str, protect_end_str) 294 295 if ',' in protect_str: 296 protect_list = protect_str.split(",") 297 protect_defs = ('defined(%s)' % d for d in protect_list) 298 protect_def_str = ' && '.join(protect_defs) 299 protect_if_str = '#if %s\n' % protect_def_str 300 protect_end_str = '#endif // %s\n' % protect_def_str 301 else: 302 protect_if_str = '#ifdef %s\n' % protect_str 303 protect_end_str = '#endif // %s\n' % protect_str 304 305 return (protect_if_str, protect_end_str) 306 307 def typeMayAlias(self, typeName): 308 if not self.may_alias: 309 # First time we have asked if a type may alias. 310 # So, populate the set of all names of types that may. 311 312 # Everyone with an explicit mayalias="true" 313 self.may_alias = set(typeName 314 for typeName, data in self.registry.typedict.items() 315 if data.elem.get('mayalias') == 'true') 316 317 # Every type mentioned in some other type's parentstruct attribute. 318 parent_structs = (otherType.elem.get('parentstruct') 319 for otherType in self.registry.typedict.values()) 320 self.may_alias.update(set(x for x in parent_structs 321 if x is not None)) 322 return typeName in self.may_alias 323 324 def genStruct(self, typeinfo, typeName, alias): 325 """Generate struct (e.g. C "struct" type). 326 327 This is a special case of the <type> tag where the contents are 328 interpreted as a set of <member> tags instead of freeform C 329 C type declarations. The <member> tags are just like <param> 330 tags - they are a declaration of a struct or union member. 331 Only simple member declarations are supported (no nested 332 structs etc.) 333 334 If alias is not None, then this struct aliases another; just 335 generate a typedef of that alias.""" 336 OutputGenerator.genStruct(self, typeinfo, typeName, alias) 337 338 typeElem = typeinfo.elem 339 340 if alias: 341 body = 'typedef ' + alias + ' ' + typeName + ';\n' 342 else: 343 body = '' 344 (protect_begin, protect_end) = self.genProtectString(typeElem.get('protect')) 345 if protect_begin: 346 body += protect_begin 347 body += 'typedef ' + typeElem.get('category') 348 349 # This is an OpenXR-specific alternative where aliasing refers 350 # to an inheritance hierarchy of types rather than C-level type 351 # aliases. 352 if self.genOpts.genAliasMacro and self.typeMayAlias(typeName): 353 body += ' ' + self.genOpts.aliasMacro 354 355 body += ' ' + typeName + ' {\n' 356 357 targetLen = self.getMaxCParamTypeLength(typeinfo) 358 for member in typeElem.findall('.//member'): 359 body += self.makeCParamDecl(member, targetLen + 4) 360 body += ';\n' 361 body += '} ' + typeName + ';\n' 362 if protect_end: 363 body += protect_end 364 365 self.appendSection('struct', body) 366 367 def genGroup(self, groupinfo, groupName, alias=None): 368 """Generate groups (e.g. C "enum" type). 369 370 These are concatenated together with other types. 371 372 If alias is not None, it is the name of another group type 373 which aliases this type; just generate that alias.""" 374 OutputGenerator.genGroup(self, groupinfo, groupName, alias) 375 groupElem = groupinfo.elem 376 377 # After either enumerated type or alias paths, add the declaration 378 # to the appropriate section for the group being defined. 379 if groupElem.get('type') == 'bitmask': 380 section = 'bitmask' 381 else: 382 section = 'group' 383 384 if alias: 385 # If the group name is aliased, just emit a typedef declaration 386 # for the alias. 387 body = 'typedef ' + alias + ' ' + groupName + ';\n' 388 self.appendSection(section, body) 389 else: 390 (section, body) = self.buildEnumCDecl(self.genOpts.genEnumBeginEndRange, groupinfo, groupName) 391 self.appendSection(section, "\n" + body) 392 393 def genEnum(self, enuminfo, name, alias): 394 """Generate the C declaration for a constant (a single <enum> value).""" 395 396 OutputGenerator.genEnum(self, enuminfo, name, alias) 397 398 body = self.buildConstantCDecl(enuminfo, name, alias) 399 self.appendSection('enum', body) 400 401 def genCmd(self, cmdinfo, name, alias): 402 "Command generation" 403 OutputGenerator.genCmd(self, cmdinfo, name, alias) 404 405 # if alias: 406 # prefix = '// ' + name + ' is an alias of command ' + alias + '\n' 407 # else: 408 # prefix = '' 409 410 prefix = '' 411 decls = self.makeCDecls(cmdinfo.elem) 412 self.appendSection('command', prefix + decls[0] + '\n') 413 if self.genOpts.genFuncPointers: 414 self.appendSection('commandPointer', decls[1]) 415 416 def misracstyle(self): 417 return self.genOpts.misracstyle; 418 419 def misracppstyle(self): 420 return self.genOpts.misracppstyle; 421