unicodedata.c 37.8 KB
Newer Older
1 2
/* ------------------------------------------------------------------------

3
   unicodedata -- Provides access to the Unicode 5.2 data base.
4

5
   Data was extracted from the Unicode 5.2 UnicodeData.txt file.
6

7 8
   Written by Marc-Andre Lemburg (mal@lemburg.com).
   Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com)
9
   Modified by Martin v. Löwis (martin@v.loewis.de)
10

11
   Copyright (c) Corporation for National Research Initiatives.
12 13 14 15

   ------------------------------------------------------------------------ */

#include "Python.h"
16
#include "ucnhash.h"
17
#include "structmember.h"
18 19

/* character properties */
20

21
typedef struct {
22 23 24 25 26 27 28 29
    const unsigned char category;       /* index into
                                           _PyUnicode_CategoryNames */
    const unsigned char combining;      /* combining class value 0 - 255 */
    const unsigned char bidirectional;  /* index into
                                           _PyUnicode_BidirectionalNames */
    const unsigned char mirrored;       /* true if mirrored in bidir mode */
    const unsigned char east_asian_width;       /* index into
                                                   _PyUnicode_EastAsianWidth */
30
    const unsigned char normalization_quick_check; /* see is_normalized() */
31 32
} _PyUnicode_DatabaseRecord;

33 34 35 36 37
typedef struct change_record {
    /* sequence of fields should be the same as in merge_old_version */
    const unsigned char bidir_changed;
    const unsigned char category_changed;
    const unsigned char decimal_changed;
38
    const unsigned char mirrored_changed;
39
    const double numeric_changed;
40 41
} change_record;

42 43 44 45
/* data file generated by Tools/unicode/makeunicodedata.py */
#include "unicodedata_db.h"

static const _PyUnicode_DatabaseRecord*
46
_getrecord_ex(Py_UCS4 code)
47 48
{
    int index;
49
    if (code >= 0x110000)
50 51 52 53 54 55 56 57 58
        index = 0;
    else {
        index = index1[(code>>SHIFT)];
        index = index2[(index<<SHIFT)+(code&((1<<SHIFT)-1))];
    }

    return &_PyUnicode_Database_Records[index];
}

59 60 61 62 63 64 65 66 67 68 69
/* ------------- Previous-version API ------------------------------------- */
typedef struct previous_version {
    PyObject_HEAD
    const char *name;
    const change_record* (*getrecord)(Py_UCS4);
    Py_UCS4 (*normalization)(Py_UCS4);
} PreviousDBVersion;

#define get_old_record(self, v)    ((((PreviousDBVersion*)self)->getrecord)(v))

static PyMemberDef DB_members[] = {
70
        {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
71 72 73
        {NULL}
};

74
/* forward declaration */
75
static PyTypeObject UCD_Type;
76
#define UCD_Check(o) (Py_TYPE(o)==&UCD_Type)
77 78 79 80 81

static PyObject*
new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4),
                     Py_UCS4 (*normalization)(Py_UCS4))
{
82 83 84 85 86 87
        PreviousDBVersion *self;
        self = PyObject_New(PreviousDBVersion, &UCD_Type);
        if (self == NULL)
                return NULL;
        self->name = name;
        self->getrecord = getrecord;
88
        self->normalization = normalization;
89
        return (PyObject*)self;
90 91
}

92 93 94 95 96 97

static Py_UCS4 getuchar(PyUnicodeObject *obj)
{
    Py_UNICODE *v = PyUnicode_AS_UNICODE(obj);

    if (PyUnicode_GET_SIZE(obj) == 1)
98
        return *v;
99 100 101 102
#ifndef Py_UNICODE_WIDE
    else if ((PyUnicode_GET_SIZE(obj) == 2) &&
             (0xD800 <= v[0] && v[0] <= 0xDBFF) &&
             (0xDC00 <= v[1] && v[1] <= 0xDFFF))
103
        return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
104 105 106 107 108 109
#endif
    PyErr_SetString(PyExc_TypeError,
                    "need a single Unicode character as parameter");
    return (Py_UCS4)-1;
}

110 111
/* --- Module API --------------------------------------------------------- */

112 113 114 115 116 117 118
PyDoc_STRVAR(unicodedata_decimal__doc__,
"decimal(unichr[, default])\n\
\n\
Returns the decimal value assigned to the Unicode character unichr\n\
as integer. If no such value is defined, default is returned, or, if\n\
not given, ValueError is raised.");

119
static PyObject *
120
unicodedata_decimal(PyObject *self, PyObject *args)
121 122 123
{
    PyUnicodeObject *v;
    PyObject *defobj = NULL;
124
    int have_old = 0;
125
    long rc;
126
    Py_UCS4 c;
127

128
    if (!PyArg_ParseTuple(args, "O!|O:decimal", &PyUnicode_Type, &v, &defobj))
129
        return NULL;
130 131
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
132
        return NULL;
133

134
    if (self && UCD_Check(self)) {
135
        const change_record *old = get_old_record(self, c);
136 137 138 139
        if (old->category_changed == 0) {
            /* unassigned */
            have_old = 1;
            rc = -1;
140
        }
141 142 143 144 145 146 147
        else if (old->decimal_changed != 0xFF) {
            have_old = 1;
            rc = old->decimal_changed;
        }
    }

    if (!have_old)
148
        rc = Py_UNICODE_TODECIMAL(c);
149
    if (rc < 0) {
150 151 152
        if (defobj == NULL) {
            PyErr_SetString(PyExc_ValueError,
                            "not a decimal");
153
            return NULL;
154 155 156 157 158
        }
        else {
            Py_INCREF(defobj);
            return defobj;
        }
159
    }
160
    return PyLong_FromLong(rc);
161 162
}

