1#! /usr/bin/env python3 2# This script generates the symbol.py source file. 3 4import sys 5import re 6 7def main(inFileName="Include/graminit.h", outFileName="Lib/symbol.py"): 8 try: 9 fp = open(inFileName) 10 except OSError as err: 11 sys.stderr.write("I/O error: %s\n" % str(err)) 12 sys.exit(1) 13 with fp: 14 lines = fp.read().split("\n") 15 prog = re.compile( 16 "#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)", 17 re.IGNORECASE) 18 tokens = {} 19 for line in lines: 20 match = prog.match(line) 21 if match: 22 name, val = match.group(1, 2) 23 val = int(val) 24 tokens[val] = name # reverse so we can sort them... 25 keys = sorted(tokens.keys()) 26 # load the output skeleton from the target: 27 try: 28 fp = open(outFileName) 29 except OSError as err: 30 sys.stderr.write("I/O error: %s\n" % str(err)) 31 sys.exit(2) 32 with fp: 33 format = fp.read().split("\n") 34 try: 35 start = format.index("#--start constants--") + 1 36 end = format.index("#--end constants--") 37 except ValueError: 38 sys.stderr.write("target does not contain format markers") 39 sys.exit(3) 40 lines = [] 41 for val in keys: 42 lines.append("%s = %d" % (tokens[val], val)) 43 format[start:end] = lines 44 try: 45 fp = open(outFileName, 'w') 46 except OSError as err: 47 sys.stderr.write("I/O error: %s\n" % str(err)) 48 sys.exit(4) 49 with fp: 50 fp.write("\n".join(format)) 51 52if __name__ == '__main__': 53 main(*sys.argv[1:]) 54