3 # Run this script like so:
5 # ./update-gtranslit.py /path/to/glibc/localedata/locales > gtranslit-data.h
11 localedir = sys.argv[1]
14 # returns true if the name looks like a POSIX locale name
15 def looks_like_locale(name):
16 name, _, variant = name.partition("@")
21 lang, _, land = name.partition("_")
23 return len(lang) == 2 or len(lang) == 3 and len(land) == 2
26 # handles <U1234> style escapes
34 start_escape = string.find("<", i)
36 if start_escape == -1:
37 chunks.append(string[i:])
40 assert string[start_escape : (start_escape + 2)] == "<U"
43 end_escape = string.find(">", start_escape)
44 assert end_escape != -1
46 chunks.append(chr(int(string[start_escape:end_escape], 16)))
49 return "".join(chunks)
52 # Checks if a string is ascii
54 return all(ord(c) < 0x80 for c in string)
57 # A Mapping is a map from non-ascii strings to ascii strings.
59 # It corresponds to a sequence of one or more mapping lines:
61 # <U00C4> "<U0041><U0308>";"<U0041><U0045>"
66 self.serialised = None
71 # <U00C4> "<U0041><U0308>";"<U0041><U0045>" % \
72 # LATIN CAPITAL LETTER A WITH DIAERESIS.
74 # and adds the first all-ascii choice (or IGNORE) to the mapping
75 # dictionary, with the origin string as the key. In the case of
76 # IGNORE, stores the empty string.
77 def consider_mapping_line(self, line):
78 key, value, rest = (line + " % comment").split(maxsplit=2)
82 for alternative in value.split(";"):
83 if alternative[0] == '"' and alternative[-1] == '"':
84 unescaped = unescape(alternative[1:-1])
85 if is_ascii(unescaped):
86 self.mapping[key] = unescaped
89 elif alternative[0] == "<" and alternative[-1] == ">":
90 unescaped = unescape(alternative)
91 if is_ascii(unescaped):
92 self.mapping[key] = unescaped
95 elif alternative == "IGNORE":
96 self.mapping[key] = ""
99 # Performs a normal dictionary merge, but ensures that there are no
100 # conflicting entries between the original dictionary and the requested
102 def merge_mapping(self, changes):
103 for key in changes.mapping:
104 if key in self.mapping:
105 assert self.mapping[key] == changes.mapping[key]
107 self.mapping.update(changes.mapping)
109 # Can't get much flatter...
110 def get_flattened(self):
113 def serialise(self, serialiser):
114 if self.serialised is None:
115 self.serialised = serialiser.add_mapping(self.mapping)
117 return self.serialised
120 # A Chain is a sequence of mappings and chains.
122 # A chain contains another chain whenever "copy" or "include" is
123 # encountered in a source file.
125 # A chain contains a mapping whenever a sequence of mapping lines:
127 # <U00C4> "<U0041><U0308>";"<U0041><U0045>"
129 # is encountered in a file.
131 # The order of lookup is reverse: later entries override earlier ones.
133 def __init__(self, name):
134 self.serialised = None
139 self.read_from_file(os.path.join(localedir, name))
141 def read_from_file(self, filename):
142 current_mapping = None
146 fp = open(filename, encoding="ascii", errors="surrogateescape")
152 if line == "END LC_CTYPE":
155 if line.startswith("copy") or line.startswith("include"):
157 self.chain.append(current_mapping)
159 copyname = unescape(line.split('"', 3)[1])
160 copyfile = get_chain(copyname)
161 self.chain.append(copyfile)
164 current_mapping = None
166 elif line == "translit_start":
169 elif line == "translit_end":
172 elif in_translit and line.startswith("<U"):
173 if not current_mapping:
174 current_mapping = Mapping()
176 current_mapping.consider_mapping_line(line)
178 elif line == "" or line.startswith("%"):
181 elif "default_missing <U003F>":
185 print("unknown line:", line)
188 elif line == "LC_CTYPE":
192 self.chain.append(current_mapping)
194 # If there is only one link to this chain, we may as well just
195 # return the contents of the chain so that they can be merged into
196 # our sole parent directly. Otherwise, return ourselves.
197 def get_flattened(self):
199 return sum((item.get_flattened() for item in self.chain), [])
203 def serialise(self, serialiser):
204 if self.serialised is None:
205 # Before we serialise, see if we can optimise a bit
206 self.chain = sum((item.get_flattened() for item in self.chain), [])
209 while i < len(self.chain) - 1:
210 if isinstance(self.chain[i], Mapping) and isinstance(
211 self.chain[i + 1], Mapping
213 # We have two mappings in a row. Try to merge them.
214 self.chain[i].merge_mapping(self.chain[i + 1])
215 del self.chain[i + 1]
219 # If all that is left is one item, just serialise that directly
220 if len(self.chain) == 1:
221 self.serialised = self.chain[0].serialise(serialiser)
223 ids = [item.serialise(serialiser) for item in self.chain]
224 self.serialised = serialiser.add_chain(ids)
226 return self.serialised
229 # Chain cache -- allows sharing of common chains
234 if name not in chains:
235 chains[name] = Chain(name)
240 # Remove the country name from a locale, preserving variant
241 # eg: 'sr_RS@latin' -> 'sr@latin'
242 def remove_country(string):
243 base, at, variant = string.partition("@")
244 lang, _, land = base.partition("_")
245 return lang + at + variant
248 def encode_range(start, end):
252 assert start < 0x1000
255 result = 0x8000 + (length << 12) + start
257 assert result < 0x10000
262 def c_pair_array(array):
263 return "{ " + ", ".join("{ %u, %u }" % pair for pair in array) + " };"
272 def add_mapping(self, mapping):
273 if mapping in self.mappings:
274 mapping_id = self.mappings.index(mapping)
276 mapping_id = len(self.mappings)
277 self.mappings.append(mapping)
279 assert mapping_id < 128
282 def add_chain(self, chain):
283 if chain in self.chains:
284 chain_id = self.chains.index(chain)
286 chain_id = len(self.chains)
287 self.chains.append(chain)
289 assert chain_id < 128
290 return 128 + chain_id
292 def add_locale(self, name, item_id):
293 self.locales[name] = item_id
295 def add_default(self, item_id):
296 self.default = item_id
298 def optimise_locales(self):
299 # Check if all regions of a language/variant agree
300 languages = list(set(remove_country(locale) for locale in self.locales))
302 for language in languages:
304 locale for locale in self.locales if remove_country(locale) == language
307 item_id = self.locales[locales[0]]
308 if all(self.locales[locale] == item_id for locale in locales):
309 self.locales[language] = item_id
310 for locale in locales:
311 del self.locales[locale]
313 # Check if a variant is the same as the non-variant form
314 # eg: 'de@euro' and 'de'
315 for variant in list(locale for locale in self.locales if "@" in locale):
316 base, _, _ = variant.partition("@")
317 if base in self.locales and self.locales[base] == self.locales[variant]:
318 del self.locales[variant]
320 # Eliminate any entries that are just the same as the C locale
321 for locale in list(self.locales):
322 if self.locales[locale] == self.default:
323 del self.locales[locale]
337 for mapping in self.mappings:
338 mapping_ranges.append((len(mappings_table), len(mapping)))
340 for key in sorted(mapping):
341 if len(key) == 1 and ord(key[0]) < 0x8000:
342 src_range = ord(key[0])
344 existing = src_table.find(key)
346 start = len(src_table)
347 assert all(ord(c) <= 0x10FFFF for c in key)
349 src_range = encode_range(start, len(src_table))
350 max_lookup = max(max_lookup, len(key))
352 src_range = encode_range(existing, existing + len(key))
355 if len(value) == 1 and ord(value[0]) < 0x80:
356 ascii_range = ord(value[0])
358 existing = ascii_table.find(value)
360 start = len(ascii_table)
361 assert all(ord(c) < 0x80 for c in value)
363 ascii_range = encode_range(start, len(ascii_table))
365 ascii_range = encode_range(existing, existing + len(value))
367 mappings_table.append((src_range, ascii_range))
369 for chain in self.chains:
370 chain_starts.append(len(chains_table))
372 for item_id in reversed(chain):
373 assert item_id < 0xFF
374 chains_table.append(item_id)
375 chains_table.append(0xFF)
377 for locale in sorted(self.locales):
378 max_localename = max(max_localename, len(locale))
379 name_offset = len(locale_names)
380 assert all(ord(c) <= 0x7F for c in locale)
381 locale_names += locale + "\0"
383 item_id = self.locales[locale]
385 assert name_offset < 256
387 locale_index.append((name_offset, item_id))
389 print("/* Generated by update-gtranslit.py */")
390 print("#define MAX_KEY_SIZE", max_lookup)
391 print("#define MAX_LOCALE_NAME", max_localename)
393 "static const gunichar src_table[] = {",
394 ", ".join(str(ord(c)) for c in src_table),
397 # cannot do this in plain ascii because of trigraphs... :(
399 "static const gchar ascii_table[] = {",
400 ", ".join(str(ord(c)) for c in ascii_table),
404 "static const struct mapping_entry mappings_table[] =",
405 c_pair_array(mappings_table),
408 "static const struct mapping_range mapping_ranges[] =",
409 c_pair_array(mapping_ranges),
412 "static const guint8 chains_table[] = {",
413 ", ".join(str(i) for i in chains_table),
417 "static const guint8 chain_starts[] = {",
418 ", ".join(str(i) for i in chain_starts),
422 'static const gchar locale_names[] = "'
423 + locale_names.replace("\0", "\\0")
427 "static const struct locale_entry locale_index[] = ",
428 c_pair_array(locale_index),
430 print("static const guint8 default_item_id = %u;" % (self.default,))
439 for name in os.listdir(localedir):
440 if looks_like_locale(name):
441 chain = get_chain(name)
442 locales.append(chain)
445 serialiser = Serialiser()
447 for locale in locales:
448 serialiser.add_locale(locale.name, locale.serialise(serialiser))
450 i18n = get_chain("i18n").serialise(serialiser)
451 combining = get_chain("translit_combining").serialise(serialiser)
452 serialiser.add_default(serialiser.add_chain([i18n, combining]))
454 serialiser.optimise_locales()