163 164 165 166 167 168 169
PyDoc_STRVAR(unicodedata_digit__doc__,
"digit(unichr[, default])\n\
\n\
Returns the digit value assigned to the Unicode character unichr as\n\
integer. If no such value is defined, default is returned, or, if\n\
not given, ValueError is raised.");

170
static PyObject *
171
unicodedata_digit(PyObject *self, PyObject *args)
172 173 174 175
{
    PyUnicodeObject *v;
    PyObject *defobj = NULL;
    long rc;
176
    Py_UCS4 c;
177

178
    if (!PyArg_ParseTuple(args, "O!|O:digit", &PyUnicode_Type, &v, &defobj))
179
        return NULL;
180 181
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
182
        return NULL;
183
    rc = Py_UNICODE_TODIGIT(c);
184
    if (rc < 0) {
185 186
        if (defobj == NULL) {
            PyErr_SetString(PyExc_ValueError, "not a digit");
187
            return NULL;
188 189 190 191 192
        }
        else {
            Py_INCREF(defobj);
            return defobj;
        }
193
    }
194
    return PyLong_FromLong(rc);
195 196
}

197 198 199 200 201 202 203
PyDoc_STRVAR(unicodedata_numeric__doc__,
"numeric(unichr[, default])\n\
\n\
Returns the numeric value assigned to the Unicode character unichr\n\
as float. If no such value is defined, default is returned, or, if\n\
not given, ValueError is raised.");

204
static PyObject *
205
unicodedata_numeric(PyObject *self, PyObject *args)
206 207 208
{
    PyUnicodeObject *v;
    PyObject *defobj = NULL;
209
    int have_old = 0;
210
    double rc;
211
    Py_UCS4 c;
212

213
    if (!PyArg_ParseTuple(args, "O!|O:numeric", &PyUnicode_Type, &v, &defobj))
214
        return NULL;
215 216 217
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
218

219
    if (self && UCD_Check(self)) {
220
        const change_record *old = get_old_record(self, c);
221 222 223
        if (old->category_changed == 0) {
            /* unassigned */
            have_old = 1;
224
            rc = -1.0;
225
        }
226 227 228 229 230 231 232
        else if (old->decimal_changed != 0xFF) {
            have_old = 1;
            rc = old->decimal_changed;
        }
    }

    if (!have_old)
233
        rc = Py_UNICODE_TONUMERIC(c);
234
    if (rc == -1.0) {
235 236 237 238 239 240 241 242
        if (defobj == NULL) {
            PyErr_SetString(PyExc_ValueError, "not a numeric character");
            return NULL;
        }
        else {
            Py_INCREF(defobj);
            return defobj;
        }
243 244 245 246
    }
    return PyFloat_FromDouble(rc);
}

247 248 249 250 251 252
PyDoc_STRVAR(unicodedata_category__doc__,
"category(unichr)\n\
\n\
Returns the general category assigned to the Unicode character\n\
unichr as string.");

253
static PyObject *
254
unicodedata_category(PyObject *self, PyObject *args)
255 256 257
{
    PyUnicodeObject *v;
    int index;
258
    Py_UCS4 c;
259 260

    if (!PyArg_ParseTuple(args, "O!:category",
261 262
                          &PyUnicode_Type, &v))
        return NULL;
263 264 265 266
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
    index = (int) _getrecord_ex(c)->category;
267
    if (self && UCD_Check(self)) {
268
        const change_record *old = get_old_record(self, c);
269 270 271
        if (old->category_changed != 0xFF)
            index = old->category_changed;
    }
272
    return PyUnicode_FromString(_PyUnicode_CategoryNames[index]);
273 274
}

275 276 277 278 279 280 281
PyDoc_STRVAR(unicodedata_bidirectional__doc__,
"bidirectional(unichr)\n\
\n\
Returns the bidirectional category assigned to the Unicode character\n\
unichr as string. If no such value is defined, an empty string is\n\
returned.");

282
static PyObject *
283
unicodedata_bidirectional(PyObject *self, PyObject *args)
284 285 286
{
    PyUnicodeObject *v;
    int index;
287
    Py_UCS4 c;
288 289

    if (!PyArg_ParseTuple(args, "O!:bidirectional",
290 291
                          &PyUnicode_Type, &v))
        return NULL;
292 293 294 295
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
    index = (int) _getrecord_ex(c)->bidirectional;
296
    if (self && UCD_Check(self)) {
297
        const change_record *old = get_old_record(self, c);
298 299 300 301 302
        if (old->category_changed == 0)
            index = 0; /* unassigned */
        else if (old->bidir_changed != 0xFF)
            index = old->bidir_changed;
    }
303
    return PyUnicode_FromString(_PyUnicode_BidirectionalNames[index]);
304 305
}

306 307 308 309 310 311 312
PyDoc_STRVAR(unicodedata_combining__doc__,
"combining(unichr)\n\
\n\
Returns the canonical combining class assigned to the Unicode\n\
character unichr as integer. Returns 0 if no combining class is\n\
defined.");

313
static PyObject *
314
unicodedata_combining(PyObject *self, PyObject *args)
315 316
{
    PyUnicodeObject *v;
317
    int index;
318
    Py_UCS4 c;
319 320

    if (!PyArg_ParseTuple(args, "O!:combining",
321 322
                          &PyUnicode_Type, &v))
        return NULL;
323 324 325 326
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
    index = (int) _getrecord_ex(c)->combining;
327
    if (self && UCD_Check(self)) {
328
        const change_record *old = get_old_record(self, c);
329 330 331
        if (old->category_changed == 0)
            index = 0; /* unassigned */
    }
332
    return PyLong_FromLong(index);
333 334
}

