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