This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
[perl #53908] perlpodspec typo "Encoding::Supported"
[perl5.git] / locale.c
1 /*    locale.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2005, 2006, 2007, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  * A Elbereth Gilthoniel,
13  * silivren penna míriel
14  * o menel aglar elenath!
15  * Na-chaered palan-díriel
16  * o galadhremmin ennorath,
17  * Fanuilos, le linnathon
18  * nef aear, si nef aearon!
19  */
20
21 /* utility functions for handling locale-specific stuff like what
22  * character represents the decimal point.
23  */
24
25 #include "EXTERN.h"
26 #define PERL_IN_LOCALE_C
27 #include "perl.h"
28
29 #ifdef I_LOCALE
30 #  include <locale.h>
31 #endif
32
33 #ifdef I_LANGINFO
34 #   include <langinfo.h>
35 #endif
36
37 #include "reentr.h"
38
39 #if defined(USE_LOCALE_NUMERIC) || defined(USE_LOCALE_COLLATE)
40 /*
41  * Standardize the locale name from a string returned by 'setlocale'.
42  *
43  * The standard return value of setlocale() is either
44  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
45  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
46  *     (the space-separated values represent the various sublocales,
47  *      in some unspecificed order)
48  *
49  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
50  * which is harmful for further use of the string in setlocale().
51  *
52  */
53 STATIC char *
54 S_stdize_locale(pTHX_ char *locs)
55 {
56     const char * const s = strchr(locs, '=');
57     bool okay = TRUE;
58
59     PERL_ARGS_ASSERT_STDIZE_LOCALE;
60
61     if (s) {
62         const char * const t = strchr(s, '.');
63         okay = FALSE;
64         if (t) {
65             const char * const u = strchr(t, '\n');
66             if (u && (u[1] == 0)) {
67                 const STRLEN len = u - s;
68                 Move(s + 1, locs, len, char);
69                 locs[len] = 0;
70                 okay = TRUE;
71             }
72         }
73     }
74
75     if (!okay)
76         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
77
78     return locs;
79 }
80 #endif
81
82 void
83 Perl_set_numeric_radix(pTHX)
84 {
85 #ifdef USE_LOCALE_NUMERIC
86     dVAR;
87 # ifdef HAS_LOCALECONV
88     const struct lconv* const lc = localeconv();
89
90     if (lc && lc->decimal_point) {
91         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
92             SvREFCNT_dec(PL_numeric_radix_sv);
93             PL_numeric_radix_sv = NULL;
94         }
95         else {
96             if (PL_numeric_radix_sv)
97                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
98             else
99                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
100         }
101     }
102     else
103         PL_numeric_radix_sv = NULL;
104 # endif /* HAS_LOCALECONV */
105 #endif /* USE_LOCALE_NUMERIC */
106 }
107
108 /*
109  * Set up for a new numeric locale.
110  */
111 void
112 Perl_new_numeric(pTHX_ const char *newnum)
113 {
114 #ifdef USE_LOCALE_NUMERIC
115     dVAR;
116
117     if (! newnum) {
118         Safefree(PL_numeric_name);
119         PL_numeric_name = NULL;
120         PL_numeric_standard = TRUE;
121         PL_numeric_local = TRUE;
122         return;
123     }
124
125     if (! PL_numeric_name || strNE(PL_numeric_name, newnum)) {
126         Safefree(PL_numeric_name);
127         PL_numeric_name = stdize_locale(savepv(newnum));
128         PL_numeric_standard = ((*newnum == 'C' && newnum[1] == '\0')
129                                || strEQ(newnum, "POSIX"));
130         PL_numeric_local = TRUE;
131         set_numeric_radix();
132     }
133
134 #endif /* USE_LOCALE_NUMERIC */
135 }
136
137 void
138 Perl_set_numeric_standard(pTHX)
139 {
140 #ifdef USE_LOCALE_NUMERIC
141     dVAR;
142
143     if (! PL_numeric_standard) {
144         setlocale(LC_NUMERIC, "C");
145         PL_numeric_standard = TRUE;
146         PL_numeric_local = FALSE;
147         set_numeric_radix();
148     }
149
150 #endif /* USE_LOCALE_NUMERIC */
151 }
152
153 void
154 Perl_set_numeric_local(pTHX)
155 {
156 #ifdef USE_LOCALE_NUMERIC
157     dVAR;
158
159     if (! PL_numeric_local) {
160         setlocale(LC_NUMERIC, PL_numeric_name);
161         PL_numeric_standard = FALSE;
162         PL_numeric_local = TRUE;
163         set_numeric_radix();
164     }
165
166 #endif /* USE_LOCALE_NUMERIC */
167 }
168
169 /*
170  * Set up for a new ctype locale.
171  */
172 void
173 Perl_new_ctype(pTHX_ const char *newctype)
174 {
175 #ifdef USE_LOCALE_CTYPE
176     dVAR;
177     int i;
178
179     PERL_ARGS_ASSERT_NEW_CTYPE;
180
181     for (i = 0; i < 256; i++) {
182         if (isUPPER_LC(i))
183             PL_fold_locale[i] = toLOWER_LC(i);
184         else if (isLOWER_LC(i))
185             PL_fold_locale[i] = toUPPER_LC(i);
186         else
187             PL_fold_locale[i] = i;
188     }
189
190 #endif /* USE_LOCALE_CTYPE */
191     PERL_ARGS_ASSERT_NEW_CTYPE;
192     PERL_UNUSED_ARG(newctype);
193     PERL_UNUSED_CONTEXT;
194 }
195
196 /*
197  * Set up for a new collation locale.
198  */
199 void
200 Perl_new_collate(pTHX_ const char *newcoll)
201 {
202 #ifdef USE_LOCALE_COLLATE
203     dVAR;
204
205     if (! newcoll) {
206         if (PL_collation_name) {
207             ++PL_collation_ix;
208             Safefree(PL_collation_name);
209             PL_collation_name = NULL;
210         }
211         PL_collation_standard = TRUE;
212         PL_collxfrm_base = 0;
213         PL_collxfrm_mult = 2;
214         return;
215     }
216
217     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
218         ++PL_collation_ix;
219         Safefree(PL_collation_name);
220         PL_collation_name = stdize_locale(savepv(newcoll));
221         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
222                                  || strEQ(newcoll, "POSIX"));
223
224         {
225           /*  2: at most so many chars ('a', 'b'). */
226           /* 50: surely no system expands a char more. */
227 #define XFRMBUFSIZE  (2 * 50)
228           char xbuf[XFRMBUFSIZE];
229           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
230           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
231           const SSize_t mult = fb - fa;
232           if (mult < 1)
233               Perl_croak(aTHX_ "strxfrm() gets absurd");
234           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
235           PL_collxfrm_mult = mult;
236         }
237     }
238
239 #endif /* USE_LOCALE_COLLATE */
240 }
241
242 /*
243  * Initialize locale awareness.
244  */
245 int
246 Perl_init_i18nl10n(pTHX_ int printwarn)
247 {
248     int ok = 1;
249     /* returns
250      *    1 = set ok or not applicable,
251      *    0 = fallback to C locale,
252      *   -1 = fallback to C locale failed
253      */
254
255 #if defined(USE_LOCALE)
256     dVAR;
257
258 #ifdef USE_LOCALE_CTYPE
259     char *curctype   = NULL;
260 #endif /* USE_LOCALE_CTYPE */
261 #ifdef USE_LOCALE_COLLATE
262     char *curcoll    = NULL;
263 #endif /* USE_LOCALE_COLLATE */
264 #ifdef USE_LOCALE_NUMERIC
265     char *curnum     = NULL;
266 #endif /* USE_LOCALE_NUMERIC */
267 #ifdef __GLIBC__
268     char * const language   = PerlEnv_getenv("LANGUAGE");
269 #endif
270     char * const lc_all     = PerlEnv_getenv("LC_ALL");
271     char * const lang       = PerlEnv_getenv("LANG");
272     bool setlocale_failure = FALSE;
273
274 #ifdef LOCALE_ENVIRON_REQUIRED
275
276     /*
277      * Ultrix setlocale(..., "") fails if there are no environment
278      * variables from which to get a locale name.
279      */
280
281     bool done = FALSE;
282
283 #ifdef LC_ALL
284     if (lang) {
285         if (setlocale(LC_ALL, ""))
286             done = TRUE;
287         else
288             setlocale_failure = TRUE;
289     }
290     if (!setlocale_failure) {
291 #ifdef USE_LOCALE_CTYPE
292         Safefree(curctype);
293         if (! (curctype =
294                setlocale(LC_CTYPE,
295                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
296                                     ? "" : NULL)))
297             setlocale_failure = TRUE;
298         else
299             curctype = savepv(curctype);
300 #endif /* USE_LOCALE_CTYPE */
301 #ifdef USE_LOCALE_COLLATE
302         Safefree(curcoll);
303         if (! (curcoll =
304                setlocale(LC_COLLATE,
305                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
306                                    ? "" : NULL)))
307             setlocale_failure = TRUE;
308         else
309             curcoll = savepv(curcoll);
310 #endif /* USE_LOCALE_COLLATE */
311 #ifdef USE_LOCALE_NUMERIC
312         Safefree(curnum);
313         if (! (curnum =
314                setlocale(LC_NUMERIC,
315                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
316                                   ? "" : NULL)))
317             setlocale_failure = TRUE;
318         else
319             curnum = savepv(curnum);
320 #endif /* USE_LOCALE_NUMERIC */
321     }
322
323 #endif /* LC_ALL */
324
325 #endif /* !LOCALE_ENVIRON_REQUIRED */
326
327 #ifdef LC_ALL
328     if (! setlocale(LC_ALL, ""))
329         setlocale_failure = TRUE;
330 #endif /* LC_ALL */
331
332     if (!setlocale_failure) {
333 #ifdef USE_LOCALE_CTYPE
334         Safefree(curctype);
335         if (! (curctype = setlocale(LC_CTYPE, "")))
336             setlocale_failure = TRUE;
337         else
338             curctype = savepv(curctype);
339 #endif /* USE_LOCALE_CTYPE */
340 #ifdef USE_LOCALE_COLLATE
341         Safefree(curcoll);
342         if (! (curcoll = setlocale(LC_COLLATE, "")))
343             setlocale_failure = TRUE;
344         else
345             curcoll = savepv(curcoll);
346 #endif /* USE_LOCALE_COLLATE */
347 #ifdef USE_LOCALE_NUMERIC
348         Safefree(curnum);
349         if (! (curnum = setlocale(LC_NUMERIC, "")))
350             setlocale_failure = TRUE;
351         else
352             curnum = savepv(curnum);
353 #endif /* USE_LOCALE_NUMERIC */
354     }
355
356     if (setlocale_failure) {
357         char *p;
358         const bool locwarn = (printwarn > 1 ||
359                         (printwarn &&
360                          (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
361
362         if (locwarn) {
363 #ifdef LC_ALL
364
365             PerlIO_printf(Perl_error_log,
366                "perl: warning: Setting locale failed.\n");
367
368 #else /* !LC_ALL */
369
370             PerlIO_printf(Perl_error_log,
371                "perl: warning: Setting locale failed for the categories:\n\t");
372 #ifdef USE_LOCALE_CTYPE
373             if (! curctype)
374                 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
375 #endif /* USE_LOCALE_CTYPE */
376 #ifdef USE_LOCALE_COLLATE
377             if (! curcoll)
378                 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
379 #endif /* USE_LOCALE_COLLATE */
380 #ifdef USE_LOCALE_NUMERIC
381             if (! curnum)
382                 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
383 #endif /* USE_LOCALE_NUMERIC */
384             PerlIO_printf(Perl_error_log, "\n");
385
386 #endif /* LC_ALL */
387
388             PerlIO_printf(Perl_error_log,
389                 "perl: warning: Please check that your locale settings:\n");
390
391 #ifdef __GLIBC__
392             PerlIO_printf(Perl_error_log,
393                           "\tLANGUAGE = %c%s%c,\n",
394                           language ? '"' : '(',
395                           language ? language : "unset",
396                           language ? '"' : ')');
397 #endif
398
399             PerlIO_printf(Perl_error_log,
400                           "\tLC_ALL = %c%s%c,\n",
401                           lc_all ? '"' : '(',
402                           lc_all ? lc_all : "unset",
403                           lc_all ? '"' : ')');
404
405 #if defined(USE_ENVIRON_ARRAY)
406             {
407               char **e;
408               for (e = environ; *e; e++) {
409                   if (strnEQ(*e, "LC_", 3)
410                         && strnNE(*e, "LC_ALL=", 7)
411                         && (p = strchr(*e, '=')))
412                       PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
413                                     (int)(p - *e), *e, p + 1);
414               }
415             }
416 #else
417             PerlIO_printf(Perl_error_log,
418                           "\t(possibly more locale environment variables)\n");
419 #endif
420
421             PerlIO_printf(Perl_error_log,
422                           "\tLANG = %c%s%c\n",
423                           lang ? '"' : '(',
424                           lang ? lang : "unset",
425                           lang ? '"' : ')');
426
427             PerlIO_printf(Perl_error_log,
428                           "    are supported and installed on your system.\n");
429         }
430
431 #ifdef LC_ALL
432
433         if (setlocale(LC_ALL, "C")) {
434             if (locwarn)
435                 PerlIO_printf(Perl_error_log,
436       "perl: warning: Falling back to the standard locale (\"C\").\n");
437             ok = 0;
438         }
439         else {
440             if (locwarn)
441                 PerlIO_printf(Perl_error_log,
442       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
443             ok = -1;
444         }
445
446 #else /* ! LC_ALL */
447
448         if (0
449 #ifdef USE_LOCALE_CTYPE
450             || !(curctype || setlocale(LC_CTYPE, "C"))
451 #endif /* USE_LOCALE_CTYPE */
452 #ifdef USE_LOCALE_COLLATE
453             || !(curcoll || setlocale(LC_COLLATE, "C"))
454 #endif /* USE_LOCALE_COLLATE */
455 #ifdef USE_LOCALE_NUMERIC
456             || !(curnum || setlocale(LC_NUMERIC, "C"))
457 #endif /* USE_LOCALE_NUMERIC */
458             )
459         {
460             if (locwarn)
461                 PerlIO_printf(Perl_error_log,
462       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
463             ok = -1;
464         }
465
466 #endif /* ! LC_ALL */
467
468 #ifdef USE_LOCALE_CTYPE
469         Safefree(curctype);
470         curctype = savepv(setlocale(LC_CTYPE, NULL));
471 #endif /* USE_LOCALE_CTYPE */
472 #ifdef USE_LOCALE_COLLATE
473         Safefree(curcoll);
474         curcoll = savepv(setlocale(LC_COLLATE, NULL));
475 #endif /* USE_LOCALE_COLLATE */
476 #ifdef USE_LOCALE_NUMERIC
477         Safefree(curnum);
478         curnum = savepv(setlocale(LC_NUMERIC, NULL));
479 #endif /* USE_LOCALE_NUMERIC */
480     }
481     else {
482
483 #ifdef USE_LOCALE_CTYPE
484     new_ctype(curctype);
485 #endif /* USE_LOCALE_CTYPE */
486
487 #ifdef USE_LOCALE_COLLATE
488     new_collate(curcoll);
489 #endif /* USE_LOCALE_COLLATE */
490
491 #ifdef USE_LOCALE_NUMERIC
492     new_numeric(curnum);
493 #endif /* USE_LOCALE_NUMERIC */
494
495     }
496
497 #endif /* USE_LOCALE */
498
499 #ifdef USE_PERLIO
500     {
501       /* Set PL_utf8locale to TRUE if using PerlIO _and_
502          any of the following are true:
503          - nl_langinfo(CODESET) contains /^utf-?8/i
504          - $ENV{LC_ALL}   contains /^utf-?8/i
505          - $ENV{LC_CTYPE} contains /^utf-?8/i
506          - $ENV{LANG}     contains /^utf-?8/i
507          The LC_ALL, LC_CTYPE, LANG obey the usual override
508          hierarchy of locale environment variables.  (LANGUAGE
509          affects only LC_MESSAGES only under glibc.) (If present,
510          it overrides LC_MESSAGES for GNU gettext, and it also
511          can have more than one locale, separated by spaces,
512          in case you need to know.)
513          If PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
514          are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer
515          on STDIN, STDOUT, STDERR, _and_ the default open discipline.
516       */
517          bool utf8locale = FALSE;
518          char *codeset = NULL;
519 #if defined(HAS_NL_LANGINFO) && defined(CODESET)
520          codeset = nl_langinfo(CODESET);
521 #endif
522          if (codeset)
523               utf8locale = (Perl_ibcmp(aTHX_ codeset, STR_WITH_LEN("UTF-8")) == 0 ||
524                             Perl_ibcmp(aTHX_ codeset, STR_WITH_LEN("UTF8") ) == 0);
525 #if defined(USE_LOCALE)
526          else { /* nl_langinfo(CODESET) is supposed to correctly
527                  * interpret the locale environment variables,
528                  * but just in case it fails, let's do this manually. */ 
529               if (lang)
530                    utf8locale = (Perl_ibcmp(aTHX_ lang, STR_WITH_LEN("UTF-8")) == 0 ||
531                                  Perl_ibcmp(aTHX_ lang, STR_WITH_LEN("UTF8") ) == 0);
532 #ifdef USE_LOCALE_CTYPE
533               if (curctype)
534                    utf8locale = (Perl_ibcmp(aTHX_ curctype, STR_WITH_LEN("UTF-8")) == 0 ||
535                                  Perl_ibcmp(aTHX_ curctype, STR_WITH_LEN("UTF8") ) == 0);
536 #endif
537               if (lc_all)
538                    utf8locale = (Perl_ibcmp(aTHX_ lc_all, STR_WITH_LEN("UTF-8")) == 0 ||
539                                  Perl_ibcmp(aTHX_ lc_all, STR_WITH_LEN("UTF8") ) == 0);
540          }
541 #endif /* USE_LOCALE */
542          if (utf8locale)
543               PL_utf8locale = TRUE;
544     }
545     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
546        This is an alternative to using the -C command line switch
547        (the -C if present will override this). */
548     {
549          const char *p = PerlEnv_getenv("PERL_UNICODE");
550          PL_unicode = p ? parse_unicode_opts(&p) : 0;
551          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
552              PL_utf8cache = -1;
553     }
554 #endif
555
556 #ifdef USE_LOCALE_CTYPE
557     Safefree(curctype);
558 #endif /* USE_LOCALE_CTYPE */
559 #ifdef USE_LOCALE_COLLATE
560     Safefree(curcoll);
561 #endif /* USE_LOCALE_COLLATE */
562 #ifdef USE_LOCALE_NUMERIC
563     Safefree(curnum);
564 #endif /* USE_LOCALE_NUMERIC */
565     return ok;
566 }
567
568 #ifdef USE_LOCALE_COLLATE
569
570 /*
571  * mem_collxfrm() is a bit like strxfrm() but with two important
572  * differences. First, it handles embedded NULs. Second, it allocates
573  * a bit more memory than needed for the transformed data itself.
574  * The real transformed data begins at offset sizeof(collationix).
575  * Please see sv_collxfrm() to see how this is used.
576  */
577
578 char *
579 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
580 {
581     dVAR;
582     char *xbuf;
583     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
584
585     PERL_ARGS_ASSERT_MEM_COLLXFRM;
586
587     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
588     /* the +1 is for the terminating NUL. */
589
590     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
591     Newx(xbuf, xAlloc, char);
592     if (! xbuf)
593         goto bad;
594
595     *(U32*)xbuf = PL_collation_ix;
596     xout = sizeof(PL_collation_ix);
597     for (xin = 0; xin < len; ) {
598         Size_t xused;
599
600         for (;;) {
601             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
602             if (xused >= PERL_INT_MAX)
603                 goto bad;
604             if ((STRLEN)xused < xAlloc - xout)
605                 break;
606             xAlloc = (2 * xAlloc) + 1;
607             Renew(xbuf, xAlloc, char);
608             if (! xbuf)
609                 goto bad;
610         }
611
612         xin += strlen(s + xin) + 1;
613         xout += xused;
614
615         /* Embedded NULs are understood but silently skipped
616          * because they make no sense in locale collation. */
617     }
618
619     xbuf[xout] = '\0';
620     *xlen = xout - sizeof(PL_collation_ix);
621     return xbuf;
622
623   bad:
624     Safefree(xbuf);
625     *xlen = 0;
626     return NULL;
627 }
628
629 #endif /* USE_LOCALE_COLLATE */
630
631 /*
632  * Local variables:
633  * c-indentation-style: bsd
634  * c-basic-offset: 4
635  * indent-tabs-mode: t
636  * End:
637  *
638  * ex: set ts=8 sts=4 sw=4 noet:
639  */