335 336 337 338 339 340 341
PyDoc_STRVAR(unicodedata_mirrored__doc__,
"mirrored(unichr)\n\
\n\
Returns the mirrored property assigned to the Unicode character\n\
unichr as integer. Returns 1 if the character has been identified as\n\
a \"mirrored\" character in bidirectional text, 0 otherwise.");

342
static PyObject *
343
unicodedata_mirrored(PyObject *self, PyObject *args)
344 345
{
    PyUnicodeObject *v;
346
    int index;
347
    Py_UCS4 c;
348 349

    if (!PyArg_ParseTuple(args, "O!:mirrored",
350 351
                          &PyUnicode_Type, &v))
        return NULL;
352 353 354 355
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
    index = (int) _getrecord_ex(c)->mirrored;
356
    if (self && UCD_Check(self)) {
357
        const change_record *old = get_old_record(self, c);
358 359
        if (old->category_changed == 0)
            index = 0; /* unassigned */
360 361
        else if (old->mirrored_changed != 0xFF)
            index = old->mirrored_changed;
362
    }
363
    return PyLong_FromLong(index);
364 365
}

366 367 368 369 370 371
PyDoc_STRVAR(unicodedata_east_asian_width__doc__,
"east_asian_width(unichr)\n\
\n\
Returns the east asian width assigned to the Unicode character\n\
unichr as string.");

372 373 374 375 376
static PyObject *
unicodedata_east_asian_width(PyObject *self, PyObject *args)
{
    PyUnicodeObject *v;
    int index;
377
    Py_UCS4 c;
378 379

    if (!PyArg_ParseTuple(args, "O!:east_asian_width",
380 381
                          &PyUnicode_Type, &v))
        return NULL;
382 383 384 385
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
    index = (int) _getrecord_ex(c)->east_asian_width;
386
    if (self && UCD_Check(self)) {
387
        const change_record *old = get_old_record(self, c);
388 389 390
        if (old->category_changed == 0)
            index = 0; /* unassigned */
    }
391
    return PyUnicode_FromString(_PyUnicode_EastAsianWidthNames[index]);
392 393
}

394 395 396 397 398 399 400
PyDoc_STRVAR(unicodedata_decomposition__doc__,
"decomposition(unichr)\n\
\n\
Returns the character decomposition mapping assigned to the Unicode\n\
character unichr as string. An empty string is returned in case no\n\
such mapping is defined.");

401
static PyObject *
402
unicodedata_decomposition(PyObject *self, PyObject *args)
403 404
{
    PyUnicodeObject *v;
405 406
    char decomp[256];
    int code, index, count, i;
407
    unsigned int prefix_index;
408
    Py_UCS4 c;
409 410

    if (!PyArg_ParseTuple(args, "O!:decomposition",
411 412
                          &PyUnicode_Type, &v))
        return NULL;
413 414 415
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
416

417
    code = (int)c;
418

419
    if (self && UCD_Check(self)) {
420
        const change_record *old = get_old_record(self, c);
421
        if (old->category_changed == 0)
422
            return PyUnicode_FromString(""); /* unassigned */
423 424
    }

425
    if (code < 0 || code >= 0x110000)
426 427 428 429 430 431 432
        index = 0;
    else {
        index = decomp_index1[(code>>DECOMP_SHIFT)];
        index = decomp_index2[(index<<DECOMP_SHIFT)+
                             (code&((1<<DECOMP_SHIFT)-1))];
    }

433
    /* high byte is number of hex bytes (usually one or two), low byte
434 435 436 437 438 439
       is prefix code (from*/
    count = decomp_data[index] >> 8;

    /* XXX: could allocate the PyString up front instead
       (strlen(prefix) + 5 * count + 1 bytes) */

440 441 442 443 444 445
    /* Based on how index is calculated above and decomp_data is generated
       from Tools/unicode/makeunicodedata.py, it should not be possible
       to overflow decomp_prefix. */
    prefix_index = decomp_data[index] & 255;
    assert(prefix_index < (sizeof(decomp_prefix)/sizeof(*decomp_prefix)));

446
    /* copy prefix */
447 448
    i = strlen(decomp_prefix[prefix_index]);
    memcpy(decomp, decomp_prefix[prefix_index], i);
449 450 451 452

    while (count-- > 0) {
        if (i)
            decomp[i++] = ' ';
453 454 455
        assert((size_t)i < sizeof(decomp));
        PyOS_snprintf(decomp + i, sizeof(decomp) - i, "%04X",
                      decomp_data[++index]);
456
        i += strlen(decomp + i);
457
    }
458

459 460
    decomp[i] = '\0';

461
    return PyUnicode_FromString(decomp);
462 463
}

464
static void
465
get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *count)
466
{
467
    if (code >= 0x110000) {
468
        *index = 0;
469
    } else if (self && UCD_Check(self) &&
470
               get_old_record(self, code)->category_changed==0) {
471 472 473
        /* unassigned in old version */
        *index = 0;
    }
474 475 476 477 478
    else {
        *index = decomp_index1[(code>>DECOMP_SHIFT)];
        *index = decomp_index2[(*index<<DECOMP_SHIFT)+
                               (code&((1<<DECOMP_SHIFT)-1))];
    }
479

480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
    /* high byte is number of hex bytes (usually one or two), low byte
       is prefix code (from*/
    *count = decomp_data[*index] >> 8;
    *prefix = decomp_data[*index] & 255;

    (*index)++;
}

#define SBase   0xAC00
#define LBase   0x1100
#define VBase   0x1161
#define TBase   0x11A7
#define LCount  19
#define VCount  21
#define TCount  28
#define NCount  (VCount*TCount)
#define SCount  (LCount*NCount)

