This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Upgrade Scalar-List-Utils from version 1.37 to 1.38
[perl5.git] / locale.c
1 /*    locale.c
2  *
3  *    Copyright (C) 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001,
4  *    2002, 2003, 2005, 2006, 2007, 2008 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  *     [p.238 of _The Lord of the Rings_, II/i: "Many Meetings"]
21  */
22
23 /* utility functions for handling locale-specific stuff like what
24  * character represents the decimal point.
25  *
26  * All C programs have an underlying locale.  Perl generally doesn't pay any
27  * attention to it except within the scope of a 'use locale'.  For most
28  * categories, it accomplishes this by just using different operations if it is
29  * in such scope than if not.  However, various libc functions called by Perl
30  * are affected by the LC_NUMERIC category, so there are macros in perl.h that
31  * are used to toggle between the current locale and the C locale depending on
32  * the desired behavior of those functions at the moment.
33  */
34
35 #include "EXTERN.h"
36 #define PERL_IN_LOCALE_C
37 #include "perl.h"
38
39 #ifdef I_LANGINFO
40 #   include <langinfo.h>
41 #endif
42
43 #include "reentr.h"
44
45 #ifdef USE_LOCALE
46
47 /*
48  * Standardize the locale name from a string returned by 'setlocale', possibly
49  * modifying that string.
50  *
51  * The typical return value of setlocale() is either
52  * (1) "xx_YY" if the first argument of setlocale() is not LC_ALL
53  * (2) "xa_YY xb_YY ..." if the first argument of setlocale() is LC_ALL
54  *     (the space-separated values represent the various sublocales,
55  *      in some unspecified order).  This is not handled by this function.
56  *
57  * In some platforms it has a form like "LC_SOMETHING=Lang_Country.866\n",
58  * which is harmful for further use of the string in setlocale().  This
59  * function removes the trailing new line and everything up through the '='
60  *
61  */
62 STATIC char *
63 S_stdize_locale(pTHX_ char *locs)
64 {
65     const char * const s = strchr(locs, '=');
66     bool okay = TRUE;
67
68     PERL_ARGS_ASSERT_STDIZE_LOCALE;
69
70     if (s) {
71         const char * const t = strchr(s, '.');
72         okay = FALSE;
73         if (t) {
74             const char * const u = strchr(t, '\n');
75             if (u && (u[1] == 0)) {
76                 const STRLEN len = u - s;
77                 Move(s + 1, locs, len, char);
78                 locs[len] = 0;
79                 okay = TRUE;
80             }
81         }
82     }
83
84     if (!okay)
85         Perl_croak(aTHX_ "Can't fix broken locale name \"%s\"", locs);
86
87     return locs;
88 }
89
90 #endif
91
92 void
93 Perl_set_numeric_radix(pTHX)
94 {
95 #ifdef USE_LOCALE_NUMERIC
96     dVAR;
97 # ifdef HAS_LOCALECONV
98     const struct lconv* const lc = localeconv();
99
100     if (lc && lc->decimal_point) {
101         if (lc->decimal_point[0] == '.' && lc->decimal_point[1] == 0) {
102             SvREFCNT_dec(PL_numeric_radix_sv);
103             PL_numeric_radix_sv = NULL;
104         }
105         else {
106             if (PL_numeric_radix_sv)
107                 sv_setpv(PL_numeric_radix_sv, lc->decimal_point);
108             else
109                 PL_numeric_radix_sv = newSVpv(lc->decimal_point, 0);
110             if (! is_ascii_string((U8 *) lc->decimal_point, 0)
111                 && is_utf8_string((U8 *) lc->decimal_point, 0)
112                 && is_cur_LC_category_utf8(LC_NUMERIC))
113             {
114                 SvUTF8_on(PL_numeric_radix_sv);
115             }
116         }
117     }
118     else
119         PL_numeric_radix_sv = NULL;
120 # endif /* HAS_LOCALECONV */
121 #endif /* USE_LOCALE_NUMERIC */
122 }
123
124 void
125 Perl_new_numeric(pTHX_ const char *newnum)
126 {
127 #ifdef USE_LOCALE_NUMERIC
128
129     /* Called after all libc setlocale() calls affecting LC_NUMERIC, to tell
130      * core Perl this and that 'newnum' is the name of the new locale.
131      * It installs this locale as the current underlying default.
132      *
133      * The default locale and the C locale can be toggled between by use of the
134      * set_numeric_local() and set_numeric_standard() functions, which should
135      * probably not be called directly, but only via macros like
136      * SET_NUMERIC_STANDARD() in perl.h.
137      *
138      * The toggling is necessary mainly so that a non-dot radix decimal point
139      * character can be output, while allowing internal calculations to use a
140      * dot.
141      *
142      * This sets several interpreter-level variables:
143      * PL_numeric_name  The default locale's name: a copy of 'newnum'
144      * PL_numeric_local A boolean indicating if the toggled state is such
145      *                  that the current locale is the default locale
146      * PL_numeric_standard A boolean indicating if the toggled state is such
147      *                  that the current locale is the C locale
148      * Note that both of the last two variables can be true at the same time,
149      * if the underlying locale is C.  (Toggling is a no-op under these
150      * circumstances.)
151      *
152      * Any code changing the locale (outside this file) should use
153      * POSIX::setlocale, which calls this function.  Therefore this function
154      * should be called directly only from this file and from
155      * POSIX::setlocale() */
156
157     char *save_newnum;
158     dVAR;
159
160     if (! newnum) {
161         Safefree(PL_numeric_name);
162         PL_numeric_name = NULL;
163         PL_numeric_standard = TRUE;
164         PL_numeric_local = TRUE;
165         return;
166     }
167
168     save_newnum = stdize_locale(savepv(newnum));
169     if (! PL_numeric_name || strNE(PL_numeric_name, save_newnum)) {
170         Safefree(PL_numeric_name);
171         PL_numeric_name = save_newnum;
172     }
173
174     PL_numeric_standard = ((*save_newnum == 'C' && save_newnum[1] == '\0')
175                             || strEQ(save_newnum, "POSIX"));
176     PL_numeric_local = TRUE;
177     set_numeric_radix();
178
179 #endif /* USE_LOCALE_NUMERIC */
180 }
181
182 void
183 Perl_set_numeric_standard(pTHX)
184 {
185 #ifdef USE_LOCALE_NUMERIC
186     dVAR;
187
188     /* Toggle the LC_NUMERIC locale to C, if not already there.  Probably
189      * should use the macros like SET_NUMERIC_STANDARD() in perl.h instead of
190      * calling this directly. */
191
192     if (! PL_numeric_standard) {
193         setlocale(LC_NUMERIC, "C");
194         PL_numeric_standard = TRUE;
195         PL_numeric_local = FALSE;
196         set_numeric_radix();
197     }
198
199 #endif /* USE_LOCALE_NUMERIC */
200 }
201
202 void
203 Perl_set_numeric_local(pTHX)
204 {
205 #ifdef USE_LOCALE_NUMERIC
206     dVAR;
207
208     /* Toggle the LC_NUMERIC locale to the current underlying default, if not
209      * already there.  Probably should use the macros like SET_NUMERIC_LOCAL()
210      * in perl.h instead of calling this directly. */
211
212     if (! PL_numeric_local) {
213         setlocale(LC_NUMERIC, PL_numeric_name);
214         PL_numeric_standard = FALSE;
215         PL_numeric_local = TRUE;
216         set_numeric_radix();
217     }
218
219 #endif /* USE_LOCALE_NUMERIC */
220 }
221
222 /*
223  * Set up for a new ctype locale.
224  */
225 void
226 Perl_new_ctype(pTHX_ const char *newctype)
227 {
228 #ifdef USE_LOCALE_CTYPE
229
230     /* Called after all libc setlocale() calls affecting LC_CTYPE, to tell
231      * core Perl this and that 'newctype' is the name of the new locale.
232      *
233      * This function sets up the folding arrays for all 256 bytes, assuming
234      * that tofold() is tolc() since fold case is not a concept in POSIX,
235      *
236      * Any code changing the locale (outside this file) should use
237      * POSIX::setlocale, which calls this function.  Therefore this function
238      * should be called directly only from this file and from
239      * POSIX::setlocale() */
240
241     dVAR;
242     UV i;
243
244     PERL_ARGS_ASSERT_NEW_CTYPE;
245
246     for (i = 0; i < 256; i++) {
247         if (isUPPER_LC((U8) i))
248             PL_fold_locale[i] = toLOWER_LC((U8) i);
249         else if (isLOWER_LC((U8) i))
250             PL_fold_locale[i] = toUPPER_LC((U8) i);
251         else
252             PL_fold_locale[i] = (U8) i;
253     }
254
255 #endif /* USE_LOCALE_CTYPE */
256     PERL_ARGS_ASSERT_NEW_CTYPE;
257     PERL_UNUSED_ARG(newctype);
258     PERL_UNUSED_CONTEXT;
259 }
260
261 void
262 Perl_new_collate(pTHX_ const char *newcoll)
263 {
264 #ifdef USE_LOCALE_COLLATE
265
266     /* Called after all libc setlocale() calls affecting LC_COLLATE, to tell
267      * core Perl this and that 'newcoll' is the name of the new locale.
268      *
269      * Any code changing the locale (outside this file) should use
270      * POSIX::setlocale, which calls this function.  Therefore this function
271      * should be called directly only from this file and from
272      * POSIX::setlocale() */
273
274     dVAR;
275
276     if (! newcoll) {
277         if (PL_collation_name) {
278             ++PL_collation_ix;
279             Safefree(PL_collation_name);
280             PL_collation_name = NULL;
281         }
282         PL_collation_standard = TRUE;
283         PL_collxfrm_base = 0;
284         PL_collxfrm_mult = 2;
285         return;
286     }
287
288     if (! PL_collation_name || strNE(PL_collation_name, newcoll)) {
289         ++PL_collation_ix;
290         Safefree(PL_collation_name);
291         PL_collation_name = stdize_locale(savepv(newcoll));
292         PL_collation_standard = ((*newcoll == 'C' && newcoll[1] == '\0')
293                                  || strEQ(newcoll, "POSIX"));
294
295         {
296           /*  2: at most so many chars ('a', 'b'). */
297           /* 50: surely no system expands a char more. */
298 #define XFRMBUFSIZE  (2 * 50)
299           char xbuf[XFRMBUFSIZE];
300           const Size_t fa = strxfrm(xbuf, "a",  XFRMBUFSIZE);
301           const Size_t fb = strxfrm(xbuf, "ab", XFRMBUFSIZE);
302           const SSize_t mult = fb - fa;
303           if (mult < 1 && !(fa == 0 && fb == 0))
304               Perl_croak(aTHX_ "panic: strxfrm() gets absurd - a => %"UVuf", ab => %"UVuf,
305                          (UV) fa, (UV) fb);
306           PL_collxfrm_base = (fa > (Size_t)mult) ? (fa - mult) : 0;
307           PL_collxfrm_mult = mult;
308         }
309     }
310
311 #endif /* USE_LOCALE_COLLATE */
312 }
313
314 /*
315  * Initialize locale awareness.
316  */
317 int
318 Perl_init_i18nl10n(pTHX_ int printwarn)
319 {
320     int ok = 1;
321     /* returns
322      *    1 = set ok or not applicable,
323      *    0 = fallback to C locale,
324      *   -1 = fallback to C locale failed
325      */
326
327 #if defined(USE_LOCALE)
328     dVAR;
329
330 #ifdef USE_LOCALE_CTYPE
331     char *curctype   = NULL;
332 #endif /* USE_LOCALE_CTYPE */
333 #ifdef USE_LOCALE_COLLATE
334     char *curcoll    = NULL;
335 #endif /* USE_LOCALE_COLLATE */
336 #ifdef USE_LOCALE_NUMERIC
337     char *curnum     = NULL;
338 #endif /* USE_LOCALE_NUMERIC */
339 #ifdef __GLIBC__
340     char * const language   = PerlEnv_getenv("LANGUAGE");
341 #endif
342     /* NULL uses the existing already set up locale */
343     const char * const setlocale_init = (PerlEnv_getenv("PERL_SKIP_LOCALE_INIT"))
344                                         ? NULL
345                                         : "";
346     char * const lc_all     = PerlEnv_getenv("LC_ALL");
347     char * const lang       = PerlEnv_getenv("LANG");
348     bool setlocale_failure = FALSE;
349
350 #ifdef LOCALE_ENVIRON_REQUIRED
351
352     /*
353      * Ultrix setlocale(..., "") fails if there are no environment
354      * variables from which to get a locale name.
355      */
356
357     bool done = FALSE;
358
359 #   ifdef LC_ALL
360     if (lang) {
361         if (setlocale(LC_ALL, setlocale_init))
362             done = TRUE;
363         else
364             setlocale_failure = TRUE;
365     }
366     if (!setlocale_failure) {
367 #       ifdef USE_LOCALE_CTYPE
368         Safefree(curctype);
369         if (! (curctype =
370                setlocale(LC_CTYPE,
371                          (!done && (lang || PerlEnv_getenv("LC_CTYPE")))
372                                     ? setlocale_init : NULL)))
373             setlocale_failure = TRUE;
374         else
375             curctype = savepv(curctype);
376 #       endif /* USE_LOCALE_CTYPE */
377 #       ifdef USE_LOCALE_COLLATE
378         Safefree(curcoll);
379         if (! (curcoll =
380                setlocale(LC_COLLATE,
381                          (!done && (lang || PerlEnv_getenv("LC_COLLATE")))
382                                    ? setlocale_init : NULL)))
383             setlocale_failure = TRUE;
384         else
385             curcoll = savepv(curcoll);
386 #       endif /* USE_LOCALE_COLLATE */
387 #       ifdef USE_LOCALE_NUMERIC
388         Safefree(curnum);
389         if (! (curnum =
390                setlocale(LC_NUMERIC,
391                          (!done && (lang || PerlEnv_getenv("LC_NUMERIC")))
392                                   ? setlocale_init : NULL)))
393             setlocale_failure = TRUE;
394         else
395             curnum = savepv(curnum);
396 #       endif /* USE_LOCALE_NUMERIC */
397     }
398
399 #   endif /* LC_ALL */
400
401 #endif /* !LOCALE_ENVIRON_REQUIRED */
402
403 #ifdef LC_ALL
404     if (! setlocale(LC_ALL, setlocale_init))
405         setlocale_failure = TRUE;
406 #endif /* LC_ALL */
407
408     if (!setlocale_failure) {
409 #ifdef USE_LOCALE_CTYPE
410         Safefree(curctype);
411         if (! (curctype = setlocale(LC_CTYPE, setlocale_init)))
412             setlocale_failure = TRUE;
413         else
414             curctype = savepv(curctype);
415 #endif /* USE_LOCALE_CTYPE */
416 #ifdef USE_LOCALE_COLLATE
417         Safefree(curcoll);
418         if (! (curcoll = setlocale(LC_COLLATE, setlocale_init)))
419             setlocale_failure = TRUE;
420         else
421             curcoll = savepv(curcoll);
422 #endif /* USE_LOCALE_COLLATE */
423 #ifdef USE_LOCALE_NUMERIC
424         Safefree(curnum);
425         if (! (curnum = setlocale(LC_NUMERIC, setlocale_init)))
426             setlocale_failure = TRUE;
427         else
428             curnum = savepv(curnum);
429 #endif /* USE_LOCALE_NUMERIC */
430     }
431
432     if (setlocale_failure) {
433         char *p;
434         const bool locwarn = (printwarn > 1 ||
435                         (printwarn &&
436                          (!(p = PerlEnv_getenv("PERL_BADLANG")) || atoi(p))));
437
438         if (locwarn) {
439 #ifdef LC_ALL
440
441             PerlIO_printf(Perl_error_log,
442                "perl: warning: Setting locale failed.\n");
443
444 #else /* !LC_ALL */
445
446             PerlIO_printf(Perl_error_log,
447                "perl: warning: Setting locale failed for the categories:\n\t");
448 #ifdef USE_LOCALE_CTYPE
449             if (! curctype)
450                 PerlIO_printf(Perl_error_log, "LC_CTYPE ");
451 #endif /* USE_LOCALE_CTYPE */
452 #ifdef USE_LOCALE_COLLATE
453             if (! curcoll)
454                 PerlIO_printf(Perl_error_log, "LC_COLLATE ");
455 #endif /* USE_LOCALE_COLLATE */
456 #ifdef USE_LOCALE_NUMERIC
457             if (! curnum)
458                 PerlIO_printf(Perl_error_log, "LC_NUMERIC ");
459 #endif /* USE_LOCALE_NUMERIC */
460             PerlIO_printf(Perl_error_log, "\n");
461
462 #endif /* LC_ALL */
463
464             PerlIO_printf(Perl_error_log,
465                 "perl: warning: Please check that your locale settings:\n");
466
467 #ifdef __GLIBC__
468             PerlIO_printf(Perl_error_log,
469                           "\tLANGUAGE = %c%s%c,\n",
470                           language ? '"' : '(',
471                           language ? language : "unset",
472                           language ? '"' : ')');
473 #endif
474
475             PerlIO_printf(Perl_error_log,
476                           "\tLC_ALL = %c%s%c,\n",
477                           lc_all ? '"' : '(',
478                           lc_all ? lc_all : "unset",
479                           lc_all ? '"' : ')');
480
481 #if defined(USE_ENVIRON_ARRAY)
482             {
483               char **e;
484               for (e = environ; *e; e++) {
485                   if (strnEQ(*e, "LC_", 3)
486                         && strnNE(*e, "LC_ALL=", 7)
487                         && (p = strchr(*e, '=')))
488                       PerlIO_printf(Perl_error_log, "\t%.*s = \"%s\",\n",
489                                     (int)(p - *e), *e, p + 1);
490               }
491             }
492 #else
493             PerlIO_printf(Perl_error_log,
494                           "\t(possibly more locale environment variables)\n");
495 #endif
496
497             PerlIO_printf(Perl_error_log,
498                           "\tLANG = %c%s%c\n",
499                           lang ? '"' : '(',
500                           lang ? lang : "unset",
501                           lang ? '"' : ')');
502
503             PerlIO_printf(Perl_error_log,
504                           "    are supported and installed on your system.\n");
505         }
506
507 #ifdef LC_ALL
508
509         if (setlocale(LC_ALL, "C")) {
510             if (locwarn)
511                 PerlIO_printf(Perl_error_log,
512       "perl: warning: Falling back to the standard locale (\"C\").\n");
513             ok = 0;
514         }
515         else {
516             if (locwarn)
517                 PerlIO_printf(Perl_error_log,
518       "perl: warning: Failed to fall back to the standard locale (\"C\").\n");
519             ok = -1;
520         }
521
522 #else /* ! LC_ALL */
523
524         if (0
525 #ifdef USE_LOCALE_CTYPE
526             || !(curctype || setlocale(LC_CTYPE, "C"))
527 #endif /* USE_LOCALE_CTYPE */
528 #ifdef USE_LOCALE_COLLATE
529             || !(curcoll || setlocale(LC_COLLATE, "C"))
530 #endif /* USE_LOCALE_COLLATE */
531 #ifdef USE_LOCALE_NUMERIC
532             || !(curnum || setlocale(LC_NUMERIC, "C"))
533 #endif /* USE_LOCALE_NUMERIC */
534             )
535         {
536             if (locwarn)
537                 PerlIO_printf(Perl_error_log,
538       "perl: warning: Cannot fall back to the standard locale (\"C\").\n");
539             ok = -1;
540         }
541
542 #endif /* ! LC_ALL */
543
544 #ifdef USE_LOCALE_CTYPE
545         Safefree(curctype);
546         curctype = savepv(setlocale(LC_CTYPE, NULL));
547 #endif /* USE_LOCALE_CTYPE */
548 #ifdef USE_LOCALE_COLLATE
549         Safefree(curcoll);
550         curcoll = savepv(setlocale(LC_COLLATE, NULL));
551 #endif /* USE_LOCALE_COLLATE */
552 #ifdef USE_LOCALE_NUMERIC
553         Safefree(curnum);
554         curnum = savepv(setlocale(LC_NUMERIC, NULL));
555 #endif /* USE_LOCALE_NUMERIC */
556     }
557     else {
558
559 #ifdef USE_LOCALE_CTYPE
560     new_ctype(curctype);
561 #endif /* USE_LOCALE_CTYPE */
562
563 #ifdef USE_LOCALE_COLLATE
564     new_collate(curcoll);
565 #endif /* USE_LOCALE_COLLATE */
566
567 #ifdef USE_LOCALE_NUMERIC
568     new_numeric(curnum);
569 #endif /* USE_LOCALE_NUMERIC */
570
571     }
572
573 #if defined(USE_PERLIO) && defined(USE_LOCALE_CTYPE)
574     {
575       /* Set PL_utf8locale to TRUE if using PerlIO _and_
576          the current LC_CTYPE locale is UTF-8.
577          If PL_utf8locale and PL_unicode (set by -C or by $ENV{PERL_UNICODE})
578          are true, perl.c:S_parse_body() will turn on the PerlIO :utf8 layer
579          on STDIN, STDOUT, STDERR, _and_ the default open discipline.
580       */
581         PL_utf8locale = is_cur_LC_category_utf8(LC_CTYPE);
582     }
583     /* Set PL_unicode to $ENV{PERL_UNICODE} if using PerlIO.
584        This is an alternative to using the -C command line switch
585        (the -C if present will override this). */
586     {
587          const char *p = PerlEnv_getenv("PERL_UNICODE");
588          PL_unicode = p ? parse_unicode_opts(&p) : 0;
589          if (PL_unicode & PERL_UNICODE_UTF8CACHEASSERT_FLAG)
590              PL_utf8cache = -1;
591     }
592 #endif
593
594 #ifdef USE_LOCALE_CTYPE
595     Safefree(curctype);
596 #endif /* USE_LOCALE_CTYPE */
597 #ifdef USE_LOCALE_COLLATE
598     Safefree(curcoll);
599 #endif /* USE_LOCALE_COLLATE */
600 #ifdef USE_LOCALE_NUMERIC
601     Safefree(curnum);
602 #endif /* USE_LOCALE_NUMERIC */
603
604 #endif /* USE_LOCALE */
605
606     return ok;
607 }
608
609 #ifdef USE_LOCALE_COLLATE
610
611 /*
612  * mem_collxfrm() is a bit like strxfrm() but with two important
613  * differences. First, it handles embedded NULs. Second, it allocates
614  * a bit more memory than needed for the transformed data itself.
615  * The real transformed data begins at offset sizeof(collationix).
616  * Please see sv_collxfrm() to see how this is used.
617  */
618
619 char *
620 Perl_mem_collxfrm(pTHX_ const char *s, STRLEN len, STRLEN *xlen)
621 {
622     dVAR;
623     char *xbuf;
624     STRLEN xAlloc, xin, xout; /* xalloc is a reserved word in VC */
625
626     PERL_ARGS_ASSERT_MEM_COLLXFRM;
627
628     /* the first sizeof(collationix) bytes are used by sv_collxfrm(). */
629     /* the +1 is for the terminating NUL. */
630
631     xAlloc = sizeof(PL_collation_ix) + PL_collxfrm_base + (PL_collxfrm_mult * len) + 1;
632     Newx(xbuf, xAlloc, char);
633     if (! xbuf)
634         goto bad;
635
636     *(U32*)xbuf = PL_collation_ix;
637     xout = sizeof(PL_collation_ix);
638     for (xin = 0; xin < len; ) {
639         Size_t xused;
640
641         for (;;) {
642             xused = strxfrm(xbuf + xout, s + xin, xAlloc - xout);
643             if (xused >= PERL_INT_MAX)
644                 goto bad;
645             if ((STRLEN)xused < xAlloc - xout)
646                 break;
647             xAlloc = (2 * xAlloc) + 1;
648             Renew(xbuf, xAlloc, char);
649             if (! xbuf)
650                 goto bad;
651         }
652
653         xin += strlen(s + xin) + 1;
654         xout += xused;
655
656         /* Embedded NULs are understood but silently skipped
657          * because they make no sense in locale collation. */
658     }
659
660     xbuf[xout] = '\0';
661     *xlen = xout - sizeof(PL_collation_ix);
662     return xbuf;
663
664   bad:
665     Safefree(xbuf);
666     *xlen = 0;
667     return NULL;
668 }
669
670 #endif /* USE_LOCALE_COLLATE */
671
672 #ifdef USE_LOCALE
673
674 STATIC bool
675 S_is_cur_LC_category_utf8(pTHX_ int category)
676 {
677     /* Returns TRUE if the current locale for 'category' is UTF-8; FALSE
678      * otherwise. 'category' may not be LC_ALL.  If the platform doesn't have
679      * nl_langinfo(), nor MB_CUR_MAX, this employs a heuristic, which hence
680      * could give the wrong result.  It errs on the side of not being a UTF-8
681      * locale. */
682
683     char *save_input_locale = NULL;
684     STRLEN final_pos;
685
686 #ifdef LC_ALL
687     assert(category != LC_ALL);
688 #endif
689
690     /* First dispose of the trivial cases */
691     save_input_locale = setlocale(category, NULL);
692     if (! save_input_locale) {
693         return FALSE;   /* XXX maybe should croak */
694     }
695     save_input_locale = stdize_locale(savepv(save_input_locale));
696     if ((*save_input_locale == 'C' && save_input_locale[1] == '\0')
697         || strEQ(save_input_locale, "POSIX"))
698     {
699         Safefree(save_input_locale);
700         return FALSE;
701     }
702
703 #if defined(USE_LOCALE_CTYPE) && (defined(MB_CUR_MAX) || defined(HAS_NL_LANGINFO) && defined(CODESET))
704
705     { /* Next try MB_CUR_MAX or nl_langinfo if available */
706
707         char *save_ctype_locale = NULL;
708         bool is_utf8;
709
710         if (category != LC_CTYPE) { /* These work only on LC_CTYPE */
711
712             /* Get the current LC_CTYPE locale */
713             save_ctype_locale = stdize_locale(savepv(setlocale(LC_CTYPE, NULL)));
714             if (! save_ctype_locale) {
715                 goto cant_use_nllanginfo;
716             }
717
718             /* If LC_CTYPE and the desired category use the same locale, this
719              * means that finding the value for LC_CTYPE is the same as finding
720              * the value for the desired category.  Otherwise, switch LC_CTYPE
721              * to the desired category's locale */
722             if (strEQ(save_ctype_locale, save_input_locale)) {
723                 Safefree(save_ctype_locale);
724                 save_ctype_locale = NULL;
725             }
726             else if (! setlocale(LC_CTYPE, save_input_locale)) {
727                 Safefree(save_ctype_locale);
728                 goto cant_use_nllanginfo;
729             }
730         }
731
732         /* Here the current LC_CTYPE is set to the locale of the category whose
733          * information is desired.  This means that MB_CUR_MAX and
734          * nl_langinfo() should give the correct results */
735
736 #   ifdef MB_CUR_MAX
737
738         /* If we switched LC_CTYPE, switch back */
739         if (save_ctype_locale) {
740             setlocale(LC_CTYPE, save_ctype_locale);
741             Safefree(save_ctype_locale);
742         }
743
744         /* Standard UTF-8 needs at least 4 bytes to represent the maximum
745          * Unicode code point.  Since UTF-8 is the only non-single byte
746          * encoding we handle, we just say any such encoding is UTF-8, and if
747          * turns out to be wrong, other things will fail */
748         is_utf8 = MB_CUR_MAX >= 4;
749
750         Safefree(save_input_locale);
751
752 #       ifdef HAS_MBTOWC
753
754         /* ... But, most system that have MB_CUR_MAX will also have mbtowc(),
755          * since they are both in the C99 standard.  We can feed a known byte
756          * string to the latter function, and check that it gives the expected
757          * result */
758         if (is_utf8) {
759             wchar_t wc;
760             if (mbtowc(&wc, HYPHEN_UTF8, strlen(HYPHEN_UTF8))
761                                                         != strlen(HYPHEN_UTF8)
762                 || wc != (wchar_t) 0x2010)
763             {
764                 is_utf8 = FALSE;
765             }
766         }
767
768 #       endif
769
770         return is_utf8;
771 #else
772 #   if defined(HAS_NL_LANGINFO) && defined(CODESET)
773         {
774             char *codeset = savepv(nl_langinfo(CODESET));
775             if (codeset) {
776
777                 /* If we switched LC_CTYPE, switch back */
778                 if (save_ctype_locale) {
779                     setlocale(LC_CTYPE, save_ctype_locale);
780                     Safefree(save_ctype_locale);
781                 }
782
783                 is_utf8 = foldEQ(codeset, STR_WITH_LEN("UTF-8"))
784                         || foldEQ(codeset, STR_WITH_LEN("UTF8"));
785
786                 Safefree(codeset);
787                 Safefree(save_input_locale);
788                 return is_utf8;
789             }
790         }
791
792 #   endif
793 #   endif
794     }
795
796   cant_use_nllanginfo:
797
798 #endif /* HAS_NL_LANGINFO etc */
799
800     /* nl_langinfo not available or failed somehow.  Look at the locale name to
801      * see if it matches qr/UTF -? 8 /ix  */
802
803     final_pos = strlen(save_input_locale) - 1;
804     if (final_pos >= 3) {
805         char *name = save_input_locale;
806
807         /* Find next 'U' or 'u' and look from there */
808         while ((name += strcspn(name, "Uu") + 1)
809                                             <= save_input_locale + final_pos - 2)
810         {
811             if (toFOLD(*(name)) != 't'
812                 || toFOLD(*(name + 1)) != 'f')
813             {
814                 continue;
815             }
816             name += 2;
817             if (*(name) == '-') {
818                 if ((name > save_input_locale + final_pos - 1)) {
819                     break;
820                 }
821                 name++;
822             }
823             if (*(name) == '8') {
824                 Safefree(save_input_locale);
825                 return TRUE;
826             }
827         }
828     }
829
830 #ifdef WIN32
831     /* http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756.aspx */
832     if (final_pos >= 4
833         && *(save_input_locale + final_pos - 0) == '1'
834         && *(save_input_locale + final_pos - 1) == '0'
835         && *(save_input_locale + final_pos - 2) == '0'
836         && *(save_input_locale + final_pos - 3) == '5'
837         && *(save_input_locale + final_pos - 4) == '6')
838     {
839         Safefree(save_input_locale);
840         return TRUE;
841     }
842 #endif
843
844     /* Other common encodings are the ISO 8859 series, which aren't UTF-8 */
845     if (instr(save_input_locale, "8859")) {
846         Safefree(save_input_locale);
847         return FALSE;
848     }
849
850 #ifdef HAS_LOCALECONV
851
852 #   ifdef USE_LOCALE_MONETARY
853
854     /* Here, there is nothing in the locale name to indicate whether the locale
855      * is UTF-8 or not.  This "name", the return of setlocale(), is actually
856      * defined to be opaque, so we can't really rely on the absence of various
857      * substrings in the name to indicate its UTF-8ness.  Look at the locale's
858      * currency symbol.  Often that will be in the native script, and if the
859      * symbol isn't in UTF-8, we know that the locale isn't.  If it is
860      * non-ASCII UTF-8, we infer that the locale is too.
861      * To do this, like above for LC_CTYPE, we first set LC_MONETARY to the
862      * locale of the desired category, if it isn't that locale already */
863
864     {
865         char *save_monetary_locale = NULL;
866         bool illegal_utf8 = FALSE;
867         bool only_ascii = FALSE;
868         const struct lconv* const lc = localeconv();
869
870         if (category != LC_MONETARY) {
871
872             save_monetary_locale = stdize_locale(savepv(setlocale(LC_MONETARY,
873                                                                   NULL)));
874             if (! save_monetary_locale) {
875                 goto cant_use_monetary;
876             }
877
878             if (strNE(save_monetary_locale, save_input_locale)) {
879                 if (! setlocale(LC_MONETARY, save_input_locale)) {
880                     Safefree(save_monetary_locale);
881                     goto cant_use_monetary;
882                 }
883             }
884         }
885
886         /* Here the current LC_MONETARY is set to the locale of the category
887          * whose information is desired. */
888
889         if (lc && lc->currency_symbol) {
890             if (! is_utf8_string((U8 *) lc->currency_symbol, 0)) {
891                 illegal_utf8 = TRUE;
892             }
893             else if (is_ascii_string((U8 *) lc->currency_symbol, 0)) {
894                 only_ascii = TRUE;
895             }
896         }
897
898         /* If we changed it, restore LC_MONETARY to its original locale */
899         if (save_monetary_locale) {
900             setlocale(LC_MONETARY, save_monetary_locale);
901             Safefree(save_monetary_locale);
902         }
903
904         Safefree(save_input_locale);
905
906         /* It isn't a UTF-8 locale if the symbol is not legal UTF-8; otherwise
907          * assume the locale is UTF-8 if and only if the symbol is non-ascii
908          * UTF-8.  (We can't really tell if the locale is UTF-8 or not if the
909          * symbol is just a '$', so we err on the side of it not being UTF-8)
910          * */
911         return (illegal_utf8)
912                 ? FALSE
913                 : ! only_ascii;
914
915     }
916   cant_use_monetary:
917
918 #   endif /* USE_LOCALE_MONETARY */
919 #endif /* HAS_LOCALECONV */
920
921 #if 0 && defined(HAS_STRERROR) && defined(USE_LOCALE_MESSAGES)
922
923 /* This code is ifdefd out because it was found to not be necessary in testing
924  * on our dromedary test machine, which has over 700 locales.  There, looking
925  * at just the currency symbol gave essentially the same results as doing this
926  * extra work.  Executing this also caused segfaults in miniperl.  I left it in
927  * so as to avoid rewriting it if real-world experience indicates that
928  * dromedary is an outlier.  Essentially, instead of returning abpve if we
929  * haven't found illegal utf8, we continue on and examine all the strerror()
930  * messages on the platform for utf8ness.  If all are ASCII, we still don't
931  * know the answer; but otherwise we have a pretty good indication of the
932  * utf8ness.  The reason this doesn't necessarily help much is that the
933  * messages may not have been translated into the locale.  The currency symbol
934  * is much more likely to have been translated.  The code below would need to
935  * be altered somewhat to just be a continuation of testing the currency
936  * symbol. */
937         int e;
938         unsigned int failures = 0, non_ascii = 0;
939         char *save_messages_locale = NULL;
940
941         /* Like above for LC_CTYPE, we set LC_MESSAGES to the locale of the
942          * desired category, if it isn't that locale already */
943
944         if (category != LC_MESSAGES) {
945
946             save_messages_locale = stdize_locale(savepv(setlocale(LC_MESSAGES,
947                                                                   NULL)));
948             if (! save_messages_locale) {
949                 goto cant_use_messages;
950             }
951
952             if (strEQ(save_messages_locale, save_input_locale)) {
953                 Safefree(save_input_locale);
954             }
955             else if (! setlocale(LC_MESSAGES, save_input_locale)) {
956                 Safefree(save_messages_locale);
957                 goto cant_use_messages;
958             }
959         }
960
961         /* Here the current LC_MESSAGES is set to the locale of the category
962          * whose information is desired.  Look through all the messages */
963
964         for (e = 0;
965 #ifdef HAS_SYS_ERRLIST
966              e <= sys_nerr
967 #endif
968              ; e++)
969         {
970             const U8* const errmsg = (U8 *) Strerror(e) ;
971             if (!errmsg)
972                 break;
973             if (! is_utf8_string(errmsg, 0)) {
974                 failures++;
975                 break;
976             }
977             else if (! is_ascii_string(errmsg, 0)) {
978                 non_ascii++;
979             }
980         }
981
982         /* And, if we changed it, restore LC_MESSAGES to its original locale */
983         if (save_messages_locale) {
984             setlocale(LC_MESSAGES, save_messages_locale);
985             Safefree(save_messages_locale);
986         }
987
988         /* Any non-UTF-8 message means not a UTF-8 locale; if all are valid,
989          * any non-ascii means it is one; otherwise we assume it isn't */
990         return (failures) ? FALSE : non_ascii;
991
992     }
993   cant_use_messages:
994
995 #endif
996
997     Safefree(save_input_locale);
998     return FALSE;
999 }
1000
1001 #endif
1002
1003 /*
1004  * Local variables:
1005  * c-indentation-style: bsd
1006  * c-basic-offset: 4
1007  * indent-tabs-mode: nil
1008  * End:
1009  *
1010  * ex: set ts=8 sts=4 sw=4 et:
1011  */