generate_language_headers.py 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. #!/usr/bin/env python
  2. # Copyright (c) 2017 Google Inc.
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Generates language headers from a JSON grammar file"""
  15. from __future__ import print_function
  16. import errno
  17. import json
  18. import os.path
  19. import re
  20. def make_path_to_file(f):
  21. """Makes all ancestor directories to the given file, if they
  22. don't yet exist.
  23. Arguments:
  24. f: The file whose ancestor directories are to be created.
  25. """
  26. dir = os.path.dirname(os.path.abspath(f))
  27. try:
  28. os.makedirs(dir)
  29. except OSError as e:
  30. if e.errno == errno.EEXIST and os.path.isdir(dir):
  31. pass
  32. else:
  33. raise
  34. class ExtInstGrammar:
  35. """The grammar for an extended instruction set"""
  36. def __init__(self, name, copyright, instructions, operand_kinds, version = None, revision = None):
  37. self.name = name
  38. self.copyright = copyright
  39. self.instructions = instructions
  40. self.operand_kinds = operand_kinds
  41. self.version = version
  42. self.revision = revision
  43. class LangGenerator:
  44. """A language-specific generator"""
  45. def __init__(self):
  46. self.upper_case_initial = re.compile('^[A-Z]')
  47. pass
  48. def comment_prefix(self):
  49. return ""
  50. def namespace_prefix(self):
  51. return ""
  52. def uses_guards(self):
  53. return False
  54. def cpp_guard_preamble(self):
  55. return ""
  56. def cpp_guard_postamble(self):
  57. return ""
  58. def enum_value(self, prefix, name, value):
  59. if self.upper_case_initial.match(name):
  60. use_name = name
  61. else:
  62. use_name = '_' + name
  63. return " {}{} = {},".format(prefix, use_name, value)
  64. def generate(self, grammar):
  65. """Returns a string that is the language-specific header for the given grammar"""
  66. parts = []
  67. if grammar.copyright:
  68. parts.extend(["{}{}".format(self.comment_prefix(), f) for f in grammar.copyright])
  69. parts.append('')
  70. guard = 'SPIRV_EXTINST_{}_H_'.format(grammar.name)
  71. if self.uses_guards:
  72. parts.append('#ifndef {}'.format(guard))
  73. parts.append('#define {}'.format(guard))
  74. parts.append('')
  75. parts.append(self.cpp_guard_preamble())
  76. if grammar.version:
  77. parts.append(self.const_definition(grammar.name, 'Version', grammar.version))
  78. if grammar.revision is not None:
  79. parts.append(self.const_definition(grammar.name, 'Revision', grammar.revision))
  80. parts.append('')
  81. if grammar.instructions:
  82. parts.append(self.enum_prefix(grammar.name, 'Instructions'))
  83. for inst in grammar.instructions:
  84. parts.append(self.enum_value(grammar.name, inst['opname'], inst['opcode']))
  85. parts.append(self.enum_end(grammar.name, 'Instructions'))
  86. parts.append('')
  87. if grammar.operand_kinds:
  88. for kind in grammar.operand_kinds:
  89. parts.append(self.enum_prefix(grammar.name, kind['kind']))
  90. for e in kind['enumerants']:
  91. parts.append(self.enum_value(grammar.name, e['enumerant'], e['value']))
  92. parts.append(self.enum_end(grammar.name, kind['kind']))
  93. parts.append('')
  94. parts.append(self.cpp_guard_postamble())
  95. if self.uses_guards:
  96. parts.append('#endif // {}'.format(guard))
  97. return '\n'.join(parts)
  98. class CLikeGenerator(LangGenerator):
  99. def uses_guards(self):
  100. return True
  101. def comment_prefix(self):
  102. return "// "
  103. def const_definition(self, prefix, var, value):
  104. # Use an anonymous enum. Don't use a static const int variable because
  105. # that can bloat binary size.
  106. return 'enum {0} {1}{2} = {3}, {1}{2}_BitWidthPadding = 0x7fffffff {4};'.format(
  107. '{', prefix, var, value, '}')
  108. def enum_prefix(self, prefix, name):
  109. return 'enum {}{} {}'.format(prefix, name, '{')
  110. def enum_end(self, prefix, enum):
  111. return ' {}{}Max = 0x7ffffff\n{};\n'.format(prefix, enum, '}')
  112. def cpp_guard_preamble(self):
  113. return '#ifdef __cplusplus\nextern "C" {\n#endif\n'
  114. def cpp_guard_postamble(self):
  115. return '#ifdef __cplusplus\n}\n#endif\n'
  116. class CGenerator(CLikeGenerator):
  117. pass
  118. def main():
  119. import argparse
  120. parser = argparse.ArgumentParser(description='Generate language headers from a JSON grammar')
  121. parser.add_argument('--extinst-name',
  122. type=str, required=True,
  123. help='The name to use in tokens')
  124. parser.add_argument('--extinst-grammar', metavar='<path>',
  125. type=str, required=True,
  126. help='input JSON grammar file for extended instruction set')
  127. parser.add_argument('--extinst-output-base', metavar='<path>',
  128. type=str, required=True,
  129. help='Basename of the language-specific output file.')
  130. args = parser.parse_args()
  131. with open(args.extinst_grammar) as json_file:
  132. grammar_json = json.loads(json_file.read())
  133. grammar = ExtInstGrammar(name = args.extinst_name,
  134. copyright = grammar_json['copyright'],
  135. instructions = grammar_json['instructions'],
  136. operand_kinds = grammar_json['operand_kinds'],
  137. version = grammar_json['version'],
  138. revision = grammar_json['revision'])
  139. make_path_to_file(args.extinst_output_base)
  140. print(CGenerator().generate(grammar), file=open(args.extinst_output_base + '.h', 'w'))
  141. if __name__ == '__main__':
  142. main()