_localemodule.c 16.9 KB
Newer Older
1
/***********************************************************
2
Copyright (C) 1997, 2002, 2003, 2007, 2008 Martin von Loewis
3 4 5 6 7 8

Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies.

This software comes with no warranty. Use at your own risk.
9

10 11
******************************************************************/

12
#define PY_SSIZE_T_CLEAN
13 14
#include "Python.h"

15 16 17
#include <stdio.h>
#include <locale.h>
#include <string.h>
18
#include <ctype.h>
19

20
#ifdef HAVE_ERRNO_H
21 22 23
#include <errno.h>
#endif

24 25 26 27
#ifdef HAVE_LANGINFO_H
#include <langinfo.h>
#endif

28 29 30 31
#ifdef HAVE_LIBINTL_H
#include <libintl.h>
#endif

32 33 34 35
#ifdef HAVE_WCHAR_H
#include <wchar.h>
#endif

36
#if defined(MS_WINDOWS)
37
#define WIN32_LEAN_AND_MEAN
38 39 40
#include <windows.h>
#endif

41
PyDoc_STRVAR(locale__doc__, "Support for POSIX locales.");
42 43 44 45 46

static PyObject *Error;

/* support functions for formatting floating point numbers */

47 48
PyDoc_STRVAR(setlocale__doc__,
"(integer,string=None) -> string. Activates/queries locale processing.");
49 50 51

/* the grouping is terminated by either 0 or CHAR_MAX */
static PyObject*
52
copy_grouping(const char* s)
53
{
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
    int i;
    PyObject *result, *val = NULL;

    if (s[0] == '\0')
        /* empty string: no grouping at all */
        return PyList_New(0);

    for (i = 0; s[i] != '\0' && s[i] != CHAR_MAX; i++)
        ; /* nothing */

    result = PyList_New(i+1);
    if (!result)
        return NULL;

    i = -1;
    do {
        i++;
71
        val = PyLong_FromLong(s[i]);
72 73 74 75
        if (!val)
            break;
        if (PyList_SetItem(result, i, val)) {
            Py_DECREF(val);
76
            val = NULL;
77 78 79 80 81 82 83
            break;
        }
    } while (s[i] != '\0' && s[i] != CHAR_MAX);

    if (!val) {
        Py_DECREF(result);
        return NULL;
84
    }
85 86

    return result;
87 88 89
}

static PyObject*
90
PyLocale_setlocale(PyObject* self, PyObject* args)
91
{
92 93 94 95 96
    int category;
    char *locale = NULL, *result;
    PyObject *result_object;

    if (!PyArg_ParseTuple(args, "i|z:setlocale", &category, &locale))
97
        return NULL;
98

99 100 101 102 103 104 105 106
#if defined(MS_WINDOWS)
    if (category < LC_MIN || category > LC_MAX)
    {
        PyErr_SetString(Error, "invalid locale category");
        return NULL;
    }
#endif

107 108 109 110 111
    if (locale) {
        /* set locale */
        result = setlocale(category, locale);
        if (!result) {
            /* operation failed, no setting was changed */
112
            PyErr_SetString(Error, "unsupported locale setting");
113 114
            return NULL;
        }
115
        result_object = PyUnicode_DecodeLocale(result, NULL);
116
        if (!result_object)
117 118 119 120 121 122 123 124
            return NULL;
    } else {
        /* get locale */
        result = setlocale(category, NULL);
        if (!result) {
            PyErr_SetString(Error, "locale query failed");
            return NULL;
        }
125
        result_object = PyUnicode_DecodeLocale(result, NULL);
126
    }
127
    return result_object;
128 129
}

130 131
PyDoc_STRVAR(localeconv__doc__,
"() -> dict. Returns numeric and monetary locale-specific parameters.");
132 133

