pypy /pypy/module/_locale/interp_locale.py

Language Python Lines 367
MD5 Hash 5d158a70a3634541cfb106dc64b78ba6 Estimated Cost $6,779 (why?)
Repository https://bitbucket.org/pypy/pypy/ View Raw File View Project SPDX
  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
from rpython.rlib import rposix
from rpython.rlib.rarithmetic import intmask

from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.gateway import unwrap_spec

from rpython.rlib import rlocale
from pypy.module.exceptions.interp_exceptions import _new_exception, W_Exception
from rpython.rtyper.lltypesystem import lltype, rffi

W_Error = _new_exception('Error', W_Exception, 'locale error')

import sys

def make_error(space, msg):
    return OperationError(space.gettypeobject(W_Error.typedef), space.wrap(msg))

def rewrap_error(space, e):
    return OperationError(space.gettypeobject(W_Error.typedef),
                          space.wrap(e.message))

def _fixup_ulcase(space):
    stringmod = space.call_function(
        space.getattr(space.getbuiltinmodule('__builtin__'),
                      space.wrap('__import__')), space.wrap('string'))
    # create uppercase map string
    ul = []
    for c in xrange(256):
        if rlocale.isupper(c):
            ul.append(chr(c))
    space.setattr(stringmod, space.wrap('uppercase'), space.wrap(''.join(ul)))

    # create lowercase string
    ul = []
    for c in xrange(256):
        if rlocale.islower(c):
            ul.append(chr(c))
    space.setattr(stringmod, space.wrap('lowercase'), space.wrap(''.join(ul)))

    # create letters string
    ul = []
    for c in xrange(256):
        if rlocale.isalpha(c):
            ul.append(chr(c))
    space.setattr(stringmod, space.wrap('letters'), space.wrap(''.join(ul)))

@unwrap_spec(category=int)
def setlocale(space, category, w_locale=None):
    "(integer,string=None) -> string. Activates/queries locale processing."

    if space.is_none(w_locale):
        locale = None
    else:
        locale = space.str_w(w_locale)
    try:
        result = rlocale.setlocale(category, locale)
    except rlocale.LocaleError as e:
        raise rewrap_error(space, e)

    # record changes to LC_CTYPE
    if category in (rlocale.LC_CTYPE, rlocale.LC_ALL):
        _fixup_ulcase(space)

    return space.wrap(result)

def _w_copy_grouping(space, text):
    groups = [ space.wrap(ord(group)) for group in text ]
    if groups:
        groups.append(space.wrap(0))
    return space.newlist(groups)

def localeconv(space):
    "() -> dict. Returns numeric and monetary locale-specific parameters."
    lp = rlocale.localeconv()

    # Numeric information
    w_result = space.newdict()
    w = space.wrap
    space.setitem(w_result, w("decimal_point"),
                  w(rffi.charp2str(lp.c_decimal_point)))
    space.setitem(w_result, w("thousands_sep"),
                  w(rffi.charp2str(lp.c_thousands_sep)))
    space.setitem(w_result, w("grouping"),
                  _w_copy_grouping(space, rffi.charp2str(lp.c_grouping)))
    space.setitem(w_result, w("int_curr_symbol"),
                  w(rffi.charp2str(lp.c_int_curr_symbol)))
    space.setitem(w_result, w("currency_symbol"),
                  w(rffi.charp2str(lp.c_currency_symbol)))
    space.setitem(w_result, w("mon_decimal_point"),
                  w(rffi.charp2str(lp.c_mon_decimal_point)))
    space.setitem(w_result, w("mon_thousands_sep"),
                  w(rffi.charp2str(lp.c_mon_thousands_sep)))
    space.setitem(w_result, w("mon_grouping"),
                  _w_copy_grouping(space, rffi.charp2str(lp.c_mon_grouping)))
    space.setitem(w_result, w("positive_sign"),
                  w(rffi.charp2str(lp.c_positive_sign)))
    space.setitem(w_result, w("negative_sign"),
                  w(rffi.charp2str(lp.c_negative_sign)))
    space.setitem(w_result, w("int_frac_digits"),
                  w(lp.c_int_frac_digits))
    space.setitem(w_result, w("frac_digits"),
                  w(lp.c_frac_digits))
    space.setitem(w_result, w("p_cs_precedes"),
                  w(lp.c_p_cs_precedes))
    space.setitem(w_result, w("p_sep_by_space"),
                  w(lp.c_p_sep_by_space))
    space.setitem(w_result, w("n_cs_precedes"),
                  w(lp.c_n_cs_precedes))
    space.setitem(w_result, w("n_sep_by_space"),
                  w(lp.c_n_sep_by_space))
    space.setitem(w_result, w("p_sign_posn"),
                  w(lp.c_p_sign_posn))
    space.setitem(w_result, w("n_sign_posn"),
                  w(lp.c_n_sign_posn))

    return w_result

