mkstringprep.py 9.76 KB
Newer Older
1
import re, unicodedata, sys
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

if sys.maxunicode == 65535:
    raise RuntimeError, "need UCS-4 Python"

def gen_category(cats):
    for i in range(0, 0x110000):
        if unicodedata.category(unichr(i)) in cats:
            yield(i)

def gen_bidirectional(cats):
    for i in range(0, 0x110000):
        if unicodedata.bidirectional(unichr(i)) in cats:
            yield(i)

def compact_set(l):
    single = []
    tuple = []
    prev = None
    span = 0
    for e in l:
        if prev is None:
            prev = e
            span = 0
            continue
        if prev+span+1 != e:
            if span > 2:
                tuple.append((prev,prev+span+1))
            else:
                for i in range(prev, prev+span+1):
                    single.append(i)
            prev = e
            span = 0
        else:
            span += 1
    if span:
        tuple.append((prev,prev+span+1))
    else:
        single.append(prev)
    tuple = " + ".join(["range(%d,%d)" % t for t in tuple])
    if not single:
42
        return "set(%s)" % tuple
43
    if not tuple:
44 45
        return "set(%s)" % repr(single)
    return "set(%s + %s)" % (repr(single),tuple)
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

############## Read the tables in the RFC #######################

data = open("rfc3454.txt").readlines()

tables = []
curname = None
for l in data:
    l = l.strip()
    if not l:
        continue
    # Skip RFC page breaks
    if l.startswith("Hoffman & Blanchet") or\
       l.startswith("RFC 3454"):
        continue
    # Find start/end lines
    m = re.match("----- (Start|End) Table ([A-Z](.[0-9])+) -----", l)
    if m:
        if m.group(1) == "Start":
            if curname:
                raise "Double Start",(curname, l)
            curname = m.group(2)
            table = {}
            tables.append((curname, table))
            continue
        else:
            if not curname:
                raise "End without start", l
            curname = None
            continue
    if not curname:
        continue
    # Now we are in a table
    fields = l.split(";")
    if len(fields) > 1:
        # Drop comment field
        fields = fields[:-1]
    if len(fields) == 1:
        fields = fields[0].split("-")
        if len(fields) > 1:
            # range
            try:
                start, end = fields
            except ValueError:
                raise "Unpacking problem", l
        else:
            start = end = fields[0]
        start = int(start, 16)
        end = int(end, 16)
        for i in range(start, end+1):
            table[i] = i
    else:
        code, value = fields
        value = value.strip()
        if value:
            value = [int(v, 16) for v in value.split(" ")]
        else:
            # table B.1
            value = None
        table[int(code, 16)] = value

########### Generate compact Python versions of the tables #############

print """# This file is generated by mkstringprep.py. DO NOT EDIT.
\"\"\"Library that exposes various tables found in the StringPrep RFC 3454.

There are two kinds of tables: sets, for which a member test is provided,
and mappings, for which a mapping function is provided.
\"\"\"

116
import unicodedata
117 118 119 120 121 122 123 124 125
"""

print "assert unicodedata.unidata_version == %s" % repr(unicodedata.unidata_version)

# A.1 is the table of unassigned characters
# XXX Plane 15 PUA is listed as unassigned in Python.
name, table = tables[0]
del tables[0]
assert name == "A.1"
126 127
table = set(table.keys())
Cn = set(gen_category(["Cn"]))
128 129

# FDD0..FDEF are process internal codes
130
Cn -= set(range(0xFDD0, 0xFDF0))
131
# not a character
132 133
Cn -= set(range(0xFFFE, 0x110000, 0x10000))
Cn -= set(range(0xFFFF, 0x110000, 0x10000))
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

# assert table == Cn

print """
def in_table_a1(code):
    if unicodedata.category(code) != 'Cn': return False
    c = ord(code)
    if 0xFDD0 <= c < 0xFDF0: return False
    return (c & 0xFFFF) not in (0xFFFE, 0xFFFF)
"""

# B.1 cannot easily be derived
name, table = tables[0]
del tables[0]
assert name == "B.1"
table = table.keys()
table.sort()
print """
b1_set = """ + compact_set(table) + """
def in_table_b1(code):
    return ord(code) in b1_set
"""

# B.2 and B.3 is case folding.
# It takes CaseFolding.txt into account, which is
# not available in the Python database. Since
# B.2 is derived from B.3, we process B.3 first.
# B.3 supposedly *is* CaseFolding-3.2.0.txt.

name, table_b2 = tables[0]
del tables[0]
assert name == "B.2"

name, table_b3 = tables[0]
del tables[0]
assert name == "B.3"

# B.3 is mostly Python's .lower, except for a number
# of special cases, e.g. considering canonical forms.

b3_exceptions = {}

for k,v in table_b2.items():
    if map(ord, unichr(k).lower()) != v:
        b3_exceptions[k] = u"".join(map(unichr,v))

b3 = b3_exceptions.items()
b3.sort()

print """
b3_exceptions = {"""
for i,(k,v) in enumerate(b3):
    print "0x%x:%s," % (k, repr(v)),
    if i % 4 == 3:
        print
print "}"

print """
def map_table_b3(code):
    r = b3_exceptions.get(ord(code))
    if r is not None: return r
    return code.lower()
"""

def map_table_b3(code):
    r = b3_exceptions.get(ord(code))
    if r is not None: return r
    return code.lower()

# B.2 is case folding for NFKC. This is the same as B.3,
# except where NormalizeWithKC(Fold(a)) !=
# NormalizeWithKC(Fold(NormalizeWithKC(Fold(a))))

