This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
loc_tools.pl: properly load fallback locales
[perl5.git] / t / loc_tools.pl
CommitLineData
73fc293b 1# Common tools for test files files to find the locales which exist on the
13022195 2# system. Caller should have verified that this isn't miniperl before calling
abfe20b2 3# the functions.
73fc293b
KW
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
bb31ec6a
KW
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
e1f89022
KW
13use strict;
14
a274778c 15eval { require POSIX; import POSIX 'locale_h'; };
e1f89022 16my $has_locale_h = ! $@;
a274778c 17
6fa6c80b
KW
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.
24my $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
29my %category_name;
cd1f7080 30my %category_number;
86e85139 31if ($has_locale_h) {
6fa6c80b
KW
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";
cd1f7080 52 $category_number{$name} = $number;
6fa6c80b
KW
53 }
54}
55
759b442c
KW
56sub _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
13022195
KW
67sub _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
bb31ec6a
KW
78sub _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
cd1f7080
KW
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
774ee090 83 # reference to a list of categories. The list MUST be sorted so that
cd1f7080
KW
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.
bb31ec6a 91
73fc293b 92 my $locale = shift;
9b0711ee 93 my $categories = shift;
73fc293b 94 my $list = shift;
2c6c88ec 95 my $allow_incompatible = shift;
f079f9b7 96
162eb2b8 97 return if ! $locale || grep { $locale eq $_ } @$list;
9b0711ee
KW
98
99 $categories = [ $categories ] unless ref $categories;
100
f079f9b7
KW
101 my $badutf8 = 0;
102 my $plays_well = 1;
103
104 use warnings 'locale';
105
106 local $SIG{__WARN__} = sub {
973072b2
KW
107 $badutf8 = 1 if grep { /Malformed UTF-8/ } @_;
108 $plays_well = 0 if grep { /Locale .* may not work well/i } @_;
f079f9b7
KW
109 };
110
9c5fc553
KW
111 # Incompatible locales aren't warned about unless using locales.
112 use locale;
113
9b0711ee 114 foreach my $category (@$categories) {
cd1f7080
KW
115 die "category '$category' must instead be a number"
116 unless $category =~ / ^ -? \d+ $ /x;
117
9b0711ee 118 return unless setlocale($category, $locale);
caf06cdc 119 last if $badutf8 || ! $plays_well;
73fc293b
KW
120 }
121
122 if ($badutf8) {
13022195 123 _my_fail("Verify locale name doesn't contain malformed utf8");
73fc293b
KW
124 return;
125 }
caf06cdc 126 push @$list, $locale if $plays_well || $allow_incompatible;
73fc293b
KW
127}
128
bb31ec6a 129sub _decode_encodings { # For use only by other functions in this file!
73fc293b
KW
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";
d646bffe
KW
141 push @enc, "$_.65001"; # Windows UTF-8
142 push @enc, "$_.ACP"; # Windows ANSI code page
143 push @enc, "$_.OCP"; # Windows OEM code page
cf34c81f 144 push @enc, "$_.1252"; # Windows
73fc293b
KW
145 }
146 }
147 if ($^O eq 'os390') {
148 push @enc, qw(IBM-037 IBM-819 IBM-1047);
149 }
150 push @enc, "UTF-8";
d646bffe 151 push @enc, "65001"; # Windows UTF-8
73fc293b
KW
152
153 return @enc;
154}
155
128e4113
KW
156sub 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
cd1f7080
KW
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.
128e4113 167 #
cd1f7080
KW
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.
128e4113 177
a274778c 178 use Config;
128e4113
KW
179
180 return 0 unless $Config{d_setlocale}
181 # I (khw) cargo-culted the '?' in the pattern on the
182 # next line.
a274778c 183 && $Config{ccflags} !~ /\bD?NO_LOCALE\b/
cfe9fa91 184 && $has_locale_h;
128e4113
KW
185
186 # Done with the global possibilities. Now check if any passed in category
187 # is disabled.
cd1f7080 188
128e4113 189 my $categories_ref = shift;
cd1f7080
KW
190 my $return_categories_numbers = 0;
191 my @categories_numbers;
192 my $has_LC_ALL = 0;
193 my $has_LC_COLLATE = 0;
194
e6965c14 195 if (defined $categories_ref) {
cd1f7080
KW
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
308482c2
KW
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};
e6965c14
KW
214 }
215 else {
308482c2
KW
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;
e6965c14
KW
226 }
227
308482c2
KW
228 return 0 if $number <= $max_bad_category_number
229 || $Config{ccflags} =~ /\bD?NO_LOCALE_$name\b/;
cfe9fa91
KW
230
231 eval "defined &POSIX::LC_$name";
232 return 0 if $@;
cd1f7080
KW
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'};
128e4113 256 }
cd1f7080
KW
257 if ($has_LC_ALL) {
258 push @categories_numbers, $category_number{'ALL'};
259 }
260 $$categories_ref = \@categories_numbers;
128e4113
KW
261 }
262
263 return 1;
264}
265
266
cd1f7080
KW
267sub 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
9b0711ee 279 my $categories = shift;
2c6c88ec 280 my $allow_incompatible = shift // 0;
73fc293b 281
cd1f7080
KW
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().
d369fd5b
KW
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);
128e4113
KW
294 return if ((($^O eq 'MSWin32' && !$winxp) || $^O eq 'NetWare')
295 && $Config{cc} =~ /^(cl|gcc|g\+\+|ici)/i);
d369fd5b
KW
296
297 # UWIN seems to loop after taint tests, just skip for now
128e4113 298 return if ($^O =~ /^uwin/);
d369fd5b 299
e1f89022 300 my @Locale;
2c6c88ec
KW
301 _trylocale("C", $categories, \@Locale, $allow_incompatible);
302 _trylocale("POSIX", $categories, \@Locale, $allow_incompatible);
73fc293b 303 foreach (0..15) {
2c6c88ec
KW
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);
73fc293b
KW
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.
8b76dc1d 317 delete local $ENV{PATH} if $^O ne 'VMS' or $Config{d_setenv};
73fc293b
KW
318
319 # Other subversive stuff.
8b76dc1d 320 delete local @ENV{qw(IFS CDPATH ENV BASH_ENV)};
73fc293b
KW
321
322 if (-x "/usr/bin/locale"
1ae6ead9 323 && open(LOCALES, '-|', "/usr/bin/locale -a 2>/dev/null"))
73fc293b
KW
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;
2c6c88ec 331 _trylocale($_, $categories, \@Locale, $allow_incompatible);
73fc293b
KW
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;
2c6c88ec 343 _trylocale($_, $categories, \@Locale, $allow_incompatible);
73fc293b
KW
344 }
345 close(LOCALES);
346 } elsif (($^O eq 'openbsd' || $^O eq 'bitrig' ) && -e '/usr/share/locale') {
347
7e1e0d99
KW
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.
73fc293b
KW
351
352 opendir(LOCALES, '/usr/share/locale');
353 while ($_ = readdir(LOCALES)) {
354 chomp;
2c6c88ec 355 _trylocale($_, $categories, \@Locale, $allow_incompatible);
73fc293b
KW
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
589c4ae0
KW
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/)
9969000e
TK
366 ? _source_location() . "/lib/locale/utf8"
367 : _source_location() . "/lib/locale/latin1";
589c4ae0
KW
368 if (-e $data_file) {
369 @Data = do $data_file;
370 }
371 else {
372 _my_diag(__FILE__ . ":" . __LINE__ . ": '$data_file' doesn't exist");
73fc293b
KW
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;
759b442c
KW
381 _my_diag(__FILE__ . ":" . __LINE__ . ": Unexpected syntax in '$line'")
382 unless defined $locale_name;
73fc293b
KW
383 my @enc = _decode_encodings($encodings);
384 foreach my $loc (split(/ /, $locale_name)) {
2c6c88ec 385 _trylocale($loc, $categories, \@Locale, $allow_incompatible);
73fc293b 386 foreach my $enc (@enc) {
f079f9b7 387 _trylocale("$loc.$enc", $categories, \@Locale,
2c6c88ec 388 $allow_incompatible);
73fc293b
KW
389 }
390 $loc = lc $loc;
391 foreach my $enc (@enc) {
f079f9b7 392 _trylocale("$loc.$enc", $categories, \@Locale,
2c6c88ec 393 $allow_incompatible);
73fc293b
KW
394 }
395 }
396 foreach my $lang (split(/ /, $language_codes)) {
2c6c88ec 397 _trylocale($lang, $categories, \@Locale, $allow_incompatible);
73fc293b
KW
398 foreach my $country (split(/ /, $country_codes)) {
399 my $lc = "${lang}_${country}";
2c6c88ec 400 _trylocale($lc, $categories, \@Locale, $allow_incompatible);
73fc293b 401 foreach my $enc (@enc) {
f079f9b7 402 _trylocale("$lc.$enc", $categories, \@Locale,
2c6c88ec 403 $allow_incompatible);
73fc293b
KW
404 }
405 my $lC = "${lang}_\U${country}";
2c6c88ec 406 _trylocale($lC, $categories, \@Locale, $allow_incompatible);
73fc293b 407 foreach my $enc (@enc) {
f079f9b7 408 _trylocale("$lC.$enc", $categories, \@Locale,
2c6c88ec 409 $allow_incompatible);
73fc293b
KW
410 }
411 }
412 }
413 }
414 }
415
416 @Locale = sort @Locale;
417
418 return @Locale;
73fc293b
KW
419}
420
ab8b8bcc 421sub is_locale_utf8 ($) { # Return a boolean as to if core Perl thinks the input
9b0711ee 422 # is a UTF-8 locale
92c0a900
KW
423
424 # On z/OS, even locales marked as UTF-8 aren't.
425 return 0 if ord "A" != 65;
426
cfe9fa91 427 return 0 unless locales_enabled('LC_CTYPE');
21732d5c 428
ab8b8bcc
KW
429 my $locale = shift;
430
31f05a37 431 use locale;
f079f9b7 432 no warnings 'locale'; # We may be trying out a weird locale
31f05a37
KW
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;
ab8b8bcc
KW
465}
466
c1d1e689 467sub find_utf8_ctype_locale (;$) { # Return the name of a locale that core Perl
9b0711ee
KW
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
cfe9fa91
KW
473 return unless locales_enabled('LC_CTYPE');
474
ab8b8bcc 475 my $locales_ref = shift;
21732d5c 476
ab8b8bcc 477 if (! defined $locales_ref) {
21732d5c 478
2c6c88ec 479 my @locales = find_locales(&POSIX::LC_CTYPE());
ab8b8bcc
KW
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
9969000e
TK
490# returns full path to the directory containing the current source
491# file, inspired by mauke's Dir::Self
492sub _source_location {
493 require File::Spec;
494
495 my $caller_filename = (caller)[1];
496
497 return File::Spec->rel2abs(
498 File::Spec->catpath(
499 (File::Spec->splitpath($caller_filename))[0, 1]
500 )
501 );
502}
503
73fc293b
KW
5041
505
506# Format of data is: locale_name, language_codes, country_codes, encodings
507__DATA__
508Afrikaans:af:za:1 15
509Arabic:ar:dz eg sa:6 arabic8
510Brezhoneg Breton:br:fr:1 15
511Bulgarski Bulgarian:bg:bg:5
512Chinese:zh:cn tw:cn.EUC eucCN eucTW euc.CN euc.TW Big5 GB2312 tw.EUC
513Hrvatski Croatian:hr:hr:2
514Cymraeg Welsh:cy:cy:1 14 15
515Czech:cs:cz:2
516Dansk Danish:da:dk:1 15
517Nederlands Dutch:nl:be nl:1 15
518English American British:en:au ca gb ie nz us uk zw:1 15 cp850
519Esperanto:eo:eo:3
520Eesti Estonian:et:ee:4 6 13
521Suomi Finnish:fi:fi:1 15
522Flamish::fl:1 15
523Deutsch German:de:at be ch de lu:1 15
524Euskaraz Basque:eu:es fr:1 15
525Galego Galician:gl:es:1 15
526Ellada Greek:el:gr:7 g8
527Frysk:fy:nl:1 15
528Greenlandic:kl:gl:4 6
529Hebrew:iw:il:8 hebrew8
530Hungarian:hu:hu:2
531Indonesian:id:id:1 15
532Gaeilge Irish:ga:IE:1 14 15
533Italiano Italian:it:ch it:1 15
534Nihongo Japanese:ja:jp:euc eucJP jp.EUC sjis
535Korean:ko:kr:
536Latine Latin:la:va:1 15
537Latvian:lv:lv:4 6 13
538Lithuanian:lt:lt:4 6 13
539Macedonian:mk:mk:1 15
540Maltese:mt:mt:3
541Moldovan:mo:mo:2
542Norsk Norwegian:no no\@nynorsk nb nn:no:1 15
543Occitan:oc:es:1 15
544Polski Polish:pl:pl:2
545Rumanian:ro:ro:2
546Russki Russian:ru:ru su ua:5 koi8 koi8r KOI8-R koi8u cp1251 cp866
547Serbski Serbian:sr:yu:5
548Slovak:sk:sk:2
549Slovene Slovenian:sl:si:2
550Sqhip Albanian:sq:sq:1 15
551Svenska Swedish:sv:fi se:1 15
552Thai:th:th:11 tis620
553Turkish:tr:tr:9 turkish8
554Yiddish:yi::1 15