Debian Codegraph @

tools/idna-data

raw
1 #!/usr/bin/env python3
2
3 import argparse, collections, datetime, os, re, sys, tempfile
4 from urllib.request import urlopen
5
6 # Use intranges.intranges_from_list() from the sibling idna directory
7 sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "idna"))
8 from intranges import intranges_from_list
9
10 PREFERRED_VERSION = "17.0.0"
11 DOWNLOAD_TIMEOUT = 60 # seconds, per file
12 UCD_URL = "https://www.unicode.org/Public/{version}/ucd/{filename}"
13 UTS46_URL = "https://www.unicode.org/Public/{version}/idna/{filename}"
14
15 DEFAULT_CACHE_DIR = "~/.cache/unidata"
16
17 # Scripts affected by IDNA contextual rules
18 CONTEXT_SCRIPTS = sorted(["Greek", "Han", "Hebrew", "Hiragana", "Katakana"])
19
20 UTS46_STATUSES = {
21 "valid": ("V", False),
22 "ignored": ("I", False),
23 "mapped": ("M", True),
24 "deviation": ("D", True),
25 "disallowed": ("X", False),
26 }
27
28 # Exceptions are manually assigned in Section 2.6 of RFC 5892.
29 exceptions = {
30 0x00DF: "PVALID", # LATIN SMALL LETTER SHARP S
31 0x03C2: "PVALID", # GREEK SMALL LETTER FINAL SIGMA
32 0x06FD: "PVALID", # ARABIC SIGN SINDHI AMPERSAND
33 0x06FE: "PVALID", # ARABIC SIGN SINDHI POSTPOSITION MEN
34 0x0F0B: "PVALID", # TIBETAN MARK INTERSYLLABIC TSHEG
35 0x3007: "PVALID", # IDEOGRAPHIC NUMBER ZERO
36 0x00B7: "CONTEXTO", # MIDDLE DOT
37 0x0375: "CONTEXTO", # GREEK LOWER NUMERAL SIGN (KERAIA)
38 0x05F3: "CONTEXTO", # HEBREW PUNCTUATION GERESH
39 0x05F4: "CONTEXTO", # HEBREW PUNCTUATION GERSHAYIM
40 0x30FB: "CONTEXTO", # KATAKANA MIDDLE DOT
41 0x0660: "CONTEXTO", # ARABIC-INDIC DIGIT ZERO
42 0x0661: "CONTEXTO", # ARABIC-INDIC DIGIT ONE
43 0x0662: "CONTEXTO", # ARABIC-INDIC DIGIT TWO
44 0x0663: "CONTEXTO", # ARABIC-INDIC DIGIT THREE
45 0x0664: "CONTEXTO", # ARABIC-INDIC DIGIT FOUR
46 0x0665: "CONTEXTO", # ARABIC-INDIC DIGIT FIVE
47 0x0666: "CONTEXTO", # ARABIC-INDIC DIGIT SIX
48 0x0667: "CONTEXTO", # ARABIC-INDIC DIGIT SEVEN
49 0x0668: "CONTEXTO", # ARABIC-INDIC DIGIT EIGHT
50 0x0669: "CONTEXTO", # ARABIC-INDIC DIGIT NINE
51 0x06F0: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT ZERO
52 0x06F1: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT ONE
53 0x06F2: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT TWO
54 0x06F3: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT THREE
55 0x06F4: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT FOUR
56 0x06F5: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT FIVE
57 0x06F6: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT SIX
58 0x06F7: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT SEVEN
59 0x06F8: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT EIGHT
60 0x06F9: "CONTEXTO", # EXTENDED ARABIC-INDIC DIGIT NINE
61 0x0640: "DISALLOWED", # ARABIC TATWEEL
62 0x07FA: "DISALLOWED", # NKO LAJANYALAN
63 0x302E: "DISALLOWED", # HANGUL SINGLE DOT TONE MARK
64 0x302F: "DISALLOWED", # HANGUL DOUBLE DOT TONE MARK
65 0x3031: "DISALLOWED", # VERTICAL KANA REPEAT MARK
66 0x3032: "DISALLOWED", # VERTICAL KANA REPEAT WITH VOICED SOUND MARK
67 0x3033: "DISALLOWED", # VERTICAL KANA REPEAT MARK UPPER HALF
68 0x3034: "DISALLOWED", # VERTICAL KANA REPEAT WITH VOICED SOUND MARK UPPER HA
69 0x3035: "DISALLOWED", # VERTICAL KANA REPEAT MARK LOWER HALF
70 0x303B: "DISALLOWED", # VERTICAL IDEOGRAPHIC ITERATION MARK
71 }
72 backwardscompatible = {}
73
74
75 def hexrange(start, end):
76 return range(int(start, 16), int(end, 16) + 1)
77
78
79 def hexvalue(value):
80 return int(value, 16)
81
82
83 _RE_UNICODE = re.compile("\\\\u([0-9a-fA-F]{4})")
84 _RE_SURROGATE = re.compile("[\ud800-\udbff][\udc00-\udfff]")
85
86
87 def unicode_fixup(string):
88 """Replace backslash-u-XXXX with appropriate unicode characters."""
89 return _RE_SURROGATE.sub(
90 lambda match: chr((ord(match.group(0)[0]) - 0xD800) * 0x400 + ord(match.group(0)[1]) - 0xDC00 + 0x10000),
91 _RE_UNICODE.sub(lambda match: chr(int(match.group(1), 16)), string),
92 )
93
94
95 def stable_repr(string, ucdata, quote="'"):
96 """Return a Python literal for ``string`` that does not depend on the host interpreter.
97
98 Mirrors ``str.__repr__`` (quote selection, escapes) but decides whether a
99 non-ASCII codepoint is printable from the UCD version being processed rather
100 than from the running Python's ``unicodedata``, so the generated files are
101 byte-identical no matter which Python regenerates them. ``quote`` selects
102 the preferred quote character; the other one is used if that avoids escaping.
103 """
104 other = '"' if quote == "'" else "'"
105 if quote in string and other not in string:
106 quote, other = other, quote
107 out = [quote]
108 for ch in string:
109 cp = ord(ch)
110 if ch == quote or ch == "\\":
111 out.append("\\" + ch)
112 elif ch == "\t":
113 out.append("\\t")
114 elif ch == "\n":
115 out.append("\\n")
116 elif ch == "\r":
117 out.append("\\r")
118 elif cp < 0x20 or cp == 0x7F:
119 out.append("\\x{:02x}".format(cp))
120 elif cp < 0x7F:
121 out.append(ch)
122 elif ucdata.printable(cp):
123 out.append(ch)
124 elif cp <= 0xFF:
125 out.append("\\x{:02x}".format(cp))
126 elif cp <= 0xFFFF:
127 out.append("\\u{:04x}".format(cp))
128 else:
129 out.append("\\U{:08x}".format(cp))
130 out.append(quote)
131 return "".join(out)
132
133
134 class UnicodeVersion(object):
135 def __init__(self, version):
136 result = re.match(r"^(?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)$", version)
137 if result:
138 self.major = int(result.group("major"))
139 self.minor = int(result.group("minor"))
140 self.patch = int(result.group("patch"))
141 self.numerical = (self.major << 8) + (self.minor << 4) + self.patch
142 self.latest = False
143 elif version == "latest":
144 self.latest = True
145 else:
146 raise ValueError("Unrecognized Unicode version")
147
148 def __repr__(self, with_date=True):
149 if self.latest:
150 if with_date:
151 return "latest@{}".format(datetime.datetime.now().strftime("%Y-%m-%d"))
152 else:
153 return "latest"
154 else:
155 return "{}.{}.{}".format(self.major, self.minor, self.patch)
156
157 @property
158 def tag(self):
159 return self.__repr__(with_date=False)
160
161 def __gt__(self, other):
162 if self.latest:
163 return True
164 return self.numerical > other.numerical
165
166 def __eq__(self, other):
167 if self.latest:
168 return False
169 return self.numerical == other.numerical
170
171
172 class UnicodeData(object):
173 def __init__(self, version, cache, args):
174 self.version = UnicodeVersion(version)
175 self.source = args.source
176 self.cache = cache
177 self.max = 0
178
179 self._load_unicodedata()
180 self._load_proplist()
181 self._load_derivedcoreprops()
182 self._load_blocks()
183 self._load_hangulst()
184 self._load_arabicshaping()
185 self._load_scripts()
186 self._load_nfkc_cf()
187 self._load_uts46mapping()
188 self._load_uts46testvectors()
189
190 def _load_unicodedata(self):
191 f_ud = self._ucdfile("UnicodeData.txt")
192 self.ucd_data = {}
193 range_begin = None
194 for line in f_ud.splitlines():
195 fields = line.split(";")
196 value = int(fields[0], 16)
197 start_marker = re.match("^<(?P<name>.*?), First>$", fields[1])
198 end_marker = re.match("^<(?P<name>.*?), Last>$", fields[1])
199 if start_marker:
200 range_begin = value
201 elif end_marker:
202 for i in range(range_begin, value + 1):
203 fields[1] = "<{}>".format(end_marker.group("name"))
204 self.ucd_data[i] = fields[1:]
205 range_begin = None
206 else:
207 self.ucd_data[value] = fields[1:]
208
209 def _load_proplist(self):
210 f_pl = self._ucdfile("PropList.txt")
211 self.ucd_props = collections.defaultdict(list)
212 for line in f_pl.splitlines():
213 result = re.match(r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*(?P<prop>\S+)\s*(|\#.*)$", line)
214 if result:
215 if result.group("end"):
216 for i in hexrange(result.group("start"), result.group("end")):
217 self.ucd_props[i].append(result.group("prop"))
218 else:
219 i = hexvalue(result.group("start"))
220 self.ucd_props[i].append(result.group("prop"))
221
222 def _load_derivedcoreprops(self):
223 f_dcp = self._ucdfile("DerivedCoreProperties.txt")
224 for line in f_dcp.splitlines():
225 result = re.match(r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*(?P<prop>\S+)\s*(|\#.*)$", line)
226 if result:
227 if result.group("end"):
228 for i in hexrange(result.group("start"), result.group("end")):
229 self.ucd_props[i].append(result.group("prop"))
230 else:
231 i = hexvalue(result.group("start"))
232 self.ucd_props[i].append(result.group("prop"))
233
234 def _load_blocks(self):
235 self.ucd_block = {}
236 f_b = self._ucdfile("Blocks.txt")
237 for line in f_b.splitlines():
238 result = re.match(r"^(?P<start>[0-9A-F]{4,6})\.\.(?P<end>[0-9A-F]{4,6})\s*;\s*(?P<block>.*)\s*$", line)
239 if result:
240 for i in hexrange(result.group("start"), result.group("end")):
241 self.ucd_block[i] = result.group("block")
242 self.max = max(self.max, i)
243
244 def _load_hangulst(self):
245 self.ucd_hst = {}
246 f_hst = self._ucdfile("HangulSyllableType.txt")
247 for line in f_hst.splitlines():
248 result = re.match(r"^(?P<start>[0-9A-F]{4,6})\.\.(?P<end>[0-9A-F]{4,6})\s*;\s*(?P<type>\S+)\s*(|\#.*)$", line)
249 if result:
250 for i in hexrange(result.group("start"), result.group("end")):
251 self.ucd_hst[i] = result.group("type")
252
253 def _load_arabicshaping(self):
254 self.ucd_as = {}
255 f_as = self._ucdfile("extracted/DerivedJoiningType.txt")
256 for line in f_as.splitlines():
257 result = re.match(r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*(?P<jt>\S+)\s*(|\#.*)$", line)
258 if result:
259 if result.group("end"):
260 for i in hexrange(result.group("start"), result.group("end")):
261 self.ucd_as[i] = result.group("jt")
262 else:
263 i = hexvalue(result.group("start"))
264 self.ucd_as[i] = result.group("jt")
265
266 def _load_scripts(self):
267 self.ucd_s = {}
268 f_s = self._ucdfile("Scripts.txt")
269 for line in f_s.splitlines():
270 result = re.match(r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*(?P<script>\S+)\s*(|\#.*)$", line)
271 if result:
272 if not result.group("script") in self.ucd_s:
273 self.ucd_s[result.group("script")] = set()
274 if result.group("end"):
275 for i in hexrange(result.group("start"), result.group("end")):
276 self.ucd_s[result.group("script")].add(i)
277 else:
278 i = hexvalue(result.group("start"))
279 self.ucd_s[result.group("script")].add(i)
280
281 def _load_nfkc_cf(self):
282 self.ucd_nfkc_cf = {}
283 f_nfkc = self._ucdfile("DerivedNormalizationProps.txt")
284 for line in f_nfkc.splitlines():
285 result = re.match(
286 r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*NFKC_CF\s*;\s*(?P<mapping>[0-9A-F\s]*)\s*(|\#.*)$",
287 line,
288 )
289 if result:
290 mapping = "".join(chr(int(x, 16)) for x in result.group("mapping").split()) if result.group("mapping").strip() else ""
291 if result.group("end"):
292 for i in hexrange(result.group("start"), result.group("end")):
293 self.ucd_nfkc_cf[i] = mapping
294 else:
295 i = hexvalue(result.group("start"))
296 self.ucd_nfkc_cf[i] = mapping
297
298 def _load_uts46mapping(self):
299 self.ucd_idnamt = {}
300 f_idnamt = self._ucdfile("IdnaMappingTable.txt", urlbase=UTS46_URL)
301 for line in f_idnamt.splitlines():
302 result = re.match(r"^(?P<start>[0-9A-F]{4,6})(|\.\.(?P<end>[0-9A-F]{4,6}))\s*;\s*(?P<fields>[^#]+)", line)
303 if result:
304 fields = [x.strip() for x in result.group("fields").split(";")]
305 if result.group("end"):
306 for i in hexrange(result.group("start"), result.group("end")):
307 self.ucd_idnamt[i] = fields
308 else:
309 i = hexvalue(result.group("start"))
310 self.ucd_idnamt[i] = fields
311
312 def _load_uts46testvectors(self):
313 self.ucd_uts46tests = []
314 f_uts46tests = self._ucdfile("IdnaTestV2.txt", urlbase=UTS46_URL)
315 for lineno, line in enumerate(f_uts46tests.splitlines()):
316 if "#" in line:
317 line = line.split("#", 1)[0]
318 if not line:
319 continue
320 self.ucd_uts46tests.append((lineno + 1, tuple(field.strip() for field in unicode_fixup(line).split(";"))))
321
322 def _ucdfile(self, filename, urlbase=UCD_URL):
323 if self.source:
324 with open("{}/{}".format(self.source, filename)) as f:
325 return f.read()
326 else:
327 cache_file = None
328 if self.cache:
329 cache_file = os.path.expanduser("{}/{}/{}".format(self.cache, self.version.tag, filename))
330 if os.path.isfile(cache_file):
331 with open(cache_file) as f:
332 return f.read()
333
334 version_path = self.version.tag
335 if version_path == "latest":
336 version_path = "UCD/latest"
337 url = urlbase.format(
338 version=version_path,
339 filename=filename,
340 )
341 with urlopen(url, timeout=DOWNLOAD_TIMEOUT) as response:
342 content = response.read().decode("utf-8")
343
344 if cache_file:
345 # Write to a temporary file alongside the cache file and rename
346 # it into place, so an interrupted run cannot leave a truncated
347 # file that later runs would trust as the real thing.
348 cache_dir = os.path.dirname(cache_file)
349 os.makedirs(cache_dir, exist_ok=True)
350 fd, tmp_file = tempfile.mkstemp(dir=cache_dir, prefix=os.path.basename(filename) + ".")
351 try:
352 with os.fdopen(fd, "wb") as f:
353 f.write(content.encode("utf-8"))
354 os.replace(tmp_file, cache_file)
355 except BaseException:
356 os.unlink(tmp_file)
357 raise
358
359 return str(content)
360
361 def printable(self, cp):
362 """Whether ``str.__repr__`` would emit codepoint ``cp`` literally.
363
364 CPython treats every codepoint in general categories C* and Z* as
365 non-printable, except U+0020 SPACE; unassigned codepoints (absent from
366 UnicodeData.txt) are category Cn and therefore non-printable.
367 """
368 if cp == 0x20:
369 return True
370 fields = self.ucd_data.get(cp)
371 return fields is not None and fields[1][0] not in ("C", "Z")
372
373 def codepoints(self):
374 for i in range(0, self.max + 1):
375 yield CodePoint(i, ucdata=self)
376
377
378 class CodePoint:
379 def __init__(self, value=None, ucdata=None):
380 self.value = value
381 self.ucdata = ucdata
382
383 @property
384 def exception_value(self):
385 return exceptions.get(self.value, False)
386
387 @property
388 def compat_value(self):
389 return backwardscompatible.get(self.value, False)
390
391 @property
392 def name(self):
393 if self.value in self.ucdata.ucd_data:
394 return self.ucdata.ucd_data[self.value][0]
395 elif "Noncharacter_Code_Point" in self.ucdata.ucd_props[self.value]:
396 return "<noncharacter>"
397 else:
398 return "<reserved>"
399
400 @property
401 def general_category(self):
402 return self.ucdata.ucd_data.get(self.value, [None, None])[1]
403
404 @property
405 def unassigned(self):
406 return not ("Noncharacter_Code_Point" in self.ucdata.ucd_props[self.value] or self.value in self.ucdata.ucd_data)
407
408 @property
409 def ldh(self):
410 if self.value == 0x002D or self.value in range(0x0030, 0x0039 + 1) or self.value in range(0x0061, 0x007A + 1):
411 return True
412 return False
413
414 @property
415 def join_control(self):
416 return "Join_Control" in self.ucdata.ucd_props[self.value]
417
418 @property
419 def joining_type(self):
420 return self.ucdata.ucd_as.get(self.value, None)
421
422 @property
423 def char(self):
424 return chr(self.value)
425
426 @property
427 def nfkc_cf(self):
428 return self.ucdata.ucd_nfkc_cf.get(self.value, self.char)
429
430 @property
431 def unstable(self):
432 return self.char != self.nfkc_cf
433
434 @property
435 def in_ignorableproperties(self):
436 for prop in ["Default_Ignorable_Code_Point", "White_Space", "Noncharacter_Code_Point"]:
437 if prop in self.ucdata.ucd_props[self.value]:
438 return True
439 return False
440
441 @property
442 def in_ignorableblocks(self):
443 return self.ucdata.ucd_block.get(self.value) in (
444 "Combining Diacritical Marks for Symbols",
445 "Musical Symbols",
446 "Ancient Greek Musical Notation",
447 )
448
449 @property
450 def oldhanguljamo(self):
451 return self.ucdata.ucd_hst.get(self.value) in ("L", "V", "T")
452
453 @property
454 def in_lettersdigits(self):
455 return self.general_category in ("Ll", "Lu", "Lo", "Nd", "Lm", "Mn", "Mc")
456
457 @property
458 def idna2008_status(self):
459 if self.exception_value:
460 return self.exception_value
461 elif self.compat_value:
462 return self.compat_value
463 elif self.unassigned:
464 return "UNASSIGNED"
465 elif self.ldh:
466 return "PVALID"
467 elif self.join_control:
468 return "CONTEXTJ"
469 elif self.unstable:
470 return "DISALLOWED"
471 elif self.in_ignorableproperties:
472 return "DISALLOWED"
473 elif self.in_ignorableblocks:
474 return "DISALLOWED"
475 elif self.oldhanguljamo:
476 return "DISALLOWED"
477 elif self.in_lettersdigits:
478 return "PVALID"
479 else:
480 return "DISALLOWED"
481
482 @property
483 def uts46_data(self):
484 return self.ucdata.ucd_idnamt.get(self.value, None)
485
486 @property
487 def uts46_status(self):
488 return " ".join(self.uts46_data)
489
490
491 def diagnose_codepoint(codepoint, args, ucdata):
492 cp = CodePoint(codepoint, ucdata=ucdata)
493
494 print("U+{:04X}:".format(codepoint))
495 print(" Name: {}".format(cp.name))
496 print("1 Exceptions: {}".format(exceptions.get(codepoint, False)))
497 print("2 Backwards Compat: {}".format(backwardscompatible.get(codepoint, False)))
498 print("3 Unassigned: {}".format(cp.unassigned))
499 print("4 LDH: {}".format(cp.ldh))
500 print(" Properties: {}".format(" ".join(sorted(ucdata.ucd_props.get(codepoint, ["None"])))))
501 print("5 .Join Control: {}".format(cp.join_control))
502 print(" NFKC CF: {}".format(" ".join(["U+{:04X}".format(ord(x)) for x in cp.nfkc_cf])))
503 print("6 .Unstable: {}".format(cp.unstable))
504 print("7 .Ignorable Prop: {}".format(cp.in_ignorableproperties))
505 print(" Block: {}".format(ucdata.ucd_block.get(codepoint, None)))
506 print("8 .Ignorable Block: {}".format(cp.in_ignorableblocks))
507 print(" Hangul Syll Type: {}".format(ucdata.ucd_hst.get(codepoint, None)))
508 print("9 .Old Hangul Jamo: {}".format(cp.oldhanguljamo))
509 print(" General Category: {}".format(cp.general_category))
510 print("10 .Letters Digits: {}".format(cp.in_lettersdigits))
511 print("== IDNA 2008: {}".format(cp.idna2008_status))
512 print("== UTS 46: {}".format(cp.uts46_status))
513 print("(Unicode {})".format(ucdata.version))
514
515
516 def ucdrange(start, end):
517 if start == end:
518 return ("{:04X}".format(start.value), start.name)
519 else:
520 return ("{:04X}..{:04X}".format(start.value, end.value), "{}..{}".format(start.name, end.name))
521
522
523 def upper_hex(value):
524 num = hex(value)
525 return num[:2] + num[2:].upper()
526
527
528 def optimised_list(d):
529 values = intranges_from_list(d)
530 if len(values) == 1:
531 for value in values:
532 # Respect ruff format style
533 yield "({},),".format(upper_hex(value))
534 else:
535 yield "("
536 for value in values:
537 yield " {},".format(upper_hex(value))
538 yield " ),"
539
540
541 def make_table(args, ucdata):
542 last_status = None
543 cps = []
544 table_data = []
545
546 for cp in ucdata.codepoints():
547 status = cp.idna2008_status
548 if last_status and last_status != status:
549 (values, description) = ucdrange(cps[0], cps[-1])
550 table_data.append([values, last_status, description])
551 cps = []
552 last_status = status
553 cps.append(cp)
554 (values, description) = ucdrange(cps[0], cps[-1])
555 table_data.append([values, last_status, description])
556
557 if args.dir:
558 f = open("{}/idna-table-{}.txt".format(args.dir, ucdata.version), "wb")
559 for row in table_data:
560 f.write("{:12}; {:12}# {:.44}\n".format(*row).encode("ascii"))
561 f.close()
562
563 else:
564 for row in table_data:
565 print("{:12}; {:12}# {:.44}".format(*row))
566
567
568 def idna_libdata(ucdata):
569 yield "# This file is automatically generated by tools/idna-data\n"
570 yield '__version__ = "{}"\n'.format(ucdata.version)
571
572 #
573 # Script classifications are used by some CONTEXTO rules in RFC 5891
574 #
575 yield "scripts = {"
576 for script in CONTEXT_SCRIPTS:
577 prefix = ' "{}": '.format(script)
578 for line in optimised_list(ucdata.ucd_s[script]):
579 yield prefix + line
580 prefix = ""
581 yield "}"
582
583 #
584 # Joining types are used by CONTEXTJ rule A.1. Grouped by type and
585 # range-encoded so the table stays compact and lookups use intranges.
586 #
587 yield ""
588 yield ""
589 yield "joining_types = {"
590 joining_types = {}
591 for cp in ucdata.codepoints():
592 if cp.joining_type:
593 joining_types.setdefault(cp.joining_type, set()).add(cp.value)
594 for jt in sorted(joining_types):
595 prefix = ' "{}": '.format(jt)
596 for line in optimised_list(joining_types[jt]):
597 yield prefix + line
598 prefix = ""
599 yield "}"
600
601 #
602 # These are the classification of codepoints into PVALID, CONTEXTO, CONTEXTJ, etc.
603 #
604 yield ""
605 yield ""
606 yield "codepoint_classes = {"
607 classes = {}
608 for cp in ucdata.codepoints():
609 status = cp.idna2008_status
610 if status in ("UNASSIGNED", "DISALLOWED"):
611 continue
612 if not status in classes:
613 classes[status] = set()
614 classes[status].add(cp.value)
615 for status in ["PVALID", "CONTEXTJ", "CONTEXTO"]:
616 prefix = ' "{}": '.format(status)
617 for line in optimised_list(classes[status]):
618 yield prefix + line
619 prefix = ""
620 yield "}"
621
622
623 def uts46_ranges(ucdata):
624 """Yield (codepoint, status, mapping_or_None) for each UTS #46 row.
625
626 Consecutive codepoints with identical (status, mapping) are collapsed:
627 only the first codepoint of each run is yielded, except for the dense
628 0x00..0xFF prefix where every codepoint is yielded so callers can use
629 the fast index == codepoint path."""
630 last = (None, None)
631 for cp in ucdata.codepoints():
632 fields = cp.uts46_data
633 if not fields:
634 continue
635 status, mapping = UTS46_STATUSES[fields[0]]
636 if mapping:
637 mapping = "".join(chr(int(codepoint, 16)) for codepoint in fields[1].split())
638 else:
639 mapping = None
640 if cp.value > 255 and (status, mapping) == last:
641 continue
642 last = (status, mapping)
643 yield cp.value, status, mapping
644
645
646 def uts46_libdata(ucdata):
647 yield "# This file is automatically generated by tools/idna-data\n"
648 yield "from __future__ import annotations\n"
649 yield "from array import array\n"
650 yield '"""IDNA Mapping Table from UTS46."""\n\n'
651
652 yield '__version__ = "{}"\n'.format(ucdata.version)
653
654 rows = list(uts46_ranges(ucdata))
655
656 yield "uts46_starts: array[int] = array("
657 yield ' "I",'
658 yield " ("
659 for cp, _status, _mapping in rows:
660 yield " 0x{:X},".format(cp)
661 yield " ),"
662 yield ")"
663 yield ""
664
665 yield "uts46_statuses: bytes = ("
666 chunk = []
667 for _cp, status, _mapping in rows:
668 chunk.append(status)
669 if len(chunk) == 64:
670 yield ' b"{}"'.format("".join(chunk))
671 chunk = []
672 if chunk:
673 yield ' b"{}"'.format("".join(chunk))
674 yield ")"
675 yield ""
676
677 yield "uts46_replacements: tuple[str | None, ...] = ("
678 for _cp, _status, mapping in rows:
679 if mapping is None:
680 yield " None,"
681 else:
682 yield " {},".format(stable_repr(mapping, ucdata, quote='"'))
683 yield ")"
684
685
686 def uts46_tests(ucdata):
687 skip_tests = [
688 # These appear to be errors in the test vectors so we skip building tests for
689 # them from UTS46 data. All relate to incorrectly applying bidi rules across
690 # label boundaries. Appears independently confirmed at
691 # http://www.alvestrand.no/pipermail/idna-update/2017-January/007946.html
692 "0\u00e0.\u05d0",
693 "0a\u0300.\u05d0",
694 "0A\u0300.\u05d0",
695 "0\u00c0.\u05d0",
696 "xn--0-sfa.xn--4db",
697 "\u00e0\u02c7.\u05d0",
698 "a\u0300\u02c7.\u05d0",
699 "A\u0300\u02c7.\u05d0",
700 "\u00c0\u02c7.\u05d0",
701 "xn--0ca88g.xn--4db",
702 "0A.\u05d0",
703 "0a.\u05d0",
704 "0a.xn--4db",
705 "c.xn--0-eha.xn--4db",
706 "c.0\u00fc.\u05d0",
707 "c.0u\u0308.\u05d0",
708 "C.0U\u0308.\u05d0",
709 "C.0\u00dc.\u05d0",
710 "C.0\u00fc.\u05d0",
711 "C.0\u0075\u0308.\u05d0",
712 "\u06b6\u06df\u3002\u2087\ua806",
713 "\u06b6\u06df\u30027\ua806",
714 "xn--pkb6f.xn--7-x93e",
715 "\u06b6\u06df.7\ua806",
716 "1.\uac7e6.\U00010c41\u06d0",
717 "1.\u1100\u1165\u11b56.\U00010c41\u06d0",
718 "1.xn--6-945e.xn--glb1794k",
719 # Test vectors that expect an error when there is a trailing
720 # dot.
721 "a.b.c.d.",
722 "xn--gl0as212a.i.",
723 "繱𑖿.i.",
724 "繱𑖿.I.",
725 "xn--1ug6928ac48e.i.",
726 "繱𑖿\u200d.i.",
727 "繱𑖿\u200d.I.",
728 "xn--9hb7344k.",
729 "𐫇١.",
730 "123456789012345678901234567890123456789012345678901234567890123.123456789012345678901234567890123456789012345678901234567890123.123456789012345678901234567890123456789012345678901234567890123.123456789012345678901234567890123456789012345678901234567890b.",
731 "xn--rt6a.",
732 "鱊.",
733 "xn--4-0bd15808a.",
734 "𞤺ߌ4.",
735 "xn--hva754s.",
736 "ⴖͦ.",
737 "xn--ss-f4j.b.",
738 "ss်.b.",
739 "xn--gky8837e.",
740 "璼𝨭.",
741 "xn--7zv.",
742 "梉.",
743 "xn--ss-59d.",
744 "ss۫.",
745 "123456789012345678901234567890123456789012345678901234567890123.1234567890ä123456789012345678901234567890123456789012345.123456789012345678901234567890123456789012345678901234567890123.123456789012345678901234567890123456789012345678901234567890b.",
746 "123456789012345678901234567890123456789012345678901234567890123.xn--1234567890123456789012345678901234567890123456789012345-kue.123456789012345678901234567890123456789012345678901234567890123.123456789012345678901234567890123456789012345678901234567890b.",
747 # Codepoints U+32931 and U+32B9A are new in Unicode 17.0 and have no
748 # bidirectional properties in Python runtimes bundled with Unicode 16.0
749 # or earlier, causing spurious IDNABidiError failures.
750 "\U0003293120.\u97F3.\uA866\u0031.",
751 "xn--20-9802c.xn--0w5a.xn--1-eg4e.",
752 "xn--9-i0j5967eg3qz.ss",
753 "\U00032b9a\u0039\uA369\u17D3.ss",
754 "\U00032b9a\u0039\uA369\u17D3.SS",
755 ]
756
757 yield "# This file is automatically generated by tools/idna-data\n"
758 yield "import unittest\n"
759 yield "import idna\n\n"
760 yield "class UTS46Tests(unittest.TestCase):\n"
761
762 for lineno, fields in ucdata.ucd_uts46tests:
763 (
764 source,
765 to_unicode,
766 to_unicode_status,
767 to_ascii,
768 to_ascii_status,
769 to_ascii_t,
770 to_ascii_t_status,
771 ) = fields
772
773 if source in skip_tests:
774 continue
775
776 # Per UTS46 test vectors, if the result is "", expect a blank string, but
777 # if the result is blank, expect the input string.
778 if to_unicode == '""':
779 to_unicode = ""
780 elif not to_unicode:
781 to_unicode = source
782 if not to_unicode_status:
783 to_unicode_status = "[]"
784 if to_ascii == '""':
785 to_ascii = ""
786 elif not to_ascii:
787 to_ascii = to_unicode
788 if not to_ascii_status:
789 to_ascii_status = to_unicode_status
790 if to_ascii_t == '""':
791 to_ascii_t = ""
792 elif not to_ascii_t:
793 to_ascii_t = to_ascii
794 if not to_ascii_t_status:
795 to_ascii_t_status = to_ascii_status
796
797 # Is this label IDNA 2008 legal according to UTS46 mapping table?
798 nv8 = False
799 for codepoint in to_unicode:
800 try:
801 field = ucdata.ucd_idnamt[ord(codepoint)][2]
802 except IndexError:
803 field = ""
804 if field == "NV8" or field == "XV8":
805 nv8 = ord(codepoint)
806
807 yield " def test_uts46_{}(self):".format(lineno)
808
809 source_repr = stable_repr(source, ucdata)
810 if to_unicode_status == "[]" and not nv8:
811 yield (
812 " self.assertEqual(idna.decode({}, uts46=True, strict=True), {})".format(
813 source_repr, stable_repr(to_unicode, ucdata)
814 )
815 )
816 else:
817 yield (" self.assertRaises(idna.IDNAError, idna.decode, {}, strict=True)".format(source_repr))
818 if to_ascii_status == "[]" and not nv8:
819 yield (
820 " self.assertEqual(idna.encode({}, uts46=True, strict=True), b{})".format(
821 source_repr, stable_repr(to_ascii, ucdata)
822 )
823 )
824 else:
825 yield (" self.assertRaises(idna.IDNAError, idna.encode, {}, strict=True)".format(source_repr))
826 yield ""
827
828
829 def make_libdata(args, ucdata):
830 dest_dir = args.dir or "."
831 test_dir = args.test_dir or dest_dir
832
833 target_filename = os.path.join(dest_dir, "idnadata.py")
834 with open(target_filename, "wb") as target:
835 for line in idna_libdata(ucdata):
836 target.write((line + "\n").encode("utf-8"))
837
838 target_filename = os.path.join(dest_dir, "uts46data.py")
839 with open(target_filename, "wb") as target:
840 for line in uts46_libdata(ucdata):
841 target.write((line + "\n").encode("utf-8"))
842
843 target_filename = os.path.join(test_dir, "test_idna_uts46.py")
844 with open(target_filename, "wb") as target:
845 for line in uts46_tests(ucdata):
846 target.write((line + "\n").encode("utf-8"))
847
848
849 def arg_error(message, parser):
850 parser.print_usage()
851 print("{}: error: {}".format(sys.argv[0], message))
852 sys.exit(2)
853
854
855 def main():
856 parser = argparse.ArgumentParser(description="Determine IDNA code-point validity data")
857 parser.add_argument(
858 "action", type=str, default="preferred", help="Task to perform (make-libdata, make-tables, <codepoint>)"
859 )
860
861 parser.add_argument("--version", type=str, default="preferred", help="Unicode version to use (preferred, latest, <x.y.z>)")
862 parser.add_argument("--source", type=str, default=None, help="Where to fetch Unicode data (file path)")
863 parser.add_argument("--dir", type=str, default=None, help="Where to export the output")
864 parser.add_argument("--test-dir", type=str, default=None, help="Where to export test files (defaults to --dir)")
865 parser.add_argument("--cache", type=str, default=None, help="Where to cache Unicode data")
866 parser.add_argument("--no-cache", action="store_true", help="Don't cache Unicode data")
867
868 args = parser.parse_args()
869
870 if args.version == "preferred":
871 target_version = PREFERRED_VERSION
872 else:
873 target_version = args.version
874
875 if args.cache and args.no_cache:
876 arg_error("I can't both --cache and --no-cache", parser)
877 cache = args.cache or DEFAULT_CACHE_DIR
878 if args.no_cache:
879 cache = None
880
881 ucdata = UnicodeData(target_version, cache, args)
882
883 if args.action == "make-table":
884 make_table(args, ucdata)
885 elif args.action == "make-libdata":
886 make_libdata(args, ucdata)
887 else:
888 result = re.match(r"(?i)^(U\+|)(?P<cp>[0-9A-F]{4,6})$", args.action)
889 if result:
890 codepoint = int(result.group("cp"), 16)
891 diagnose_codepoint(codepoint, args, ucdata)
892 sys.exit(0)
893 arg_error("Don't recognize action or codepoint value", parser)
894
895
896 if __name__ == "__main__":
897 main()