def map_table_b2(a):
    al = map_table_b3(a)
    b = unicodedata.normalize("NFKC", al)
    bl = u"".join([map_table_b3(ch) for ch in b])
    c = unicodedata.normalize("NFKC", bl)
    if b != c:
        return c
    else:
        return al

specials = {}
for k,v in table_b2.items():
    if map(ord, map_table_b2(unichr(k))) != v:
        specials[k] = v

# B.3 should not add any additional special cases
assert specials == {}

print """
def map_table_b2(a):
    al = map_table_b3(a)
    b = unicodedata.normalize("NFKC", al)
    bl = u"".join([map_table_b3(ch) for ch in b])
    c = unicodedata.normalize("NFKC", bl)
    if b != c:
        return c
    else:
        return al
"""

# C.1.1 is a table with a single character
name, table = tables[0]
del tables[0]
assert name == "C.1.1"
assert table == {0x20:0x20}

print """
def in_table_c11(code):
    return code == u" "
"""

# C.1.2 is the rest of all space characters
name, table = tables[0]
del tables[0]
assert name == "C.1.2"

253 254
# table = set(table.keys())
# Zs = set(gen_category(["Zs"])) - set([0x20])
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
# assert Zs == table

print """
def in_table_c12(code):
    return unicodedata.category(code) == "Zs" and code != u" "

def in_table_c11_c12(code):
    return unicodedata.category(code) == "Zs"
"""

# C.2.1 ASCII control characters
name, table_c21 = tables[0]
del tables[0]
assert name == "C.2.1"

270 271 272
Cc = set(gen_category(["Cc"]))
Cc_ascii = Cc & set(range(128))
table_c21 = set(table_c21.keys())
273 274 275 276 277 278 279 280 281 282 283 284 285 286
assert Cc_ascii == table_c21

print """
def in_table_c21(code):
    return ord(code) < 128 and unicodedata.category(code) == "Cc"
"""

# C.2.2 Non-ASCII control characters. It also includes
# a number of characters in category Cf.
name, table_c22 = tables[0]
del tables[0]
assert name == "C.2.2"

Cc_nonascii = Cc - Cc_ascii
287
table_c22 = set(table_c22.keys())
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
assert len(Cc_nonascii - table_c22) == 0

specials = list(table_c22 - Cc_nonascii)
specials.sort()

print """c22_specials = """ + compact_set(specials) + """
def in_table_c22(code):
    c = ord(code)
    if c < 128: return False
    if unicodedata.category(code) == "Cc": return True
    return c in c22_specials

def in_table_c21_c22(code):
    return unicodedata.category(code) == "Cc" or \\
           ord(code) in c22_specials
"""

# C.3 Private use
name, table = tables[0]
del tables[0]
assert name == "C.3"

310 311
Co = set(gen_category(["Co"]))
assert set(table.keys()) == Co
312 313 314 315 316 317 318 319 320 321 322 323

print """
def in_table_c3(code):
    return unicodedata.category(code) == "Co"
"""

# C.4 Non-character code points, xFFFE, xFFFF
# plus process internal codes
name, table = tables[0]
del tables[0]
assert name == "C.4"

324
nonchar = set(range(0xFDD0,0xFDF0) +
325 326
              range(0xFFFE,0x110000,0x10000) +
              range(0xFFFF,0x110000,0x10000))
327
table = set(table.keys())
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
assert table == nonchar

print """
def in_table_c4(code):
    c = ord(code)
    if c < 0xFDD0: return False
    if c < 0xFDF0: return True
    return (ord(code) & 0xFFFF) in (0xFFFE, 0xFFFF)
"""

# C.5 Surrogate codes
name, table = tables[0]
del tables[0]
assert name == "C.5"

343 344
Cs = set(gen_category(["Cs"]))
assert set(table.keys()) == Cs
345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

print """
def in_table_c5(code):
    return unicodedata.category(code) == "Cs"
"""

# C.6 Inappropriate for plain text
name, table = tables[0]
del tables[0]
assert name == "C.6"

table = table.keys()
table.sort()

print """
c6_set = """ + compact_set(table) + """
def in_table_c6(code):
    return ord(code) in c6_set
"""

# C.7 Inappropriate for canonical representation
name, table = tables[0]
del tables[0]
assert name == "C.7"

table = table.keys()
table.sort()

print """
c7_set = """ + compact_set(table) + """
def in_table_c7(code):
    return ord(code) in c7_set
"""

# C.8 Change display properties or are deprecated
name, table = tables[0]
del tables[0]
assert name == "C.8"

table = table.keys()
table.sort()

print """
c8_set = """ + compact_set(table) + """
def in_table_c8(code):
    return ord(code) in c8_set
"""

# C.9 Tagging characters
name, table = tables[0]
del tables[0]
assert name == "C.9"

table = table.keys()
table.sort()

print """
c9_set = """ + compact_set(table) + """
def in_table_c9(code):
    return ord(code) in c9_set
"""

# D.1 Characters with bidirectional property "R" or "AL"
name, table = tables[0]
del tables[0]
assert name == "D.1"

412 413
RandAL = set(gen_bidirectional(["R","AL"]))
assert set(table.keys()) == RandAL
414 415 416 417 418 419 420 421 422 423 424

print """
def in_table_d1(code):
    return unicodedata.bidirectional(code) in ("R","AL")
"""

# D.2 Characters with bidirectional property "L"
name, table = tables[0]
del tables[0]
assert name == "D.2"

425 426
L = set(gen_bidirectional(["L"]))
assert set(table.keys()) == L
427 428 429 430 431

print """
def in_table_d2(code):
    return unicodedata.bidirectional(code) == "L"
"""