static PyObject*
499
nfd_nfkd(PyObject *self, PyObject *input, int k)
500 501 502 503
{
    PyObject *result;
    Py_UNICODE *i, *end, *o;
    /* Longest decomposition in Unicode 3.2: U+FDFA */
504
    Py_UNICODE stack[20];
505 506
    Py_ssize_t space, isize;
    int index, prefix, count, stackptr;
507
    unsigned char prev, cur;
508

509 510 511 512 513 514 515 516 517 518 519 520 521 522 523
    stackptr = 0;
    isize = PyUnicode_GET_SIZE(input);
    /* Overallocate atmost 10 characters. */
    space = (isize > 10 ? 10 : isize) + isize;
    result = PyUnicode_FromUnicode(NULL, space);
    if (!result)
        return NULL;
    i = PyUnicode_AS_UNICODE(input);
    end = i + isize;
    o = PyUnicode_AS_UNICODE(result);

    while (i < end) {
        stack[stackptr++] = *i++;
        while(stackptr) {
            Py_UNICODE code = stack[--stackptr];
524 525 526
            /* Hangul Decomposition adds three characters in
               a single step, so we need atleast that much room. */
            if (space < 3) {
527
                Py_ssize_t newsize = PyUnicode_GET_SIZE(result) + 10;
528 529
                space += 10;
                if (PyUnicode_Resize(&result, newsize) == -1)
530
                    return NULL;
531
                o = PyUnicode_AS_UNICODE(result) + newsize - space;
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
            }
            /* Hangul Decomposition. */
            if (SBase <= code && code < (SBase+SCount)) {
                int SIndex = code - SBase;
                int L = LBase + SIndex / NCount;
                int V = VBase + (SIndex % NCount) / TCount;
                int T = TBase + SIndex % TCount;
                *o++ = L;
                *o++ = V;
                space -= 2;
                if (T != TBase) {
                    *o++ = T;
                    space --;
                }
                continue;
            }
548
            /* normalization changes */
549
            if (self && UCD_Check(self)) {
550 551 552 553 554 555 556 557 558
                Py_UCS4 value = ((PreviousDBVersion*)self)->normalization(code);
                if (value != 0) {
                    stack[stackptr++] = value;
                    continue;
                }
            }

            /* Other decompositions. */
            get_decomp_record(self, code, &index, &prefix, &count);
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

            /* Copy character if it is not decomposable, or has a
               compatibility decomposition, but we do NFD. */
            if (!count || (prefix && !k)) {
                *o++ = code;
                space--;
                continue;
            }
            /* Copy decomposition onto the stack, in reverse
               order.  */
            while(count) {
                code = decomp_data[index + (--count)];
                stack[stackptr++] = code;
            }
        }
    }

    /* Drop overallocation. Cannot fail. */
    PyUnicode_Resize(&result, PyUnicode_GET_SIZE(result) - space);

    /* Sort canonically. */
    i = PyUnicode_AS_UNICODE(result);
    prev = _getrecord_ex(*i)->combining;
    end = i + PyUnicode_GET_SIZE(result);
    for (i++; i < end; i++) {
        cur = _getrecord_ex(*i)->combining;
        if (prev == 0 || cur == 0 || prev <= cur) {
            prev = cur;
            continue;
        }
        /* Non-canonical order. Need to switch *i with previous. */
        o = i - 1;
        while (1) {
            Py_UNICODE tmp = o[1];
            o[1] = o[0];
            o[0] = tmp;
            o--;
            if (o < PyUnicode_AS_UNICODE(result))
                break;
            prev = _getrecord_ex(*o)->combining;
            if (prev == 0 || prev <= cur)
                break;
        }
        prev = _getrecord_ex(*i)->combining;
    }
    return result;
}

static int
608
find_nfc_index(PyObject *self, struct reindex* nfc, Py_UNICODE code)
609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
{
    int index;
    for (index = 0; nfc[index].start; index++) {
        int start = nfc[index].start;
        if (code < start)
            return -1;
        if (code <= start + nfc[index].count) {
            int delta = code - start;
            return nfc[index].index + delta;
        }
    }
    return -1;
}

