makeqstrdata.py 3.73 KB
Newer Older
1
2
3
4
5
6
"""
Process raw qstr file and output qstr data with length, hash and data bytes.

This script works with Python 2.6, 2.7, 3.3 and 3.4.
"""

7
8
from __future__ import print_function

9
import re
10
import sys
11
12
13
14
15
16
17

# codepoint2name is different in Python 2 to Python 3
import platform
if platform.python_version_tuple()[0] == '2':
    from htmlentitydefs import codepoint2name
elif platform.python_version_tuple()[0] == '3':
    from html.entities import codepoint2name
18
codepoint2name[ord('-')] = 'hyphen';
19

20
# add some custom names to map characters that aren't in HTML
21
22
23
codepoint2name[ord(' ')] = 'space'
codepoint2name[ord('\'')] = 'squot'
codepoint2name[ord(',')] = 'comma'
24
codepoint2name[ord('.')] = 'dot'
25
26
codepoint2name[ord(':')] = 'colon'
codepoint2name[ord('/')] = 'slash'
Damien George's avatar
Damien George committed
27
codepoint2name[ord('%')] = 'percent'
28
codepoint2name[ord('#')] = 'hash'
29
30
31
32
codepoint2name[ord('(')] = 'paren_open'
codepoint2name[ord(')')] = 'paren_close'
codepoint2name[ord('[')] = 'bracket_open'
codepoint2name[ord(']')] = 'bracket_close'
33
34
codepoint2name[ord('{')] = 'brace_open'
codepoint2name[ord('}')] = 'brace_close'
35
codepoint2name[ord('*')] = 'star'
36
codepoint2name[ord('!')] = 'bang'
37
codepoint2name[ord('\\')] = 'backslash'
38

39
40
# this must match the equivalent function in qstr.c
def compute_hash(qstr):
41
    hash = 5381
42
    for char in qstr:
43
        hash = (hash * 33) ^ ord(char)
44
45
    # Make sure that valid hash is never zero, zero means "hash not computed"
    return (hash & 0xffff) or 1
46
47
48

def do_work(infiles):
    # read the qstrs in from the input files
49
    qcfgs = {}
50
    qstrs = {}
51
52
53
    for infile in infiles:
        with open(infile, 'rt') as f:
            for line in f:
54
55
56
57
58
59
60
61
62
63
64
65
                line = line.strip()

                # is this a config line?
                match = re.match(r'^QCFG\((.+), (.+)\)', line)
                if match:
                    value = match.group(2)
                    if value[0] == '(' and value[-1] == ')':
                        # strip parenthesis from config value
                        value = value[1:-1]
                    qcfgs[match.group(1)] = value
                    continue

66
                # is this a QSTR line?
67
                match = re.match(r'^Q\((.*)\)$', line)
68
                if not match:
69
                    continue
70
71
72

                # get the qstr value
                qstr = match.group(1)
73
                ident = re.sub(r'[^A-Za-z0-9_]', lambda s: "_" + codepoint2name[ord(s.group(0))] + "_", qstr)
74
75

                # don't add duplicates
76
                if ident in qstrs:
77
78
                    continue

79
                # add the qstr to the list, with order number to retain original order in file
80
                qstrs[ident] = (len(qstrs), ident, qstr)
81

82
83
84
85
86
    # get config variables
    cfg_bytes_len = int(qcfgs['BYTES_IN_LEN'])
    cfg_max_len = 1 << (8 * cfg_bytes_len)

    # print out the starte of the generated C header file
87
    print('// This file was automatically generated by makeqstrdata.py')
88
    print('')
89

90
    # add NULL qstr with no hash or data
91
92
93
    print('QDEF(MP_QSTR_NULL, (const byte*)"\\x00\\x00%s" "")' % ('\\x00' * cfg_bytes_len))

    # go through each qstr and print it out
94
    for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]):
95
        qhash = compute_hash(qstr)
96
97
        # Calculate len of str, taking escapes into account
        qlen = len(qstr.replace("\\\\", "-").replace("\\", ""))
98
        qdata = qstr.replace('"', '\\"')
99
100
101
        if qlen >= cfg_max_len:
            print('qstr is too long:', qstr)
            assert False
102
        qlen_str = ('\\x%02x' * cfg_bytes_len) % tuple(((qlen >> (8 * i)) & 0xff) for i in range(cfg_bytes_len))
103
        print('QDEF(MP_QSTR_%s, (const byte*)"\\x%02x\\x%02x%s" "%s")' % (ident, qhash & 0xff, (qhash >> 8) & 0xff, qlen_str, qdata))
104
105

if __name__ == "__main__":
106
    do_work(sys.argv[1:])