Debian Codegraph @

rpython/rlib/rlocale.py

raw symbols SCIP
1
2 """ The rpython-level part of locale module
3 """
4
5 import sys
6
7 from rpython.rtyper.lltypesystem import rffi, lltype
8 from rpython.translator.tool.cbuild import ExternalCompilationInfo
9 from rpython.rtyper.tool import rffi_platform as platform
10 from rpython.rtyper.extfunc import register_external
11
12 class LocaleError(Exception):
13 def __init__(self, message):
14 self.message = message
15
16 HAVE_LANGINFO = sys.platform != 'win32'
17 HAVE_LIBINTL = sys.platform != 'win32'
18 libraries = []
19
20 if HAVE_LIBINTL:
21 try:
22 platform.verify_eci(ExternalCompilationInfo(includes=['libintl.h'],
23 libraries=['intl']))
24 libraries.append('intl')
25 except platform.CompilationError:
26 try:
27 platform.verify_eci(ExternalCompilationInfo(includes=['libintl.h']))
28 except platform.CompilationError:
29 HAVE_LIBINTL = False
30
31 class CConfig:
32 includes = ['locale.h', 'limits.h', 'ctype.h', 'wchar.h']
33 libraries = libraries
34
35 if HAVE_LANGINFO:
36 includes += ['langinfo.h']
37 if HAVE_LIBINTL:
38 includes += ['libintl.h']
39 if sys.platform == 'win32':
40 includes += ['windows.h']
41 _compilation_info_ = ExternalCompilationInfo(
42 includes=includes, libraries=libraries
43 )
44 HAVE_BIND_TEXTDOMAIN_CODESET = platform.Has('bind_textdomain_codeset')
45 lconv = platform.Struct("struct lconv", [
46 # Numeric (non-monetary) information.
47 ("decimal_point", rffi.CCHARP), # Decimal point character.
48 ("thousands_sep", rffi.CCHARP), # Thousands separator.
49
50 ## Each element is the number of digits in each group;
51 ## elements with higher indices are farther left.
52 ## An element with value CHAR_MAX means that no further grouping is done.
53 ## An element with value 0 means that the previous element is used
54 ## for all groups farther left. */
55 ("grouping", rffi.CCHARP),
56
57 ## Monetary information.
58
59 ## First three chars are a currency symbol from ISO 4217.
60 ## Fourth char is the separator. Fifth char is '\0'.
61 ("int_curr_symbol", rffi.CCHARP),
62 ("currency_symbol", rffi.CCHARP), # Local currency symbol.
63 ("mon_decimal_point", rffi.CCHARP), # Decimal point character.
64 ("mon_thousands_sep", rffi.CCHARP), # Thousands separator.
65 ("mon_grouping", rffi.CCHARP), # Like `grouping' element (above).
66 ("positive_sign", rffi.CCHARP), # Sign for positive values.
67 ("negative_sign", rffi.CCHARP), # Sign for negative values.
68 ("int_frac_digits", rffi.UCHAR), # Int'l fractional digits.
69
70 ("frac_digits", rffi.UCHAR), # Local fractional digits.
71 ## 1 if currency_symbol precedes a positive value, 0 if succeeds.
72 ("p_cs_precedes", rffi.UCHAR),
73 ## 1 iff a space separates currency_symbol from a positive value.
74 ("p_sep_by_space", rffi.UCHAR),
75 ## 1 if currency_symbol precedes a negative value, 0 if succeeds.
76 ("n_cs_precedes", rffi.UCHAR),
77 ## 1 iff a space separates currency_symbol from a negative value.
78 ("n_sep_by_space", rffi.UCHAR),
79
80 ## Positive and negative sign positions:
81 ## 0 Parentheses surround the quantity and currency_symbol.
82 ## 1 The sign string precedes the quantity and currency_symbol.
83 ## 2 The sign string follows the quantity and currency_symbol.
84 ## 3 The sign string immediately precedes the currency_symbol.
85 ## 4 The sign string immediately follows the currency_symbol.
86 ("p_sign_posn", rffi.UCHAR),
87 ("n_sign_posn", rffi.UCHAR),
88 ])
89
90
91 constants = {}
92 constant_names = (
93 'LC_CTYPE',
94 'LC_NUMERIC',
95 'LC_TIME',
96 'LC_COLLATE',
97 'LC_MONETARY',
98 'LC_MESSAGES',
99 'LC_ALL',
100 'LC_PAPER',
101 'LC_NAME',
102 'LC_ADDRESS',
103 'LC_TELEPHONE',
104 'LC_MEASUREMENT',
105 'LC_IDENTIFICATION',
106 'LC_MIN',
107 'LC_MAX',
108 # from limits.h
109 'CHAR_MAX',
110 )
111
112 for name in constant_names:
113 setattr(CConfig, name, platform.DefinedConstantInteger(name))
114
115 langinfo_names = []
116 if HAVE_LANGINFO:
117 # some of these consts have an additional #ifdef directives
118 # should we support them?
119 langinfo_names.extend('RADIXCHAR THOUSEP CRNCYSTR D_T_FMT D_FMT T_FMT '
120 'AM_STR PM_STR CODESET T_FMT_AMPM ERA ERA_D_FMT '
121 'ERA_D_T_FMT ERA_T_FMT ALT_DIGITS YESEXPR NOEXPR '
122 '_DATE_FMT'.split())
123 for i in range(1, 8):
124 langinfo_names.append("DAY_%d" % i)
125 langinfo_names.append("ABDAY_%d" % i)
126 for i in range(1, 13):
127 langinfo_names.append("MON_%d" % i)
128 langinfo_names.append("ABMON_%d" % i)
129
130 if sys.platform == 'win32':
131 langinfo_names.extend('LOCALE_USER_DEFAULT LOCALE_SISO639LANGNAME '
132 'LOCALE_SISO3166CTRYNAME LOCALE_IDEFAULTLANGUAGE '
133 ''.split())
134
135
136 for name in langinfo_names:
137 setattr(CConfig, name, platform.DefinedConstantInteger(name))
138
139 class cConfig(object):
140 pass
141
142 for k, v in platform.configure(CConfig).items():
143 setattr(cConfig, k, v)
144
145 # needed to export the constants inside and outside. see __init__.py
146 for name in constant_names:
147 value = getattr(cConfig, name)
148 if value is not None:
149 constants[name] = value
150
151 for name in langinfo_names:
152 value = getattr(cConfig, name)
153 if value is not None and sys.platform != 'win32':
154 constants[name] = value
155
156 locals().update(constants)
157
158 HAVE_BIND_TEXTDOMAIN_CODESET = cConfig.HAVE_BIND_TEXTDOMAIN_CODESET
159
160 def external(name, args, result, calling_conv='c', **kwds):
161 return rffi.llexternal(name, args, result,
162 compilation_info=CConfig._compilation_info_,
163 calling_conv=calling_conv,
164 sandboxsafe=True, **kwds)
165
166 _lconv = lltype.Ptr(cConfig.lconv)
167 localeconv = external('localeconv', [], _lconv)
168
169 def numeric_formatting():
170 """Specialized function to get formatting for numbers"""
171 return numeric_formatting_impl()
172
173 def numeric_formatting_impl():
174 conv = localeconv()
175 decimal_point = rffi.charp2str(conv.c_decimal_point)
176 thousands_sep = rffi.charp2str(conv.c_thousands_sep)
177 grouping = rffi.charp2str(conv.c_grouping)
178 return decimal_point, thousands_sep, grouping
179
180 register_external(numeric_formatting, [], (str, str, str),
181 llimpl=numeric_formatting_impl,
182 sandboxsafe=True)
183
184
185 _setlocale = external('setlocale', [rffi.INT, rffi.CCHARP], rffi.CCHARP)
186
187 def setlocale(category, locale):
188 if cConfig.LC_MAX is not None:
189 if not cConfig.LC_MIN <= category <= cConfig.LC_MAX:
190 raise LocaleError("invalid locale category")
191 ll_result = _setlocale(rffi.cast(rffi.INT, category), locale)
192 if not ll_result:
193 raise LocaleError("unsupported locale setting")
194 return rffi.charp2str(ll_result)
195
196 isalpha = external('isalpha', [rffi.INT], rffi.INT)
197 isupper = external('isupper', [rffi.INT], rffi.INT)
198 toupper = external('toupper', [rffi.INT], rffi.INT)
199 islower = external('islower', [rffi.INT], rffi.INT)
200 tolower = external('tolower', [rffi.INT], rffi.INT)
201 isalnum = external('isalnum', [rffi.INT], rffi.INT)
202
203 if HAVE_LANGINFO:
204 _nl_langinfo = external('nl_langinfo', [rffi.INT], rffi.CCHARP)
205
206 def nl_langinfo(key):
207 if key in constants.values():
208 ret = _nl_langinfo(rffi.cast(rffi.INT, key))
209 if ret:
210 return rffi.charp2str(ret)
211 raise ValueError
212
213 #___________________________________________________________________
214 # getdefaultlocale() implementation for Windows
215
216 if sys.platform == 'win32':
217 from rpython.rlib import rwin32
218 LCID = LCTYPE = rwin32.DWORD
219 GetACP = external('GetACP',
220 [], rffi.INT,
221 calling_conv='win')
222 GetLocaleInfo = external('GetLocaleInfoA',
223 [LCID, LCTYPE, rwin32.LPSTR, rffi.INT], rffi.INT,
224 calling_conv='win')
225
226 def getdefaultlocale():
227 encoding = "cp%d" % GetACP()
228
229 BUFSIZE = 50
230 buf_lang = lltype.malloc(rffi.CCHARP.TO, BUFSIZE, flavor='raw')
231 buf_country = lltype.malloc(rffi.CCHARP.TO, BUFSIZE, flavor='raw')
232
233 try:
234 if (GetLocaleInfo(cConfig.LOCALE_USER_DEFAULT,
235 cConfig.LOCALE_SISO639LANGNAME,
236 buf_lang, BUFSIZE) and
237 GetLocaleInfo(cConfig.LOCALE_USER_DEFAULT,
238 cConfig.LOCALE_SISO3166CTRYNAME,
239 buf_country, BUFSIZE)):
240 lang = rffi.charp2str(buf_lang)
241 country = rffi.charp2str(buf_country)
242 language = "%s_%s" % (lang, country)
243
244 # If we end up here, this windows version didn't know about
245 # ISO639/ISO3166 names (it's probably Windows 95). Return the
246 # Windows language identifier instead (a hexadecimal number)
247 elif GetLocaleInfo(cConfig.LOCALE_USER_DEFAULT,
248 cConfig.LOCALE_IDEFAULTLANGUAGE,
249 buf_lang, BUFSIZE):
250 lang = rffi.charp2str(buf_lang)
251 language = "0x%s" % (lang,)
252
253 else:
254 language = None
255 finally:
256 lltype.free(buf_lang, flavor='raw')
257 lltype.free(buf_country, flavor='raw')
258
259 return language, encoding