static PyObject*
624
nfc_nfkc(PyObject *self, PyObject *input, int k)
625 626 627 628 629 630 631 632
{
    PyObject *result;
    Py_UNICODE *i, *i1, *o, *end;
    int f,l,index,index1,comb;
    Py_UNICODE code;
    Py_UNICODE *skipped[20];
    int cskipped = 0;

633
    result = nfd_nfkd(self, input, k);
634 635 636 637 638 639 640 641 642 643 644
    if (!result)
        return NULL;

    /* We are going to modify result in-place.
       If nfd_nfkd is changed to sometimes return the input,
       this code needs to be reviewed. */
    assert(result != input);

    i = PyUnicode_AS_UNICODE(result);
    end = i + PyUnicode_GET_SIZE(result);
    o = PyUnicode_AS_UNICODE(result);
645

646 647 648 649
  again:
    while (i < end) {
      for (index = 0; index < cskipped; index++) {
          if (skipped[index] == i) {
650
              /* *i character is skipped.
651 652 653 654
                 Remove from list. */
              skipped[index] = skipped[cskipped-1];
              cskipped--;
              i++;
Martin v. Löwis's avatar
Martin v. Löwis committed
655
              goto again; /* continue while */
656 657 658 659 660
          }
      }
      /* Hangul Composition. We don't need to check for <LV,T>
         pairs, since we always have decomposed data. */
      if (LBase <= *i && *i < (LBase+LCount) &&
661
          i + 1 < end &&
662 663 664 665 666 667 668 669 670 671 672 673 674 675 676
          VBase <= i[1] && i[1] <= (VBase+VCount)) {
          int LIndex, VIndex;
          LIndex = i[0] - LBase;
          VIndex = i[1] - VBase;
          code = SBase + (LIndex*VCount+VIndex)*TCount;
          i+=2;
          if (i < end &&
              TBase <= *i && *i <= (TBase+TCount)) {
              code += *i-TBase;
              i++;
          }
          *o++ = code;
          continue;
      }

677
      f = find_nfc_index(self, nfc_first, *i);
678 679 680 681 682 683 684 685 686
      if (f == -1) {
          *o++ = *i++;
          continue;
      }
      /* Find next unblocked character. */
      i1 = i+1;
      comb = 0;
      while (i1 < end) {
          int comb1 = _getrecord_ex(*i1)->combining;
687 688 689 690 691 692 693 694
          if (comb) {
              if (comb1 == 0)
                  break;
              if (comb >= comb1) {
                  /* Character is blocked. */
                  i1++;
                  continue;
              }
695
          }
696
          l = find_nfc_index(self, nfc_last, *i1);
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
          /* *i1 cannot be combined with *i. If *i1
             is a starter, we don't need to look further.
             Otherwise, record the combining class. */
          if (l == -1) {
            not_combinable:
              if (comb1 == 0)
                  break;
              comb = comb1;
              i1++;
              continue;
          }
          index = f*TOTAL_LAST + l;
          index1 = comp_index[index >> COMP_SHIFT];
          code = comp_data[(index1<<COMP_SHIFT)+
                           (index&((1<<COMP_SHIFT)-1))];
          if (code == 0)
              goto not_combinable;
714

715 716 717
          /* Replace the original character. */
          *i = code;
          /* Mark the second character unused. */
718
          assert(cskipped < 20);
719 720
          skipped[cskipped++] = i1;
          i1++;
721
          f = find_nfc_index(self, nfc_first, *i);
722 723 724 725 726 727 728 729 730
          if (f == -1)
              break;
      }
      *o++ = *i++;
    }
    if (o != end)
        PyUnicode_Resize(&result, o - PyUnicode_AS_UNICODE(result));
    return result;
}
731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763

/* Return 1 if the input is certainly normalized, 0 if it might not be. */
static int
is_normalized(PyObject *self, PyObject *input, int nfc, int k)
{
    Py_UNICODE *i, *end;
    unsigned char prev_combining = 0, quickcheck_mask;

    /* An older version of the database is requested, quickchecks must be
       disabled. */
    if (self && UCD_Check(self))
        return 0;

    /* The two quickcheck bits at this shift mean 0=Yes, 1=Maybe, 2=No,
       as described in http://unicode.org/reports/tr15/#Annex8. */
    quickcheck_mask = 3 << ((nfc ? 4 : 0) + (k ? 2 : 0));

    i = PyUnicode_AS_UNICODE(input);
    end = i + PyUnicode_GET_SIZE(input);
    while (i < end) {
        const _PyUnicode_DatabaseRecord *record = _getrecord_ex(*i++);
        unsigned char combining = record->combining;
        unsigned char quickcheck = record->normalization_quick_check;

        if (quickcheck & quickcheck_mask)
            return 0; /* this string might need normalization */
        if (combining && prev_combining > combining)
            return 0; /* non-canonical sort order, not normalized */
        prev_combining = combining;
    }
    return 1; /* certainly normalized */
}

764 765 766 767 768 769
PyDoc_STRVAR(unicodedata_normalize__doc__,
"normalize(form, unistr)\n\
\n\
Return the normal form 'form' for the Unicode string unistr.  Valid\n\
values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.");

770 771 772 773 774 775
static PyObject*
unicodedata_normalize(PyObject *self, PyObject *args)
{
    char *form;
    PyObject *input;

Hye-Shik Chang's avatar
Hye-Shik Chang committed
776
    if(!PyArg_ParseTuple(args, "sO!:normalize",
777 778 779
                         &form, &PyUnicode_Type, &input))
        return NULL;

780 781 782 783 784 785 786
    if (PyUnicode_GetSize(input) == 0) {
        /* Special case empty input strings, since resizing
           them  later would cause internal errors. */
        Py_INCREF(input);
        return input;
    }

787 788 789 790 791
    if (strcmp(form, "NFC") == 0) {
        if (is_normalized(self, input, 1, 0)) {
            Py_INCREF(input);
            return input;
        }
792
        return nfc_nfkc(self, input, 0);
793 794 795 796 797 798
    }
    if (strcmp(form, "NFKC") == 0) {
        if (is_normalized(self, input, 1, 1)) {
            Py_INCREF(input);
            return input;
        }
799
        return nfc_nfkc(self, input, 1);
800 801 802 803 804 805
    }
    if (strcmp(form, "NFD") == 0) {
        if (is_normalized(self, input, 0, 0)) {
            Py_INCREF(input);
            return input;
        }
806
        return nfd_nfkd(self, input, 0);
807 808 809 810 811 812
    }
    if (strcmp(form, "NFKD") == 0) {
        if (is_normalized(self, input, 0, 1)) {
            Py_INCREF(input);
            return input;
        }
813
        return nfd_nfkd(self, input, 1);
814
    }
815 816 817 818
    PyErr_SetString(PyExc_ValueError, "invalid normalization form");
    return NULL;
}

819 820 821 822 823 824 825 826 827 828
/* -------------------------------------------------------------------- */
/* unicode character name tables */

/* data file generated by Tools/unicode/makeunicodedata.py */
#include "unicodename_db.h"

/* -------------------------------------------------------------------- */
/* database code (cut and pasted from the unidb package) */

