summaryrefslogtreecommitdiff
path: root/build/tools/gentranstab.pl
blob: 0e9205a586f90bf4610f007626ebaae37858136f (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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
#!/usr/bin/perl

use warnings;
use strict;

# Usage: gentranstab.pl <path to transtab>

usage() if (@ARGV != 1);

my $transtab = shift @ARGV;

open TRANSTAB,"<$transtab" or die "Failed opening $transtab: $!\n";

print <<EOF;
/* This file is autogenerated. Manual changes will be lost */

#include <assert.h>
#include <inttypes.h>
#include <stdbool.h>

#include "internal.h"

static int translit_write_character(struct encoding_context *e,
		UCS4 c, char **buffer, size_t *buflen, bool use_transout)
{
	Encoding *out = use_transout ? e->transout : e->out;
	int ret;

	if (out != NULL) {
		char *prev_buf = *buffer;
		size_t prev_len = *buflen;

		ret = encoding_write(out, c, buffer, (int *) buflen);

		if (ret <= 0)
			*buflen = prev_len - (*buffer - prev_buf);
	} else {
		ret = iconv_eightbit_write(e, c, buffer, (int *) buflen);
	}

	return ret;
}

static int translit_try_sequence(struct encoding_context *e,
		const size_t seqlen, const UCS2 *replacement)
{
	char *tmpbuf, *ptmpbuf;
	size_t orig_tmplen, tmplen, index;
	int ret = 1;

	/* First, determine if sequence can be written to target encoding */
	/* Worst case: conversion to UTF-8 (needing 6 bytes per character) */
	orig_tmplen = tmplen = (seqlen + 1) * 6;
	ptmpbuf = tmpbuf = malloc(tmplen);
	if (tmpbuf == NULL)
		return 0;

	/* Reset the transout codec */
	if (e->transout != NULL) {
		encoding_reset(e->transout);
		encoding_set_flags(e->transout, e->outflags, e->outflags);
	}

	for (index = 0; index < seqlen; index++) {
		UCS4 c = replacement[index];
		do {
			ret = translit_write_character(e, c, &ptmpbuf,
					&tmplen, true);
			if (ret == 0) {
				char *tmp = realloc(tmpbuf, orig_tmplen * 2);
				if (tmp == NULL)
					break;

				ptmpbuf = tmp + (ptmpbuf - tmpbuf);
				tmpbuf = tmp;
				tmplen += orig_tmplen;
				orig_tmplen *= 2;
			}
		} while (ret == 0);

		if (ret <= 0)
			break;
	}

	free(tmpbuf);

	if (ret <= 0) {
		/* Consider lack of memory an inability to write the output */
		return -1;
	}

	e->substitution = replacement;
	e->substlen = seqlen;

	/* Emit replacement for real */
	return translit_flush_replacement(e);
}

int translit_flush_replacement(struct encoding_context *e)
{
	const UCS2 *substitution = e->substitution;
	size_t substlen = e->substlen;
	int ret = 1;

	while (substlen > 0) {
		UCS4 c = substitution[0];
		
		ret = translit_write_character(e, c,
				e->outbuf, e->outbytesleft, false);
		assert(ret != -1);
		if (ret <= 0)
			break;

		substitution++;
		substlen--;
	}

	e->substitution = substitution;
	e->substlen = substlen;

	return ret;
}

EOF

# Map from codepoint -> ttvals ref
# ttvals is a list of chars ref
my %transmap = ();
# Length, in characters, of longest substitution string seen so far
my $maxsubst = 0;
# Total number of substitution strings encountered
my $numsubsts = 0;
# Map from substitution string -> start index in charbin
my %substs = ();
# Accumulated list of substitution character sequences
my @charbin = ();

# Read in transtab data
while (my $line = <TRANSTAB>) {
	# Skip comments and blank lines
	next if ($line =~ /^%/);
	next if ($line =~ /^\s*$/);

	# Format: <codepoint> <data>
	my ($codepoint, $data) = split(' ', $line);

	# Strip '<U' from start, and '>' from end of input codepoint
	$codepoint =~ s/^<U([^>]+)>/$1/;

	# Data is a list of semi-colon-separated substitutions
	my @substitutions = split(';', $data);

	my @ttvals = ();

	foreach my $sub (@substitutions) {
		# Strip quotes around substitution sequence
		$sub =~ s/"([^"]*)"/$1/;

		$numsubsts++;

		if ($sub eq "") {
			# Special-case empty substitutions
			my @empty = ();
			push(@ttvals, \@empty);
			next;
		}

		# Split characters in sequence
		my @chars = split('<', $sub);
		shift @chars;
		my $num_chars = scalar(@chars);

		# Strip leading 'U' and trailing '>'
		map { $_ =~ s/U([^>]+)>/$1/; } @chars;

		$maxsubst = $num_chars if ($num_chars > $maxsubst);

		# Stringify chars to produce hash key
		my $hkey = "@chars";

		# Find/insert in bin, if new substitution
		if (!defined($substs{$hkey})) {
			my $pos = find_in_bin(\@chars, $num_chars);

			$substs{$hkey} = $pos;
		}

		# Append to list of substitutions for codepoint
		push(@ttvals, \@chars);
	}

	# Insert into transmap
	$transmap{$codepoint} = \@ttvals;
}