_strcoll = rlocale.external('strcoll', [rffi.CCHARP, rffi.CCHARP], rffi.INT)
_wcscoll = rlocale.external('wcscoll', [rffi.CWCHARP, rffi.CWCHARP], rffi.INT)


def strcoll(space, w_s1, w_s2):
    "string,string -> int. Compares two strings according to the locale."

    if (space.isinstance_w(w_s1, space.w_str) and
        space.isinstance_w(w_s2, space.w_str)):

        s1, s2 = space.str_w(w_s1), space.str_w(w_s2)
        s1_c = rffi.str2charp(s1)
        s2_c = rffi.str2charp(s2)
        try:
            return space.wrap(_strcoll(s1_c, s2_c))
        finally:
            rffi.free_charp(s1_c)
            rffi.free_charp(s2_c)

    s1, s2 = space.unicode_w(w_s1), space.unicode_w(w_s2)

    s1_c = rffi.unicode2wcharp(s1)
    s2_c = rffi.unicode2wcharp(s2)
    try:
        result = _wcscoll(s1_c, s2_c)
    finally:
        rffi.free_wcharp(s1_c)
        rffi.free_wcharp(s2_c)

    return space.wrap(result)

_strxfrm = rlocale.external('strxfrm',
                    [rffi.CCHARP, rffi.CCHARP, rffi.SIZE_T], rffi.SIZE_T)

@unwrap_spec(s=str)
def strxfrm(space, s):
    "string -> string. Returns a string that behaves for cmp locale-aware."
    n1 = len(s) + 1

    buf = lltype.malloc(rffi.CCHARP.TO, n1, flavor="raw", zero=True)
    s_c = rffi.str2charp(s)
    try:
        n2 = _strxfrm(buf, s_c, n1) + 1
    finally:
        rffi.free_charp(s_c)
    if n2 > n1:
        # more space needed
        lltype.free(buf, flavor="raw")
        buf = lltype.malloc(rffi.CCHARP.TO, intmask(n2),
                            flavor="raw", zero=True)
        s_c = rffi.str2charp(s)
        try:
            _strxfrm(buf, s_c, n2)
        finally:
            rffi.free_charp(s_c)

    val = rffi.charp2str(buf)
    lltype.free(buf, flavor="raw")

    return space.wrap(val)

if rlocale.HAVE_LANGINFO:

    @unwrap_spec(key=int)
    def nl_langinfo(space, key):
        """nl_langinfo(key) -> string
        Return the value for the locale information associated with key."""

        try:
            return space.wrap(rlocale.nl_langinfo(key))
        except ValueError:
            raise oefmt(space.w_ValueError, "unsupported langinfo constant")

#___________________________________________________________________
# HAVE_LIBINTL dependence