static unsigned long
829
_gethash(const char *s, int len, int scale)
830 831 832 833 834
{
    int i;
    unsigned long h = 0;
    unsigned long ix;
    for (i = 0; i < len; i++) {
835
        h = (h * scale) + (unsigned char) toupper(Py_CHARMASK(s[i]));
836 837 838 839 840 841 842
        ix = h & 0xff000000;
        if (ix)
            h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
    }
    return h;
}

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
static char *hangul_syllables[][3] = {
    { "G",  "A",   ""   },
    { "GG", "AE",  "G"  },
    { "N",  "YA",  "GG" },
    { "D",  "YAE", "GS" },
    { "DD", "EO",  "N", },
    { "R",  "E",   "NJ" },
    { "M",  "YEO", "NH" },
    { "B",  "YE",  "D"  },
    { "BB", "O",   "L"  },
    { "S",  "WA",  "LG" },
    { "SS", "WAE", "LM" },
    { "",   "OE",  "LB" },
    { "J",  "YO",  "LS" },
    { "JJ", "U",   "LT" },
    { "C",  "WEO", "LP" },
    { "K",  "WE",  "LH" },
    { "T",  "WI",  "M"  },
    { "P",  "YU",  "B"  },
    { "H",  "EU",  "BS" },
    { 0,    "YI",  "S"  },
    { 0,    "I",   "SS" },
    { 0,    0,     "NG" },
    { 0,    0,     "J"  },
    { 0,    0,     "C"  },
    { 0,    0,     "K"  },
    { 0,    0,     "T"  },
    { 0,    0,     "P"  },
    { 0,    0,     "H"  }
};

874
/* These ranges need to match makeunicodedata.py:cjk_ranges. */
875 876 877
static int
is_unified_ideograph(Py_UCS4 code)
{
878 879 880 881 882 883
    return
        (0x3400 <= code && code <= 0x4DB5)   || /* CJK Ideograph Extension A */
        (0x4E00 <= code && code <= 0x9FCB)   || /* CJK Ideograph */
        (0x20000 <= code && code <= 0x2A6D6) || /* CJK Ideograph Extension B */
        (0x2A700 <= code && code <= 0x2B734) || /* CJK Ideograph Extension C */
        (0x2B740 <= code && code <= 0x2B81D);   /* CJK Ideograph Extension D */
884 885
}

886
static int
887
_getucname(PyObject *self, Py_UCS4 code, char* buffer, int buflen)
888 889 890 891 892 893
{
    int offset;
    int i;
    int word;
    unsigned char* w;

894 895 896
    if (code >= 0x110000)
        return 0;

897
    if (self && UCD_Check(self)) {
898 899 900 901
        const change_record *old = get_old_record(self, code);
        if (old->category_changed == 0) {
            /* unassigned */
            return 0;
902
        }
903 904
    }

Martin v. Löwis's avatar
Martin v. Löwis committed
905
    if (SBase <= code && code < SBase+SCount) {
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
        /* Hangul syllable. */
        int SIndex = code - SBase;
        int L = SIndex / NCount;
        int V = (SIndex % NCount) / TCount;
        int T = SIndex % TCount;

        if (buflen < 27)
            /* Worst case: HANGUL SYLLABLE <10chars>. */
            return 0;
        strcpy(buffer, "HANGUL SYLLABLE ");
        buffer += 16;
        strcpy(buffer, hangul_syllables[L][0]);
        buffer += strlen(hangul_syllables[L][0]);
        strcpy(buffer, hangul_syllables[V][1]);
        buffer += strlen(hangul_syllables[V][1]);
        strcpy(buffer, hangul_syllables[T][2]);
        buffer += strlen(hangul_syllables[T][2]);
        *buffer = '\0';
        return 1;
925 926
    }

927
    if (is_unified_ideograph(code)) {
928 929 930 931 932 933 934
        if (buflen < 28)
            /* Worst case: CJK UNIFIED IDEOGRAPH-20000 */
            return 0;
        sprintf(buffer, "CJK UNIFIED IDEOGRAPH-%X", code);
        return 1;
    }

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976
    /* get offset into phrasebook */
    offset = phrasebook_offset1[(code>>phrasebook_shift)];
    offset = phrasebook_offset2[(offset<<phrasebook_shift) +
                               (code&((1<<phrasebook_shift)-1))];
    if (!offset)
        return 0;

    i = 0;

    for (;;) {
        /* get word index */
        word = phrasebook[offset] - phrasebook_short;
        if (word >= 0) {
            word = (word << 8) + phrasebook[offset+1];
            offset += 2;
        } else
            word = phrasebook[offset++];
        if (i) {
            if (i > buflen)
                return 0; /* buffer overflow */
            buffer[i++] = ' ';
        }
        /* copy word string from lexicon.  the last character in the
           word has bit 7 set.  the last word in a string ends with
           0x80 */
        w = lexicon + lexicon_offset[word];
        while (*w < 128) {
            if (i >= buflen)
                return 0; /* buffer overflow */
            buffer[i++] = *w++;
        }
        if (i >= buflen)
            return 0; /* buffer overflow */
        buffer[i++] = *w & 127;
        if (*w == 128)
            break; /* end of word */
    }

    return 1;
}

static int
977
_cmpname(PyObject *self, int code, const char* name, int namelen)
978 979 980 981
{
    /* check if code corresponds to the given name */
    int i;
    char buffer[NAME_MAXLEN];
982
    if (!_getucname(self, code, buffer, sizeof(buffer)))
983 984
        return 0;
    for (i = 0; i < namelen; i++) {
985
        if (toupper(Py_CHARMASK(name[i])) != buffer[i])
986 987 988 989 990
            return 0;
    }
    return buffer[namelen] == '\0';
}