close TRANSTAB;

# Ensure transtab is representable
die "Charbin length exceeds 2^13!" if $#charbin >= 2**13;
die "Maxsubst exceeds 8!" if $maxsubst >= 2**3;

print <<EOF;
struct translit_entry {
	uint32_t codepoint : 16,
	         offset    : 13,
		 length    :  3;
};

EOF

# Emit substitution data
my $cblen = @charbin;
print "static const UCS2 substdata[$cblen] = {\n";
foreach my $c (@charbin) {
	print "\t0x$c,\n";
}
print "};\n\n";

# Emit transliteration LUT
my $ttlen = $numsubsts + 1; # + 1 for sentinel
print "static const struct translit_entry transtab[$ttlen] = {\n";
foreach my $codepoint (sort(keys %transmap)) {
	my $ttvals = $transmap{$codepoint};

	for my $subst (@$ttvals) {
		my $hkey = "@$subst";

		if ($hkey ne "") {
			my $slen = @$subst;
			print "\t{ 0x$codepoint, $substs{$hkey}, $slen },\n";
		} else {
			print "\t{ 0x$codepoint, 0, 0 },\n";
		}
	}
}
# Place sentinel at the end
print "\t{ 0, 0, 0 }\n";
print "};\n\n";

print <<EOF;
static int translit_tab_cmp(const void *a, const void *b)
{
	const struct translit_entry *aa = (const struct translit_entry *) a;
	const struct translit_entry *bb = (const struct translit_entry *) b;

	return (int) aa->codepoint - (int) bb->codepoint;
}

int translit_substitute(struct encoding_context *e, UCS4 c)
{
	static const UCS2 default_subst[1] = { '?' };
	int ret = 1;

	if (c <= 0xFFFF) {
		struct translit_entry key = { c, 0, 0 };
		const struct translit_entry *res;

		res = bsearch(&key, transtab, $numsubsts,
				sizeof(struct translit_entry),
				translit_tab_cmp);
		if (res != NULL) {
			/* Reverse until we find the first entry for c */
			while (res > transtab) {
				if (res[-1].codepoint != c)
					break;
				res--;
			}

			/* Try substitutions in turn, until we run out */
			while (res->codepoint == c) {			
				ret = translit_try_sequence(e, res->length,
						substdata + res->offset);
				if (ret >= 0)
					return ret;

				res++;
			}
		}
	}

	/* Last-ditch replacement: must succeed */
	return translit_try_sequence(e, 1, default_subst);
}
EOF

# Search bin for existing sequence, or append if not found.
#
# The intent here is to minimise duplication of substitution
# sequences. This implementation is decidedly trivial, and
# makes no attempt to discover the optimal insertion order.
#
# Inspection of the output indicates that we use approximately
# 5.5 bytes of storage for each substitution sequence 
# encountered (4 of these are the translit_entry, so there
# doesn't seem much point in trying to optimise the layout of
# the charbin any further.)
sub find_in_bin
{
	my $pchars = shift;
	my $pcharslen = shift;
	my $binlen = scalar(@charbin);
	my $offset = 0;

	# Search bin for pchars
	while ($offset <= $binlen - $pcharslen) {
		my @slice = @charbin[$offset .. $offset + $pcharslen - 1];

		last if aeq(\@slice, $pchars);

		$offset++;
	}

	if ($offset <= $binlen - $pcharslen) {
		# Found in bin
		return $offset;
	} else {
		# Not found, so append
		push(@charbin, @$pchars);
		return $binlen;
	}
}

# Compare two arrays for equality
sub aeq
{
	my ($aref, $bref) = @_;
	return 0 unless @$aref == @$bref;

	my $idx = 0;
	for my $item (@$aref) {
		return 0 unless $item eq $bref->[$idx++];
	}

	return 1;
}

sub usage
{
	print STDERR <<EOF;
Usage: gentranstab.pl <path to transtab>
EOF

	exit 1;
}