if rlocale.HAVE_LIBINTL:
    _gettext = rlocale.external('gettext', [rffi.CCHARP], rffi.CCHARP)

    @unwrap_spec(msg=str)
    def gettext(space, msg):
        """gettext(msg) -> string
        Return translation of msg."""
        msg_c = rffi.str2charp(msg)
        try:
            return space.wrap(rffi.charp2str(_gettext(msg_c)))
        finally:
            rffi.free_charp(msg_c)

    _dgettext = rlocale.external('dgettext', [rffi.CCHARP, rffi.CCHARP], rffi.CCHARP)

    @unwrap_spec(msg=str)
    def dgettext(space, w_domain, msg):
        """dgettext(domain, msg) -> string
        Return translation of msg in domain."""
        if space.is_w(w_domain, space.w_None):
            domain = None
            msg_c = rffi.str2charp(msg)
            try:
                result = _dgettext(domain, msg_c)
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(msg_c)
        else:
            domain = space.str_w(w_domain)
            domain_c = rffi.str2charp(domain)
            msg_c = rffi.str2charp(msg)
            try:
                result = _dgettext(domain_c, msg_c)
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(msg_c)

        return space.wrap(result)

    _dcgettext = rlocale.external('dcgettext', [rffi.CCHARP, rffi.CCHARP, rffi.INT],
                                                                rffi.CCHARP)

    @unwrap_spec(msg=str, category=int)
    def dcgettext(space, w_domain, msg, category):
        """dcgettext(domain, msg, category) -> string
        Return translation of msg in domain and category."""

        if space.is_w(w_domain, space.w_None):
            domain = None
            msg_c = rffi.str2charp(msg)
            try:
                result = _dcgettext(domain, msg_c, rffi.cast(rffi.INT, category))
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(msg_c)
        else:
            domain = space.str_w(w_domain)
            domain_c = rffi.str2charp(domain)
            msg_c = rffi.str2charp(msg)
            try:
                result = _dcgettext(domain_c, msg_c,
                                    rffi.cast(rffi.INT, category))
                # note that 'result' may be the same pointer as 'msg_c',
                # so it must be converted to an RPython string *before*
                # we free msg_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(msg_c)

        return space.wrap(result)


    _textdomain = rlocale.external('textdomain', [rffi.CCHARP], rffi.CCHARP)

    def textdomain(space, w_domain):
        """textdomain(domain) -> string
        Set the C library's textdomain to domain, returning the new domain."""

        if space.is_w(w_domain, space.w_None):
            domain = None
            result = _textdomain(domain)
            result = rffi.charp2str(result)
        else:
            domain = space.str_w(w_domain)
            domain_c = rffi.str2charp(domain)
            try:
                result = _textdomain(domain_c)
                # note that 'result' may be the same pointer as 'domain_c'
                # (maybe?) so it must be converted to an RPython string
                # *before* we free domain_c.
                result = rffi.charp2str(result)
            finally:
                rffi.free_charp(domain_c)

        return space.wrap(result)

    _bindtextdomain = rlocale.external('bindtextdomain', [rffi.CCHARP, rffi.CCHARP],
                                                                rffi.CCHARP,
                                       save_err=rffi.RFFI_SAVE_ERRNO)

    @unwrap_spec(domain=str)
    def bindtextdomain(space, domain, w_dir):
        """bindtextdomain(domain, dir) -> string
        Bind the C library's domain to dir."""

        if space.is_w(w_dir, space.w_None):
            dir = None
            domain_c = rffi.str2charp(domain)
            try:
                dirname = _bindtextdomain(domain_c, dir)
            finally:
                rffi.free_charp(domain_c)
        else:
            dir = space.str_w(w_dir)
            domain_c = rffi.str2charp(domain)
            dir_c = rffi.str2charp(dir)
            try:
                dirname = _bindtextdomain(domain_c, dir_c)
            finally:
                rffi.free_charp(domain_c)
                rffi.free_charp(dir_c)

        if not dirname:
            errno = rposix.get_saved_errno()
            raise OperationError(space.w_OSError, space.wrap(errno))
        return space.wrap(rffi.charp2str(dirname))

    _bind_textdomain_codeset = rlocale.external('bind_textdomain_codeset',
                                    [rffi.CCHARP, rffi.CCHARP], rffi.CCHARP)

    if rlocale.HAVE_BIND_TEXTDOMAIN_CODESET:
        @unwrap_spec(domain=str)
        def bind_textdomain_codeset(space, domain, w_codeset):
            """bind_textdomain_codeset(domain, codeset) -> string
            Bind the C library's domain to codeset."""

            if space.is_w(w_codeset, space.w_None):
                codeset = None
                domain_c = rffi.str2charp(domain)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset)
                finally:
                    rffi.free_charp(domain_c)
            else:
                codeset = space.str_w(w_codeset)
                domain_c = rffi.str2charp(domain)
                codeset_c = rffi.str2charp(codeset)
                try:
                    result = _bind_textdomain_codeset(domain_c, codeset_c)
                finally:
                    rffi.free_charp(domain_c)
                    rffi.free_charp(codeset_c)

            if not result:
                return space.w_None
            else:
                return space.wrap(rffi.charp2str(result))

if sys.platform == 'win32':
    def getdefaultlocale(space):
        language, encoding = rlocale.getdefaultlocale()
        return space.newtuple([space.wrap(language), space.wrap(encoding)])
Back to Top