blob: dbafd47d52aec3d1767ccca98e29633ac9bf8df3 [file] [log] [blame]
Damien George55baff42014-01-21 21:40:13 +00001import argparse
2import re
Paul Sokolovskyab5d0822014-01-24 00:22:00 +02003from htmlentitydefs import codepoint2name
Damien George55baff42014-01-21 21:40:13 +00004
5# this must match the equivalent function in qstr.c
6def compute_hash(qstr):
7 hash = 0
8 for char in qstr:
9 hash += ord(char)
10 return hash & 0xffff
11
12def do_work(infiles):
13 # read the qstrs in from the input files
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020014 qstrs = {}
Damien George55baff42014-01-21 21:40:13 +000015 for infile in infiles:
16 with open(infile, 'rt') as f:
17 line_number = 0
18 for line in f:
19 line_number += 1
20 line = line.strip()
21
22 # ignore blank lines and comments
23 if len(line) == 0 or line.startswith('//'):
24 continue
25
26 # verify line is of the correct form
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020027 match = re.match(r'Q\((.+)\)$', line)
Damien George55baff42014-01-21 21:40:13 +000028 if not match:
29 print('({}:{}) bad qstr format, got {}'.format(infile, line_number, line))
30 return False
31
32 # get the qstr value
33 qstr = match.group(1)
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020034 ident = re.sub(r'[^A-Za-z0-9_]', lambda s: "_" + codepoint2name[ord(s.group(0))] + "_", qstr)
Damien George55baff42014-01-21 21:40:13 +000035
36 # don't add duplicates
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020037 if ident in qstrs:
Damien George55baff42014-01-21 21:40:13 +000038 continue
39
40 # add the qstr to the list
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020041 qstrs[ident] = qstr
Damien George55baff42014-01-21 21:40:13 +000042
43 # process the qstrs, printing out the generated C header file
44 print('// This file was automatically generated by makeqstrdata.py')
Dave Hylands7a996b12014-01-21 15:28:27 -080045 print('')
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020046 for ident, qstr in qstrs.items():
Damien George55baff42014-01-21 21:40:13 +000047 qhash = compute_hash(qstr)
48 qlen = len(qstr)
Paul Sokolovskyab5d0822014-01-24 00:22:00 +020049 print('Q({}, (const byte*)"\\x{:02x}\\x{:02x}\\x{:02x}\\x{:02x}" "{}")'.format(ident, qhash & 0xff, (qhash >> 8) & 0xff, qlen & 0xff, (qlen >> 8) & 0xff, qstr))
Damien George55baff42014-01-21 21:40:13 +000050
51 return True
52
53def main():
54 arg_parser = argparse.ArgumentParser(description='Process raw qstr file and output qstr data with length, hash and data bytes')
55 arg_parser.add_argument('files', nargs='+', help='input file(s)')
56 args = arg_parser.parse_args()
57
58 result = do_work(args.files)
59 if not result:
60 print('exiting with error code')
61 exit(1)
62
63if __name__ == "__main__":
64 main()