991
static void
992 993 994 995 996
find_syllable(const char *str, int *len, int *pos, int count, int column)
{
    int i, len1;
    *len = -1;
    for (i = 0; i < count; i++) {
997 998 999 1000 1001 1002 1003 1004
        char *s = hangul_syllables[i][column];
        len1 = strlen(s);
        if (len1 <= *len)
            continue;
        if (strncmp(str, s, len1) == 0) {
            *len = len1;
            *pos = i;
        }
1005 1006
    }
    if (*len == -1) {
1007
        *len = 0;
1008 1009 1010
    }
}

1011
static int
1012
_getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code)
1013 1014 1015 1016 1017
{
    unsigned int h, v;
    unsigned int mask = code_size-1;
    unsigned int i, incr;

1018 1019
    /* Check for hangul syllables. */
    if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031
        int len, L = -1, V = -1, T = -1;
        const char *pos = name + 16;
        find_syllable(pos, &len, &L, LCount, 0);
        pos += len;
        find_syllable(pos, &len, &V, VCount, 1);
        pos += len;
        find_syllable(pos, &len, &T, TCount, 2);
        pos += len;
        if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
            *code = SBase + (L*VCount+V)*TCount + T;
            return 1;
        }
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
        /* Otherwise, it's an illegal syllable name. */
        return 0;
    }

    /* Check for unified ideographs. */
    if (strncmp(name, "CJK UNIFIED IDEOGRAPH-", 22) == 0) {
        /* Four or five hexdigits must follow. */
        v = 0;
        name += 22;
        namelen -= 22;
        if (namelen != 4 && namelen != 5)
            return 0;
        while (namelen--) {
            v *= 16;
            if (*name >= '0' && *name <= '9')
                v += *name - '0';
            else if (*name >= 'A' && *name <= 'F')
                v += *name - 'A' + 10;
            else
                return 0;
            name++;
        }
1054 1055
        if (!is_unified_ideograph(v))
            return 0;
1056 1057
        *code = v;
        return 1;
1058 1059
    }

1060 1061 1062 1063
    /* the following is the same as python's dictionary lookup, with
       only minor changes.  see the makeunicodedata script for more
       details */

1064
    h = (unsigned int) _gethash(name, namelen, code_magic);
1065 1066 1067 1068
    i = (~h) & mask;
    v = code_hash[i];
    if (!v)
        return 0;
1069
    if (_cmpname(self, v, name, namelen)) {
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079
        *code = v;
        return 1;
    }
    incr = (h ^ (h >> 3)) & mask;
    if (!incr)
        incr = mask;
    for (;;) {
        i = (i + incr) & mask;
        v = code_hash[i];
        if (!v)
1080
            return 0;
1081
        if (_cmpname(self, v, name, namelen)) {
1082 1083 1084 1085 1086 1087 1088 1089 1090
            *code = v;
            return 1;
        }
        incr = incr << 1;
        if (incr > mask)
            incr = incr ^ code_poly;
    }
}

1091
static const _PyUnicode_Name_CAPI hashAPI =
1092 1093
{
    sizeof(_PyUnicode_Name_CAPI),
1094
    _getucname,
1095
    _getcode
1096 1097 1098 1099 1100
};

/* -------------------------------------------------------------------- */
/* Python bindings */

1101 1102 1103 1104 1105 1106
PyDoc_STRVAR(unicodedata_name__doc__,
"name(unichr[, default])\n\
Returns the name assigned to the Unicode character unichr as a\n\
string. If no name is defined, default is returned, or, if not\n\
given, ValueError is raised.");

1107 1108 1109 1110
static PyObject *
unicodedata_name(PyObject* self, PyObject* args)
{
    char name[NAME_MAXLEN];
1111
    Py_UCS4 c;
1112 1113 1114 1115 1116 1117

    PyUnicodeObject* v;
    PyObject* defobj = NULL;
    if (!PyArg_ParseTuple(args, "O!|O:name", &PyUnicode_Type, &v, &defobj))
        return NULL;

1118 1119 1120
    c = getuchar(v);
    if (c == (Py_UCS4)-1)
        return NULL;
1121

1122
    if (!_getucname(self, c, name, sizeof(name))) {
1123 1124
        if (defobj == NULL) {
            PyErr_SetString(PyExc_ValueError, "no such name");
1125
            return NULL;
1126 1127 1128 1129 1130
        }
        else {
            Py_INCREF(defobj);
            return defobj;
        }
1131 1132
    }

1133
    return PyUnicode_FromString(name);
1134 1135
}

1136 1137 1138 1139 1140 1141 1142
PyDoc_STRVAR(unicodedata_lookup__doc__,
"lookup(name)\n\
\n\
Look up character by name.  If a character with the\n\
given name is found, return the corresponding Unicode\n\
character.  If not found, KeyError is raised.");

1143 1144 1145 1146
static PyObject *
unicodedata_lookup(PyObject* self, PyObject* args)
{
    Py_UCS4 code;
1147
    Py_UNICODE str[2];
1148 1149 1150 1151 1152 1153

    char* name;
    int namelen;
    if (!PyArg_ParseTuple(args, "s#:lookup", &name, &namelen))
        return NULL;

1154
    if (!_getcode(self, name, namelen, &code)) {
1155 1156
        PyErr_Format(PyExc_KeyError, "undefined character name '%s'",
                     name);
1157 1158 1159
        return NULL;
    }

1160 1161 1162 1163 1164 1165 1166
#ifndef Py_UNICODE_WIDE
    if (code >= 0x10000) {
        str[0] = 0xd800 + ((code - 0x10000) >> 10);
        str[1] = 0xdc00 + ((code - 0x10000) & 0x3ff);
        return PyUnicode_FromUnicode(str, 2);
    }
#endif
1167
    str[0] = (Py_UNICODE) code;
1168
    return PyUnicode_FromUnicode(str, 1);
1169 1170
}

