summaryrefslogtreecommitdiffstats
path: root/Tools/scripts/generate_symbol_py.py
blob: 9219b096e4d67d5993e861e46cce2d7e7f1b318f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#! /usr/bin/env python3
# This script generates the symbol.py source file.

import sys
import re

def main(inFileName="Include/graminit.h", outFileName="Lib/symbol.py"):
    try:
        fp = open(inFileName)
    except OSError as err:
        sys.stderr.write("I/O error: %s\n" % str(err))
        sys.exit(1)
    with fp:
        lines = fp.read().split("\n")
    prog = re.compile(
        "#define[ \t][ \t]*([A-Z0-9][A-Z0-9_]*)[ \t][ \t]*([0-9][0-9]*)",
        re.IGNORECASE)
    tokens = {}
    for line in lines:
        match = prog.match(line)
        if match:
            name, val = match.group(1, 2)
            val = int(val)
            tokens[val] = name          # reverse so we can sort them...
    keys = sorted(tokens.keys())
    # load the output skeleton from the target:
    try:
        fp = open(outFileName)
    except OSError as err:
        sys.stderr.write("I/O error: %s\n" % str(err))
        sys.exit(2)
    with fp:
        format = fp.read().split("\n")
    try:
        start = format.index("#--start constants--") + 1
        end = format.index("#--end constants--")
    except ValueError:
        sys.stderr.write("target does not contain format markers")
        sys.exit(3)
    lines = []
    for val in keys:
        lines.append("%s = %d" % (tokens[val], val))
    format[start:end] = lines
    try:
        fp = open(outFileName, 'w')
    except OSError as err:
        sys.stderr.write("I/O error: %s\n" % str(err))
        sys.exit(4)
    with fp:
        fp.write("\n".join(format))

if __name__ == '__main__':
    main(*sys.argv[1:])