static PyObject*
134
PyLocale_localeconv(PyObject* self)
135
{
136 137 138 139 140
    PyObject* result;
    struct lconv *l;
    PyObject *x;

    result = PyDict_New();
141 142
    if (!result)
        return NULL;
143 144 145 146 147 148 149

    /* if LC_NUMERIC is different in the C library, use saved value */
    l = localeconv();

    /* hopefully, the localeconv result survives the C library calls
       involved herein */

150 151 152 153
#define RESULT(key, obj)\
    do { \
        if (obj == NULL) \
            goto failed; \
154 155
        if (PyDict_SetItemString(result, key, obj) < 0) { \
            Py_DECREF(obj); \
156
            goto failed; \
157
        } \
158 159 160
        Py_DECREF(obj); \
    } while (0)

161
#define RESULT_STRING(s)\
162 163 164 165
    do { \
        x = PyUnicode_DecodeLocale(l->s, NULL); \
        RESULT(#s, x); \
    } while (0)
166 167

#define RESULT_INT(i)\
168 169 170 171
    do { \
        x = PyLong_FromLong(l->i); \
        RESULT(#i, x); \
    } while (0)
172 173

    /* Numeric information */
174 175 176
    RESULT_STRING(decimal_point);
    RESULT_STRING(thousands_sep);
    x = copy_grouping(l->grouping);
177
    RESULT("grouping", x);
178 179 180 181 182 183 184

    /* Monetary information */
    RESULT_STRING(int_curr_symbol);
    RESULT_STRING(currency_symbol);
    RESULT_STRING(mon_decimal_point);
    RESULT_STRING(mon_thousands_sep);
    x = copy_grouping(l->mon_grouping);
185 186
    RESULT("mon_grouping", x);

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
    RESULT_STRING(positive_sign);
    RESULT_STRING(negative_sign);
    RESULT_INT(int_frac_digits);
    RESULT_INT(frac_digits);
    RESULT_INT(p_cs_precedes);
    RESULT_INT(p_sep_by_space);
    RESULT_INT(n_cs_precedes);
    RESULT_INT(n_sep_by_space);
    RESULT_INT(p_sign_posn);
    RESULT_INT(n_sign_posn);
    return result;

  failed:
    Py_XDECREF(result);
    return NULL;
202 203
}

204
#if defined(HAVE_WCSCOLL)
205 206
PyDoc_STRVAR(strcoll__doc__,
"string,string -> int. Compares two strings according to the locale.");
207 208

static PyObject*
209
PyLocale_strcoll(PyObject* self, PyObject* args)
210
{
211 212
    PyObject *os1, *os2, *result = NULL;
    wchar_t *ws1 = NULL, *ws2 = NULL;
213

214
    if (!PyArg_ParseTuple(args, "UU:strcoll", &os1, &os2))
215 216
        return NULL;
    /* Convert the unicode strings to wchar[]. */
217
    ws1 = PyUnicode_AsWideCharString(os1, NULL);
218
    if (ws1 == NULL)
219
        goto done;
220
    ws2 = PyUnicode_AsWideCharString(os2, NULL);
221
    if (ws2 == NULL)
222 223
        goto done;
    /* Collate the strings. */
224
    result = PyLong_FromLong(wcscoll(ws1, ws2));
225 226 227 228 229
  done:
    /* Deallocate everything. */
    if (ws1) PyMem_FREE(ws1);
    if (ws2) PyMem_FREE(ws2);
    return result;
230
}
231
#endif
232

233
#ifdef HAVE_WCSXFRM
234
PyDoc_STRVAR(strxfrm__doc__,
235 236 237
"strxfrm(string) -> string.\n\
\n\
Return a string that can be used as a key for locale-aware comparisons.");
238 239

static PyObject*
240
PyLocale_strxfrm(PyObject* self, PyObject* args)
241
{
242 243 244 245
    PyObject *str;
    Py_ssize_t n1;
    wchar_t *s = NULL, *buf = NULL;
    size_t n2;
246
    PyObject *result = NULL;
247

248
    if (!PyArg_ParseTuple(args, "U:strxfrm", &str))
249 250
        return NULL;

251 252 253
    s = PyUnicode_AsWideCharString(str, &n1);
    if (s == NULL)
        goto exit;
254

255
    /* assume no change in size, first */
256
    n1 = n1 + 1;
257
    buf = PyMem_New(wchar_t, n1);
258 259 260 261 262
    if (!buf) {
        PyErr_NoMemory();
        goto exit;
    }
    n2 = wcsxfrm(buf, s, n1);
263
    if (n2 >= (size_t)n1) {
264
        /* more space needed */
265 266
        wchar_t * new_buf = PyMem_Realloc(buf, (n2+1)*sizeof(wchar_t));
        if (!new_buf) {
267 268 269
            PyErr_NoMemory();
            goto exit;
        }
270
        buf = new_buf;
271
        n2 = wcsxfrm(buf, s, n2+1);
272
    }
273
    result = PyUnicode_FromWideChar(buf, n2);
274 275 276 277 278
exit:
    if (buf)
        PyMem_Free(buf);
    if (s)
        PyMem_Free(s);
279
    return result;
280
}
281
#endif
282

283
#if defined(MS_WINDOWS)
284
static PyObject*
285
PyLocale_getdefaultlocale(PyObject* self)
286 287 288 289
{
    char encoding[100];
    char locale[100];

290
    PyOS_snprintf(encoding, sizeof(encoding), "cp%d", GetACP());
291 292 293 294

    if (GetLocaleInfo(LOCALE_USER_DEFAULT,
                      LOCALE_SISO639LANGNAME,
                      locale, sizeof(locale))) {
Martin v. Löwis's avatar
Martin v. Löwis committed
295
        Py_ssize_t i = strlen(locale);
296 297 298
        locale[i++] = '_';
        if (GetLocaleInfo(LOCALE_USER_DEFAULT,
                          LOCALE_SISO3166CTRYNAME,
Martin v. Löwis's avatar
Martin v. Löwis committed
299
                          locale+i, (int)(sizeof(locale)-i)))
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
            return Py_BuildValue("ss", locale, encoding);
    }

    /* If we end up here, this windows version didn't know about
       ISO639/ISO3166 names (it's probably Windows 95).  Return the
       Windows language identifier instead (a hexadecimal number) */

    locale[0] = '0';
    locale[1] = 'x';
    if (GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_IDEFAULTLANGUAGE,
                      locale+2, sizeof(locale)-2)) {
        return Py_BuildValue("ss", locale, encoding);
    }

    /* cannot determine the language code (very unlikely) */
    Py_INCREF(Py_None);
    return Py_BuildValue("Os", Py_None, encoding);
}
#endif

320
#ifdef HAVE_LANGINFO_H
321
#define LANGINFO(X) {#X, X}
322
static struct langinfo_constant{
323 324 325
    char* name;
    int value;
} langinfo_constants[] =
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
{
    /* These constants should exist on any langinfo implementation */
    LANGINFO(DAY_1),
    LANGINFO(DAY_2),
    LANGINFO(DAY_3),
    LANGINFO(DAY_4),
    LANGINFO(DAY_5),
    LANGINFO(DAY_6),
    LANGINFO(DAY_7),

    LANGINFO(ABDAY_1),
    LANGINFO(ABDAY_2),
    LANGINFO(ABDAY_3),
    LANGINFO(ABDAY_4),
    LANGINFO(ABDAY_5),
    LANGINFO(ABDAY_6),
    LANGINFO(ABDAY_7),

    LANGINFO(MON_1),
    LANGINFO(MON_2),
    LANGINFO(MON_3),
    LANGINFO(MON_4),
    LANGINFO(MON_5),
    LANGINFO(MON_6),
    LANGINFO(MON_7),
    LANGINFO(MON_8),
    LANGINFO(MON_9),
    LANGINFO(MON_10),
    LANGINFO(MON_11),
    LANGINFO(MON_12),

    LANGINFO(ABMON_1),
    LANGINFO(ABMON_2),
    LANGINFO(ABMON_3),
    LANGINFO(ABMON_4),
    LANGINFO(ABMON_5),
    LANGINFO(ABMON_6),
    LANGINFO(ABMON_7),
    LANGINFO(ABMON_8),
    LANGINFO(ABMON_9),
    LANGINFO(ABMON_10),
    LANGINFO(ABMON_11),
    LANGINFO(ABMON_12),

#ifdef RADIXCHAR
    /* The following are not available with glibc 2.0 */
    LANGINFO(RADIXCHAR),
    LANGINFO(THOUSEP),
    /* YESSTR and NOSTR are deprecated in glibc, since they are
       a special case of message translation, which should be rather
       done using gettext. So we don't expose it to Python in the
       first place.
    LANGINFO(YESSTR),
    LANGINFO(NOSTR),
    */
    LANGINFO(CRNCYSTR),
#endif

    LANGINFO(D_T_FMT),
    LANGINFO(D_FMT),
    LANGINFO(T_FMT),
    LANGINFO(AM_STR),
    LANGINFO(PM_STR),

390 391 392 393 394
    /* The following constants are available only with XPG4, but...
       AIX 3.2. only has CODESET.
       OpenBSD doesn't have CODESET but has T_FMT_AMPM, and doesn't have
       a few of the others.
       Solution: ifdef-test them all. */
395 396
#ifdef CODESET
    LANGINFO(CODESET),
397 398
#endif
#ifdef T_FMT_AMPM
399
    LANGINFO(T_FMT_AMPM),
400 401
#endif
#ifdef ERA
402
    LANGINFO(ERA),
403 404
#endif
#ifdef ERA_D_FMT
405
    LANGINFO(ERA_D_FMT),
406 407
#endif
#ifdef ERA_D_T_FMT
408
    LANGINFO(ERA_D_T_FMT),
409 410
#endif
#ifdef ERA_T_FMT
411
    LANGINFO(ERA_T_FMT),
412 413
#endif
#ifdef ALT_DIGITS
414
    LANGINFO(ALT_DIGITS),
415 416
#endif
#ifdef YESEXPR
417
    LANGINFO(YESEXPR),
418 419
#endif
#ifdef NOEXPR
420 421 422 423 424 425 426 427 428
    LANGINFO(NOEXPR),
#endif
#ifdef _DATE_FMT
    /* This is not available in all glibc versions that have CODESET. */
    LANGINFO(_DATE_FMT),
#endif
    {0, 0}
};

429
PyDoc_STRVAR(nl_langinfo__doc__,
430
"nl_langinfo(key) -> string\n"
431
"Return the value for the locale information associated with key.");
432 433 434 435

static PyObject*
PyLocale_nl_langinfo(PyObject* self, PyObject* args)
{
436
    int item, i;
437 438
    if (!PyArg_ParseTuple(args, "i:nl_langinfo", &item))
        return NULL;
439 440
    /* Check whether this is a supported constant. GNU libc sometimes
       returns numeric values in the char* return value, which would
Neal Norwitz's avatar
Neal Norwitz committed
441
       crash PyUnicode_FromString.  */
442
    for (i = 0; langinfo_constants[i].name; i++)
443 444 445 446
        if (langinfo_constants[i].value == item) {
            /* Check NULL as a workaround for GNU libc's returning NULL
               instead of an empty string for nl_langinfo(ERA).  */
            const char *result = nl_langinfo(item);
447
            result = result != NULL ? result : "";
448
            return PyUnicode_DecodeLocale(result, NULL);
449
        }
450 451
    PyErr_SetString(PyExc_ValueError, "unsupported langinfo constant");
    return NULL;
452
}
453
#endif /* HAVE_LANGINFO_H */
454 455 456

#ifdef HAVE_LIBINTL_H

457
PyDoc_STRVAR(gettext__doc__,
458
"gettext(msg) -> string\n"
459
"Return translation of msg.");
460 461 462 463

static PyObject*
PyIntl_gettext(PyObject* self, PyObject *args)
{
464 465 466
    char *in;
    if (!PyArg_ParseTuple(args, "s", &in))
        return 0;
467
    return PyUnicode_DecodeLocale(gettext(in), NULL);
468 469
}

470
PyDoc_STRVAR(dgettext__doc__,
471
"dgettext(domain, msg) -> string\n"
472
"Return translation of msg in domain.");
473 474 475 476

static PyObject*
PyIntl_dgettext(PyObject* self, PyObject *args)
{
477 478 479
    char *domain, *in;
    if (!PyArg_ParseTuple(args, "zs", &domain, &in))
        return 0;
480
    return PyUnicode_DecodeLocale(dgettext(domain, in), NULL);
481 482
}

483
PyDoc_STRVAR(dcgettext__doc__,
484
"dcgettext(domain, msg, category) -> string\n"
485
"Return translation of msg in domain and category.");
486 487 488 489

static PyObject*
PyIntl_dcgettext(PyObject *self, PyObject *args)
{
490 491 492 493
    char *domain, *msgid;
    int category;
    if (!PyArg_ParseTuple(args, "zsi", &domain, &msgid, &category))
        return 0;
494
    return PyUnicode_DecodeLocale(dcgettext(domain,msgid,category), NULL);
495 496
}

497
PyDoc_STRVAR(textdomain__doc__,
498
"textdomain(domain) -> string\n"
499
"Set the C library's textdmain to domain, returning the new domain.");
500 501 502 503

static PyObject*
PyIntl_textdomain(PyObject* self, PyObject* args)
{
504 505 506 507 508 509 510 511
    char *domain;
    if (!PyArg_ParseTuple(args, "z", &domain))
        return 0;
    domain = textdomain(domain);
    if (!domain) {
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
512
    return PyUnicode_DecodeLocale(domain, NULL);
513 514
}

515
PyDoc_STRVAR(bindtextdomain__doc__,
516
"bindtextdomain(domain, dir) -> string\n"
517
"Bind the C library's domain to dir.");
518 519 520 521

static PyObject*
PyIntl_bindtextdomain(PyObject* self,PyObject*args)
{
522 523 524
    char *domain, *dirname, *current_dirname;
    PyObject *dirname_obj, *dirname_bytes = NULL, *result;
    if (!PyArg_ParseTuple(args, "sO", &domain, &dirname_obj))
525 526 527 528 529
        return 0;
    if (!strlen(domain)) {
        PyErr_SetString(Error, "domain must be a non-empty string");
        return 0;
    }
530 531 532 533 534 535 536 537 538 539 540
    if (dirname_obj != Py_None) {
        if (!PyUnicode_FSConverter(dirname_obj, &dirname_bytes))
            return NULL;
        dirname = PyBytes_AsString(dirname_bytes);
    } else {
        dirname_bytes = NULL;
        dirname = NULL;
    }
    current_dirname = bindtextdomain(domain, dirname);
    if (current_dirname == NULL) {
        Py_XDECREF(dirname_bytes);
541 542 543
        PyErr_SetFromErrno(PyExc_OSError);
        return NULL;
    }
544
    result = PyUnicode_DecodeLocale(current_dirname, NULL);
545 546
    Py_XDECREF(dirname_bytes);
    return result;
547 548
}

549 550 551 552 553 554 555 556
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
PyDoc_STRVAR(bind_textdomain_codeset__doc__,
"bind_textdomain_codeset(domain, codeset) -> string\n"
"Bind the C library's domain to codeset.");

static PyObject*
PyIntl_bind_textdomain_codeset(PyObject* self,PyObject*args)
{
557 558 559 560 561
    char *domain,*codeset;
    if (!PyArg_ParseTuple(args, "sz", &domain, &codeset))
        return NULL;
    codeset = bind_textdomain_codeset(domain, codeset);
    if (codeset)
562
        return PyUnicode_DecodeLocale(codeset, NULL);
563
    Py_RETURN_NONE;
564 565 566
}
#endif

567
#endif
568

569
static struct PyMethodDef PyLocale_Methods[] = {
570
  {"setlocale", (PyCFunction) PyLocale_setlocale,
571
   METH_VARARGS, setlocale__doc__},
572
  {"localeconv", (PyCFunction) PyLocale_localeconv,
573
   METH_NOARGS, localeconv__doc__},
574
#ifdef HAVE_WCSCOLL
575
  {"strcoll", (PyCFunction) PyLocale_strcoll,
576
   METH_VARARGS, strcoll__doc__},
577 578
#endif
#ifdef HAVE_WCSXFRM
579
  {"strxfrm", (PyCFunction) PyLocale_strxfrm,
580
   METH_VARARGS, strxfrm__doc__},
581
#endif
582
#if defined(MS_WINDOWS)
583
  {"_getdefaultlocale", (PyCFunction) PyLocale_getdefaultlocale, METH_NOARGS},
584
#endif
585 586 587 588
#ifdef HAVE_LANGINFO_H
  {"nl_langinfo", (PyCFunction) PyLocale_nl_langinfo,
   METH_VARARGS, nl_langinfo__doc__},
#endif
589
#ifdef HAVE_LIBINTL_H
590 591 592 593 594 595 596 597 598 599
  {"gettext",(PyCFunction)PyIntl_gettext,METH_VARARGS,
    gettext__doc__},
  {"dgettext",(PyCFunction)PyIntl_dgettext,METH_VARARGS,
   dgettext__doc__},
  {"dcgettext",(PyCFunction)PyIntl_dcgettext,METH_VARARGS,
    dcgettext__doc__},
  {"textdomain",(PyCFunction)PyIntl_textdomain,METH_VARARGS,
   textdomain__doc__},
  {"bindtextdomain",(PyCFunction)PyIntl_bindtextdomain,METH_VARARGS,
   bindtextdomain__doc__},
600 601 602 603
#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  {"bind_textdomain_codeset",(PyCFunction)PyIntl_bind_textdomain_codeset,
   METH_VARARGS, bind_textdomain_codeset__doc__},
#endif
604
#endif
605 606 607
  {NULL, NULL}
};

608 609

static struct PyModuleDef _localemodule = {
610 611 612 613 614 615 616 617 618
    PyModuleDef_HEAD_INIT,
    "_locale",
    locale__doc__,
    -1,
    PyLocale_Methods,
    NULL,
    NULL,
    NULL,
    NULL
619 620
};

621
PyMODINIT_FUNC
622
PyInit__locale(void)
623
{
624
    PyObject *m, *d, *x;
625 626 627
#ifdef HAVE_LANGINFO_H
    int i;
#endif
628

629
    m = PyModule_Create(&_localemodule);
630
    if (m == NULL)
631
    return NULL;
632

633
    d = PyModule_GetDict(m);
634

635
    x = PyLong_FromLong(LC_CTYPE);
636 637 638
    PyDict_SetItemString(d, "LC_CTYPE", x);
    Py_XDECREF(x);

639
    x = PyLong_FromLong(LC_TIME);
640 641 642
    PyDict_SetItemString(d, "LC_TIME", x);
    Py_XDECREF(x);

643
    x = PyLong_FromLong(LC_COLLATE);
644 645 646
    PyDict_SetItemString(d, "LC_COLLATE", x);
    Py_XDECREF(x);

647
    x = PyLong_FromLong(LC_MONETARY);
648 649
    PyDict_SetItemString(d, "LC_MONETARY", x);
    Py_XDECREF(x);
650

651
#ifdef LC_MESSAGES
652
    x = PyLong_FromLong(LC_MESSAGES);
653 654
    PyDict_SetItemString(d, "LC_MESSAGES", x);
    Py_XDECREF(x);
655
#endif /* LC_MESSAGES */
656

657
    x = PyLong_FromLong(LC_NUMERIC);
658 659
    PyDict_SetItemString(d, "LC_NUMERIC", x);
    Py_XDECREF(x);
660

661
    x = PyLong_FromLong(LC_ALL);
662 663
    PyDict_SetItemString(d, "LC_ALL", x);
    Py_XDECREF(x);
664

665
    x = PyLong_FromLong(CHAR_MAX);
666 667
    PyDict_SetItemString(d, "CHAR_MAX", x);
    Py_XDECREF(x);
668

669 670
    Error = PyErr_NewException("locale.Error", NULL, NULL);
    PyDict_SetItemString(d, "Error", Error);
671

672
#ifdef HAVE_LANGINFO_H
673
    for (i = 0; langinfo_constants[i].name; i++) {
674 675
        PyModule_AddIntConstant(m, langinfo_constants[i].name,
                                langinfo_constants[i].value);
676
    }
677
#endif
678
    return m;
679
}
680

681
/*
682 683 684 685 686
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
End:
*/