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 238 if section is None: 239 self.logMsg('error', 'Missing section in appendSection (probably a <type> element missing its \'category\' attribute. Text:', text) 240 exit(1) 241 242 self.sections[section].append(text) 243 self.feature_not_empty = True 244 245 def genType(self, typeinfo, name, alias): 246 "Generate type." 247 OutputGenerator.genType(self, typeinfo, name, alias) 248 typeElem = typeinfo.elem 249 250 # Vulkan: 251 # Determine the category of the type, and the type section to add 252 # its definition to. 253 # 'funcpointer' is added to the 'struct' section as a workaround for 254 # internal issue #877, since structures and function pointer types 255 # can have cross-dependencies. 256 category = typeElem.get('category') 257 if category == 'funcpointer': 258 section = 'struct' 259 else: 260 section = category 261 262 if category in ('struct', 'union'): 263 # If the type is a struct type, generate it using the 264 # special-purpose generator. 265 self.genStruct(typeinfo, name, alias) 266 else: 267 # OpenXR: this section was not under 'else:' previously, just fell through 268 if alias: 269 # If the type is an alias, just emit a typedef declaration 270 body = 'typedef ' + alias + ' ' + name + ';\n' 271 else: 272 # Replace <apientry /> tags with an APIENTRY-style string 273 # (from self.genOpts). Copy other text through unchanged. 274 # If the resulting text is an empty string, do not emit it. 275 body = noneStr(typeElem.text) 276 for elem in typeElem: 277 if elem.tag == 'apientry': 278 body += self.genOpts.apientry + noneStr(elem.tail) 279 else: 280 body += noneStr(elem.text) + noneStr(elem.tail) 281 if body: 282 # Add extra newline after multi-line entries. 283 if '\n' in body[0:-1]: 284 body += '\n' 285 self.appendSection(section, body) 286 287 def genProtectString(self, protect_str): 288 """Generate protection string. 289 290 Protection strings are the strings defining the OS/Platform/Graphics 291 requirements for a given OpenXR command. When generating the 292 language header files, we need to make sure the items specific to a 293 graphics API or OS platform are properly wrapped in #ifs.""" 294 protect_if_str = '' 295 protect_end_str = '' 296 if not protect_str: 297 return (protect_if_str, protect_end_str) 298 299 if ',' in protect_str: 300 protect_list = protect_str.split(",") 301 protect_defs = ('defined(%s)' % d for d in protect_list) 302 protect_def_str = ' && '.join(protect_defs) 303 protect_if_str = '#if %s\n' % protect_def_str 304 protect_end_str = '#endif // %s\n' % protect_def_str 305 else: 306 protect_if_str = '#ifdef %s\n' % protect_str 307 protect_end_str = '#endif // %s\n' % protect_str 308 309 return (protect_if_str, protect_end_str) 310 311 def typeMayAlias(self, typeName): 312 if not self.may_alias: 313 # First time we have asked if a type may alias. 314 # So, populate the set of all names of types that may. 315 316 # Everyone with an explicit mayalias="true" 317 self.may_alias = set(typeName 318 for typeName, data in self.registry.typedict.items() 319 if data.elem.get('mayalias') == 'true') 320 321 # Every type mentioned in some other type's parentstruct attribute. 322 parent_structs = (otherType.elem.get('parentstruct') 323 for otherType in self.registry.typedict.values()) 324 self.may_alias.update(set(x for x in parent_structs 325 if x is not None)) 326 return typeName in self.may_alias 327 328 def genStruct(self, typeinfo, typeName, alias): 329 """Generate struct (e.g. C "struct" type). 330 331 This is a special case of the <type> tag where the contents are 332 interpreted as a set of <member> tags instead of freeform C 333 C type declarations. The <member> tags are just like <param> 334 tags - they are a declaration of a struct or union member. 335 Only simple member declarations are supported (no nested 336 structs etc.) 337 338 If alias is not None, then this struct aliases another; just 339 generate a typedef of that alias.""" 340 OutputGenerator.genStruct(self, typeinfo, typeName, alias) 341 342 typeElem = typeinfo.elem 343 344 if alias: 345 body = 'typedef ' + alias + ' ' + typeName + ';\n' 346 else: 347 body = '' 348 (protect_begin, protect_end) = self.genProtectString(typeElem.get('protect')) 349 if protect_begin: 350 body += protect_begin 351 body += 'typedef ' + typeElem.get('category') 352 353 # This is an OpenXR-specific alternative where aliasing refers 354 # to an inheritance hierarchy of types rather than C-level type 355 # aliases. 356 if self.genOpts.genAliasMacro and self.typeMayAlias(typeName): 357 body += ' ' + self.genOpts.aliasMacro 358 359 body += ' ' + typeName + ' {\n' 360 361 targetLen = self.getMaxCParamTypeLength(typeinfo) 362 for member in typeElem.findall('.//member'): 363 body += self.makeCParamDecl(member, targetLen + 4) 364 body += ';\n' 365 body += '} ' + typeName + ';\n' 366 if protect_end: 367 body += protect_end 368 369 self.appendSection('struct', body) 370 371 def genGroup(self, groupinfo, groupName, alias=None): 372 """Generate groups (e.g. C "enum" type). 373 374 These are concatenated together with other types. 375 376 If alias is not None, it is the name of another group type 377 which aliases this type; just generate that alias.""" 378 OutputGenerator.genGroup(self, groupinfo, groupName, alias) 379 groupElem = groupinfo.elem 380 381 # After either enumerated type or alias paths, add the declaration 382 # to the appropriate section for the group being defined. 383 if groupElem.get('type') == 'bitmask': 384 section = 'bitmask' 385 else: 386 section = 'group' 387 388 if alias: 389 # If the group name is aliased, just emit a typedef declaration 390 # for the alias. 391 body = 'typedef ' + alias + ' ' + groupName + ';\n' 392 self.appendSection(section, body) 393 else: 394 (section, body) = self.buildEnumCDecl(self.genOpts.genEnumBeginEndRange, groupinfo, groupName) 395 self.appendSection(section, "\n" + body) 396 397 def genEnum(self, enuminfo, name, alias): 398 """Generate the C declaration for a constant (a single <enum> value).""" 399 400 OutputGenerator.genEnum(self, enuminfo, name, alias) 401 402 body = self.buildConstantCDecl(enuminfo, name, alias) 403 self.appendSection('enum', body) 404 405 def genCmd(self, cmdinfo, name, alias): 406 "Command generation" 407 OutputGenerator.genCmd(self, cmdinfo, name, alias) 408 409 # if alias: 410 # prefix = '// ' + name + ' is an alias of command ' + alias + '\n' 411 # else: 412 # prefix = '' 413 414 prefix = '' 415 decls = self.makeCDecls(cmdinfo.elem) 416 self.appendSection('command', prefix + decls[0] + '\n') 417 if self.genOpts.genFuncPointers: 418 self.appendSection('commandPointer', decls[1]) 419 420 def misracstyle(self): 421 return self.genOpts.misracstyle; 422 423 def misracppstyle(self): 424 return self.genOpts.misracppstyle; 425