summaryrefslogtreecommitdiffstats
path: root/Tools/unicode/makeunicodedata.py
blob: 3a362ec7f02174314e10434d5bf0df034a141f4f (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
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
#
# (re)generate unicode property and type databases
#
# this script converts a unicode 3.0 database file to
# Modules/unicodedata_db.h, Modules/unicodename_db.h,
# and Objects/unicodetype_db.h
#
# history:
# 2000-09-24 fl   created (based on bits and pieces from unidb)
# 2000-09-25 fl   merged tim's splitbin fixes, separate decomposition table
# 2000-09-25 fl   added character type table
# 2000-09-26 fl   added LINEBREAK, DECIMAL, and DIGIT flags/fields (2.0)
# 2000-11-03 fl   expand first/last ranges
# 2001-01-19 fl   added character name tables (2.1)
#
# written by Fredrik Lundh (fredrik@pythonware.com), September 2000
#

import sys

SCRIPT = sys.argv[0]
VERSION = "2.1"

UNICODE_DATA = "UnicodeData-Latest.txt"

CATEGORY_NAMES = [ "Cn", "Lu", "Ll", "Lt", "Mn", "Mc", "Me", "Nd",
    "Nl", "No", "Zs", "Zl", "Zp", "Cc", "Cf", "Cs", "Co", "Cn", "Lm",
    "Lo", "Pc", "Pd", "Ps", "Pe", "Pi", "Pf", "Po", "Sm", "Sc", "Sk",
    "So" ]

BIDIRECTIONAL_NAMES = [ "", "L", "LRE", "LRO", "R", "AL", "RLE", "RLO",
    "PDF", "EN", "ES", "ET", "AN", "CS", "NSM", "BN", "B", "S", "WS",
    "ON" ]

# note: should match definitions in Objects/unicodectype.c
ALPHA_MASK = 0x01
DECIMAL_MASK = 0x02
DIGIT_MASK = 0x04
LOWER_MASK = 0x08
LINEBREAK_MASK = 0x10
SPACE_MASK = 0x20
TITLE_MASK = 0x40
UPPER_MASK = 0x80

def maketables(trace=0):

    print "--- Reading", UNICODE_DATA, "..."

    unicode = UnicodeData(UNICODE_DATA)

    print len(filter(None, unicode.table)), "characters"

    makeunicodedata(unicode, trace)
    makeunicodetype(unicode, trace)
    makeunicodename(unicode, trace)

# --------------------------------------------------------------------
# unicode character properties

def makeunicodedata(unicode, trace):

    dummy = (0, 0, 0, 0)
    table = [dummy]
    cache = {0: dummy}
    index = [0] * len(unicode.chars)

    FILE = "Modules/unicodedata_db.h"

    print "--- Preparing", FILE, "..."

    # 1) database properties

    for char in unicode.chars:
        record = unicode.table[char]
        if record:
            # extract database properties
            category = CATEGORY_NAMES.index(record[2])
            combining = int(record[3])
            bidirectional = BIDIRECTIONAL_NAMES.index(record[4])
            mirrored = record[9] == "Y"
            item = (
                category, combining, bidirectional, mirrored
                )
            # add entry to index and item tables
            i = cache.get(item)
            if i is None:
                cache[item] = i = len(table)
                table.append(item)
            index[char] = i

    # 2) decomposition data

    # FIXME: <fl> using the encoding stuff from unidb would save
    # another 50k or so, but I'll leave that for 2.1...

    decomp_data = [""]
    decomp_index = [0] * len(unicode.chars)

    for char in unicode.chars:
        record = unicode.table[char]
        if record:
            if record[5]:
                try:
                    i = decomp_data.index(record[5])
                except ValueError:
                    i = len(decomp_data)
                    decomp_data.append(record[5])
            else:
                i = 0
            decomp_index[char] = i

    print len(table), "unique properties"
    print len(decomp_data), "unique decomposition entries"

    print "--- Writing", FILE, "..."

    fp = open(FILE, "w")
    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
    print >>fp
    print >>fp, "/* a list of unique database records */"
    print >>fp, \
          "const _PyUnicode_DatabaseRecord _PyUnicode_Database_Records[] = {"
    for item in table:
        print >>fp, "    {%d, %d, %d, %d}," % item
    print >>fp, "};"
    print >>fp

    # FIXME: <fl> the following tables could be made static, and
    # the support code moved into unicodedatabase.c

    print >>fp, "/* string literals */"
    print >>fp, "const char *_PyUnicode_CategoryNames[] = {"
    for name in CATEGORY_NAMES:
        print >>fp, "    \"%s\"," % name
    print >>fp, "    NULL"
    print >>fp, "};"

    print >>fp, "const char *_PyUnicode_BidirectionalNames[] = {"
    for name in BIDIRECTIONAL_NAMES:
        print >>fp, "    \"%s\"," % name
    print >>fp, "    NULL"
    print >>fp, "};"

    print >>fp, "static const char *decomp_data[] = {"
    for name in decomp_data:
        print >>fp, "    \"%s\"," % name
    print >>fp, "    NULL"
    print >>fp, "};"

    # split record index table
    index1, index2, shift = splitbins(index, trace)

    print >>fp, "/* index tables for the database records */"
    print >>fp, "#define SHIFT", shift
    Array("index1", index1).dump(fp)
    Array("index2", index2).dump(fp)

    # split decomposition index table
    index1, index2, shift = splitbins(decomp_index, trace)

    print >>fp, "/* index tables for the decomposition data */"
    print >>fp, "#define DECOMP_SHIFT", shift
    Array("decomp_index1", index1).dump(fp)
    Array("decomp_index2", index2).dump(fp)

    fp.close()

# --------------------------------------------------------------------
# unicode character type tables

def makeunicodetype(unicode, trace):

    FILE = "Objects/unicodetype_db.h"

    print "--- Preparing", FILE, "..."

    # extract unicode types
    dummy = (0, 0, 0, 0, 0, 0)
    table = [dummy]
    cache = {0: dummy}
    index = [0] * len(unicode.chars)

    for char in unicode.chars:
        record = unicode.table[char]
        if record:
            # extract database properties
            category = record[2]
            bidirectional = record[4]
            flags = 0
            if category in ["Lm", "Lt", "Lu", "Ll", "Lo"]:
                flags |= ALPHA_MASK
            if category == "Ll":
                flags |= LOWER_MASK
            if category == "Zl" or bidirectional == "B":
                flags |= LINEBREAK_MASK
            if category == "Zs" or bidirectional in ("WS", "B", "S"):
                flags |= SPACE_MASK
            if category == "Lt":
                flags |= TITLE_MASK
            if category == "Lu":
                flags |= UPPER_MASK
            # use delta predictor for upper/lower/title
            if record[12]:
                upper = (int(record[12], 16) - char) & 0xffff
            else:
                upper = 0
            if record[13]:
                lower = (int(record[13], 16) - char) & 0xffff
            else:
                lower = 0
            if record[14]:
                title = (int(record[14], 16) - char) & 0xffff
            else:
                title = 0
            # decimal digit, integer digit
            decimal = 0
            if record[6]:
                flags |= DECIMAL_MASK
                decimal = int(record[6])
            digit = 0
            if record[7]:
                flags |= DIGIT_MASK
                digit = int(record[7])
            item = (
                flags, upper, lower, title, decimal, digit
                )
            # add entry to index and item tables
            i = cache.get(item)
            if i is None:
                cache[item] = i = len(table)
                table.append(item)
            index[char] = i

    print len(table), "unique character type entries"

    print "--- Writing", FILE, "..."

    fp = open(FILE, "w")
    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
    print >>fp
    print >>fp, "/* a list of unique character type descriptors */"
    print >>fp, "const _PyUnicode_TypeRecord _PyUnicode_TypeRecords[] = {"
    for item in table:
        print >>fp, "    {%d, %d, %d, %d, %d, %d}," % item
    print >>fp, "};"
    print >>fp

    # split decomposition index table
    index1, index2, shift = splitbins(index, trace)

    print >>fp, "/* type indexes */"
    print >>fp, "#define SHIFT", shift
    Array("index1", index1).dump(fp)
    Array("index2", index2).dump(fp)

    fp.close()

# --------------------------------------------------------------------
# unicode name database

def makeunicodename(unicode, trace):

    FILE = "Modules/unicodename_db.h"

    print "--- Preparing", FILE, "..."

    # collect names
    names = [None] * len(unicode.chars)

    for char in unicode.chars:
        record = unicode.table[char]
        if record:
            name = record[1].strip()
            if name and name[0] != "<":
                names[char] = name + chr(0)

    print len(filter(lambda n: n is not None, names)), "distinct names"

    # collect unique words from names (note that we differ between
    # words inside a sentence, and words ending a sentence.  the
    # latter includes the trailing null byte.

    words = {}
    n = b = 0
    for char in unicode.chars:
        name = names[char]
        if name:
            w = name.split()
            b = b + len(name)
            n = n + len(w)
            for w in w:
                l = words.get(w)
                if l:
                    l.append(None)
                else:
                    words[w] = [len(words)]

    print n, "words in text;", b, "bytes"

    wordlist = words.items()

    # sort on falling frequency
    wordlist.sort(lambda a, b: len(b[1])-len(a[1]))

    # statistics
    n = 0
    for i in range(128):
        n = n + len(wordlist[i][1])
    print n, "short words (7-bit indices)"

    # pick the 128 most commonly used words, and sort the rest on
    # falling length (to maximize overlap)

    wordlist, wordtail = wordlist[:128], wordlist[128:]
    wordtail.sort(lambda a, b: len(b[0])-len(a[0]))
    wordlist.extend(wordtail)

    # generate lexicon from words

    lexicon_offset = [0]
    lexicon = ""
    words = {}

    # build a lexicon string
    offset = 0
    for w, x in wordlist:
        # encoding: bit 7 indicates last character in word (chr(128)
        # indicates the last character in an entire string)
        ww = w[:-1] + chr(ord(w[-1])+128)
        # reuse string tails, when possible
        o = string.find(lexicon, ww)
        if o < 0:
            o = offset
            lexicon = lexicon + ww
            offset = offset + len(w)
        words[w] = len(lexicon_offset)
        lexicon_offset.append(offset)

    print len(words), "words in lexicon;", len(lexicon), "bytes"

    assert len(words) < 32768 # 15-bit word indices

    lexicon = map(ord, lexicon)

    # generate phrasebook from names and lexicon
    phrasebook = [0]
    phrasebook_offset = [0] * len(unicode.chars)
    for char in unicode.chars:
        name = names[char]
        if name:
            w = name.split()
            phrasebook_offset[char] = len(phrasebook)
            for w in w:
                i = words[w]
                if i < 128:
                    phrasebook.append(128+i)
                else:
                    phrasebook.append(i>>8)
                    phrasebook.append(i&255)

    #
    # unicode name hash table

    # extract names
    data = []
    for char in unicode.chars:
        record = unicode.table[char]
        if record:
            name = record[1].strip()
            if name and name[0] != "<":
                data.append((name, char))

    # the magic number 47 was chosen to minimize the number of
    # collisions on the current data set.  if you like, change it
    # and see what happens...

    codehash = Hash("code", data, 47)

    print "--- Writing", FILE, "..."

    fp = open(FILE, "w")
    print >>fp, "/* this file was generated by %s %s */" % (SCRIPT, VERSION)
    print >>fp
    print >>fp, "#define NAME_MAXLEN", 256
    print >>fp
    print >>fp, "/* lexicon */"
    Array("lexicon", lexicon).dump(fp)
    Array("lexicon_offset", lexicon_offset).dump(fp)

    # split decomposition index table
    offset1, offset2, shift = splitbins(phrasebook_offset, trace)

    print >>fp, "/* code->name phrasebook */"
    print >>fp, "#define phrasebook_shift", shift

    Array("phrasebook", phrasebook).dump(fp)
    Array("phrasebook_offset1", offset1).dump(fp)
    Array("phrasebook_offset2", offset2).dump(fp)

    print >>fp, "/* name->code dictionary */"
    codehash.dump(fp)

    fp.close()

# --------------------------------------------------------------------
# the following support code is taken from the unidb utilities
# Copyright (c) 1999-2000 by Secret Labs AB

# load a unicode-data file from disk

import string, sys

class UnicodeData:

    def __init__(self, filename, expand=1):
        file = open(filename)
        table = [None] * 65536
        while 1:
            s = file.readline()
            if not s:
                break
            s = string.split(string.strip(s), ";")
            char = string.atoi(s[0], 16)
            table[char] = s

        # expand first-last ranges (ignore surrogates and private use)
        if expand:
            field = None
            for i in range(0, 0xD800):
                s = table[i]
                if s:
                    if s[1][-6:] == "First>":
                        s[1] = ""
                        field = s[:]
                    elif s[1][-5:] == "Last>":
                        s[1] = ""
                        field = None
                elif field:
                    field[0] = hex(i)
                    table[i] = field

        # public attributes
        self.filename = filename
        self.table = table
        self.chars = range(65536) # unicode

    def uselatin1(self):
        # restrict character range to ISO Latin 1
        self.chars = range(256)

# hash table tools

# this is a straight-forward reimplementation of Python's built-in
# dictionary type, using a static data structure, and a custom string
# hash algorithm.

def myhash(s, magic):
    h = 0
    for c in map(ord, string.upper(s)):
        h = (h * magic) + c
        ix = h & 0xff000000
        if ix:
            h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff
    return h

SIZES = [
    (4,3), (8,3), (16,3), (32,5), (64,3), (128,3), (256,29), (512,17),
    (1024,9), (2048,5), (4096,83), (8192,27), (16384,43), (32768,3),
    (65536,45), (131072,9), (262144,39), (524288,39), (1048576,9),
    (2097152,5), (4194304,3), (8388608,33), (16777216,27)
]

class Hash:
    def __init__(self, name, data, magic):
        # turn a (key, value) list into a static hash table structure

        # determine table size
        for size, poly in SIZES:
            if size > len(data):
                poly = size + poly
                break
        else:
            raise AssertionError, "ran out of polynominals"

        print size, "slots in hash table"

        table = [None] * size

        mask = size-1

        n = 0

        hash = myhash

        # initialize hash table
        for key, value in data:
            h = hash(key, magic)
            i = (~h) & mask
            v = table[i]
            if v is None:
                table[i] = value
                continue
            incr = (h ^ (h >> 3)) & mask;
            if not incr:
                incr = mask
            while 1:
                n = n + 1
                i = (i + incr) & mask
                v = table[i]
                if v is None:
                    table[i] = value
                    break
                incr = incr << 1
                if incr > mask:
                    incr = incr ^ poly

        print n, "collisions"
        self.collisions = n

        for i in range(len(table)):
            if table[i] is None:
                table[i] = 0

        self.data = Array(name + "_hash", table)
        self.magic = magic
        self.name = name
        self.size = size
        self.poly = poly

    def dump(self, file):
        # write data to file, as a C array
        self.data.dump(file)
        file.write("#define %s_magic %d\n" % (self.name, self.magic))
        file.write("#define %s_size %d\n" % (self.name, self.size))
        file.write("#define %s_poly %d\n" % (self.name, self.poly))

# stuff to deal with arrays of unsigned integers

class Array:

    def __init__(self, name, data):
        self.name = name
        self.data = data

    def dump(self, file):
        # write data to file, as a C array
        size = getsize(self.data)
        # print >>sys.stderr, self.name+":", size*len(self.data), "bytes"
        file.write("static ")
        if size == 1:
            file.write("unsigned char")
        elif size == 2:
            file.write("unsigned short")
        else:
            file.write("unsigned int")
        file.write(" " + self.name + "[] = {\n")
        if self.data:
            s = "    "
            for item in self.data:
                i = str(item) + ", "
                if len(s) + len(i) > 78:
                    file.write(s + "\n")
                    s = "    " + i
                else:
                    s = s + i
            if string.strip(s):
                file.write(s + "\n")
        file.write("};\n\n")

def getsize(data):
    # return smallest possible integer size for the given array
    maxdata = max(data)
    if maxdata < 256:
        return 1
    elif maxdata < 65536:
        return 2
    else:
        return 4

def splitbins(t, trace=0):
    """t, trace=0 -> (t1, t2, shift).  Split a table to save space.

    t is a sequence of ints.  This function can be useful to save space if
    many of the ints are the same.  t1 and t2 are lists of ints, and shift
    is an int, chosen to minimize the combined size of t1 and t2 (in C
    code), and where for each i in range(len(t)),
        t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
    where mask is a bitmask isolating the last "shift" bits.

    If optional arg trace is non-zero (default zero), progress info
    is printed to sys.stderr.  The higher the value, the more info
    you'll get.
    """

    import sys
    if trace:
        def dump(t1, t2, shift, bytes):
            print >>sys.stderr, "%d+%d bins at shift %d; %d bytes" % (
                len(t1), len(t2), shift, bytes)
        print >>sys.stderr, "Size of original table:", len(t)*getsize(t), \
                            "bytes"
    n = len(t)-1    # last valid index
    maxshift = 0    # the most we can shift n and still have something left
    if n > 0:
        while n >> 1:
            n >>= 1
            maxshift += 1
    del n
    bytes = sys.maxint  # smallest total size so far
    t = tuple(t)    # so slices can be dict keys
    for shift in range(maxshift + 1):
        t1 = []
        t2 = []
        size = 2**shift
        bincache = {}
        for i in range(0, len(t), size):
            bin = t[i:i+size]
            index = bincache.get(bin)
            if index is None:
                index = len(t2)
                bincache[bin] = index
                t2.extend(bin)
            t1.append(index >> shift)
        # determine memory size
        b = len(t1)*getsize(t1) + len(t2)*getsize(t2)
        if trace > 1:
            dump(t1, t2, shift, b)
        if b < bytes:
            best = t1, t2, shift
            bytes = b
    t1, t2, shift = best
    if trace:
        print >>sys.stderr, "Best:",
        dump(t1, t2, shift, bytes)
    if __debug__:
        # exhaustively verify that the decomposition is correct
        mask = ~((~0) << shift) # i.e., low-bit mask of shift bits
        for i in xrange(len(t)):
            assert t[i] == t2[(t1[i >> shift] << shift) + (i & mask)]
    return best

if __name__ == "__main__":
    maketables(1)