1171 1172 1173
/* XXX Add doc strings. */

static PyMethodDef unicodedata_functions[] = {
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192
    {"decimal", unicodedata_decimal, METH_VARARGS, unicodedata_decimal__doc__},
    {"digit", unicodedata_digit, METH_VARARGS, unicodedata_digit__doc__},
    {"numeric", unicodedata_numeric, METH_VARARGS, unicodedata_numeric__doc__},
    {"category", unicodedata_category, METH_VARARGS,
                 unicodedata_category__doc__},
    {"bidirectional", unicodedata_bidirectional, METH_VARARGS,
                      unicodedata_bidirectional__doc__},
    {"combining", unicodedata_combining, METH_VARARGS,
                  unicodedata_combining__doc__},
    {"mirrored", unicodedata_mirrored, METH_VARARGS,
                 unicodedata_mirrored__doc__},
    {"east_asian_width", unicodedata_east_asian_width, METH_VARARGS,
                         unicodedata_east_asian_width__doc__},
    {"decomposition", unicodedata_decomposition, METH_VARARGS,
                      unicodedata_decomposition__doc__},
    {"name", unicodedata_name, METH_VARARGS, unicodedata_name__doc__},
    {"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__},
    {"normalize", unicodedata_normalize, METH_VARARGS,
                  unicodedata_normalize__doc__},
1193
    {NULL, NULL}                /* sentinel */
1194 1195
};

1196
static PyTypeObject UCD_Type = {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        /* The ob_type field must be initialized in the module init function
         * to be portable to Windows without using C++. */
        PyVarObject_HEAD_INIT(NULL, 0)
        "unicodedata.UCD",              /*tp_name*/
        sizeof(PreviousDBVersion),      /*tp_basicsize*/
        0,                      /*tp_itemsize*/
        /* methods */
        (destructor)PyObject_Del, /*tp_dealloc*/
        0,                      /*tp_print*/
        0,                      /*tp_getattr*/
        0,                      /*tp_setattr*/
        0,                      /*tp_reserved*/
        0,                      /*tp_repr*/
        0,                      /*tp_as_number*/
        0,                      /*tp_as_sequence*/
        0,                      /*tp_as_mapping*/
        0,                      /*tp_hash*/
1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240
        0,                      /*tp_call*/
        0,                      /*tp_str*/
        PyObject_GenericGetAttr,/*tp_getattro*/
        0,                      /*tp_setattro*/
        0,                      /*tp_as_buffer*/
        Py_TPFLAGS_DEFAULT,     /*tp_flags*/
        0,                      /*tp_doc*/
        0,                      /*tp_traverse*/
        0,                      /*tp_clear*/
        0,                      /*tp_richcompare*/
        0,                      /*tp_weaklistoffset*/
        0,                      /*tp_iter*/
        0,                      /*tp_iternext*/
        unicodedata_functions,  /*tp_methods*/
        DB_members,             /*tp_members*/
        0,                      /*tp_getset*/
        0,                      /*tp_base*/
        0,                      /*tp_dict*/
        0,                      /*tp_descr_get*/
        0,                      /*tp_descr_set*/
        0,                      /*tp_dictoffset*/
        0,                      /*tp_init*/
        0,                      /*tp_alloc*/
        0,                      /*tp_new*/
        0,                      /*tp_free*/
        0,                      /*tp_is_gc*/
};
1241

1242 1243 1244 1245
PyDoc_STRVAR(unicodedata_docstring,
"This module provides access to the Unicode Character Database which\n\
defines character properties for all Unicode characters. The data in\n\
this database is based on the UnicodeData.txt file version\n\
1246
5.2.0 which is publically available from ftp://ftp.unicode.org/.\n\
1247 1248
\n\
The module uses the same names and symbols as defined by the\n\
1249 1250
UnicodeData File Format 5.2.0 (see\n\
http://www.unicode.org/reports/tr44/tr44-4.html).");
1251

1252 1253

static struct PyModuleDef unicodedatamodule = {
1254 1255 1256 1257 1258 1259 1260 1261 1262
        PyModuleDef_HEAD_INIT,
        "unicodedata",
        unicodedata_docstring,
        -1,
        unicodedata_functions,
        NULL,
        NULL,
        NULL,
        NULL
1263 1264
};

1265
PyMODINIT_FUNC
1266
PyInit_unicodedata(void)
1267
{
1268
    PyObject *m, *v;
1269

1270
    Py_TYPE(&UCD_Type) = &PyType_Type;
1271

1272
    m = PyModule_Create(&unicodedatamodule);
1273
    if (!m)
1274
        return NULL;
1275

1276
    PyModule_AddStringConstant(m, "unidata_version", UNIDATA_VERSION);
Martin v. Löwis's avatar
Martin v. Löwis committed
1277
    Py_INCREF(&UCD_Type);
1278
    PyModule_AddObject(m, "UCD", (PyObject*)&UCD_Type);
1279

1280 1281 1282
    /* Previous versions */
    v = new_previous_version("3.2.0", get_change_3_2_0, normalization_3_2_0);
    if (v != NULL)
1283
        PyModule_AddObject(m, "ucd_3_2_0", v);
1284

1285
    /* Export C API */
1286
    v = PyCapsule_New((void *)&hashAPI, PyUnicodeData_CAPSULE_NAME, NULL);
1287 1288
    if (v != NULL)
        PyModule_AddObject(m, "ucnhash_CAPI", v);
1289
    return m;
1290
}
1291

1292
/*
1293 1294
Local variables:
c-basic-offset: 4
1295
indent-tabs-mode: nil
1296 1297
End:
*/