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