/
generate_escape_tables.py
executable file
·91 lines (84 loc) · 2.36 KB
/
generate_escape_tables.py
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
#
# Generate Escape tables.
# Copyright 2011 Facebook
#
# @author Tudor Bosman (tudorb@fb.com)
#
import os
from optparse import OptionParser
OUTPUT_FILE = "EscapeTables.cpp"
def generate(f):
f.write("namespace folly {\n"
"namespace detail {\n"
"\n")
f.write("extern const char cEscapeTable[] =\n")
escapes = dict((
('"', '\\"'),
('\\', '\\\\'),
('?', '?'),
('\n', 'n'),
('\r', 'r'),
('\t', 't'),
))
for i in range(0, 256):
if i % 64 == 0:
if i != 0:
f.write("\"\n")
f.write(" \"")
c = chr(i)
if c in escapes:
c = escapes[c]
elif i < 32 or i > 126:
c = 'O' # octal
else:
c = 'P' # printable
f.write(c)
f.write("\";\n"
"\n")
f.write("extern const char cUnescapeTable[] =\n")
for i in range(0, 256):
if i % 64 == 0:
if i != 0:
f.write("\"\n")
f.write(" \"")
c = chr(i)
if c in '\'?':
f.write(c)
elif c in '"\\abfnrtv':
f.write("\\" + c)
elif i >= ord('0') and i <= ord('7'):
f.write("O") # octal
elif c == "x":
f.write("X") # hex
else:
f.write("I") # invalid
f.write("\";\n"
"\n"
"extern const unsigned char hexTable[] = {")
for i in range(0, 256):
if i % 16 == 0:
f.write("\n ")
if i >= ord('0') and i <= ord('9'):
f.write("{0:2d}, ".format(i - ord('0')))
elif i >= ord('a') and i <= ord('f'):
f.write("{0:2d}, ".format(i - ord('a') + 10))
elif i >= ord('A') and i <= ord('F'):
f.write("{0:2d}, ".format(i - ord('A') + 10))
else:
f.write("16, ")
f.write("\n};\n"
"\n")
f.write("} // namespace detail\n"
"} // namespace folly\n")
def main():
parser = OptionParser()
parser.add_option("--install_dir", dest="install_dir", default=".",
help="write output to DIR", metavar="DIR")
parser.add_option("--fbcode_dir")
(options, args) = parser.parse_args()
f = open(os.path.join(options.install_dir, OUTPUT_FILE), "w")
generate(f)
f.close()
if __name__ == "__main__":
main()