generate_vim_syntax.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #!/usr/bin/env python
  2. # Copyright (c) 2016 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 Vim syntax rules for SPIR-V assembly (.spvasm) files"""
  15. from __future__ import print_function
  16. import json
  17. PREAMBLE="""" Vim syntax file
  18. " Language: spvasm
  19. " Generated by SPIRV-Tools
  20. if version < 600
  21. syntax clear
  22. elseif exists("b:current_syntax")
  23. finish
  24. endif
  25. syn case match
  26. """
  27. POSTAMBLE="""
  28. syntax keyword spvasmTodo TODO FIXME contained
  29. syn match spvasmIdNumber /%\d\+\>/
  30. " The assembler treats the leading minus sign as part of the number token.
  31. " This applies to integers, and to floats below.
  32. syn match spvasmNumber /-\?\<\d\+\>/
  33. " Floating point literals.
  34. " In general, C++ requires at least digit in the mantissa, and the
  35. " floating point is optional. This applies to both the regular decimal float
  36. " case and the hex float case.
  37. " First case: digits before the optional decimal, no trailing digits.
  38. syn match spvasmFloat /-\?\d\+\.\?\(e[+-]\d\+\)\?/
  39. " Second case: optional digits before decimal, trailing digits
  40. syn match spvasmFloat /-\?\d*\.\d\+\(e[+-]\d\+\)\?/
  41. " First case: hex digits before the optional decimal, no trailing hex digits.
  42. syn match spvasmFloat /-\?0[xX]\\x\+\.\?p[-+]\d\+/
  43. " Second case: optional hex digits before decimal, trailing hex digits
  44. syn match spvasmFloat /-\?0[xX]\\x*\.\\x\+p[-+]\d\+/
  45. syn match spvasmComment /;.*$/ contains=spvasmTodo
  46. syn region spvasmString start=/"/ skip=/\\\\"/ end=/"/
  47. syn match spvasmId /%[a-zA-Z_][a-zA-Z_0-9]*/
  48. " Highlight unknown constants and statements as errors
  49. syn match spvasmError /[a-zA-Z][a-zA-Z_0-9]*/
  50. if version >= 508 || !exists("did_c_syn_inits")
  51. if version < 508
  52. let did_c_syn_inits = 1
  53. command -nargs=+ HiLink hi link <args>
  54. else
  55. command -nargs=+ HiLink hi def link <args>
  56. endif
  57. HiLink spvasmStatement Statement
  58. HiLink spvasmNumber Number
  59. HiLink spvasmComment Comment
  60. HiLink spvasmString String
  61. HiLink spvasmFloat Float
  62. HiLink spvasmConstant Constant
  63. HiLink spvasmIdNumber Identifier
  64. HiLink spvasmId Identifier
  65. HiLink spvasmTodo Todo
  66. delcommand HiLink
  67. endif
  68. let b:current_syntax = "spvasm"
  69. """
  70. # This list is taken from the description of OpSpecConstantOp in SPIR-V 1.1.
  71. # TODO(dneto): Propose that this information be embedded in the grammar file.
  72. SPEC_CONSTANT_OP_OPCODES = """
  73. OpSConvert, OpFConvert
  74. OpSNegate, OpNot
  75. OpIAdd, OpISub
  76. OpIMul, OpUDiv, OpSDiv, OpUMod, OpSRem, OpSMod
  77. OpShiftRightLogical, OpShiftRightArithmetic, OpShiftLeftLogical
  78. OpBitwiseOr, OpBitwiseXor, OpBitwiseAnd
  79. OpVectorShuffle, OpCompositeExtract, OpCompositeInsert
  80. OpLogicalOr, OpLogicalAnd, OpLogicalNot,
  81. OpLogicalEqual, OpLogicalNotEqual
  82. OpSelect
  83. OpIEqual, OpINotEqual
  84. OpULessThan, OpSLessThan
  85. OpUGreaterThan, OpSGreaterThan
  86. OpULessThanEqual, OpSLessThanEqual
  87. OpUGreaterThanEqual, OpSGreaterThanEqual
  88. OpQuantizeToF16
  89. OpConvertFToS, OpConvertSToF
  90. OpConvertFToU, OpConvertUToF
  91. OpUConvert
  92. OpConvertPtrToU, OpConvertUToPtr
  93. OpGenericCastToPtr, OpPtrCastToGeneric
  94. OpBitcast
  95. OpFNegate
  96. OpFAdd, OpFSub
  97. OpFMul, OpFDiv
  98. OpFRem, OpFMod
  99. OpAccessChain, OpInBoundsAccessChain
  100. OpPtrAccessChain, OpInBoundsPtrAccessChain"""
  101. def EmitAsStatement(name):
  102. """Emits the given name as a statement token"""
  103. print('syn keyword spvasmStatement', name)
  104. def EmitAsEnumerant(name):
  105. """Emits the given name as an named operand token"""
  106. print('syn keyword spvasmConstant', name)
  107. def main():
  108. """Parses arguments, then generates the Vim syntax rules for SPIR-V assembly
  109. on stdout."""
  110. import argparse
  111. parser = argparse.ArgumentParser(description='Generate SPIR-V info tables')
  112. parser.add_argument('--spirv-core-grammar', metavar='<path>',
  113. type=str, required=True,
  114. help='input JSON grammar file for core SPIR-V '
  115. 'instructions')
  116. parser.add_argument('--extinst-glsl-grammar', metavar='<path>',
  117. type=str, required=False, default=None,
  118. help='input JSON grammar file for GLSL extended '
  119. 'instruction set')
  120. parser.add_argument('--extinst-opencl-grammar', metavar='<path>',
  121. type=str, required=False, default=None,
  122. help='input JSON grammar file for OpenGL extended '
  123. 'instruction set')
  124. parser.add_argument('--extinst-debuginfo-grammar', metavar='<path>',
  125. type=str, required=False, default=None,
  126. help='input JSON grammar file for DebugInfo extended '
  127. 'instruction set')
  128. args = parser.parse_args()
  129. # Generate the syntax rules.
  130. print(PREAMBLE)
  131. core = json.loads(open(args.spirv_core_grammar).read())
  132. print('\n" Core instructions')
  133. for inst in core["instructions"]:
  134. EmitAsStatement(inst['opname'])
  135. print('\n" Core operand enums')
  136. for operand_kind in core["operand_kinds"]:
  137. if 'enumerants' in operand_kind:
  138. for e in operand_kind['enumerants']:
  139. EmitAsEnumerant(e['enumerant'])
  140. if args.extinst_glsl_grammar is not None:
  141. print('\n" GLSL.std.450 extended instructions')
  142. glsl = json.loads(open(args.extinst_glsl_grammar).read())
  143. # These opcodes are really enumerant operands for the OpExtInst
  144. # instruction.
  145. for inst in glsl["instructions"]:
  146. EmitAsEnumerant(inst['opname'])
  147. if args.extinst_opencl_grammar is not None:
  148. print('\n" OpenCL.std extended instructions')
  149. opencl = json.loads(open(args.extinst_opencl_grammar).read())
  150. for inst in opencl["instructions"]:
  151. EmitAsEnumerant(inst['opname'])
  152. if args.extinst_debuginfo_grammar is not None:
  153. print('\n" DebugInfo extended instructions')
  154. debuginfo = json.loads(open(args.extinst_debuginfo_grammar).read())
  155. for inst in debuginfo["instructions"]:
  156. EmitAsEnumerant(inst['opname'])
  157. print('\n" DebugInfo operand enums')
  158. for operand_kind in debuginfo["operand_kinds"]:
  159. if 'enumerants' in operand_kind:
  160. for e in operand_kind['enumerants']:
  161. EmitAsEnumerant(e['enumerant'])
  162. print('\n" OpSpecConstantOp opcodes')
  163. for word in SPEC_CONSTANT_OP_OPCODES.split(' '):
  164. stripped = word.strip('\n,')
  165. if stripped != "":
  166. # Treat as an enumerant, but without the leading "Op"
  167. EmitAsEnumerant(stripped[2:])
  168. print(POSTAMBLE)
  169. if __name__ == '__main__':
  170. main()