This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
locale.c: Create a block around some code; indent
[perl5.git] / t / loc_tools.pl
1 # Common tools for test files files to find the locales which exist on the
2 # system.  Caller should have verified that this isn't miniperl before calling
3 # the functions.
4
5 # Note that it's okay that some languages have their native names
6 # capitalized here even though that's not "right".  They are lowercased
7 # anyway later during the scanning process (and besides, some clueless
8 # vendor might have them capitalized erroneously anyway).
9
10 # Functions whose names begin with underscore are internal helper functions
11 # for this file, and are not to be used by outside callers.
12
13 use strict;
14
15 eval { require POSIX; import POSIX 'locale_h'; };
16 my $has_locale_h = ! $@;
17
18 # LC_ALL can be -1 on some platforms.  And, in fact the implementors could
19 # legally use any integer to represent any category.  But it makes the most
20 # sense for them to have used small integers.  Below, we create new locale
21 # numbers for ones missing from this machine.  We make them very negative,
22 # hopefully more negative than anything likely to be a valid category on the
23 # platform, but also below is a check to be sure that our guess is valid.
24 my $max_bad_category_number = -1000000;
25
26 # Initialize this hash so that it looks like e.g.,
27 #   6 => 'CTYPE',
28 # where 6 is the value of &POSIX::LC_CTYPE
29 my %category_name;
30 my %category_number;
31 if ($has_locale_h) {
32     my $number_for_missing_category = $max_bad_category_number;
33     foreach my $name (qw(ALL COLLATE CTYPE MESSAGES MONETARY NUMERIC TIME)) {
34         my $number = eval "&POSIX::LC_$name";
35
36         if ($@) {
37             # Use a negative number (smaller than any legitimate category
38             # number) if the platform doesn't support this category, so we
39             # have an entry for all the ones that might be specified in calls
40             # to us.
41             $number = $number_for_missing_category-- if $@;
42         }
43         elsif (   $number !~ / ^ -? \d+ $ /x
44                || $number <=  $max_bad_category_number)
45         {
46             # We think this should be an int.  And it has to be larger than
47             # any of our synthetic numbers.
48             die "Unexpected locale category number '$number' for LC_$name"
49         }
50
51         $category_name{$number} = "$name";
52         $category_number{$name} = $number;
53     }
54 }
55
56 sub _my_diag($) {
57     my $message = shift;
58     if (defined &main::diag) {
59         diag($message);
60     }
61     else {
62         local($\, $", $,) = (undef, ' ', '');
63         print STDERR $message, "\n";
64     }
65 }
66
67 sub _my_fail($) {
68     my $message = shift;
69     if (defined &main::fail) {
70         fail($message);
71     }
72     else {
73         local($\, $", $,) = (undef, ' ', '');
74         print "not ok 0 $message\n";
75     }
76 }
77
78 sub _trylocale ($$$$) { # For use only by other functions in this file!
79
80     # Adds the locale given by the first parameter to the list given by the
81     # 3rd iff the platform supports the locale in each of the category numbers
82     # given by the 2nd parameter, which is either a single category or a
83     # reference to a list of categories.  The list MUST be sorted so that
84     # CTYPE is first, COLLATE is last unless ALL is present, in which case
85     # that comes after COLLATE.  This is because locale.c detects bad locales
86     # only with CTYPE, and COLLATE on some platforms can core dump if it is a
87     # bad locale.
88     #
89     # The 4th parameter is true if to accept locales that aren't apparently
90     # fully compatible with Perl.
91
92     my $locale = shift;
93     my $categories = shift;
94     my $list = shift;
95     my $allow_incompatible = shift;
96
97     return if ! $locale || grep { $locale eq $_ } @$list;
98
99     $categories = [ $categories ] unless ref $categories;
100
101     my $badutf8 = 0;
102     my $plays_well = 1;
103
104     use warnings 'locale';
105
106     local $SIG{__WARN__} = sub {
107         $badutf8 = 1 if grep { /Malformed UTF-8/ } @_;
108         $plays_well = 0 if grep { /Locale .* may not work well/i } @_;
109     };
110
111     # Incompatible locales aren't warned about unless using locales.
112     use locale;
113
114     foreach my $category (@$categories) {
115         die "category '$category' must instead be a number"
116                                             unless $category =~ / ^ -? \d+ $ /x;
117
118         return unless setlocale($category, $locale);
119         last if $badutf8 || ! $plays_well;
120     }
121
122     if ($badutf8) {
123         _my_fail("Verify locale name doesn't contain malformed utf8");
124         return;
125     }
126     push @$list, $locale if $plays_well || $allow_incompatible;
127 }
128
129 sub _decode_encodings { # For use only by other functions in this file!
130     my @enc;
131
132     foreach (split(/ /, shift)) {
133         if (/^(\d+)$/) {
134             push @enc, "ISO8859-$1";
135             push @enc, "iso8859$1";     # HP
136             if ($1 eq '1') {
137                  push @enc, "roman8";   # HP
138             }
139             push @enc, $_;
140             push @enc, "$_.UTF-8";
141             push @enc, "$_.65001"; # Windows UTF-8
142             push @enc, "$_.ACP"; # Windows ANSI code page
143             push @enc, "$_.OCP"; # Windows OEM code page
144             push @enc, "$_.1252"; # Windows
145         }
146     }
147     if ($^O eq 'os390') {
148         push @enc, qw(IBM-037 IBM-819 IBM-1047);
149     }
150     push @enc, "UTF-8";
151     push @enc, "65001"; # Windows UTF-8
152
153     return @enc;
154 }
155
156 sub locales_enabled(;$) {
157     # Returns 0 if no locale handling is available on this platform; otherwise
158     # 1.
159     #
160     # The optional parameter is a reference to a list of individual POSIX
161     # locale categories.  If any of the individual categories specified by the
162     # optional parameter is all digits (and an optional leading minus), it is
163     # taken to be the C enum for the category (e.g., &POSIX::LC_CTYPE).
164     # Otherwise it should be a string name of the category, like 'LC_TIME'.
165     # The initial 'LC_' is optional.  It is a fatal error to call this with
166     # something that isn't a known category to the platform.
167     #
168     # This optional parameter denotes which POSIX locale categories must be
169     # available on the platform.  If any aren't available, this function
170     # returns 0; otherwise it returns 1 and changes the list for the caller so
171     # that any category names are converted into their equivalent numbers, and
172     # sorts it to match the expectations of _trylocale.
173     #
174     # It is acceptable for the second parameter to be just a simple scalar
175     # denoting a single category (either name or number).  No conversion into
176     # a number is done in this case.
177
178     use Config;
179
180     return 0 unless    $Config{d_setlocale}
181                         # I (khw) cargo-culted the '?' in the pattern on the
182                         # next line.
183                     && $Config{ccflags} !~ /\bD?NO_LOCALE\b/
184                     && $has_locale_h;
185
186     # Done with the global possibilities.  Now check if any passed in category
187     # is disabled.
188
189     my $categories_ref = shift;
190     my $return_categories_numbers = 0;
191     my @categories_numbers;
192     my $has_LC_ALL = 0;
193     my $has_LC_COLLATE = 0;
194
195     if (defined $categories_ref) {
196         my @local_categories_copy;
197
198         if (ref $categories_ref) {
199             @local_categories_copy = @$$categories_ref;
200             $return_categories_numbers = 1;
201         }
202         else {  # Single category passed in
203             @local_categories_copy = $categories_ref;
204         }
205
206         for my $category_name_or_number (@local_categories_copy) {
207             my $name;
208             my $number;
209             if ($category_name_or_number =~ / ^ -? \d+ $ /x) {
210                 $number = $category_name_or_number;
211                 die "Invalid locale category number '$number'"
212                     unless grep { $number == $_ } keys %category_name;
213                 $name = $category_name{$number};
214             }
215             else {
216                 $name = $category_name_or_number;
217                 $name =~ s/ ^ LC_ //x;
218                 foreach my $trial (keys %category_name) {
219                     if ($category_name{$trial} eq $name) {
220                         $number = $trial;
221                         last;
222                     }
223                 }
224                 die "Invalid locale category name '$name'"
225                     unless defined $number;
226             }
227
228             return 0 if    $number <= $max_bad_category_number
229                         || $Config{ccflags} =~ /\bD?NO_LOCALE_$name\b/;
230
231             eval "defined &POSIX::LC_$name";
232             return 0 if $@;
233
234             if ($return_categories_numbers) {
235                 if ($name eq 'CTYPE') {
236                     unshift @categories_numbers, $number;   # Always first
237                 }
238                 elsif ($name eq 'ALL') {
239                     $has_LC_ALL = 1;
240                 }
241                 elsif ($name eq 'COLLATE') {
242                     $has_LC_COLLATE = 1;
243                 }
244                 else {
245                     push @categories_numbers, $number;
246                 }
247             }
248         }
249     }
250
251     if ($return_categories_numbers) {
252
253         # COLLATE comes after all other locales except ALL, which comes last
254         if ($has_LC_COLLATE) {
255             push @categories_numbers, $category_number{'COLLATE'};
256         }
257         if ($has_LC_ALL) {
258             push @categories_numbers, $category_number{'ALL'};
259         }
260         $$categories_ref = \@categories_numbers;
261     }
262
263     return 1;
264 }
265
266
267 sub find_locales ($;$) {
268
269     # Returns an array of all the locales we found on the system.  If the
270     # optional 2nd parameter is non-zero, the list includes all found locales;
271     # otherwise it is restricted to those locales that play well with Perl, as
272     # far as we can easily determine.
273     #
274     # The first parameter is either a single locale category or a reference to
275     # a list of categories to find valid locales for it (or in the case of
276     # multiple) for all of them.  Each category can be a name (like 'LC_ALL'
277     # or simply 'ALL') or the C enum value for the category.
278
279     my $categories = shift;
280     my $allow_incompatible = shift // 0;
281
282     $categories = [ $categories ] unless ref $categories;
283     return unless locales_enabled(\$categories);
284
285     # Note, the subroutine call above converts the $categories into a form
286     # suitable for _trylocale().
287
288     # Visual C's CRT goes silly on strings of the form "en_US.ISO8859-1"
289     # and mingw32 uses said silly CRT
290     # This doesn't seem to be an issue any more, at least on Windows XP,
291     # so re-enable the tests for Windows XP onwards.
292     my $winxp = ($^O eq 'MSWin32' && defined &Win32::GetOSVersion &&
293                     join('.', (Win32::GetOSVersion())[1..2]) >= 5.1);
294     return if ((($^O eq 'MSWin32' && !$winxp) || $^O eq 'NetWare')
295                 && $Config{cc} =~ /^(cl|gcc|g\+\+|ici)/i);
296
297     # UWIN seems to loop after taint tests, just skip for now
298     return if ($^O =~ /^uwin/);
299
300     my @Locale;
301     _trylocale("C", $categories, \@Locale, $allow_incompatible);
302     _trylocale("POSIX", $categories, \@Locale, $allow_incompatible);
303     foreach (0..15) {
304         _trylocale("ISO8859-$_", $categories, \@Locale, $allow_incompatible);
305         _trylocale("iso8859$_", $categories, \@Locale, $allow_incompatible);
306         _trylocale("iso8859-$_", $categories, \@Locale, $allow_incompatible);
307         _trylocale("iso_8859_$_", $categories, \@Locale, $allow_incompatible);
308         _trylocale("isolatin$_", $categories, \@Locale, $allow_incompatible);
309         _trylocale("isolatin-$_", $categories, \@Locale, $allow_incompatible);
310         _trylocale("iso_latin_$_", $categories, \@Locale, $allow_incompatible);
311     }
312
313     # Sanitize the environment so that we can run the external 'locale'
314     # program without the taint mode getting grumpy.
315
316     # $ENV{PATH} is special in VMS.
317     delete local $ENV{PATH} if $^O ne 'VMS' or $Config{d_setenv};
318
319     # Other subversive stuff.
320     delete local @ENV{qw(IFS CDPATH ENV BASH_ENV)};
321
322     if (-x "/usr/bin/locale"
323         && open(LOCALES, '-|', "/usr/bin/locale -a 2>/dev/null"))
324     {
325         while (<LOCALES>) {
326             # It seems that /usr/bin/locale steadfastly outputs 8 bit data, which
327             # ain't great when we're running this testPERL_UNICODE= so that utf8
328             # locales will cause all IO hadles to default to (assume) utf8
329             next unless utf8::valid($_);
330             chomp;
331             _trylocale($_, $categories, \@Locale, $allow_incompatible);
332         }
333         close(LOCALES);
334     } elsif ($^O eq 'VMS'
335              && defined($ENV{'SYS$I18N_LOCALE'})
336              && -d 'SYS$I18N_LOCALE')
337     {
338     # The SYS$I18N_LOCALE logical name search list was not present on
339     # VAX VMS V5.5-12, but was on AXP && VAX VMS V6.2 as well as later versions.
340         opendir(LOCALES, "SYS\$I18N_LOCALE:");
341         while ($_ = readdir(LOCALES)) {
342             chomp;
343             _trylocale($_, $categories, \@Locale, $allow_incompatible);
344         }
345         close(LOCALES);
346     } elsif (($^O eq 'openbsd' || $^O eq 'bitrig' ) && -e '/usr/share/locale') {
347
348         # OpenBSD doesn't have a locale executable, so reading
349         # /usr/share/locale is much easier and faster than the last resort
350         # method.
351
352         opendir(LOCALES, '/usr/share/locale');
353         while ($_ = readdir(LOCALES)) {
354             chomp;
355             _trylocale($_, $categories, \@Locale, $allow_incompatible);
356         }
357         close(LOCALES);
358     } else { # Final fallback.  Try our list of locales hard-coded here
359
360         # This is going to be slow.
361         my @Data;
362
363         # Locales whose name differs if the utf8 bit is on are stored in these
364         # two files with appropriate encodings.
365         my $data_file = ($^H & 0x08 || (${^OPEN} || "") =~ /:utf8/)
366                         ? _source_location() . "/lib/locale/utf8"
367                         : _source_location() . "/lib/locale/latin1";
368         if (-e $data_file) {
369             @Data = do $data_file;
370         }
371         else {
372             _my_diag(__FILE__ . ":" . __LINE__ . ": '$data_file' doesn't exist");
373         }
374
375         # The rest of the locales are in this file.
376         push @Data, <DATA>;
377
378         foreach my $line (@Data) {
379             my ($locale_name, $language_codes, $country_codes, $encodings) =
380                 split /:/, $line;
381             _my_diag(__FILE__ . ":" . __LINE__ . ": Unexpected syntax in '$line'")
382                                                      unless defined $locale_name;
383             my @enc = _decode_encodings($encodings);
384             foreach my $loc (split(/ /, $locale_name)) {
385                 _trylocale($loc, $categories, \@Locale, $allow_incompatible);
386                 foreach my $enc (@enc) {
387                     _trylocale("$loc.$enc", $categories, \@Locale,
388                                                             $allow_incompatible);
389                 }
390                 $loc = lc $loc;
391                 foreach my $enc (@enc) {
392                     _trylocale("$loc.$enc", $categories, \@Locale,
393                                                             $allow_incompatible);
394                 }
395             }
396             foreach my $lang (split(/ /, $language_codes)) {
397                 _trylocale($lang, $categories, \@Locale, $allow_incompatible);
398                 foreach my $country (split(/ /, $country_codes)) {
399                     my $lc = "${lang}_${country}";
400                     _trylocale($lc, $categories, \@Locale, $allow_incompatible);
401                     foreach my $enc (@enc) {
402                         _trylocale("$lc.$enc", $categories, \@Locale,
403                                                             $allow_incompatible);
404                     }
405                     my $lC = "${lang}_\U${country}";
406                     _trylocale($lC, $categories, \@Locale, $allow_incompatible);
407                     foreach my $enc (@enc) {
408                         _trylocale("$lC.$enc", $categories, \@Locale,
409                                                             $allow_incompatible);
410                     }
411                 }
412             }
413         }
414     }
415
416     @Locale = sort @Locale;
417
418     return @Locale;
419 }
420
421 sub is_locale_utf8 ($) { # Return a boolean as to if core Perl thinks the input
422                          # is a UTF-8 locale
423
424     # On z/OS, even locales marked as UTF-8 aren't.
425     return 0 if ord "A" != 65;
426
427     return 0 unless locales_enabled('LC_CTYPE');
428
429     my $locale = shift;
430
431     use locale;
432     no warnings 'locale'; # We may be trying out a weird locale
433
434     my $save_locale = setlocale(&POSIX::LC_CTYPE());
435     if (! $save_locale) {
436         ok(0, "Verify could save previous locale");
437         return 0;
438     }
439
440     if (! setlocale(&POSIX::LC_CTYPE(), $locale)) {
441         ok(0, "Verify could setlocale to $locale");
442         return 0;
443     }
444
445     my $ret = 0;
446
447     # Use an op that gives different results for UTF-8 than any other locale.
448     # If a platform has UTF-8 locales, there should be at least one locale on
449     # most platforms with UTF-8 in its name, so if there is a bug in the op
450     # giving a false negative, we should get a failure for those locales as we
451     # go through testing all the locales on the platform.
452     if (CORE::fc(chr utf8::unicode_to_native(0xdf)) ne "ss") {
453         if ($locale =~ /UTF-?8/i) {
454             ok (0, "Verify $locale with UTF-8 in name is a UTF-8 locale");
455         }
456     }
457     else {
458         $ret = 1;
459     }
460
461     die "Couldn't restore locale '$save_locale'"
462         unless setlocale(&POSIX::LC_CTYPE(), $save_locale);
463
464     return $ret;
465 }
466
467 sub find_utf8_ctype_locale (;$) { # Return the name of a locale that core Perl
468                                   # thinks is a UTF-8 LC_CTYPE locale.
469                                   # Optional parameter is a reference to a
470                                   # list of locales to try; if omitted, this
471                                   # tries all locales it can find on the
472                                   # platform
473     return unless locales_enabled('LC_CTYPE');
474
475     my $locales_ref = shift;
476
477     if (! defined $locales_ref) {
478
479         my @locales = find_locales(&POSIX::LC_CTYPE());
480         $locales_ref = \@locales;
481     }
482
483     foreach my $locale (@$locales_ref) {
484         return $locale if is_locale_utf8($locale);
485     }
486
487     return;
488 }
489
490 # returns full path to the directory containing the current source
491 # file, inspired by mauke's Dir::Self
492 sub _source_location {
493     require File::Spec;
494
495     my $caller_filename = (caller)[1];
496
497     my $loc = File::Spec->rel2abs(
498         File::Spec->catpath(
499             (File::Spec->splitpath($caller_filename))[0, 1], ''
500         )
501     );
502
503     return ($loc =~ /^(.*)$/)[0]; # untaint
504 }
505
506 1
507
508 # Format of data is: locale_name, language_codes, country_codes, encodings
509 __DATA__
510 Afrikaans:af:za:1 15
511 Arabic:ar:dz eg sa:6 arabic8
512 Brezhoneg Breton:br:fr:1 15
513 Bulgarski Bulgarian:bg:bg:5
514 Chinese:zh:cn tw:cn.EUC eucCN eucTW euc.CN euc.TW Big5 GB2312 tw.EUC
515 Hrvatski Croatian:hr:hr:2
516 Cymraeg Welsh:cy:cy:1 14 15
517 Czech:cs:cz:2
518 Dansk Danish:da:dk:1 15
519 Nederlands Dutch:nl:be nl:1 15
520 English American British:en:au ca gb ie nz us uk zw:1 15 cp850
521 Esperanto:eo:eo:3
522 Eesti Estonian:et:ee:4 6 13
523 Suomi Finnish:fi:fi:1 15
524 Flamish::fl:1 15
525 Deutsch German:de:at be ch de lu:1 15
526 Euskaraz Basque:eu:es fr:1 15
527 Galego Galician:gl:es:1 15
528 Ellada Greek:el:gr:7 g8
529 Frysk:fy:nl:1 15
530 Greenlandic:kl:gl:4 6
531 Hebrew:iw:il:8 hebrew8
532 Hungarian:hu:hu:2
533 Indonesian:id:id:1 15
534 Gaeilge Irish:ga:IE:1 14 15
535 Italiano Italian:it:ch it:1 15
536 Nihongo Japanese:ja:jp:euc eucJP jp.EUC sjis
537 Korean:ko:kr:
538 Latine Latin:la:va:1 15
539 Latvian:lv:lv:4 6 13
540 Lithuanian:lt:lt:4 6 13
541 Macedonian:mk:mk:1 15
542 Maltese:mt:mt:3
543 Moldovan:mo:mo:2
544 Norsk Norwegian:no no\@nynorsk nb nn:no:1 15
545 Occitan:oc:es:1 15
546 Polski Polish:pl:pl:2
547 Rumanian:ro:ro:2
548 Russki Russian:ru:ru su ua:5 koi8 koi8r KOI8-R koi8u cp1251 cp866
549 Serbski Serbian:sr:yu:5
550 Slovak:sk:sk:2
551 Slovene Slovenian:sl:si:2
552 Sqhip Albanian:sq:sq:1 15
553 Svenska Swedish:sv:fi se:1 15
554 Thai:th:th:11 tis620
555 Turkish:tr:tr:9 turkish8
556 Yiddish:yi::1 15