summaryrefslogtreecommitdiff
path: root/locale/gen-translit.py
blob: df2170a9a954935e08d8cc773f223dd29b3ca20c (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
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#!/usr/bin/python3
# Generate the locale/C-translit.h file.
# Copyright (C) 2018-2019 Free Software Foundation, Inc.
# This file is part of the GNU C Library.
#
# The GNU C Library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# The GNU C Library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with the GNU C Library; if not, see
# <http://www.gnu.org/licenses/>.

import re
import sys


class StringLiteral:
    "Source of a string literal and its decomposition into code points."
    def __init__(self, s):
        # States:
        #  0 regular character sequence
        #  1 backslash seen
        #  2 in hexadecimal escape sequence
        state = 0
        result = []
        for ch in s:
            if state == 0:
                if ch == '\\':
                    state = 1
                else:
                    result.append(ord(ch))
            elif state == 1:
                if ch in "\\\"":
                    result.append(ord(ch))
                    state = 0
                elif ch == 'x':
                    state = 2
                    result.append(0)
                else:
                    raise ValueError("invalid character {!r} in {!r}".format(
                        ch, s))
            elif state == 2:
                if ch in "0123456789abcdefABCDEF":
                    result[-1] = result[-1] * 16 + int(ch, 16)
                else:
                    if ch == '\\':
                        state = 1
                    else:
                        state = 0
        if state == 1:
            raise ValueError("trailing backslash in {!r}".format(s))

        self.source = s
        self.decoded = tuple(result)


class Translit:
    "Pair of transliteration and source."

    __RE_TRANSLIT = re.compile(
        r'^"((?:[^"\\]|\\x[0-9a-fA-F])+)"\s+'
        r'"((?:[^"\\]|\\["\\])*)"\s*(?:#.*)?$')

    def __init__(self, line):
        match = self.__RE_TRANSLIT.match(line)
        if not match:
            raise IOError("invalid line {}: {!r}".format(
                lineno + 1, line))
        codepoints, replacement = match.groups()
        self.codepoints = StringLiteral(codepoints)
        self.replacement = StringLiteral(replacement)


# List of Translit objects.
translits = []

# Read transliterations from standard input.
for lineno, line in enumerate(sys.stdin):
    line = line.strip()
    # Skip empty lines and comments.
    if (not line) or line[0] == '#':
        continue
    translit = Translit(line)
    # Check ordering of codepoints.
    if translits \
       and translit.codepoints.decoded <= translits[-1].codepoints.decoded:
        raise IOError("unexpected codepoint {!r} on line {}: {!r}".format(
            translit.codeponts.decoded, lineno + 1, line))
    translits.append(translit)

# Generate the C sources.
write = sys.stdout.write
write("#include <stdint.h>\n")
write("#define NTRANSLIT {}\n".format(len(translits)))

write("static const uint32_t translit_from_idx[] =\n{\n  ")
col = 2
total = 0
for translit in translits:
    if total > 0:
        if col + 7 >= 79:
            write(",\n  ")
            col = 2
        else:
            write(", ")
            col += 2
    write("{:4}".format(total))
    total += len(translit.codepoints.decoded) + 1
    col += 4
write("\n};\n")

write("static const wchar_t translit_from_tbl[] =\n ")
col = 1
first = True
for translit in translits:
    if first:
        first = False
    else:
        if col + 6 >= 79:
            write("\n ")
            col = 1
        write(" L\"\\0\"")
        col += 6
    if col > 2 and col + len(translit.codepoints.source) + 4 >= 79:
        write("\n  ")
        col = 2
    else:
        write(" ")
        col += 1
    write("L\"{}\"".format(translit.codepoints.source))
    col += len(translit.codepoints.source) + 3
write(";\n")

write("static const uint32_t translit_to_idx[] =\n{\n  ")
col = 2
total = 0
for translit in translits:
    if total > 0:
        if col + 7 >= 79:
            write(",\n  ")
            col = 2
        else:
            write(", ")
            col += 2
    write("{:4}".format(total))
    total += len(translit.replacement.decoded) + 2
    col += 4
write("\n};\n")

write("static const wchar_t translit_to_tbl[] =\n ")
col = 1
first = True
for translit in translits:
    if first:
        first = False
    else:
        if col + 6 >= 79:
            write("\n ")
            col = 1
        write(" L\"\\0\"")
        col += 6
    if col > 2 and col + len(translit.replacement.source) + 6 >= 79:
        write("\n  ")
        col = 2
    else:
        write(" ")
        col += 1
    write("L\"{}\\0\"".format(translit.replacement.source))
    col += len(translit.replacement.source) + 5
write(";\n")