This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Move isUTF8_CHAR helper function, and reimplement it
[perl5.git] / utf8.c
CommitLineData
a0ed51b3
LW
1/* utf8.c
2 *
1129b882 3 * Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
b94e2f88 4 * by Larry Wall and others
a0ed51b3
LW
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/*
4ac71550
TC
12 * 'What a fix!' said Sam. 'That's the one place in all the lands we've ever
13 * heard of that we don't want to see any closer; and that's the one place
14 * we're trying to get to! And that's just where we can't get, nohow.'
15 *
cdad3b53 16 * [p.603 of _The Lord of the Rings_, IV/I: "The Taming of Sméagol"]
a0ed51b3
LW
17 *
18 * 'Well do I understand your speech,' he answered in the same language;
19 * 'yet few strangers do so. Why then do you not speak in the Common Tongue,
4ac71550 20 * as is the custom in the West, if you wish to be answered?'
cdad3b53 21 * --Gandalf, addressing Théoden's door wardens
4ac71550
TC
22 *
23 * [p.508 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
a0ed51b3
LW
24 *
25 * ...the travellers perceived that the floor was paved with stones of many
26 * hues; branching runes and strange devices intertwined beneath their feet.
4ac71550
TC
27 *
28 * [p.512 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
a0ed51b3
LW
29 */
30
31#include "EXTERN.h"
864dbfa3 32#define PERL_IN_UTF8_C
a0ed51b3 33#include "perl.h"
b992490d 34#include "invlist_inline.h"
a0ed51b3 35
27da23d5
JH
36static const char unees[] =
37 "Malformed UTF-8 character (unexpected end of string)";
760c7c2f 38static const char cp_above_legal_max[] =
2d212e86 39 "Use of code point 0x%"UVXf" is deprecated; the permissible max is 0x%"UVXf"";
760c7c2f 40
114d9c4d 41#define MAX_NON_DEPRECATED_CP ((UV) (IV_MAX))
901b21bf 42
48ef279e 43/*
ccfc67b7 44=head1 Unicode Support
7fefc6c1 45These are various utility functions for manipulating UTF8-encoded
72d33970 46strings. For the uninitiated, this is a method of representing arbitrary
61296642 47Unicode characters as a variable number of bytes, in such a way that
56da48f7
DM
48characters in the ASCII range are unmodified, and a zero byte never appears
49within non-zero characters.
166f8a29 50
eaf7a4d2
CS
51=cut
52*/
53
54/*
378516de 55=for apidoc uvoffuni_to_utf8_flags
eebe1485 56
a27992cc 57THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
de69f3af
KW
58Instead, B<Almost all code should use L</uvchr_to_utf8> or
59L</uvchr_to_utf8_flags>>.
a27992cc 60
de69f3af
KW
61This function is like them, but the input is a strict Unicode
62(as opposed to native) code point. Only in very rare circumstances should code
63not be using the native code point.
949cf498 64
efa9cd84 65For details, see the description for L</uvchr_to_utf8_flags>.
949cf498 66
eebe1485
SC
67=cut
68*/
69
8ee1cdcb
KW
70#define HANDLE_UNICODE_SURROGATE(uv, flags) \
71 STMT_START { \
72 if (flags & UNICODE_WARN_SURROGATE) { \
73 Perl_ck_warner_d(aTHX_ packWARN(WARN_SURROGATE), \
74 "UTF-16 surrogate U+%04"UVXf, uv); \
75 } \
76 if (flags & UNICODE_DISALLOW_SURROGATE) { \
77 return NULL; \
78 } \
79 } STMT_END;
80
81#define HANDLE_UNICODE_NONCHAR(uv, flags) \
82 STMT_START { \
83 if (flags & UNICODE_WARN_NONCHAR) { \
84 Perl_ck_warner_d(aTHX_ packWARN(WARN_NONCHAR), \
85 "Unicode non-character U+%04"UVXf" is not " \
86 "recommended for open interchange", uv); \
87 } \
88 if (flags & UNICODE_DISALLOW_NONCHAR) { \
89 return NULL; \
90 } \
91 } STMT_END;
92
ba6ed43c
KW
93/* Use shorter names internally in this file */
94#define SHIFT UTF_ACCUMULATION_SHIFT
95#undef MARK
96#define MARK UTF_CONTINUATION_MARK
97#define MASK UTF_CONTINUATION_MASK
98
dfe13c55 99U8 *
378516de 100Perl_uvoffuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
a0ed51b3 101{
378516de 102 PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS;
7918f24d 103
2d1545e5 104 if (OFFUNI_IS_INVARIANT(uv)) {
4c8cd605 105 *d++ = LATIN1_TO_NATIVE(uv);
d9432125
KW
106 return d;
107 }
facc1dc2 108
3ea68d71 109 if (uv <= MAX_UTF8_TWO_BYTE) {
facc1dc2
KW
110 *d++ = I8_TO_NATIVE_UTF8(( uv >> SHIFT) | UTF_START_MARK(2));
111 *d++ = I8_TO_NATIVE_UTF8(( uv & MASK) | MARK);
3ea68d71
KW
112 return d;
113 }
d9432125 114
ba6ed43c
KW
115 /* Not 2-byte; test for and handle 3-byte result. In the test immediately
116 * below, the 16 is for start bytes E0-EF (which are all the possible ones
117 * for 3 byte characters). The 2 is for 2 continuation bytes; these each
118 * contribute SHIFT bits. This yields 0x4000 on EBCDIC platforms, 0x1_0000
119 * on ASCII; so 3 bytes covers the range 0x400-0x3FFF on EBCDIC;
120 * 0x800-0xFFFF on ASCII */
121 if (uv < (16 * (1U << (2 * SHIFT)))) {
122 *d++ = I8_TO_NATIVE_UTF8(( uv >> ((3 - 1) * SHIFT)) | UTF_START_MARK(3));
123 *d++ = I8_TO_NATIVE_UTF8(((uv >> ((2 - 1) * SHIFT)) & MASK) | MARK);
124 *d++ = I8_TO_NATIVE_UTF8(( uv /* (1 - 1) */ & MASK) | MARK);
125
126#ifndef EBCDIC /* These problematic code points are 4 bytes on EBCDIC, so
127 aren't tested here */
128 /* The most likely code points in this range are below the surrogates.
129 * Do an extra test to quickly exclude those. */
130 if (UNLIKELY(uv >= UNICODE_SURROGATE_FIRST)) {
131 if (UNLIKELY( UNICODE_IS_32_CONTIGUOUS_NONCHARS(uv)
132 || UNICODE_IS_END_PLANE_NONCHAR_GIVEN_NOT_SUPER(uv)))
133 {
8ee1cdcb
KW
134 HANDLE_UNICODE_NONCHAR(uv, flags);
135 }
136 else if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
137 HANDLE_UNICODE_SURROGATE(uv, flags);
760c7c2f 138 }
ba6ed43c
KW
139 }
140#endif
141 return d;
142 }
143
144 /* Not 3-byte; that means the code point is at least 0x1_0000 on ASCII
145 * platforms, and 0x4000 on EBCDIC. There are problematic cases that can
146 * happen starting with 4-byte characters on ASCII platforms. We unify the
147 * code for these with EBCDIC, even though some of them require 5-bytes on
148 * those, because khw believes the code saving is worth the very slight
149 * performance hit on these high EBCDIC code points. */
150
151 if (UNLIKELY(UNICODE_IS_SUPER(uv))) {
a5bf80e0
KW
152 if ( UNLIKELY(uv > MAX_NON_DEPRECATED_CP)
153 && ckWARN_d(WARN_DEPRECATED))
154 {
155 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
156 cp_above_legal_max, uv, MAX_NON_DEPRECATED_CP);
157 }
158 if ( (flags & UNICODE_WARN_SUPER)
159 || ( UNICODE_IS_ABOVE_31_BIT(uv)
160 && (flags & UNICODE_WARN_ABOVE_31_BIT)))
161 {
162 Perl_ck_warner_d(aTHX_ packWARN(WARN_NON_UNICODE),
163
164 /* Choose the more dire applicable warning */
165 (UNICODE_IS_ABOVE_31_BIT(uv))
166 ? "Code point 0x%"UVXf" is not Unicode, and not portable"
167 : "Code point 0x%"UVXf" is not Unicode, may not be portable",
168 uv);
169 }
170 if (flags & UNICODE_DISALLOW_SUPER
171 || ( UNICODE_IS_ABOVE_31_BIT(uv)
172 && (flags & UNICODE_DISALLOW_ABOVE_31_BIT)))
173 {
174 return NULL;
175 }
176 }
ba6ed43c
KW
177 else if (UNLIKELY(UNICODE_IS_END_PLANE_NONCHAR_GIVEN_NOT_SUPER(uv))) {
178 HANDLE_UNICODE_NONCHAR(uv, flags);
507b9800 179 }
d9432125 180
ba6ed43c
KW
181 /* Test for and handle 4-byte result. In the test immediately below, the
182 * 8 is for start bytes F0-F7 (which are all the possible ones for 4 byte
183 * characters). The 3 is for 3 continuation bytes; these each contribute
184 * SHIFT bits. This yields 0x4_0000 on EBCDIC platforms, 0x20_0000 on
185 * ASCII, so 4 bytes covers the range 0x4000-0x3_FFFF on EBCDIC;
186 * 0x1_0000-0x1F_FFFF on ASCII */
187 if (uv < (8 * (1U << (3 * SHIFT)))) {
188 *d++ = I8_TO_NATIVE_UTF8(( uv >> ((4 - 1) * SHIFT)) | UTF_START_MARK(4));
189 *d++ = I8_TO_NATIVE_UTF8(((uv >> ((3 - 1) * SHIFT)) & MASK) | MARK);
190 *d++ = I8_TO_NATIVE_UTF8(((uv >> ((2 - 1) * SHIFT)) & MASK) | MARK);
191 *d++ = I8_TO_NATIVE_UTF8(( uv /* (1 - 1) */ & MASK) | MARK);
192
193#ifdef EBCDIC /* These were handled on ASCII platforms in the code for 3-byte
194 characters. The end-plane non-characters for EBCDIC were
195 handled just above */
196 if (UNLIKELY(UNICODE_IS_32_CONTIGUOUS_NONCHARS(uv))) {
197 HANDLE_UNICODE_NONCHAR(uv, flags);
d528804a 198 }
ba6ed43c
KW
199 else if (UNLIKELY(UNICODE_IS_SURROGATE(uv))) {
200 HANDLE_UNICODE_SURROGATE(uv, flags);
201 }
202#endif
203
204 return d;
205 }
206
207 /* Not 4-byte; that means the code point is at least 0x20_0000 on ASCII
208 * platforms, and 0x4000 on EBCDIC. At this point we switch to a loop
209 * format. The unrolled version above turns out to not save all that much
210 * time, and at these high code points (well above the legal Unicode range
211 * on ASCII platforms, and well above anything in common use in EBCDIC),
212 * khw believes that less code outweighs slight performance gains. */
213
d9432125 214 {
5aaebcb3 215 STRLEN len = OFFUNISKIP(uv);
1d72bdf6
NIS
216 U8 *p = d+len-1;
217 while (p > d) {
4c8cd605 218 *p-- = I8_TO_NATIVE_UTF8((uv & UTF_CONTINUATION_MASK) | UTF_CONTINUATION_MARK);
1d72bdf6
NIS
219 uv >>= UTF_ACCUMULATION_SHIFT;
220 }
4c8cd605 221 *p = I8_TO_NATIVE_UTF8((uv & UTF_START_MASK(len)) | UTF_START_MARK(len));
1d72bdf6
NIS
222 return d+len;
223 }
a0ed51b3 224}
a5bf80e0 225
646ca15d 226/*
07693fe6
KW
227=for apidoc uvchr_to_utf8
228
bcb1a2d4 229Adds the UTF-8 representation of the native code point C<uv> to the end
f2fc1b45 230of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
c749c9fd
KW
231C<UTF8_MAXBYTES+1>) free bytes available. The return value is the pointer to
232the byte after the end of the new character. In other words,
07693fe6
KW
233
234 d = uvchr_to_utf8(d, uv);
235
236is the recommended wide native character-aware way of saying
237
238 *(d++) = uv;
239
760c7c2f
KW
240This function accepts any UV as input, but very high code points (above
241C<IV_MAX> on the platform) will raise a deprecation warning. This is
242typically 0x7FFF_FFFF in a 32-bit word.
243
244It is possible to forbid or warn on non-Unicode code points, or those that may
245be problematic by using L</uvchr_to_utf8_flags>.
de69f3af 246
07693fe6
KW
247=cut
248*/
249
de69f3af
KW
250/* This is also a macro */
251PERL_CALLCONV U8* Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv);
252
07693fe6
KW
253U8 *
254Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv)
255{
de69f3af 256 return uvchr_to_utf8(d, uv);
07693fe6
KW
257}
258
de69f3af
KW
259/*
260=for apidoc uvchr_to_utf8_flags
261
262Adds the UTF-8 representation of the native code point C<uv> to the end
f2fc1b45 263of the string C<d>; C<d> should have at least C<UVCHR_SKIP(uv)+1> (up to
c749c9fd
KW
264C<UTF8_MAXBYTES+1>) free bytes available. The return value is the pointer to
265the byte after the end of the new character. In other words,
de69f3af
KW
266
267 d = uvchr_to_utf8_flags(d, uv, flags);
268
269or, in most cases,
270
271 d = uvchr_to_utf8_flags(d, uv, 0);
272
273This is the Unicode-aware way of saying
274
275 *(d++) = uv;
276
760c7c2f
KW
277If C<flags> is 0, this function accepts any UV as input, but very high code
278points (above C<IV_MAX> for the platform) will raise a deprecation warning.
279This is typically 0x7FFF_FFFF in a 32-bit word.
280
281Specifying C<flags> can further restrict what is allowed and not warned on, as
282follows:
de69f3af 283
796b6530 284If C<uv> is a Unicode surrogate code point and C<UNICODE_WARN_SURROGATE> is set,
7ee537e6
KW
285the function will raise a warning, provided UTF8 warnings are enabled. If
286instead C<UNICODE_DISALLOW_SURROGATE> is set, the function will fail and return
287NULL. If both flags are set, the function will both warn and return NULL.
de69f3af 288
760c7c2f
KW
289Similarly, the C<UNICODE_WARN_NONCHAR> and C<UNICODE_DISALLOW_NONCHAR> flags
290affect how the function handles a Unicode non-character.
93e6dbd6 291
760c7c2f
KW
292And likewise, the C<UNICODE_WARN_SUPER> and C<UNICODE_DISALLOW_SUPER> flags
293affect the handling of code points that are above the Unicode maximum of
2940x10FFFF. Languages other than Perl may not be able to accept files that
295contain these.
93e6dbd6
KW
296
297The flag C<UNICODE_WARN_ILLEGAL_INTERCHANGE> selects all three of
298the above WARN flags; and C<UNICODE_DISALLOW_ILLEGAL_INTERCHANGE> selects all
299three DISALLOW flags.
300
ab8e6d41
KW
301Code points above 0x7FFF_FFFF (2**31 - 1) were never specified in any standard,
302so using them is more problematic than other above-Unicode code points. Perl
303invented an extension to UTF-8 to represent the ones above 2**36-1, so it is
304likely that non-Perl languages will not be able to read files that contain
305these that written by the perl interpreter; nor would Perl understand files
306written by something that uses a different extension. For these reasons, there
307is a separate set of flags that can warn and/or disallow these extremely high
308code points, even if other above-Unicode ones are accepted. These are the
760c7c2f
KW
309C<UNICODE_WARN_ABOVE_31_BIT> and C<UNICODE_DISALLOW_ABOVE_31_BIT> flags. These
310are entirely independent from the deprecation warning for code points above
311C<IV_MAX>. On 32-bit machines, it will eventually be forbidden to have any
312code point that needs more than 31 bits to represent. When that happens,
313effectively the C<UNICODE_DISALLOW_ABOVE_31_BIT> flag will always be set on
31432-bit machines. (Of course C<UNICODE_DISALLOW_SUPER> will treat all
ab8e6d41
KW
315above-Unicode code points, including these, as malformations; and
316C<UNICODE_WARN_SUPER> warns on these.)
317
318On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing
319extremely high code points kicks in at 0x3FFF_FFFF (2**30 -1), which is lower
320than on ASCII. Prior to that, code points 2**31 and higher were simply
321unrepresentable, and a different, incompatible method was used to represent
322code points between 2**30 and 2**31 - 1. The flags C<UNICODE_WARN_ABOVE_31_BIT>
323and C<UNICODE_DISALLOW_ABOVE_31_BIT> have the same function as on ASCII
324platforms, warning and disallowing 2**31 and higher.
de69f3af 325
de69f3af
KW
326=cut
327*/
328
329/* This is also a macro */
330PERL_CALLCONV U8* Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags);
331
07693fe6
KW
332U8 *
333Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
334{
de69f3af 335 return uvchr_to_utf8_flags(d, uv, flags);
07693fe6
KW
336}
337
338/*
768c67ee 339
35f8c9bd
KW
340A helper function for the macro isUTF8_CHAR(), which should be used instead of
341this function. The macro will handle smaller code points directly saving time,
342using this function as a fall-back for higher code points. This function
343assumes that it is not called with an invariant character, and that
344's + len - 1' is within bounds of the string 's'.
345
346Tests if the string C<s> of at least length 'len' is a valid variant UTF-8
347character. 0 is returned if not, otherwise, 'len' is returned.
348
349*/
350
351STRLEN
352Perl__is_utf8_char_slow(const U8 * const s, const STRLEN len)
353{
354 const U8 *e;
355 const U8 *x, *y;
356
357 PERL_ARGS_ASSERT__IS_UTF8_CHAR_SLOW;
358
359 if (UNLIKELY(! UTF8_IS_START(*s))) {
360 return 0;
361 }
362
363 e = s + len;
364
365 for (x = s + 1; x < e; x++) {
366 if (UNLIKELY(! UTF8_IS_CONTINUATION(*x))) {
367 return 0;
368 }
369 }
370
371#ifndef EBCDIC
372
373 /* Here is syntactically valid. Make sure this isn't the start of an
374 * overlong. These values were found by manually inspecting the UTF-8
375 * patterns. See the tables in utf8.h and utfebcdic.h */
376
377 /* This is not needed on modern perls where C0 and C1 are not considered
378 * start bytes. */
379#if 0
380 if (UNLIKELY(*s < 0xC2)) {
381 return 0;
382 }
383#endif
384
385 if (len > 1) {
386 if ( (*s == 0xE0 && UNLIKELY(s[1] < 0xA0))
387 || (*s == 0xF0 && UNLIKELY(s[1] < 0x90))
388 || (*s == 0xF8 && UNLIKELY(s[1] < 0x88))
389 || (*s == 0xFC && UNLIKELY(s[1] < 0x84))
390 || (*s == 0xFE && UNLIKELY(s[1] < 0x82)))
391 {
392 return 0;
393 }
394 if ((len > 6 && UNLIKELY(*s == 0xFF) && UNLIKELY(s[6] < 0x81))) {
395 return 0;
396 }
397 }
398
399#else /* For EBCDIC, we use I8, which is the same on all code pages */
400 {
401 const U8 s0 = NATIVE_UTF8_TO_I8(*s);
402
403 /* On modern perls C0-C4 aren't considered start bytes */
404 if ( /* s0 < 0xC5 || */ s0 == 0xE0) {
405 return 0;
406 }
407
408 if (len >= 1) {
409 const U8 s1 = NATIVE_UTF8_TO_I8(s[1]);
410
411 if ( (s0 == 0xF0 && UNLIKELY(s1 < 0xB0))
412 || (s0 == 0xF8 && UNLIKELY(s1 < 0xA8))
413 || (s0 == 0xFC && UNLIKELY(s1 < 0xA4))
414 || (s0 == 0xFE && UNLIKELY(s1 < 0x82)))
415 {
416 return 0;
417 }
418 if ((len > 7 && UNLIKELY(s0 == 0xFF) && UNLIKELY(s[7] < 0xA1))) {
419 return 0;
420 }
421 }
422 }
423
424#endif
425
426 /* Now see if this would overflow a UV on this platform. See if the UTF8
427 * for this code point is larger than that for the highest representable
428 * code point */
429 y = (const U8 *) HIGHEST_REPRESENTABLE_UTF8;
430
431 for (x = s; x < e; x++, y++) {
432
433 /* If the same at this byte, go on to the next */
434 if (UNLIKELY(NATIVE_UTF8_TO_I8(*x) == *y)) {
435 continue;
436 }
437
438 /* If this is larger, it overflows */
439 if (UNLIKELY(NATIVE_UTF8_TO_I8(*x) > *y)) {
440 return 0;
441 }
442
443 /* But if smaller, it won't */
444 break;
445 }
446
447 return len;
448}
449
450/*
451
de69f3af 452=for apidoc utf8n_to_uvchr
378516de
KW
453
454THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
de69f3af 455Most code should use L</utf8_to_uvchr_buf>() rather than call this directly.
67e989fb 456
9041c2e3 457Bottom level UTF-8 decode routine.
de69f3af 458Returns the native code point value of the first character in the string C<s>,
746afd53
KW
459which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than
460C<curlen> bytes; C<*retlen> (if C<retlen> isn't NULL) will be set to
461the length, in bytes, of that character.
949cf498
KW
462
463The value of C<flags> determines the behavior when C<s> does not point to a
464well-formed UTF-8 character. If C<flags> is 0, when a malformation is found,
524080c4
KW
465zero is returned and C<*retlen> is set so that (S<C<s> + C<*retlen>>) is the
466next possible position in C<s> that could begin a non-malformed character.
467Also, if UTF-8 warnings haven't been lexically disabled, a warning is raised.
949cf498
KW
468
469Various ALLOW flags can be set in C<flags> to allow (and not warn on)
470individual types of malformations, such as the sequence being overlong (that
471is, when there is a shorter sequence that can express the same code point;
472overlong sequences are expressly forbidden in the UTF-8 standard due to
473potential security issues). Another malformation example is the first byte of
474a character not being a legal first byte. See F<utf8.h> for the list of such
524080c4
KW
475flags. For allowed 0 length strings, this function returns 0; for allowed
476overlong sequences, the computed code point is returned; for all other allowed
477malformations, the Unicode REPLACEMENT CHARACTER is returned, as these have no
478determinable reasonable value.
949cf498 479
796b6530 480The C<UTF8_CHECK_ONLY> flag overrides the behavior when a non-allowed (by other
949cf498
KW
481flags) malformation is found. If this flag is set, the routine assumes that
482the caller will raise a warning, and this function will silently just set
d088425d
KW
483C<retlen> to C<-1> (cast to C<STRLEN>) and return zero.
484
75200dff 485Note that this API requires disambiguation between successful decoding a C<NUL>
796b6530 486character, and an error return (unless the C<UTF8_CHECK_ONLY> flag is set), as
d088425d 487in both cases, 0 is returned. To disambiguate, upon a zero return, see if the
75200dff
KW
488first byte of C<s> is 0 as well. If so, the input was a C<NUL>; if not, the
489input had an error.
949cf498
KW
490
491Certain code points are considered problematic. These are Unicode surrogates,
746afd53 492Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF.
949cf498 493By default these are considered regular code points, but certain situations
5eafe189 494warrant special handling for them. If C<flags> contains
796b6530
KW
495C<UTF8_DISALLOW_ILLEGAL_INTERCHANGE>, all three classes are treated as
496malformations and handled as such. The flags C<UTF8_DISALLOW_SURROGATE>,
497C<UTF8_DISALLOW_NONCHAR>, and C<UTF8_DISALLOW_SUPER> (meaning above the legal
498Unicode maximum) can be set to disallow these categories individually.
499
500The flags C<UTF8_WARN_ILLEGAL_INTERCHANGE>, C<UTF8_WARN_SURROGATE>,
501C<UTF8_WARN_NONCHAR>, and C<UTF8_WARN_SUPER> will cause warning messages to be
502raised for their respective categories, but otherwise the code points are
503considered valid (not malformations). To get a category to both be treated as
504a malformation and raise a warning, specify both the WARN and DISALLOW flags.
949cf498 505(But note that warnings are not raised if lexically disabled nor if
796b6530 506C<UTF8_CHECK_ONLY> is also specified.)
949cf498 507
760c7c2f
KW
508It is now deprecated to have very high code points (above C<IV_MAX> on the
509platforms) and this function will raise a deprecation warning for these (unless
510such warnings are turned off). This value, is typically 0x7FFF_FFFF (2**31 -1)
511in a 32-bit word.
ab8e6d41
KW
512
513Code points above 0x7FFF_FFFF (2**31 - 1) were never specified in any standard,
514so using them is more problematic than other above-Unicode code points. Perl
515invented an extension to UTF-8 to represent the ones above 2**36-1, so it is
516likely that non-Perl languages will not be able to read files that contain
517these that written by the perl interpreter; nor would Perl understand files
518written by something that uses a different extension. For these reasons, there
519is a separate set of flags that can warn and/or disallow these extremely high
520code points, even if other above-Unicode ones are accepted. These are the
760c7c2f
KW
521C<UTF8_WARN_ABOVE_31_BIT> and C<UTF8_DISALLOW_ABOVE_31_BIT> flags. These
522are entirely independent from the deprecation warning for code points above
523C<IV_MAX>. On 32-bit machines, it will eventually be forbidden to have any
524code point that needs more than 31 bits to represent. When that happens,
525effectively the C<UTF8_DISALLOW_ABOVE_31_BIT> flag will always be set on
52632-bit machines. (Of course C<UTF8_DISALLOW_SUPER> will treat all
ab8e6d41
KW
527above-Unicode code points, including these, as malformations; and
528C<UTF8_WARN_SUPER> warns on these.)
529
530On EBCDIC platforms starting in Perl v5.24, the Perl extension for representing
531extremely high code points kicks in at 0x3FFF_FFFF (2**30 -1), which is lower
532than on ASCII. Prior to that, code points 2**31 and higher were simply
533unrepresentable, and a different, incompatible method was used to represent
534code points between 2**30 and 2**31 - 1. The flags C<UTF8_WARN_ABOVE_31_BIT>
535and C<UTF8_DISALLOW_ABOVE_31_BIT> have the same function as on ASCII
536platforms, warning and disallowing 2**31 and higher.
949cf498
KW
537
538All other code points corresponding to Unicode characters, including private
539use and those yet to be assigned, are never considered malformed and never
540warn.
67e989fb 541
37607a96
PK
542=cut
543*/
67e989fb 544
a0ed51b3 545UV
de69f3af 546Perl_utf8n_to_uvchr(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
a0ed51b3 547{
d4c19fe8 548 const U8 * const s0 = s;
eb83ed87 549 U8 overflow_byte = '\0'; /* Save byte in case of overflow */
0b8d30e8 550 U8 * send;
eb83ed87
KW
551 UV uv = *s;
552 STRLEN expectlen;
949cf498 553 SV* sv = NULL;
eb83ed87
KW
554 UV outlier_ret = 0; /* return value when input is in error or problematic
555 */
556 UV pack_warn = 0; /* Save result of packWARN() for later */
557 bool unexpected_non_continuation = FALSE;
558 bool overflowed = FALSE;
2f8f112e 559 bool do_overlong_test = TRUE; /* May have to skip this test */
a0dbb045 560
eb83ed87 561 const char* const malformed_text = "Malformed UTF-8 character";
7918f24d 562
de69f3af 563 PERL_ARGS_ASSERT_UTF8N_TO_UVCHR;
a0dbb045 564
eb83ed87
KW
565 /* The order of malformation tests here is important. We should consume as
566 * few bytes as possible in order to not skip any valid character. This is
567 * required by the Unicode Standard (section 3.9 of Unicode 6.0); see also
568 * http://unicode.org/reports/tr36 for more discussion as to why. For
569 * example, once we've done a UTF8SKIP, we can tell the expected number of
570 * bytes, and could fail right off the bat if the input parameters indicate
571 * that there are too few available. But it could be that just that first
572 * byte is garbled, and the intended character occupies fewer bytes. If we
573 * blindly assumed that the first byte is correct, and skipped based on
574 * that number, we could skip over a valid input character. So instead, we
575 * always examine the sequence byte-by-byte.
576 *
577 * We also should not consume too few bytes, otherwise someone could inject
578 * things. For example, an input could be deliberately designed to
579 * overflow, and if this code bailed out immediately upon discovering that,
e2660c54 580 * returning to the caller C<*retlen> pointing to the very next byte (one
eb83ed87
KW
581 * which is actually part of of the overflowing sequence), that could look
582 * legitimate to the caller, which could discard the initial partial
583 * sequence and process the rest, inappropriately */
584
585 /* Zero length strings, if allowed, of necessity are zero */
b5b9af04 586 if (UNLIKELY(curlen == 0)) {
eb83ed87
KW
587 if (retlen) {
588 *retlen = 0;
589 }
a0dbb045 590
eb83ed87
KW
591 if (flags & UTF8_ALLOW_EMPTY) {
592 return 0;
593 }
594 if (! (flags & UTF8_CHECK_ONLY)) {
595 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (empty string)", malformed_text));
596 }
0c443dc2
JH
597 goto malformed;
598 }
599
eb83ed87
KW
600 expectlen = UTF8SKIP(s);
601
602 /* A well-formed UTF-8 character, as the vast majority of calls to this
603 * function will be for, has this expected length. For efficiency, set
604 * things up here to return it. It will be overriden only in those rare
605 * cases where a malformation is found */
606 if (retlen) {
607 *retlen = expectlen;
608 }
609
610 /* An invariant is trivially well-formed */
1d72bdf6 611 if (UTF8_IS_INVARIANT(uv)) {
de69f3af 612 return uv;
a0ed51b3 613 }
67e989fb 614
eb83ed87 615 /* A continuation character can't start a valid sequence */
b5b9af04 616 if (UNLIKELY(UTF8_IS_CONTINUATION(uv))) {
eb83ed87
KW
617 if (flags & UTF8_ALLOW_CONTINUATION) {
618 if (retlen) {
619 *retlen = 1;
620 }
621 return UNICODE_REPLACEMENT;
622 }
ba210ebe 623
eb83ed87
KW
624 if (! (flags & UTF8_CHECK_ONLY)) {
625 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected continuation byte 0x%02x, with no preceding start byte)", malformed_text, *s0));
626 }
627 curlen = 1;
ba210ebe
JH
628 goto malformed;
629 }
9041c2e3 630
dcd27b3c
KW
631 /* Here is not a continuation byte, nor an invariant. The only thing left
632 * is a start byte (possibly for an overlong) */
633
534752c1
KW
634 /* Convert to I8 on EBCDIC (no-op on ASCII), then remove the leading bits
635 * that indicate the number of bytes in the character's whole UTF-8
636 * sequence, leaving just the bits that are part of the value. */
637 uv = NATIVE_UTF8_TO_I8(uv) & UTF_START_MASK(expectlen);
ba210ebe 638
eb83ed87
KW
639 /* Now, loop through the remaining bytes in the character's sequence,
640 * accumulating each into the working value as we go. Be sure to not look
641 * past the end of the input string */
0b8d30e8
KW
642 send = (U8*) s0 + ((expectlen <= curlen) ? expectlen : curlen);
643
eb83ed87 644 for (s = s0 + 1; s < send; s++) {
b5b9af04 645 if (LIKELY(UTF8_IS_CONTINUATION(*s))) {
eb83ed87
KW
646 if (uv & UTF_ACCUMULATION_OVERFLOW_MASK) {
647
648 /* The original implementors viewed this malformation as more
649 * serious than the others (though I, khw, don't understand
650 * why, since other malformations also give very very wrong
651 * results), so there is no way to turn off checking for it.
652 * Set a flag, but keep going in the loop, so that we absorb
653 * the rest of the bytes that comprise the character. */
654 overflowed = TRUE;
655 overflow_byte = *s; /* Save for warning message's use */
656 }
8850bf83 657 uv = UTF8_ACCUMULATE(uv, *s);
eb83ed87
KW
658 }
659 else {
660 /* Here, found a non-continuation before processing all expected
661 * bytes. This byte begins a new character, so quit, even if
662 * allowing this malformation. */
663 unexpected_non_continuation = TRUE;
664 break;
665 }
666 } /* End of loop through the character's bytes */
667
668 /* Save how many bytes were actually in the character */
669 curlen = s - s0;
670
671 /* The loop above finds two types of malformations: non-continuation and/or
672 * overflow. The non-continuation malformation is really a too-short
673 * malformation, as it means that the current character ended before it was
674 * expected to (being terminated prematurely by the beginning of the next
675 * character, whereas in the too-short malformation there just are too few
676 * bytes available to hold the character. In both cases, the check below
677 * that we have found the expected number of bytes would fail if executed.)
678 * Thus the non-continuation malformation is really unnecessary, being a
679 * subset of the too-short malformation. But there may be existing
680 * applications that are expecting the non-continuation type, so we retain
681 * it, and return it in preference to the too-short malformation. (If this
682 * code were being written from scratch, the two types might be collapsed
683 * into one.) I, khw, am also giving priority to returning the
684 * non-continuation and too-short malformations over overflow when multiple
685 * ones are present. I don't know of any real reason to prefer one over
686 * the other, except that it seems to me that multiple-byte errors trumps
687 * errors from a single byte */
b5b9af04 688 if (UNLIKELY(unexpected_non_continuation)) {
eb83ed87
KW
689 if (!(flags & UTF8_ALLOW_NON_CONTINUATION)) {
690 if (! (flags & UTF8_CHECK_ONLY)) {
691 if (curlen == 1) {
692 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, immediately after start byte 0x%02x)", malformed_text, *s, *s0));
693 }
694 else {
695 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, %d bytes after start byte 0x%02x, expected %d bytes)", malformed_text, *s, (int) curlen, *s0, (int)expectlen));
a0dbb045
JH
696 }
697 }
eb83ed87
KW
698 goto malformed;
699 }
700 uv = UNICODE_REPLACEMENT;
2f8f112e
KW
701
702 /* Skip testing for overlongs, as the REPLACEMENT may not be the same
703 * as what the original expectations were. */
704 do_overlong_test = FALSE;
eb83ed87
KW
705 if (retlen) {
706 *retlen = curlen;
707 }
708 }
b5b9af04 709 else if (UNLIKELY(curlen < expectlen)) {
eb83ed87
KW
710 if (! (flags & UTF8_ALLOW_SHORT)) {
711 if (! (flags & UTF8_CHECK_ONLY)) {
712 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)curlen, curlen == 1 ? "" : "s", (int)expectlen, *s0));
a0dbb045 713 }
eb83ed87
KW
714 goto malformed;
715 }
716 uv = UNICODE_REPLACEMENT;
2f8f112e 717 do_overlong_test = FALSE;
eb83ed87
KW
718 if (retlen) {
719 *retlen = curlen;
720 }
721 }
722
b5b9af04 723 if (UNLIKELY(overflowed)) {
eb83ed87 724 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (overflow at byte 0x%02x, after start byte 0x%02x)", malformed_text, overflow_byte, *s0));
ba210ebe 725 goto malformed;
eb83ed87 726 }
eb83ed87 727
2f8f112e 728 if (do_overlong_test
5aaebcb3 729 && expectlen > (STRLEN) OFFUNISKIP(uv)
2f8f112e
KW
730 && ! (flags & UTF8_ALLOW_LONG))
731 {
eb83ed87
KW
732 /* The overlong malformation has lower precedence than the others.
733 * Note that if this malformation is allowed, we return the actual
734 * value, instead of the replacement character. This is because this
735 * value is actually well-defined. */
736 if (! (flags & UTF8_CHECK_ONLY)) {
5aaebcb3 737 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)expectlen, expectlen == 1 ? "": "s", OFFUNISKIP(uv), *s0));
eb83ed87
KW
738 }
739 goto malformed;
740 }
741
1a89bb6c 742 /* Here, the input is considered to be well-formed, but it still could be a
eb83ed87
KW
743 * problematic code point that is not allowed by the input parameters. */
744 if (uv >= UNICODE_SURROGATE_FIRST /* isn't problematic if < this */
760c7c2f
KW
745 && ((flags & ( UTF8_DISALLOW_NONCHAR
746 |UTF8_DISALLOW_SURROGATE
747 |UTF8_DISALLOW_SUPER
748 |UTF8_DISALLOW_ABOVE_31_BIT
749 |UTF8_WARN_NONCHAR
750 |UTF8_WARN_SURROGATE
751 |UTF8_WARN_SUPER
752 |UTF8_WARN_ABOVE_31_BIT))
753 || ( UNLIKELY(uv > MAX_NON_DEPRECATED_CP)
754 && ckWARN_d(WARN_DEPRECATED))))
eb83ed87 755 {
949cf498 756 if (UNICODE_IS_SURROGATE(uv)) {
ea5ced44
KW
757
758 /* By adding UTF8_CHECK_ONLY to the test, we avoid unnecessary
759 * generation of the sv, since no warnings are raised under CHECK */
eb83ed87 760 if ((flags & (UTF8_WARN_SURROGATE|UTF8_CHECK_ONLY)) == UTF8_WARN_SURROGATE
54f4afef 761 && ckWARN_d(WARN_SURROGATE))
eb83ed87 762 {
111d382d 763 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "UTF-16 surrogate U+%04"UVXf"", uv));
54f4afef 764 pack_warn = packWARN(WARN_SURROGATE);
949cf498
KW
765 }
766 if (flags & UTF8_DISALLOW_SURROGATE) {
767 goto disallowed;
768 }
769 }
949cf498 770 else if ((uv > PERL_UNICODE_MAX)) {
eb83ed87 771 if ((flags & (UTF8_WARN_SUPER|UTF8_CHECK_ONLY)) == UTF8_WARN_SUPER
ea5ced44 772 && ckWARN_d(WARN_NON_UNICODE))
eb83ed87 773 {
0bcdd8f6
KW
774 sv = sv_2mortal(Perl_newSVpvf(aTHX_
775 "Code point 0x%04"UVXf" is not Unicode, may not be portable",
776 uv));
54f4afef 777 pack_warn = packWARN(WARN_NON_UNICODE);
949cf498 778 }
c0236afe
KW
779
780 /* The maximum code point ever specified by a standard was
781 * 2**31 - 1. Anything larger than that is a Perl extension that
782 * very well may not be understood by other applications (including
783 * earlier perl versions on EBCDIC platforms). On ASCII platforms,
784 * these code points are indicated by the first UTF-8 byte being
d35f2ca5
KW
785 * 0xFE or 0xFF. We test for these after the regular SUPER ones,
786 * and before possibly bailing out, so that the slightly more dire
c0236afe
KW
787 * warning will override the regular one. */
788 if (
789#ifndef EBCDIC
790 (*s0 & 0xFE) == 0xFE /* matches both FE, FF */
791#else
792 /* The I8 for 2**31 (U+80000000) is
793 * \xFF\xA0\xA0\xA0\xA0\xA0\xA0\xA2\xA0\xA0\xA0\xA0\xA0\xA0
794 * and it turns out that on all EBCDIC pages recognized that
795 * the UTF-EBCDIC for that code point is
796 * \xFE\x41\x41\x41\x41\x41\x41\x43\x41\x41\x41\x41\x41\x41
797 * For the next lower code point, the 1047 UTF-EBCDIC is
798 * \xFE\x41\x41\x41\x41\x41\x41\x42\x73\x73\x73\x73\x73\x73
799 * The other code pages differ only in the bytes following
800 * \x42. Thus the following works (the minimum continuation
801 * byte is \x41). */
802 *s0 == 0xFE && send - s0 > 7 && ( s0[1] > 0x41
803 || s0[2] > 0x41
804 || s0[3] > 0x41
805 || s0[4] > 0x41
806 || s0[5] > 0x41
807 || s0[6] > 0x41
808 || s0[7] > 0x42)
809#endif
d35f2ca5
KW
810 && (flags & (UTF8_WARN_ABOVE_31_BIT|UTF8_WARN_SUPER
811 |UTF8_DISALLOW_ABOVE_31_BIT)))
ea5ced44 812 {
0bcdd8f6 813 if ( ! (flags & UTF8_CHECK_ONLY)
d35f2ca5 814 && (flags & (UTF8_WARN_ABOVE_31_BIT|UTF8_WARN_SUPER))
0bcdd8f6 815 && ckWARN_d(WARN_UTF8))
ea5ced44 816 {
0bcdd8f6
KW
817 sv = sv_2mortal(Perl_newSVpvf(aTHX_
818 "Code point 0x%"UVXf" is not Unicode, and not portable",
819 uv));
ea5ced44
KW
820 pack_warn = packWARN(WARN_UTF8);
821 }
d35f2ca5 822 if (flags & UTF8_DISALLOW_ABOVE_31_BIT) {
ea5ced44
KW
823 goto disallowed;
824 }
825 }
c0236afe 826
949cf498
KW
827 if (flags & UTF8_DISALLOW_SUPER) {
828 goto disallowed;
829 }
760c7c2f
KW
830
831 /* The deprecated warning overrides any non-deprecated one */
832 if (UNLIKELY(uv > MAX_NON_DEPRECATED_CP) && ckWARN_d(WARN_DEPRECATED))
833 {
834 sv = sv_2mortal(Perl_newSVpvf(aTHX_ cp_above_legal_max,
835 uv, MAX_NON_DEPRECATED_CP));
836 pack_warn = packWARN(WARN_DEPRECATED);
837 }
949cf498 838 }
4190d317
KW
839 else if (UNICODE_IS_NONCHAR(uv)) {
840 if ((flags & (UTF8_WARN_NONCHAR|UTF8_CHECK_ONLY)) == UTF8_WARN_NONCHAR
54f4afef 841 && ckWARN_d(WARN_NONCHAR))
4190d317 842 {
ba707cdc 843 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Unicode non-character U+%04"UVXf" is not recommended for open interchange", uv));
54f4afef 844 pack_warn = packWARN(WARN_NONCHAR);
4190d317
KW
845 }
846 if (flags & UTF8_DISALLOW_NONCHAR) {
847 goto disallowed;
848 }
849 }
949cf498 850
eb83ed87 851 if (sv) {
de69f3af
KW
852 outlier_ret = uv; /* Note we don't bother to convert to native,
853 as all the outlier code points are the same
854 in both ASCII and EBCDIC */
eb83ed87
KW
855 goto do_warn;
856 }
857
949cf498
KW
858 /* Here, this is not considered a malformed character, so drop through
859 * to return it */
a0ed51b3 860 }
ba210ebe 861
de69f3af 862 return UNI_TO_NATIVE(uv);
ba210ebe 863
eb83ed87
KW
864 /* There are three cases which get to beyond this point. In all 3 cases:
865 * <sv> if not null points to a string to print as a warning.
866 * <curlen> is what <*retlen> should be set to if UTF8_CHECK_ONLY isn't
867 * set.
868 * <outlier_ret> is what return value to use if UTF8_CHECK_ONLY isn't set.
869 * This is done by initializing it to 0, and changing it only
870 * for case 1).
871 * The 3 cases are:
872 * 1) The input is valid but problematic, and to be warned about. The
873 * return value is the resultant code point; <*retlen> is set to
874 * <curlen>, the number of bytes that comprise the code point.
875 * <pack_warn> contains the result of packWARN() for the warning
876 * types. The entry point for this case is the label <do_warn>;
877 * 2) The input is a valid code point but disallowed by the parameters to
878 * this function. The return value is 0. If UTF8_CHECK_ONLY is set,
879 * <*relen> is -1; otherwise it is <curlen>, the number of bytes that
880 * comprise the code point. <pack_warn> contains the result of
881 * packWARN() for the warning types. The entry point for this case is
882 * the label <disallowed>.
883 * 3) The input is malformed. The return value is 0. If UTF8_CHECK_ONLY
884 * is set, <*relen> is -1; otherwise it is <curlen>, the number of
885 * bytes that comprise the malformation. All such malformations are
886 * assumed to be warning type <utf8>. The entry point for this case
887 * is the label <malformed>.
888 */
949cf498 889
7b52d656 890 malformed:
ba210ebe 891
eb83ed87
KW
892 if (sv && ckWARN_d(WARN_UTF8)) {
893 pack_warn = packWARN(WARN_UTF8);
894 }
895
7b52d656 896 disallowed:
eb83ed87 897
fcc8fcf6 898 if (flags & UTF8_CHECK_ONLY) {
ba210ebe 899 if (retlen)
10edeb5d 900 *retlen = ((STRLEN) -1);
ba210ebe
JH
901 return 0;
902 }
903
7b52d656 904 do_warn:
5b311467 905
eb83ed87
KW
906 if (pack_warn) { /* <pack_warn> was initialized to 0, and changed only
907 if warnings are to be raised. */
f555bc63 908 const char * const string = SvPVX_const(sv);
a0dbb045 909
f555bc63
KW
910 if (PL_op)
911 Perl_warner(aTHX_ pack_warn, "%s in %s", string, OP_DESC(PL_op));
912 else
913 Perl_warner(aTHX_ pack_warn, "%s", string);
a0dbb045
JH
914 }
915
eb83ed87
KW
916 if (retlen) {
917 *retlen = curlen;
918 }
ba210ebe 919
eb83ed87 920 return outlier_ret;
a0ed51b3
LW
921}
922
8e84507e 923/*
ec5f19d0
KW
924=for apidoc utf8_to_uvchr_buf
925
926Returns the native code point of the first character in the string C<s> which
927is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
524080c4 928C<*retlen> will be set to the length, in bytes, of that character.
ec5f19d0 929
524080c4
KW
930If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
931enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
796b6530 932C<NULL>) to -1. If those warnings are off, the computed value, if well-defined
173db420 933(or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and
796b6530 934C<*retlen> is set (if C<retlen> isn't C<NULL>) so that (S<C<s> + C<*retlen>>) is
173db420 935the next possible position in C<s> that could begin a non-malformed character.
de69f3af 936See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
173db420 937returned.
ec5f19d0 938
760c7c2f
KW
939Code points above the platform's C<IV_MAX> will raise a deprecation warning,
940unless those are turned off.
941
ec5f19d0
KW
942=cut
943*/
944
945
946UV
947Perl_utf8_to_uvchr_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
948{
ec5f19d0
KW
949 assert(s < send);
950
951 return utf8n_to_uvchr(s, send - s, retlen,
952 ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
953}
954
955/*
ec5f19d0
KW
956=for apidoc utf8_to_uvuni_buf
957
de69f3af
KW
958Only in very rare circumstances should code need to be dealing in Unicode
959(as opposed to native) code points. In those few cases, use
960C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>> instead.
4f83cdcd
KW
961
962Returns the Unicode (not-native) code point of the first character in the
963string C<s> which
ec5f19d0
KW
964is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
965C<retlen> will be set to the length, in bytes, of that character.
966
524080c4
KW
967If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
968enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
969NULL) to -1. If those warnings are off, the computed value if well-defined (or
970the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
971is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
972next possible position in C<s> that could begin a non-malformed character.
de69f3af 973See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
ec5f19d0 974
760c7c2f
KW
975Code points above the platform's C<IV_MAX> will raise a deprecation warning,
976unless those are turned off.
977
ec5f19d0
KW
978=cut
979*/
980
981UV
982Perl_utf8_to_uvuni_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
983{
984 PERL_ARGS_ASSERT_UTF8_TO_UVUNI_BUF;
985
986 assert(send > s);
987
5962d97e
KW
988 /* Call the low level routine, asking for checks */
989 return NATIVE_TO_UNI(utf8_to_uvchr_buf(s, send, retlen));
ec5f19d0
KW
990}
991
b76347f2 992/*
87cea99e 993=for apidoc utf8_length
b76347f2
JH
994
995Return the length of the UTF-8 char encoded string C<s> in characters.
02eb7b47
JH
996Stops at C<e> (inclusive). If C<e E<lt> s> or if the scan would end
997up past C<e>, croaks.
b76347f2
JH
998
999=cut
1000*/
1001
1002STRLEN
35a4481c 1003Perl_utf8_length(pTHX_ const U8 *s, const U8 *e)
b76347f2
JH
1004{
1005 STRLEN len = 0;
1006
7918f24d
NC
1007 PERL_ARGS_ASSERT_UTF8_LENGTH;
1008
8850bf83
JH
1009 /* Note: cannot use UTF8_IS_...() too eagerly here since e.g.
1010 * the bitops (especially ~) can create illegal UTF-8.
1011 * In other words: in Perl UTF-8 is not just for Unicode. */
1012
a3b680e6
AL
1013 if (e < s)
1014 goto warn_and_return;
b76347f2 1015 while (s < e) {
4cbf4130 1016 s += UTF8SKIP(s);
8e91ec7f
AV
1017 len++;
1018 }
1019
1020 if (e != s) {
1021 len--;
1022 warn_and_return:
9b387841
NC
1023 if (PL_op)
1024 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1025 "%s in %s", unees, OP_DESC(PL_op));
1026 else
61a12c31 1027 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
b76347f2
JH
1028 }
1029
1030 return len;
1031}
1032
b06226ff 1033/*
fed3ba5d
NC
1034=for apidoc bytes_cmp_utf8
1035
a1433954 1036Compares the sequence of characters (stored as octets) in C<b>, C<blen> with the
72d33970
FC
1037sequence of characters (stored as UTF-8)
1038in C<u>, C<ulen>. Returns 0 if they are
fed3ba5d
NC
1039equal, -1 or -2 if the first string is less than the second string, +1 or +2
1040if the first string is greater than the second string.
1041
1042-1 or +1 is returned if the shorter string was identical to the start of the
72d33970
FC
1043longer string. -2 or +2 is returned if
1044there was a difference between characters
fed3ba5d
NC
1045within the strings.
1046
1047=cut
1048*/
1049
1050int
1051Perl_bytes_cmp_utf8(pTHX_ const U8 *b, STRLEN blen, const U8 *u, STRLEN ulen)
1052{
1053 const U8 *const bend = b + blen;
1054 const U8 *const uend = u + ulen;
1055
1056 PERL_ARGS_ASSERT_BYTES_CMP_UTF8;
fed3ba5d
NC
1057
1058 while (b < bend && u < uend) {
1059 U8 c = *u++;
1060 if (!UTF8_IS_INVARIANT(c)) {
1061 if (UTF8_IS_DOWNGRADEABLE_START(c)) {
1062 if (u < uend) {
1063 U8 c1 = *u++;
1064 if (UTF8_IS_CONTINUATION(c1)) {
a62b247b 1065 c = EIGHT_BIT_UTF8_TO_NATIVE(c, c1);
fed3ba5d
NC
1066 } else {
1067 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1068 "Malformed UTF-8 character "
1069 "(unexpected non-continuation byte 0x%02x"
1070 ", immediately after start byte 0x%02x)"
1071 /* Dear diag.t, it's in the pod. */
1072 "%s%s", c1, c,
1073 PL_op ? " in " : "",
1074 PL_op ? OP_DESC(PL_op) : "");
1075 return -2;
1076 }
1077 } else {
1078 if (PL_op)
1079 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1080 "%s in %s", unees, OP_DESC(PL_op));
1081 else
61a12c31 1082 Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
fed3ba5d
NC
1083 return -2; /* Really want to return undef :-) */
1084 }
1085 } else {
1086 return -2;
1087 }
1088 }
1089 if (*b != c) {
1090 return *b < c ? -2 : +2;
1091 }
1092 ++b;
1093 }
1094
1095 if (b == bend && u == uend)
1096 return 0;
1097
1098 return b < bend ? +1 : -1;
1099}
1100
1101/*
87cea99e 1102=for apidoc utf8_to_bytes
6940069f 1103
2bbc8d55 1104Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
a1433954
KW
1105Unlike L</bytes_to_utf8>, this over-writes the original string, and
1106updates C<len> to contain the new length.
67e989fb 1107Returns zero on failure, setting C<len> to -1.
6940069f 1108
a1433954 1109If you need a copy of the string, see L</bytes_from_utf8>.
95be277c 1110
6940069f
GS
1111=cut
1112*/
1113
1114U8 *
37607a96 1115Perl_utf8_to_bytes(pTHX_ U8 *s, STRLEN *len)
6940069f 1116{
d4c19fe8
AL
1117 U8 * const save = s;
1118 U8 * const send = s + *len;
6940069f 1119 U8 *d;
246fae53 1120
7918f24d 1121 PERL_ARGS_ASSERT_UTF8_TO_BYTES;
81611534 1122 PERL_UNUSED_CONTEXT;
7918f24d 1123
1e54db1a 1124 /* ensure valid UTF-8 and chars < 256 before updating string */
d4c19fe8 1125 while (s < send) {
d59937ca
KW
1126 if (! UTF8_IS_INVARIANT(*s)) {
1127 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1128 *len = ((STRLEN) -1);
1129 return 0;
1130 }
1131 s++;
dcad2880 1132 }
d59937ca 1133 s++;
246fae53 1134 }
dcad2880
JH
1135
1136 d = s = save;
6940069f 1137 while (s < send) {
80e0b38f
KW
1138 U8 c = *s++;
1139 if (! UTF8_IS_INVARIANT(c)) {
1140 /* Then it is two-byte encoded */
a62b247b 1141 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
80e0b38f
KW
1142 s++;
1143 }
1144 *d++ = c;
6940069f
GS
1145 }
1146 *d = '\0';
246fae53 1147 *len = d - save;
6940069f
GS
1148 return save;
1149}
1150
1151/*
87cea99e 1152=for apidoc bytes_from_utf8
f9a63242 1153
2bbc8d55 1154Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
a1433954 1155Unlike L</utf8_to_bytes> but like L</bytes_to_utf8>, returns a pointer to
ef9edfd0
JH
1156the newly-created string, and updates C<len> to contain the new
1157length. Returns the original string if no conversion occurs, C<len>
72d33970 1158is unchanged. Do nothing if C<is_utf8> points to 0. Sets C<is_utf8> to
2bbc8d55 11590 if C<s> is converted or consisted entirely of characters that are invariant
4a4088c4 1160in UTF-8 (i.e., US-ASCII on non-EBCDIC machines).
f9a63242 1161
37607a96
PK
1162=cut
1163*/
f9a63242
JH
1164
1165U8 *
e1ec3a88 1166Perl_bytes_from_utf8(pTHX_ const U8 *s, STRLEN *len, bool *is_utf8)
f9a63242 1167{
f9a63242 1168 U8 *d;
e1ec3a88
AL
1169 const U8 *start = s;
1170 const U8 *send;
f9a63242
JH
1171 I32 count = 0;
1172
7918f24d 1173 PERL_ARGS_ASSERT_BYTES_FROM_UTF8;
96a5add6 1174 PERL_UNUSED_CONTEXT;
f9a63242 1175 if (!*is_utf8)
73d840c0 1176 return (U8 *)start;
f9a63242 1177
1e54db1a 1178 /* ensure valid UTF-8 and chars < 256 before converting string */
f9a63242 1179 for (send = s + *len; s < send;) {
d59937ca
KW
1180 if (! UTF8_IS_INVARIANT(*s)) {
1181 if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
73d840c0 1182 return (U8 *)start;
d59937ca
KW
1183 }
1184 count++;
1185 s++;
db42d148 1186 }
d59937ca 1187 s++;
f9a63242
JH
1188 }
1189
35da51f7 1190 *is_utf8 = FALSE;
f9a63242 1191
212542aa 1192 Newx(d, (*len) - count + 1, U8);
ef9edfd0 1193 s = start; start = d;
f9a63242
JH
1194 while (s < send) {
1195 U8 c = *s++;
1a91c45d 1196 if (! UTF8_IS_INVARIANT(c)) {
c4d5f83a 1197 /* Then it is two-byte encoded */
a62b247b 1198 c = EIGHT_BIT_UTF8_TO_NATIVE(c, *s);
1a91c45d 1199 s++;
c4d5f83a
NIS
1200 }
1201 *d++ = c;
f9a63242
JH
1202 }
1203 *d = '\0';
1204 *len = d - start;
73d840c0 1205 return (U8 *)start;
f9a63242
JH
1206}
1207
1208/*
87cea99e 1209=for apidoc bytes_to_utf8
6940069f 1210
ff97e5cf
KW
1211Converts a string C<s> of length C<len> bytes from the native encoding into
1212UTF-8.
6662521e 1213Returns a pointer to the newly-created string, and sets C<len> to
ff97e5cf 1214reflect the new length in bytes.
6940069f 1215
75200dff 1216A C<NUL> character will be written after the end of the string.
2bbc8d55
SP
1217
1218If you want to convert to UTF-8 from encodings other than
1219the native (Latin1 or EBCDIC),
a1433954 1220see L</sv_recode_to_utf8>().
c9ada85f 1221
497711e7 1222=cut
6940069f
GS
1223*/
1224
c682ebef
FC
1225/* This logic is duplicated in sv_catpvn_flags, so any bug fixes will
1226 likewise need duplication. */
1227
6940069f 1228U8*
35a4481c 1229Perl_bytes_to_utf8(pTHX_ const U8 *s, STRLEN *len)
6940069f 1230{
35a4481c 1231 const U8 * const send = s + (*len);
6940069f
GS
1232 U8 *d;
1233 U8 *dst;
7918f24d
NC
1234
1235 PERL_ARGS_ASSERT_BYTES_TO_UTF8;
96a5add6 1236 PERL_UNUSED_CONTEXT;
6940069f 1237
212542aa 1238 Newx(d, (*len) * 2 + 1, U8);
6940069f
GS
1239 dst = d;
1240
1241 while (s < send) {
55d09dc8
KW
1242 append_utf8_from_native_byte(*s, &d);
1243 s++;
6940069f
GS
1244 }
1245 *d = '\0';
6662521e 1246 *len = d-dst;
6940069f
GS
1247 return dst;
1248}
1249
a0ed51b3 1250/*
dea0fc0b 1251 * Convert native (big-endian) or reversed (little-endian) UTF-16 to UTF-8.
a0ed51b3
LW
1252 *
1253 * Destination must be pre-extended to 3/2 source. Do not use in-place.
1254 * We optimize for native, for obvious reasons. */
1255
1256U8*
dea0fc0b 1257Perl_utf16_to_utf8(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
a0ed51b3 1258{
dea0fc0b
JH
1259 U8* pend;
1260 U8* dstart = d;
1261
7918f24d
NC
1262 PERL_ARGS_ASSERT_UTF16_TO_UTF8;
1263
dea0fc0b 1264 if (bytelen & 1)
f5992bc4 1265 Perl_croak(aTHX_ "panic: utf16_to_utf8: odd bytelen %"UVuf, (UV)bytelen);
dea0fc0b
JH
1266
1267 pend = p + bytelen;
1268
a0ed51b3 1269 while (p < pend) {
dea0fc0b
JH
1270 UV uv = (p[0] << 8) + p[1]; /* UTF-16BE */
1271 p += 2;
2d1545e5 1272 if (OFFUNI_IS_INVARIANT(uv)) {
56d37426 1273 *d++ = LATIN1_TO_NATIVE((U8) uv);
a0ed51b3
LW
1274 continue;
1275 }
56d37426
KW
1276 if (uv <= MAX_UTF8_TWO_BYTE) {
1277 *d++ = UTF8_TWO_BYTE_HI(UNI_TO_NATIVE(uv));
1278 *d++ = UTF8_TWO_BYTE_LO(UNI_TO_NATIVE(uv));
a0ed51b3
LW
1279 continue;
1280 }
46956fad
KW
1281#define FIRST_HIGH_SURROGATE UNICODE_SURROGATE_FIRST
1282#define LAST_HIGH_SURROGATE 0xDBFF
1283#define FIRST_LOW_SURROGATE 0xDC00
1284#define LAST_LOW_SURROGATE UNICODE_SURROGATE_LAST
e23c50db
KW
1285
1286 /* This assumes that most uses will be in the first Unicode plane, not
1287 * needing surrogates */
1288 if (UNLIKELY(uv >= UNICODE_SURROGATE_FIRST
1289 && uv <= UNICODE_SURROGATE_LAST))
1290 {
1291 if (UNLIKELY(p >= pend) || UNLIKELY(uv > LAST_HIGH_SURROGATE)) {
1292 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1293 }
1294 else {
01ea242b 1295 UV low = (p[0] << 8) + p[1];
e23c50db
KW
1296 if ( UNLIKELY(low < FIRST_LOW_SURROGATE)
1297 || UNLIKELY(low > LAST_LOW_SURROGATE))
1298 {
01ea242b 1299 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
e23c50db
KW
1300 }
1301 p += 2;
46956fad
KW
1302 uv = ((uv - FIRST_HIGH_SURROGATE) << 10)
1303 + (low - FIRST_LOW_SURROGATE) + 0x10000;
01ea242b 1304 }
a0ed51b3 1305 }
56d37426
KW
1306#ifdef EBCDIC
1307 d = uvoffuni_to_utf8_flags(d, uv, 0);
1308#else
a0ed51b3 1309 if (uv < 0x10000) {
eb160463
GS
1310 *d++ = (U8)(( uv >> 12) | 0xe0);
1311 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
1312 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
1313 continue;
1314 }
1315 else {
eb160463
GS
1316 *d++ = (U8)(( uv >> 18) | 0xf0);
1317 *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
1318 *d++ = (U8)(((uv >> 6) & 0x3f) | 0x80);
1319 *d++ = (U8)(( uv & 0x3f) | 0x80);
a0ed51b3
LW
1320 continue;
1321 }
56d37426 1322#endif
a0ed51b3 1323 }
dea0fc0b 1324 *newlen = d - dstart;
a0ed51b3
LW
1325 return d;
1326}
1327
1328/* Note: this one is slightly destructive of the source. */
1329
1330U8*
dea0fc0b 1331Perl_utf16_to_utf8_reversed(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
a0ed51b3
LW
1332{
1333 U8* s = (U8*)p;
d4c19fe8 1334 U8* const send = s + bytelen;
7918f24d
NC
1335
1336 PERL_ARGS_ASSERT_UTF16_TO_UTF8_REVERSED;
1337
e0ea5e2d
NC
1338 if (bytelen & 1)
1339 Perl_croak(aTHX_ "panic: utf16_to_utf8_reversed: odd bytelen %"UVuf,
1340 (UV)bytelen);
1341
a0ed51b3 1342 while (s < send) {
d4c19fe8 1343 const U8 tmp = s[0];
a0ed51b3
LW
1344 s[0] = s[1];
1345 s[1] = tmp;
1346 s += 2;
1347 }
dea0fc0b 1348 return utf16_to_utf8(p, d, bytelen, newlen);
a0ed51b3
LW
1349}
1350
922e8cb4
KW
1351bool
1352Perl__is_uni_FOO(pTHX_ const U8 classnum, const UV c)
1353{
1354 U8 tmpbuf[UTF8_MAXBYTES+1];
1355 uvchr_to_utf8(tmpbuf, c);
1356 return _is_utf8_FOO(classnum, tmpbuf);
1357}
1358
f9ae8fb6
JD
1359/* Internal function so we can deprecate the external one, and call
1360 this one from other deprecated functions in this file */
1361
f2645549
KW
1362bool
1363Perl__is_utf8_idstart(pTHX_ const U8 *p)
61b19385 1364{
f2645549 1365 PERL_ARGS_ASSERT__IS_UTF8_IDSTART;
61b19385
KW
1366
1367 if (*p == '_')
1368 return TRUE;
f25ce844 1369 return is_utf8_common(p, &PL_utf8_idstart, "IdStart", NULL);
61b19385
KW
1370}
1371
5092f92a 1372bool
eba68aa0
KW
1373Perl__is_uni_perl_idcont(pTHX_ UV c)
1374{
1375 U8 tmpbuf[UTF8_MAXBYTES+1];
1376 uvchr_to_utf8(tmpbuf, c);
1377 return _is_utf8_perl_idcont(tmpbuf);
1378}
1379
1380bool
f91dcd13
KW
1381Perl__is_uni_perl_idstart(pTHX_ UV c)
1382{
1383 U8 tmpbuf[UTF8_MAXBYTES+1];
1384 uvchr_to_utf8(tmpbuf, c);
1385 return _is_utf8_perl_idstart(tmpbuf);
1386}
1387
3a4c58c9
KW
1388UV
1389Perl__to_upper_title_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const char S_or_s)
1390{
1391 /* We have the latin1-range values compiled into the core, so just use
4a4088c4 1392 * those, converting the result to UTF-8. The only difference between upper
3a4c58c9
KW
1393 * and title case in this range is that LATIN_SMALL_LETTER_SHARP_S is
1394 * either "SS" or "Ss". Which one to use is passed into the routine in
1395 * 'S_or_s' to avoid a test */
1396
1397 UV converted = toUPPER_LATIN1_MOD(c);
1398
1399 PERL_ARGS_ASSERT__TO_UPPER_TITLE_LATIN1;
1400
1401 assert(S_or_s == 'S' || S_or_s == 's');
1402
6f2d5cbc 1403 if (UVCHR_IS_INVARIANT(converted)) { /* No difference between the two for
f4cd282c 1404 characters in this range */
3a4c58c9
KW
1405 *p = (U8) converted;
1406 *lenp = 1;
1407 return converted;
1408 }
1409
1410 /* toUPPER_LATIN1_MOD gives the correct results except for three outliers,
1411 * which it maps to one of them, so as to only have to have one check for
1412 * it in the main case */
1413 if (UNLIKELY(converted == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
1414 switch (c) {
1415 case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
1416 converted = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
1417 break;
1418 case MICRO_SIGN:
1419 converted = GREEK_CAPITAL_LETTER_MU;
1420 break;
79e064b9
KW
1421#if UNICODE_MAJOR_VERSION > 2 \
1422 || (UNICODE_MAJOR_VERSION == 2 && UNICODE_DOT_VERSION >= 1 \
1423 && UNICODE_DOT_DOT_VERSION >= 8)
3a4c58c9
KW
1424 case LATIN_SMALL_LETTER_SHARP_S:
1425 *(p)++ = 'S';
1426 *p = S_or_s;
1427 *lenp = 2;
1428 return 'S';
79e064b9 1429#endif
3a4c58c9
KW
1430 default:
1431 Perl_croak(aTHX_ "panic: to_upper_title_latin1 did not expect '%c' to map to '%c'", c, LATIN_SMALL_LETTER_Y_WITH_DIAERESIS);
e5964223 1432 NOT_REACHED; /* NOTREACHED */
3a4c58c9
KW
1433 }
1434 }
1435
1436 *(p)++ = UTF8_TWO_BYTE_HI(converted);
1437 *p = UTF8_TWO_BYTE_LO(converted);
1438 *lenp = 2;
1439
1440 return converted;
1441}
1442
50bda2c3
KW
1443/* Call the function to convert a UTF-8 encoded character to the specified case.
1444 * Note that there may be more than one character in the result.
1445 * INP is a pointer to the first byte of the input character
1446 * OUTP will be set to the first byte of the string of changed characters. It
1447 * needs to have space for UTF8_MAXBYTES_CASE+1 bytes
1448 * LENP will be set to the length in bytes of the string of changed characters
1449 *
1450 * The functions return the ordinal of the first character in the string of OUTP */
b9992569
KW
1451#define CALL_UPPER_CASE(uv, s, d, lenp) _to_utf8_case(uv, s, d, lenp, &PL_utf8_toupper, "ToUc", "")
1452#define CALL_TITLE_CASE(uv, s, d, lenp) _to_utf8_case(uv, s, d, lenp, &PL_utf8_totitle, "ToTc", "")
1453#define CALL_LOWER_CASE(uv, s, d, lenp) _to_utf8_case(uv, s, d, lenp, &PL_utf8_tolower, "ToLc", "")
50bda2c3 1454
b9992569
KW
1455/* This additionally has the input parameter 'specials', which if non-zero will
1456 * cause this to use the specials hash for folding (meaning get full case
50bda2c3 1457 * folding); otherwise, when zero, this implies a simple case fold */
b9992569 1458#define CALL_FOLD_CASE(uv, s, d, lenp, specials) _to_utf8_case(uv, s, d, lenp, &PL_utf8_tofold, "ToCf", (specials) ? "" : NULL)
c3fd2246 1459
84afefe6
JH
1460UV
1461Perl_to_uni_upper(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1462{
a1433954
KW
1463 /* Convert the Unicode character whose ordinal is <c> to its uppercase
1464 * version and store that in UTF-8 in <p> and its length in bytes in <lenp>.
1465 * Note that the <p> needs to be at least UTF8_MAXBYTES_CASE+1 bytes since
c3fd2246
KW
1466 * the changed version may be longer than the original character.
1467 *
1468 * The ordinal of the first character of the changed version is returned
1469 * (but note, as explained above, that there may be more.) */
1470
7918f24d
NC
1471 PERL_ARGS_ASSERT_TO_UNI_UPPER;
1472
3a4c58c9
KW
1473 if (c < 256) {
1474 return _to_upper_title_latin1((U8) c, p, lenp, 'S');
1475 }
1476
0ebc6274 1477 uvchr_to_utf8(p, c);
b9992569 1478 return CALL_UPPER_CASE(c, p, p, lenp);
a0ed51b3
LW
1479}
1480
84afefe6
JH
1481UV
1482Perl_to_uni_title(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1483{
7918f24d
NC
1484 PERL_ARGS_ASSERT_TO_UNI_TITLE;
1485
3a4c58c9
KW
1486 if (c < 256) {
1487 return _to_upper_title_latin1((U8) c, p, lenp, 's');
1488 }
1489
0ebc6274 1490 uvchr_to_utf8(p, c);
b9992569 1491 return CALL_TITLE_CASE(c, p, p, lenp);
a0ed51b3
LW
1492}
1493
afc16117 1494STATIC U8
81611534 1495S_to_lower_latin1(const U8 c, U8* p, STRLEN *lenp)
afc16117
KW
1496{
1497 /* We have the latin1-range values compiled into the core, so just use
4a4088c4 1498 * those, converting the result to UTF-8. Since the result is always just
a1433954 1499 * one character, we allow <p> to be NULL */
afc16117
KW
1500
1501 U8 converted = toLOWER_LATIN1(c);
1502
1503 if (p != NULL) {
6f2d5cbc 1504 if (NATIVE_BYTE_IS_INVARIANT(converted)) {
afc16117
KW
1505 *p = converted;
1506 *lenp = 1;
1507 }
1508 else {
430c9760
KW
1509 /* Result is known to always be < 256, so can use the EIGHT_BIT
1510 * macros */
1511 *p = UTF8_EIGHT_BIT_HI(converted);
1512 *(p+1) = UTF8_EIGHT_BIT_LO(converted);
afc16117
KW
1513 *lenp = 2;
1514 }
1515 }
1516 return converted;
1517}
1518
84afefe6
JH
1519UV
1520Perl_to_uni_lower(pTHX_ UV c, U8* p, STRLEN *lenp)
a0ed51b3 1521{
7918f24d
NC
1522 PERL_ARGS_ASSERT_TO_UNI_LOWER;
1523
afc16117
KW
1524 if (c < 256) {
1525 return to_lower_latin1((U8) c, p, lenp);
bca00c02
KW
1526 }
1527
afc16117 1528 uvchr_to_utf8(p, c);
b9992569 1529 return CALL_LOWER_CASE(c, p, p, lenp);
a0ed51b3
LW
1530}
1531
84afefe6 1532UV
51910141 1533Perl__to_fold_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const unsigned int flags)
a1dde8de 1534{
51910141 1535 /* Corresponds to to_lower_latin1(); <flags> bits meanings:
1ca267a5 1536 * FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
51910141 1537 * FOLD_FLAGS_FULL iff full folding is to be used;
1ca267a5
KW
1538 *
1539 * Not to be used for locale folds
51910141 1540 */
f673fad4 1541
a1dde8de
KW
1542 UV converted;
1543
1544 PERL_ARGS_ASSERT__TO_FOLD_LATIN1;
81611534 1545 PERL_UNUSED_CONTEXT;
a1dde8de 1546
1ca267a5
KW
1547 assert (! (flags & FOLD_FLAGS_LOCALE));
1548
659a7c2d 1549 if (UNLIKELY(c == MICRO_SIGN)) {
a1dde8de
KW
1550 converted = GREEK_SMALL_LETTER_MU;
1551 }
9b63e895
KW
1552#if UNICODE_MAJOR_VERSION > 3 /* no multifolds in early Unicode */ \
1553 || (UNICODE_MAJOR_VERSION == 3 && ( UNICODE_DOT_VERSION > 0) \
1554 || UNICODE_DOT_DOT_VERSION > 0)
659a7c2d
KW
1555 else if ( (flags & FOLD_FLAGS_FULL)
1556 && UNLIKELY(c == LATIN_SMALL_LETTER_SHARP_S))
1557 {
1ca267a5
KW
1558 /* If can't cross 127/128 boundary, can't return "ss"; instead return
1559 * two U+017F characters, as fc("\df") should eq fc("\x{17f}\x{17f}")
1560 * under those circumstances. */
1561 if (flags & FOLD_FLAGS_NOMIX_ASCII) {
1562 *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
1563 Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
1564 p, *lenp, U8);
1565 return LATIN_SMALL_LETTER_LONG_S;
1566 }
1567 else {
4f489194
KW
1568 *(p)++ = 's';
1569 *p = 's';
1570 *lenp = 2;
1571 return 's';
1ca267a5 1572 }
a1dde8de 1573 }
9b63e895 1574#endif
a1dde8de
KW
1575 else { /* In this range the fold of all other characters is their lower
1576 case */
1577 converted = toLOWER_LATIN1(c);
1578 }
1579
6f2d5cbc 1580 if (UVCHR_IS_INVARIANT(converted)) {
a1dde8de
KW
1581 *p = (U8) converted;
1582 *lenp = 1;
1583 }
1584 else {
1585 *(p)++ = UTF8_TWO_BYTE_HI(converted);
1586 *p = UTF8_TWO_BYTE_LO(converted);
1587 *lenp = 2;
1588 }
1589
1590 return converted;
1591}
1592
1593UV
31f05a37 1594Perl__to_uni_fold_flags(pTHX_ UV c, U8* p, STRLEN *lenp, U8 flags)
84afefe6 1595{
4b593389 1596
a0270393
KW
1597 /* Not currently externally documented, and subject to change
1598 * <flags> bits meanings:
1599 * FOLD_FLAGS_FULL iff full folding is to be used;
31f05a37
KW
1600 * FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
1601 * locale are to be used.
a0270393
KW
1602 * FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1603 */
4b593389 1604
36bb2ab6 1605 PERL_ARGS_ASSERT__TO_UNI_FOLD_FLAGS;
7918f24d 1606
780fcc9f
KW
1607 if (flags & FOLD_FLAGS_LOCALE) {
1608 /* Treat a UTF-8 locale as not being in locale at all */
1609 if (IN_UTF8_CTYPE_LOCALE) {
1610 flags &= ~FOLD_FLAGS_LOCALE;
1611 }
1612 else {
1613 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
e7b7ac46 1614 goto needs_full_generality;
780fcc9f 1615 }
31f05a37
KW
1616 }
1617
a1dde8de 1618 if (c < 256) {
e7b7ac46 1619 return _to_fold_latin1((U8) c, p, lenp,
31f05a37 1620 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
a1dde8de
KW
1621 }
1622
2f306ab9 1623 /* Here, above 255. If no special needs, just use the macro */
a0270393
KW
1624 if ( ! (flags & (FOLD_FLAGS_LOCALE|FOLD_FLAGS_NOMIX_ASCII))) {
1625 uvchr_to_utf8(p, c);
b9992569 1626 return CALL_FOLD_CASE(c, p, p, lenp, flags & FOLD_FLAGS_FULL);
a0270393
KW
1627 }
1628 else { /* Otherwise, _to_utf8_fold_flags has the intelligence to deal with
1629 the special flags. */
1630 U8 utf8_c[UTF8_MAXBYTES + 1];
e7b7ac46
KW
1631
1632 needs_full_generality:
a0270393 1633 uvchr_to_utf8(utf8_c, c);
445bf929 1634 return _to_utf8_fold_flags(utf8_c, p, lenp, flags);
a0270393 1635 }
84afefe6
JH
1636}
1637
26483009 1638PERL_STATIC_INLINE bool
5141f98e 1639S_is_utf8_common(pTHX_ const U8 *const p, SV **swash,
f25ce844 1640 const char *const swashname, SV* const invlist)
bde6a22d 1641{
ea317ccb
KW
1642 /* returns a boolean giving whether or not the UTF8-encoded character that
1643 * starts at <p> is in the swash indicated by <swashname>. <swash>
1644 * contains a pointer to where the swash indicated by <swashname>
1645 * is to be stored; which this routine will do, so that future calls will
f25ce844
KW
1646 * look at <*swash> and only generate a swash if it is not null. <invlist>
1647 * is NULL or an inversion list that defines the swash. If not null, it
1648 * saves time during initialization of the swash.
ea317ccb
KW
1649 *
1650 * Note that it is assumed that the buffer length of <p> is enough to
1651 * contain all the bytes that comprise the character. Thus, <*p> should
1652 * have been checked before this call for mal-formedness enough to assure
1653 * that. */
1654
7918f24d
NC
1655 PERL_ARGS_ASSERT_IS_UTF8_COMMON;
1656
492a624f 1657 /* The API should have included a length for the UTF-8 character in <p>,
28123549 1658 * but it doesn't. We therefore assume that p has been validated at least
492a624f
KW
1659 * as far as there being enough bytes available in it to accommodate the
1660 * character without reading beyond the end, and pass that number on to the
1661 * validating routine */
6302f837 1662 if (! isUTF8_CHAR(p, p + UTF8SKIP(p))) {
28123549
KW
1663 if (ckWARN_d(WARN_UTF8)) {
1664 Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED,WARN_UTF8),
9816f121 1665 "Passing malformed UTF-8 to \"%s\" is deprecated", swashname);
28123549
KW
1666 if (ckWARN(WARN_UTF8)) { /* This will output details as to the
1667 what the malformation is */
1668 utf8_to_uvchr_buf(p, p + UTF8SKIP(p), NULL);
1669 }
1670 }
1671 return FALSE;
1672 }
87367d5f
KW
1673 if (!*swash) {
1674 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
f25ce844
KW
1675 *swash = _core_swash_init("utf8",
1676
1677 /* Only use the name if there is no inversion
1678 * list; otherwise will go out to disk */
1679 (invlist) ? "" : swashname,
1680
1681 &PL_sv_undef, 1, 0, invlist, &flags);
87367d5f 1682 }
28123549 1683
bde6a22d
NC
1684 return swash_fetch(*swash, p, TRUE) != 0;
1685}
1686
1687bool
922e8cb4
KW
1688Perl__is_utf8_FOO(pTHX_ const U8 classnum, const U8 *p)
1689{
922e8cb4
KW
1690 PERL_ARGS_ASSERT__IS_UTF8_FOO;
1691
1692 assert(classnum < _FIRST_NON_SWASH_CC);
1693
f25ce844
KW
1694 return is_utf8_common(p,
1695 &PL_utf8_swash_ptrs[classnum],
1696 swash_property_names[classnum],
1697 PL_XPosix_ptrs[classnum]);
922e8cb4
KW
1698}
1699
1700bool
f2645549 1701Perl__is_utf8_perl_idstart(pTHX_ const U8 *p)
a0ed51b3 1702{
f2645549 1703 SV* invlist = NULL;
7918f24d 1704
f2645549 1705 PERL_ARGS_ASSERT__IS_UTF8_PERL_IDSTART;
7918f24d 1706
f2645549
KW
1707 if (! PL_utf8_perl_idstart) {
1708 invlist = _new_invlist_C_array(_Perl_IDStart_invlist);
1709 }
60071a22 1710 return is_utf8_common(p, &PL_utf8_perl_idstart, "_Perl_IDStart", invlist);
82686b01
JH
1711}
1712
1713bool
f2645549 1714Perl__is_utf8_xidstart(pTHX_ const U8 *p)
c11ff943 1715{
f2645549 1716 PERL_ARGS_ASSERT__IS_UTF8_XIDSTART;
c11ff943
KW
1717
1718 if (*p == '_')
1719 return TRUE;
f25ce844 1720 return is_utf8_common(p, &PL_utf8_xidstart, "XIdStart", NULL);
c11ff943
KW
1721}
1722
1723bool
eba68aa0
KW
1724Perl__is_utf8_perl_idcont(pTHX_ const U8 *p)
1725{
b24b43f7 1726 SV* invlist = NULL;
eba68aa0
KW
1727
1728 PERL_ARGS_ASSERT__IS_UTF8_PERL_IDCONT;
1729
b24b43f7
KW
1730 if (! PL_utf8_perl_idcont) {
1731 invlist = _new_invlist_C_array(_Perl_IDCont_invlist);
1732 }
60071a22 1733 return is_utf8_common(p, &PL_utf8_perl_idcont, "_Perl_IDCont", invlist);
eba68aa0
KW
1734}
1735
eba68aa0 1736bool
f2645549 1737Perl__is_utf8_idcont(pTHX_ const U8 *p)
82686b01 1738{
f2645549 1739 PERL_ARGS_ASSERT__IS_UTF8_IDCONT;
7918f24d 1740
f25ce844 1741 return is_utf8_common(p, &PL_utf8_idcont, "IdContinue", NULL);
a0ed51b3
LW
1742}
1743
1744bool
f2645549 1745Perl__is_utf8_xidcont(pTHX_ const U8 *p)
c11ff943 1746{
f2645549 1747 PERL_ARGS_ASSERT__IS_UTF8_XIDCONT;
c11ff943 1748
f25ce844 1749 return is_utf8_common(p, &PL_utf8_idcont, "XIdContinue", NULL);
c11ff943
KW
1750}
1751
1752bool
7dbf68d2
KW
1753Perl__is_utf8_mark(pTHX_ const U8 *p)
1754{
7dbf68d2
KW
1755 PERL_ARGS_ASSERT__IS_UTF8_MARK;
1756
f25ce844 1757 return is_utf8_common(p, &PL_utf8_mark, "IsM", NULL);
7dbf68d2
KW
1758}
1759
6b5c0936 1760/*
87cea99e 1761=for apidoc to_utf8_case
6b5c0936 1762
9da1e7cb
KW
1763Instead use the appropriate one of L</toUPPER_utf8>,
1764L</toTITLE_utf8>,
1765L</toLOWER_utf8>,
1766or L</toFOLD_utf8>.
1767
6fae5207 1768C<p> contains the pointer to the UTF-8 string encoding
a1433954
KW
1769the character that is being converted. This routine assumes that the character
1770at C<p> is well-formed.
6b5c0936 1771
6fae5207
KW
1772C<ustrp> is a pointer to the character buffer to put the
1773conversion result to. C<lenp> is a pointer to the length
6b5c0936
JH
1774of the result.
1775
6fae5207 1776C<swashp> is a pointer to the swash to use.
6b5c0936 1777
a1433954 1778Both the special and normal mappings are stored in F<lib/unicore/To/Foo.pl>,
796b6530 1779and loaded by C<SWASHNEW>, using F<lib/utf8_heavy.pl>. C<special> (usually,
0134edef 1780but not always, a multicharacter mapping), is tried first.
6b5c0936 1781
4a8240a3
KW
1782C<special> is a string, normally C<NULL> or C<"">. C<NULL> means to not use
1783any special mappings; C<""> means to use the special mappings. Values other
1784than these two are treated as the name of the hash containing the special
1785mappings, like C<"utf8::ToSpecLower">.
6b5c0936 1786
796b6530
KW
1787C<normal> is a string like C<"ToLower"> which means the swash
1788C<%utf8::ToLower>.
0134edef 1789
760c7c2f
KW
1790Code points above the platform's C<IV_MAX> will raise a deprecation warning,
1791unless those are turned off.
1792
0134edef 1793=cut */
6b5c0936 1794
2104c8d9 1795UV
9a957fbc
AL
1796Perl_to_utf8_case(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp,
1797 SV **swashp, const char *normal, const char *special)
a0ed51b3 1798{
b9992569
KW
1799 PERL_ARGS_ASSERT_TO_UTF8_CASE;
1800
1801 return _to_utf8_case(valid_utf8_to_uvchr(p, NULL), p, ustrp, lenp, swashp, normal, special);
1802}
1803
1804 /* change namve uv1 to 'from' */
6a4a25f4 1805STATIC UV
b9992569
KW
1806S__to_utf8_case(pTHX_ const UV uv1, const U8 *p, U8* ustrp, STRLEN *lenp,
1807 SV **swashp, const char *normal, const char *special)
1808{
0134edef 1809 STRLEN len = 0;
7918f24d 1810
b9992569 1811 PERL_ARGS_ASSERT__TO_UTF8_CASE;
7918f24d 1812
36eaa811
KW
1813 /* For code points that don't change case, we already know that the output
1814 * of this function is the unchanged input, so we can skip doing look-ups
1815 * for them. Unfortunately the case-changing code points are scattered
1816 * around. But there are some long consecutive ranges where there are no
1817 * case changing code points. By adding tests, we can eliminate the lookup
1818 * for all the ones in such ranges. This is currently done here only for
1819 * just a few cases where the scripts are in common use in modern commerce
1820 * (and scripts adjacent to those which can be included without additional
1821 * tests). */
1822
1823 if (uv1 >= 0x0590) {
1824 /* This keeps from needing further processing the code points most
1825 * likely to be used in the following non-cased scripts: Hebrew,
1826 * Arabic, Syriac, Thaana, NKo, Samaritan, Mandaic, Devanagari,
1827 * Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu, Kannada,
1828 * Malayalam, Sinhala, Thai, Lao, Tibetan, Myanmar */
1829 if (uv1 < 0x10A0) {
1830 goto cases_to_self;
1831 }
1832
1833 /* The following largish code point ranges also don't have case
1834 * changes, but khw didn't think they warranted extra tests to speed
1835 * them up (which would slightly slow down everything else above them):
1836 * 1100..139F Hangul Jamo, Ethiopic
1837 * 1400..1CFF Unified Canadian Aboriginal Syllabics, Ogham, Runic,
1838 * Tagalog, Hanunoo, Buhid, Tagbanwa, Khmer, Mongolian,
1839 * Limbu, Tai Le, New Tai Lue, Buginese, Tai Tham,
1840 * Combining Diacritical Marks Extended, Balinese,
1841 * Sundanese, Batak, Lepcha, Ol Chiki
1842 * 2000..206F General Punctuation
1843 */
1844
1845 if (uv1 >= 0x2D30) {
1846
1847 /* This keeps the from needing further processing the code points
1848 * most likely to be used in the following non-cased major scripts:
1849 * CJK, Katakana, Hiragana, plus some less-likely scripts.
1850 *
1851 * (0x2D30 above might have to be changed to 2F00 in the unlikely
1852 * event that Unicode eventually allocates the unused block as of
1853 * v8.0 2FE0..2FEF to code points that are cased. khw has verified
1854 * that the test suite will start having failures to alert you
1855 * should that happen) */
1856 if (uv1 < 0xA640) {
1857 goto cases_to_self;
1858 }
1859
1860 if (uv1 >= 0xAC00) {
1861 if (UNLIKELY(UNICODE_IS_SURROGATE(uv1))) {
5af9bc97
KW
1862 if (ckWARN_d(WARN_SURROGATE)) {
1863 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
1864 Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
1865 "Operation \"%s\" returns its argument for UTF-16 surrogate U+%04"UVXf"", desc, uv1);
1866 }
1867 goto cases_to_self;
1868 }
36eaa811
KW
1869
1870 /* AC00..FAFF Catches Hangul syllables and private use, plus
1871 * some others */
1872 if (uv1 < 0xFB00) {
1873 goto cases_to_self;
1874
1875 }
1876
5af9bc97
KW
1877 if (UNLIKELY(UNICODE_IS_SUPER(uv1))) {
1878 if ( UNLIKELY(uv1 > MAX_NON_DEPRECATED_CP)
1879 && ckWARN_d(WARN_DEPRECATED))
1880 {
1881 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
1882 cp_above_legal_max, uv1, MAX_NON_DEPRECATED_CP);
1883 }
1884 if (ckWARN_d(WARN_NON_UNICODE)) {
1885 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
1886 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
1887 "Operation \"%s\" returns its argument for non-Unicode code point 0x%04"UVXf"", desc, uv1);
1888 }
1889 goto cases_to_self;
1890 }
3bfc1e70
KW
1891#ifdef HIGHEST_CASE_CHANGING_CP_FOR_USE_ONLY_BY_UTF8_DOT_C
1892 if (UNLIKELY(uv1
1893 > HIGHEST_CASE_CHANGING_CP_FOR_USE_ONLY_BY_UTF8_DOT_C))
1894 {
1895
1896 /* As of this writing, this means we avoid swash creation
1897 * for anything beyond low Plane 1 */
1898 goto cases_to_self;
1899 }
1900#endif
36eaa811
KW
1901 }
1902 }
9ae3ac1a 1903
36eaa811
KW
1904 /* Note that non-characters are perfectly legal, so no warning should
1905 * be given. There are so few of them, that it isn't worth the extra
1906 * tests to avoid swash creation */
9ae3ac1a
KW
1907 }
1908
0134edef 1909 if (!*swashp) /* load on-demand */
5ab9d2ef 1910 *swashp = _core_swash_init("utf8", normal, &PL_sv_undef, 4, 0, NULL, NULL);
0134edef 1911
a6f87d8c 1912 if (special) {
0134edef 1913 /* It might be "special" (sometimes, but not always,
2a37f04d 1914 * a multicharacter mapping) */
4a8240a3 1915 HV *hv = NULL;
b08cf34e
JH
1916 SV **svp;
1917
4a8240a3
KW
1918 /* If passed in the specials name, use that; otherwise use any
1919 * given in the swash */
1920 if (*special != '\0') {
1921 hv = get_hv(special, 0);
1922 }
1923 else {
1924 svp = hv_fetchs(MUTABLE_HV(SvRV(*swashp)), "SPECIALS", 0);
1925 if (svp) {
1926 hv = MUTABLE_HV(SvRV(*svp));
1927 }
1928 }
1929
176fe009 1930 if (hv
5f560d8a 1931 && (svp = hv_fetch(hv, (const char*)p, UVCHR_SKIP(uv1), FALSE))
176fe009
KW
1932 && (*svp))
1933 {
cfd0369c 1934 const char *s;
47654450 1935
cfd0369c 1936 s = SvPV_const(*svp, len);
47654450 1937 if (len == 1)
f4cd282c 1938 /* EIGHTBIT */
c80e42f3 1939 len = uvchr_to_utf8(ustrp, *(U8*)s) - ustrp;
2a37f04d 1940 else {
d2dcd0fb 1941 Copy(s, ustrp, len, U8);
29e98929 1942 }
983ffd37 1943 }
0134edef
JH
1944 }
1945
1946 if (!len && *swashp) {
4a4088c4 1947 const UV uv2 = swash_fetch(*swashp, p, TRUE /* => is UTF-8 */);
d4c19fe8 1948
0134edef
JH
1949 if (uv2) {
1950 /* It was "normal" (a single character mapping). */
f4cd282c 1951 len = uvchr_to_utf8(ustrp, uv2) - ustrp;
2a37f04d
JH
1952 }
1953 }
1feea2c7 1954
cbe07460
KW
1955 if (len) {
1956 if (lenp) {
1957 *lenp = len;
1958 }
1959 return valid_utf8_to_uvchr(ustrp, 0);
1960 }
1961
1962 /* Here, there was no mapping defined, which means that the code point maps
1963 * to itself. Return the inputs */
e24dfe9c 1964 cases_to_self:
bfdf22ec 1965 len = UTF8SKIP(p);
ca9fab46
KW
1966 if (p != ustrp) { /* Don't copy onto itself */
1967 Copy(p, ustrp, len, U8);
1968 }
0134edef 1969
2a37f04d
JH
1970 if (lenp)
1971 *lenp = len;
1972
f4cd282c 1973 return uv1;
cbe07460 1974
a0ed51b3
LW
1975}
1976
051a06d4 1977STATIC UV
357aadde 1978S_check_locale_boundary_crossing(pTHX_ const U8* const p, const UV result, U8* const ustrp, STRLEN *lenp)
051a06d4 1979{
4a4088c4 1980 /* This is called when changing the case of a UTF-8-encoded character above
31f05a37
KW
1981 * the Latin1 range, and the operation is in a non-UTF-8 locale. If the
1982 * result contains a character that crosses the 255/256 boundary, disallow
1983 * the change, and return the original code point. See L<perlfunc/lc> for
1984 * why;
051a06d4 1985 *
a1433954
KW
1986 * p points to the original string whose case was changed; assumed
1987 * by this routine to be well-formed
051a06d4
KW
1988 * result the code point of the first character in the changed-case string
1989 * ustrp points to the changed-case string (<result> represents its first char)
1990 * lenp points to the length of <ustrp> */
1991
1992 UV original; /* To store the first code point of <p> */
1993
1994 PERL_ARGS_ASSERT_CHECK_LOCALE_BOUNDARY_CROSSING;
1995
a4f12ed7 1996 assert(UTF8_IS_ABOVE_LATIN1(*p));
051a06d4
KW
1997
1998 /* We know immediately if the first character in the string crosses the
1999 * boundary, so can skip */
2000 if (result > 255) {
2001
2002 /* Look at every character in the result; if any cross the
2003 * boundary, the whole thing is disallowed */
2004 U8* s = ustrp + UTF8SKIP(ustrp);
2005 U8* e = ustrp + *lenp;
2006 while (s < e) {
a4f12ed7 2007 if (! UTF8_IS_ABOVE_LATIN1(*s)) {
051a06d4
KW
2008 goto bad_crossing;
2009 }
2010 s += UTF8SKIP(s);
2011 }
2012
613abc6d
KW
2013 /* Here, no characters crossed, result is ok as-is, but we warn. */
2014 _CHECK_AND_OUTPUT_WIDE_LOCALE_UTF8_MSG(p, p + UTF8SKIP(p));
051a06d4
KW
2015 return result;
2016 }
2017
7b52d656 2018 bad_crossing:
051a06d4
KW
2019
2020 /* Failed, have to return the original */
4b88fb76 2021 original = valid_utf8_to_uvchr(p, lenp);
ab0b796c
KW
2022
2023 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2024 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2025 "Can't do %s(\"\\x{%"UVXf"}\") on non-UTF-8 locale; "
2026 "resolved to \"\\x{%"UVXf"}\".",
357aadde 2027 OP_DESC(PL_op),
ab0b796c
KW
2028 original,
2029 original);
051a06d4
KW
2030 Copy(p, ustrp, *lenp, char);
2031 return original;
2032}
2033
d3e79532 2034/*
87cea99e 2035=for apidoc to_utf8_upper
d3e79532 2036
1f607577 2037Instead use L</toUPPER_utf8>.
a1433954 2038
d3e79532
JH
2039=cut */
2040
051a06d4 2041/* Not currently externally documented, and subject to change:
31f05a37
KW
2042 * <flags> is set iff iff the rules from the current underlying locale are to
2043 * be used. */
051a06d4 2044
2104c8d9 2045UV
31f05a37 2046Perl__to_utf8_upper_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
a0ed51b3 2047{
051a06d4
KW
2048 UV result;
2049
2050 PERL_ARGS_ASSERT__TO_UTF8_UPPER_FLAGS;
7918f24d 2051
780fcc9f
KW
2052 if (flags) {
2053 /* Treat a UTF-8 locale as not being in locale at all */
2054 if (IN_UTF8_CTYPE_LOCALE) {
2055 flags = FALSE;
2056 }
2057 else {
2058 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2059 }
31f05a37
KW
2060 }
2061
3a4c58c9 2062 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2063 if (flags) {
2064 result = toUPPER_LC(*p);
2065 }
2066 else {
81c6c7ce 2067 return _to_upper_title_latin1(*p, ustrp, lenp, 'S');
051a06d4 2068 }
3a4c58c9
KW
2069 }
2070 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2071 if (flags) {
a62b247b 2072 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2073 result = toUPPER_LC(c);
051a06d4
KW
2074 }
2075 else {
a62b247b 2076 return _to_upper_title_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2077 ustrp, lenp, 'S');
051a06d4
KW
2078 }
2079 }
4a4088c4 2080 else { /* UTF-8, ord above 255 */
b9992569 2081 result = CALL_UPPER_CASE(valid_utf8_to_uvchr(p, NULL), p, ustrp, lenp);
051a06d4
KW
2082
2083 if (flags) {
357aadde 2084 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4
KW
2085 }
2086 return result;
2087 }
2088
4a4088c4 2089 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2090 if (UTF8_IS_INVARIANT(result)) {
2091 *ustrp = (U8) result;
2092 *lenp = 1;
2093 }
2094 else {
62cb07ea
KW
2095 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2096 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4 2097 *lenp = 2;
3a4c58c9 2098 }
baa60164 2099
051a06d4 2100 return result;
983ffd37 2101}
a0ed51b3 2102
d3e79532 2103/*
87cea99e 2104=for apidoc to_utf8_title
d3e79532 2105
1f607577 2106Instead use L</toTITLE_utf8>.
a1433954 2107
d3e79532
JH
2108=cut */
2109
051a06d4 2110/* Not currently externally documented, and subject to change:
31f05a37
KW
2111 * <flags> is set iff the rules from the current underlying locale are to be
2112 * used. Since titlecase is not defined in POSIX, for other than a
2113 * UTF-8 locale, uppercase is used instead for code points < 256.
445bf929 2114 */
051a06d4 2115
983ffd37 2116UV
31f05a37 2117Perl__to_utf8_title_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
983ffd37 2118{
051a06d4
KW
2119 UV result;
2120
2121 PERL_ARGS_ASSERT__TO_UTF8_TITLE_FLAGS;
7918f24d 2122
780fcc9f
KW
2123 if (flags) {
2124 /* Treat a UTF-8 locale as not being in locale at all */
2125 if (IN_UTF8_CTYPE_LOCALE) {
2126 flags = FALSE;
2127 }
2128 else {
2129 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2130 }
31f05a37
KW
2131 }
2132
3a4c58c9 2133 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2134 if (flags) {
2135 result = toUPPER_LC(*p);
2136 }
2137 else {
81c6c7ce 2138 return _to_upper_title_latin1(*p, ustrp, lenp, 's');
051a06d4 2139 }
3a4c58c9
KW
2140 }
2141 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2142 if (flags) {
a62b247b 2143 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2144 result = toUPPER_LC(c);
051a06d4
KW
2145 }
2146 else {
a62b247b 2147 return _to_upper_title_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2148 ustrp, lenp, 's');
051a06d4
KW
2149 }
2150 }
4a4088c4 2151 else { /* UTF-8, ord above 255 */
b9992569 2152 result = CALL_TITLE_CASE(valid_utf8_to_uvchr(p, NULL), p, ustrp, lenp);
051a06d4
KW
2153
2154 if (flags) {
357aadde 2155 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4
KW
2156 }
2157 return result;
2158 }
2159
4a4088c4 2160 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2161 if (UTF8_IS_INVARIANT(result)) {
2162 *ustrp = (U8) result;
2163 *lenp = 1;
2164 }
2165 else {
62cb07ea
KW
2166 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2167 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4 2168 *lenp = 2;
3a4c58c9
KW
2169 }
2170
051a06d4 2171 return result;
a0ed51b3
LW
2172}
2173
d3e79532 2174/*
87cea99e 2175=for apidoc to_utf8_lower
d3e79532 2176
1f607577 2177Instead use L</toLOWER_utf8>.
a1433954 2178
d3e79532
JH
2179=cut */
2180
051a06d4 2181/* Not currently externally documented, and subject to change:
31f05a37
KW
2182 * <flags> is set iff iff the rules from the current underlying locale are to
2183 * be used.
2184 */
051a06d4 2185
2104c8d9 2186UV
31f05a37 2187Perl__to_utf8_lower_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, bool flags)
a0ed51b3 2188{
051a06d4
KW
2189 UV result;
2190
051a06d4 2191 PERL_ARGS_ASSERT__TO_UTF8_LOWER_FLAGS;
7918f24d 2192
780fcc9f
KW
2193 if (flags) {
2194 /* Treat a UTF-8 locale as not being in locale at all */
2195 if (IN_UTF8_CTYPE_LOCALE) {
2196 flags = FALSE;
2197 }
2198 else {
2199 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2200 }
31f05a37
KW
2201 }
2202
968c5e6a 2203 if (UTF8_IS_INVARIANT(*p)) {
051a06d4
KW
2204 if (flags) {
2205 result = toLOWER_LC(*p);
2206 }
2207 else {
81c6c7ce 2208 return to_lower_latin1(*p, ustrp, lenp);
051a06d4 2209 }
968c5e6a
KW
2210 }
2211 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2212 if (flags) {
a62b247b 2213 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2214 result = toLOWER_LC(c);
051a06d4
KW
2215 }
2216 else {
a62b247b 2217 return to_lower_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
81c6c7ce 2218 ustrp, lenp);
051a06d4 2219 }
968c5e6a 2220 }
4a4088c4 2221 else { /* UTF-8, ord above 255 */
b9992569 2222 result = CALL_LOWER_CASE(valid_utf8_to_uvchr(p, NULL), p, ustrp, lenp);
051a06d4
KW
2223
2224 if (flags) {
357aadde 2225 result = check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4 2226 }
968c5e6a 2227
051a06d4
KW
2228 return result;
2229 }
2230
4a4088c4 2231 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2232 if (UTF8_IS_INVARIANT(result)) {
2233 *ustrp = (U8) result;
2234 *lenp = 1;
2235 }
2236 else {
62cb07ea
KW
2237 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2238 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4
KW
2239 *lenp = 2;
2240 }
2241
051a06d4 2242 return result;
b4e400f9
JH
2243}
2244
d3e79532 2245/*
87cea99e 2246=for apidoc to_utf8_fold
d3e79532 2247
1f607577 2248Instead use L</toFOLD_utf8>.
a1433954 2249
d3e79532
JH
2250=cut */
2251
051a06d4
KW
2252/* Not currently externally documented, and subject to change,
2253 * in <flags>
31f05a37
KW
2254 * bit FOLD_FLAGS_LOCALE is set iff the rules from the current underlying
2255 * locale are to be used.
051a06d4
KW
2256 * bit FOLD_FLAGS_FULL is set iff full case folds are to be used;
2257 * otherwise simple folds
a0270393
KW
2258 * bit FOLD_FLAGS_NOMIX_ASCII is set iff folds of non-ASCII to ASCII are
2259 * prohibited
445bf929 2260 */
36bb2ab6 2261
b4e400f9 2262UV
445bf929 2263Perl__to_utf8_fold_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, U8 flags)
b4e400f9 2264{
051a06d4
KW
2265 UV result;
2266
36bb2ab6 2267 PERL_ARGS_ASSERT__TO_UTF8_FOLD_FLAGS;
7918f24d 2268
a0270393
KW
2269 /* These are mutually exclusive */
2270 assert (! ((flags & FOLD_FLAGS_LOCALE) && (flags & FOLD_FLAGS_NOMIX_ASCII)));
2271
50ba90ff
KW
2272 assert(p != ustrp); /* Otherwise overwrites */
2273
780fcc9f
KW
2274 if (flags & FOLD_FLAGS_LOCALE) {
2275 /* Treat a UTF-8 locale as not being in locale at all */
2276 if (IN_UTF8_CTYPE_LOCALE) {
2277 flags &= ~FOLD_FLAGS_LOCALE;
2278 }
2279 else {
2280 _CHECK_AND_WARN_PROBLEMATIC_LOCALE;
2281 }
31f05a37
KW
2282 }
2283
a1dde8de 2284 if (UTF8_IS_INVARIANT(*p)) {
051a06d4 2285 if (flags & FOLD_FLAGS_LOCALE) {
d22b930b 2286 result = toFOLD_LC(*p);
051a06d4
KW
2287 }
2288 else {
81c6c7ce 2289 return _to_fold_latin1(*p, ustrp, lenp,
1ca267a5 2290 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
051a06d4 2291 }
a1dde8de
KW
2292 }
2293 else if UTF8_IS_DOWNGRADEABLE_START(*p) {
051a06d4 2294 if (flags & FOLD_FLAGS_LOCALE) {
a62b247b 2295 U8 c = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
68067e4e 2296 result = toFOLD_LC(c);
051a06d4
KW
2297 }
2298 else {
a62b247b 2299 return _to_fold_latin1(EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1)),
51910141 2300 ustrp, lenp,
1ca267a5 2301 flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
051a06d4 2302 }
a1dde8de 2303 }
4a4088c4 2304 else { /* UTF-8, ord above 255 */
b9992569 2305 result = CALL_FOLD_CASE(valid_utf8_to_uvchr(p, NULL), p, ustrp, lenp, flags & FOLD_FLAGS_FULL);
a1dde8de 2306
1ca267a5
KW
2307 if (flags & FOLD_FLAGS_LOCALE) {
2308
76f2ffcd 2309# define LONG_S_T LATIN_SMALL_LIGATURE_LONG_S_T_UTF8
0766489e
KW
2310 const unsigned int long_s_t_len = sizeof(LONG_S_T) - 1;
2311
2312# ifdef LATIN_CAPITAL_LETTER_SHARP_S_UTF8
2313# define CAP_SHARP_S LATIN_CAPITAL_LETTER_SHARP_S_UTF8
76f2ffcd
KW
2314
2315 const unsigned int cap_sharp_s_len = sizeof(CAP_SHARP_S) - 1;
76f2ffcd 2316
538e84ed
KW
2317 /* Special case these two characters, as what normally gets
2318 * returned under locale doesn't work */
76f2ffcd
KW
2319 if (UTF8SKIP(p) == cap_sharp_s_len
2320 && memEQ((char *) p, CAP_SHARP_S, cap_sharp_s_len))
1ca267a5 2321 {
ab0b796c
KW
2322 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2323 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2324 "Can't do fc(\"\\x{1E9E}\") on non-UTF-8 locale; "
2325 "resolved to \"\\x{17F}\\x{17F}\".");
1ca267a5
KW
2326 goto return_long_s;
2327 }
0766489e
KW
2328 else
2329#endif
2330 if (UTF8SKIP(p) == long_s_t_len
76f2ffcd 2331 && memEQ((char *) p, LONG_S_T, long_s_t_len))
9fc2026f 2332 {
ab0b796c
KW
2333 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2334 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2335 "Can't do fc(\"\\x{FB05}\") on non-UTF-8 locale; "
2336 "resolved to \"\\x{FB06}\".");
9fc2026f
KW
2337 goto return_ligature_st;
2338 }
74894415
KW
2339
2340#if UNICODE_MAJOR_VERSION == 3 \
2341 && UNICODE_DOT_VERSION == 0 \
2342 && UNICODE_DOT_DOT_VERSION == 1
2343# define DOTTED_I LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE_UTF8
2344
2345 /* And special case this on this Unicode version only, for the same
2346 * reaons the other two are special cased. They would cross the
2347 * 255/256 boundary which is forbidden under /l, and so the code
2348 * wouldn't catch that they are equivalent (which they are only in
2349 * this release) */
2350 else if (UTF8SKIP(p) == sizeof(DOTTED_I) - 1
2351 && memEQ((char *) p, DOTTED_I, sizeof(DOTTED_I) - 1))
2352 {
2353 /* diag_listed_as: Can't do %s("%s") on non-UTF-8 locale; resolved to "%s". */
2354 Perl_ck_warner(aTHX_ packWARN(WARN_LOCALE),
2355 "Can't do fc(\"\\x{0130}\") on non-UTF-8 locale; "
2356 "resolved to \"\\x{0131}\".");
2357 goto return_dotless_i;
2358 }
2359#endif
2360
357aadde 2361 return check_locale_boundary_crossing(p, result, ustrp, lenp);
051a06d4 2362 }
a0270393
KW
2363 else if (! (flags & FOLD_FLAGS_NOMIX_ASCII)) {
2364 return result;
2365 }
2366 else {
4a4088c4 2367 /* This is called when changing the case of a UTF-8-encoded
9fc2026f
KW
2368 * character above the ASCII range, and the result should not
2369 * contain an ASCII character. */
a0270393
KW
2370
2371 UV original; /* To store the first code point of <p> */
2372
2373 /* Look at every character in the result; if any cross the
2374 * boundary, the whole thing is disallowed */
2375 U8* s = ustrp;
2376 U8* e = ustrp + *lenp;
2377 while (s < e) {
2378 if (isASCII(*s)) {
2379 /* Crossed, have to return the original */
2380 original = valid_utf8_to_uvchr(p, lenp);
1ca267a5 2381
9fc2026f 2382 /* But in these instances, there is an alternative we can
1ca267a5 2383 * return that is valid */
0766489e
KW
2384 if (original == LATIN_SMALL_LETTER_SHARP_S
2385#ifdef LATIN_CAPITAL_LETTER_SHARP_S /* not defined in early Unicode releases */
2386 || original == LATIN_CAPITAL_LETTER_SHARP_S
2387#endif
2388 ) {
1ca267a5
KW
2389 goto return_long_s;
2390 }
9fc2026f
KW
2391 else if (original == LATIN_SMALL_LIGATURE_LONG_S_T) {
2392 goto return_ligature_st;
2393 }
74894415
KW
2394#if UNICODE_MAJOR_VERSION == 3 \
2395 && UNICODE_DOT_VERSION == 0 \
2396 && UNICODE_DOT_DOT_VERSION == 1
2397
2398 else if (original == LATIN_CAPITAL_LETTER_I_WITH_DOT_ABOVE) {
2399 goto return_dotless_i;
2400 }
2401#endif
a0270393
KW
2402 Copy(p, ustrp, *lenp, char);
2403 return original;
2404 }
2405 s += UTF8SKIP(s);
2406 }
051a06d4 2407
a0270393
KW
2408 /* Here, no characters crossed, result is ok as-is */
2409 return result;
2410 }
051a06d4
KW
2411 }
2412
4a4088c4 2413 /* Here, used locale rules. Convert back to UTF-8 */
051a06d4
KW
2414 if (UTF8_IS_INVARIANT(result)) {
2415 *ustrp = (U8) result;
2416 *lenp = 1;
2417 }
2418 else {
62cb07ea
KW
2419 *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2420 *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
051a06d4
KW
2421 *lenp = 2;
2422 }
2423
051a06d4 2424 return result;
1ca267a5
KW
2425
2426 return_long_s:
2427 /* Certain folds to 'ss' are prohibited by the options, but they do allow
2428 * folds to a string of two of these characters. By returning this
2429 * instead, then, e.g.,
2430 * fc("\x{1E9E}") eq fc("\x{17F}\x{17F}")
2431 * works. */
2432
2433 *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
2434 Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
2435 ustrp, *lenp, U8);
2436 return LATIN_SMALL_LETTER_LONG_S;
9fc2026f
KW
2437
2438 return_ligature_st:
2439 /* Two folds to 'st' are prohibited by the options; instead we pick one and
2440 * have the other one fold to it */
2441
2442 *lenp = sizeof(LATIN_SMALL_LIGATURE_ST_UTF8) - 1;
2443 Copy(LATIN_SMALL_LIGATURE_ST_UTF8, ustrp, *lenp, U8);
2444 return LATIN_SMALL_LIGATURE_ST;
74894415
KW
2445
2446#if UNICODE_MAJOR_VERSION == 3 \
2447 && UNICODE_DOT_VERSION == 0 \
2448 && UNICODE_DOT_DOT_VERSION == 1
2449
2450 return_dotless_i:
2451 *lenp = sizeof(LATIN_SMALL_LETTER_DOTLESS_I_UTF8) - 1;
2452 Copy(LATIN_SMALL_LETTER_DOTLESS_I_UTF8, ustrp, *lenp, U8);
2453 return LATIN_SMALL_LETTER_DOTLESS_I;
2454
2455#endif
2456
a0ed51b3
LW
2457}
2458
711a919c 2459/* Note:
f90a9a02 2460 * Returns a "swash" which is a hash described in utf8.c:Perl_swash_fetch().
711a919c
ST
2461 * C<pkg> is a pointer to a package name for SWASHNEW, should be "utf8".
2462 * For other parameters, see utf8::SWASHNEW in lib/utf8_heavy.pl.
2463 */
c4a5db0c 2464
a0ed51b3 2465SV*
7fc63493 2466Perl_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none)
a0ed51b3 2467{
c4a5db0c
KW
2468 PERL_ARGS_ASSERT_SWASH_INIT;
2469
2470 /* Returns a copy of a swash initiated by the called function. This is the
2471 * public interface, and returning a copy prevents others from doing
2472 * mischief on the original */
2473
5d3d13d1 2474 return newSVsv(_core_swash_init(pkg, name, listsv, minbits, none, NULL, NULL));
c4a5db0c
KW
2475}
2476
2477SV*
5d3d13d1 2478Perl__core_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none, SV* invlist, U8* const flags_p)
c4a5db0c 2479{
2c1f00b9
YO
2480
2481 /*NOTE NOTE NOTE - If you want to use "return" in this routine you MUST
2482 * use the following define */
2483
2484#define CORE_SWASH_INIT_RETURN(x) \
2485 PL_curpm= old_PL_curpm; \
2486 return x
2487
c4a5db0c 2488 /* Initialize and return a swash, creating it if necessary. It does this
87367d5f
KW
2489 * by calling utf8_heavy.pl in the general case. The returned value may be
2490 * the swash's inversion list instead if the input parameters allow it.
2491 * Which is returned should be immaterial to callers, as the only
923b6d4e
KW
2492 * operations permitted on a swash, swash_fetch(), _get_swash_invlist(),
2493 * and swash_to_invlist() handle both these transparently.
c4a5db0c
KW
2494 *
2495 * This interface should only be used by functions that won't destroy or
2496 * adversely change the swash, as doing so affects all other uses of the
2497 * swash in the program; the general public should use 'Perl_swash_init'
2498 * instead.
2499 *
2500 * pkg is the name of the package that <name> should be in.
2501 * name is the name of the swash to find. Typically it is a Unicode
2502 * property name, including user-defined ones
2503 * listsv is a string to initialize the swash with. It must be of the form
2504 * documented as the subroutine return value in
2505 * L<perlunicode/User-Defined Character Properties>
2506 * minbits is the number of bits required to represent each data element.
2507 * It is '1' for binary properties.
2508 * none I (khw) do not understand this one, but it is used only in tr///.
9a53f6cf 2509 * invlist is an inversion list to initialize the swash with (or NULL)
83199d38
KW
2510 * flags_p if non-NULL is the address of various input and output flag bits
2511 * to the routine, as follows: ('I' means is input to the routine;
2512 * 'O' means output from the routine. Only flags marked O are
2513 * meaningful on return.)
2514 * _CORE_SWASH_INIT_USER_DEFINED_PROPERTY indicates if the swash
2515 * came from a user-defined property. (I O)
5d3d13d1
KW
2516 * _CORE_SWASH_INIT_RETURN_IF_UNDEF indicates that instead of croaking
2517 * when the swash cannot be located, to simply return NULL. (I)
87367d5f
KW
2518 * _CORE_SWASH_INIT_ACCEPT_INVLIST indicates that the caller will accept a
2519 * return of an inversion list instead of a swash hash if this routine
2520 * thinks that would result in faster execution of swash_fetch() later
2521 * on. (I)
9a53f6cf
KW
2522 *
2523 * Thus there are three possible inputs to find the swash: <name>,
2524 * <listsv>, and <invlist>. At least one must be specified. The result
2525 * will be the union of the specified ones, although <listsv>'s various
aabbdbda
KW
2526 * actions can intersect, etc. what <name> gives. To avoid going out to
2527 * disk at all, <invlist> should specify completely what the swash should
2528 * have, and <listsv> should be &PL_sv_undef and <name> should be "".
9a53f6cf
KW
2529 *
2530 * <invlist> is only valid for binary properties */
c4a5db0c 2531
2c1f00b9
YO
2532 PMOP *old_PL_curpm= PL_curpm; /* save away the old PL_curpm */
2533
c4a5db0c 2534 SV* retval = &PL_sv_undef;
83199d38 2535 HV* swash_hv = NULL;
87367d5f
KW
2536 const int invlist_swash_boundary =
2537 (flags_p && *flags_p & _CORE_SWASH_INIT_ACCEPT_INVLIST)
2538 ? 512 /* Based on some benchmarking, but not extensive, see commit
2539 message */
2540 : -1; /* Never return just an inversion list */
9a53f6cf
KW
2541
2542 assert(listsv != &PL_sv_undef || strNE(name, "") || invlist);
2543 assert(! invlist || minbits == 1);
2544
2c1f00b9
YO
2545 PL_curpm= NULL; /* reset PL_curpm so that we dont get confused between the regex
2546 that triggered the swash init and the swash init perl logic itself.
2547 See perl #122747 */
2548
9a53f6cf
KW
2549 /* If data was passed in to go out to utf8_heavy to find the swash of, do
2550 * so */
2551 if (listsv != &PL_sv_undef || strNE(name, "")) {
69794297
KW
2552 dSP;
2553 const size_t pkg_len = strlen(pkg);
2554 const size_t name_len = strlen(name);
2555 HV * const stash = gv_stashpvn(pkg, pkg_len, 0);
2556 SV* errsv_save;
2557 GV *method;
2558
2559 PERL_ARGS_ASSERT__CORE_SWASH_INIT;
2560
2561 PUSHSTACKi(PERLSI_MAGIC);
ce3b816e 2562 ENTER;
69794297 2563 SAVEHINTS();
2782061f 2564 save_re_context();
650f067c
JL
2565 /* We might get here via a subroutine signature which uses a utf8
2566 * parameter name, at which point PL_subname will have been set
2567 * but not yet used. */
2568 save_item(PL_subname);
69794297
KW
2569 if (PL_parser && PL_parser->error_count)
2570 SAVEI8(PL_parser->error_count), PL_parser->error_count = 0;
2571 method = gv_fetchmeth(stash, "SWASHNEW", 8, -1);
4a4088c4 2572 if (!method) { /* demand load UTF-8 */
69794297 2573 ENTER;
db2c6cb3
FC
2574 if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2575 GvSV(PL_errgv) = NULL;
1a419e6b 2576#ifndef NO_TAINT_SUPPORT
69794297
KW
2577 /* It is assumed that callers of this routine are not passing in
2578 * any user derived data. */
2782061f
DM
2579 /* Need to do this after save_re_context() as it will set
2580 * PL_tainted to 1 while saving $1 etc (see the code after getrx:
2581 * in Perl_magic_get). Even line to create errsv_save can turn on
2582 * PL_tainted. */
284167a5
SM
2583 SAVEBOOL(TAINT_get);
2584 TAINT_NOT;
2585#endif
69794297
KW
2586 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, newSVpvn(pkg,pkg_len),
2587 NULL);
eed484f9 2588 {
db2c6cb3
FC
2589 /* Not ERRSV, as there is no need to vivify a scalar we are
2590 about to discard. */
2591 SV * const errsv = GvSV(PL_errgv);
2592 if (!SvTRUE(errsv)) {
2593 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2594 SvREFCNT_dec(errsv);
2595 }
eed484f9 2596 }
69794297
KW
2597 LEAVE;
2598 }
2599 SPAGAIN;
2600 PUSHMARK(SP);
2601 EXTEND(SP,5);
2602 mPUSHp(pkg, pkg_len);
2603 mPUSHp(name, name_len);
2604 PUSHs(listsv);
2605 mPUSHi(minbits);
2606 mPUSHi(none);
2607 PUTBACK;
db2c6cb3
FC
2608 if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2609 GvSV(PL_errgv) = NULL;
69794297
KW
2610 /* If we already have a pointer to the method, no need to use
2611 * call_method() to repeat the lookup. */
c41800a8
KW
2612 if (method
2613 ? call_sv(MUTABLE_SV(method), G_SCALAR)
69794297
KW
2614 : call_sv(newSVpvs_flags("SWASHNEW", SVs_TEMP), G_SCALAR | G_METHOD))
2615 {
2616 retval = *PL_stack_sp--;
2617 SvREFCNT_inc(retval);
2618 }
eed484f9 2619 {
db2c6cb3
FC
2620 /* Not ERRSV. See above. */
2621 SV * const errsv = GvSV(PL_errgv);
2622 if (!SvTRUE(errsv)) {
2623 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2624 SvREFCNT_dec(errsv);
2625 }
eed484f9 2626 }
ce3b816e 2627 LEAVE;
69794297
KW
2628 POPSTACK;
2629 if (IN_PERL_COMPILETIME) {
2630 CopHINTS_set(PL_curcop, PL_hints);
2631 }
2632 if (!SvROK(retval) || SvTYPE(SvRV(retval)) != SVt_PVHV) {
d95e4a00 2633 if (SvPOK(retval)) {
69794297
KW
2634
2635 /* If caller wants to handle missing properties, let them */
5d3d13d1 2636 if (flags_p && *flags_p & _CORE_SWASH_INIT_RETURN_IF_UNDEF) {
2c1f00b9 2637 CORE_SWASH_INIT_RETURN(NULL);
69794297
KW
2638 }
2639 Perl_croak(aTHX_
2640 "Can't find Unicode property definition \"%"SVf"\"",
2641 SVfARG(retval));
a25b5927 2642 NOT_REACHED; /* NOTREACHED */
d95e4a00 2643 }
69794297 2644 }
9a53f6cf 2645 } /* End of calling the module to find the swash */
36eb48b4 2646
83199d38
KW
2647 /* If this operation fetched a swash, and we will need it later, get it */
2648 if (retval != &PL_sv_undef
2649 && (minbits == 1 || (flags_p
2650 && ! (*flags_p
2651 & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY))))
2652 {
2653 swash_hv = MUTABLE_HV(SvRV(retval));
2654
2655 /* If we don't already know that there is a user-defined component to
2656 * this swash, and the user has indicated they wish to know if there is
2657 * one (by passing <flags_p>), find out */
2658 if (flags_p && ! (*flags_p & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)) {
2659 SV** user_defined = hv_fetchs(swash_hv, "USER_DEFINED", FALSE);
2660 if (user_defined && SvUV(*user_defined)) {
2661 *flags_p |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
2662 }
2663 }
2664 }
2665
36eb48b4
KW
2666 /* Make sure there is an inversion list for binary properties */
2667 if (minbits == 1) {
2668 SV** swash_invlistsvp = NULL;
2669 SV* swash_invlist = NULL;
9a53f6cf 2670 bool invlist_in_swash_is_valid = FALSE;
02c85471
FC
2671 bool swash_invlist_unclaimed = FALSE; /* whether swash_invlist has
2672 an unclaimed reference count */
36eb48b4 2673
9a53f6cf 2674 /* If this operation fetched a swash, get its already existing
83199d38 2675 * inversion list, or create one for it */
36eb48b4 2676
83199d38 2677 if (swash_hv) {
5c9f4bd2 2678 swash_invlistsvp = hv_fetchs(swash_hv, "V", FALSE);
9a53f6cf
KW
2679 if (swash_invlistsvp) {
2680 swash_invlist = *swash_invlistsvp;
2681 invlist_in_swash_is_valid = TRUE;
2682 }
2683 else {
36eb48b4 2684 swash_invlist = _swash_to_invlist(retval);
02c85471 2685 swash_invlist_unclaimed = TRUE;
9a53f6cf
KW
2686 }
2687 }
2688
2689 /* If an inversion list was passed in, have to include it */
2690 if (invlist) {
2691
2692 /* Any fetched swash will by now have an inversion list in it;
2693 * otherwise <swash_invlist> will be NULL, indicating that we
2694 * didn't fetch a swash */
2695 if (swash_invlist) {
2696
2697 /* Add the passed-in inversion list, which invalidates the one
2698 * already stored in the swash */
2699 invlist_in_swash_is_valid = FALSE;
2700 _invlist_union(invlist, swash_invlist, &swash_invlist);
2701 }
2702 else {
2703
87367d5f
KW
2704 /* Here, there is no swash already. Set up a minimal one, if
2705 * we are going to return a swash */
2706 if ((int) _invlist_len(invlist) > invlist_swash_boundary) {
971d486f 2707 swash_hv = newHV();
4aca0fe6 2708 retval = newRV_noinc(MUTABLE_SV(swash_hv));
87367d5f 2709 }
9a53f6cf
KW
2710 swash_invlist = invlist;
2711 }
9a53f6cf
KW
2712 }
2713
2714 /* Here, we have computed the union of all the passed-in data. It may
2715 * be that there was an inversion list in the swash which didn't get
538e84ed 2716 * touched; otherwise save the computed one */
87367d5f
KW
2717 if (! invlist_in_swash_is_valid
2718 && (int) _invlist_len(swash_invlist) > invlist_swash_boundary)
2719 {
5c9f4bd2 2720 if (! hv_stores(MUTABLE_HV(SvRV(retval)), "V", swash_invlist))
69794297
KW
2721 {
2722 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
2723 }
cc34d8c5
FC
2724 /* We just stole a reference count. */
2725 if (swash_invlist_unclaimed) swash_invlist_unclaimed = FALSE;
2726 else SvREFCNT_inc_simple_void_NN(swash_invlist);
9a53f6cf 2727 }
87367d5f 2728
dbfdbd26
KW
2729 SvREADONLY_on(swash_invlist);
2730
c41800a8 2731 /* Use the inversion list stand-alone if small enough */
87367d5f
KW
2732 if ((int) _invlist_len(swash_invlist) <= invlist_swash_boundary) {
2733 SvREFCNT_dec(retval);
02c85471
FC
2734 if (!swash_invlist_unclaimed)
2735 SvREFCNT_inc_simple_void_NN(swash_invlist);
2736 retval = newRV_noinc(swash_invlist);
87367d5f 2737 }
36eb48b4
KW
2738 }
2739
2c1f00b9
YO
2740 CORE_SWASH_INIT_RETURN(retval);
2741#undef CORE_SWASH_INIT_RETURN
a0ed51b3
LW
2742}
2743
035d37be
JH
2744
2745/* This API is wrong for special case conversions since we may need to
2746 * return several Unicode characters for a single Unicode character
2747 * (see lib/unicore/SpecCase.txt) The SWASHGET in lib/utf8_heavy.pl is
2748 * the lower-level routine, and it is similarly broken for returning
38684baa 2749 * multiple values. --jhi
b9992569 2750 * For those, you should use S__to_utf8_case() instead */
b0e3252e 2751/* Now SWASHGET is recasted into S_swatch_get in this file. */
680c470c
ST
2752
2753/* Note:
2754 * Returns the value of property/mapping C<swash> for the first character
2755 * of the string C<ptr>. If C<do_utf8> is true, the string C<ptr> is
4a4088c4 2756 * assumed to be in well-formed UTF-8. If C<do_utf8> is false, the string C<ptr>
3d0f8846 2757 * is assumed to be in native 8-bit encoding. Caches the swatch in C<swash>.
af2af982
KW
2758 *
2759 * A "swash" is a hash which contains initially the keys/values set up by
2760 * SWASHNEW. The purpose is to be able to completely represent a Unicode
2761 * property for all possible code points. Things are stored in a compact form
2762 * (see utf8_heavy.pl) so that calculation is required to find the actual
2763 * property value for a given code point. As code points are looked up, new
2764 * key/value pairs are added to the hash, so that the calculation doesn't have
2765 * to ever be re-done. Further, each calculation is done, not just for the
2766 * desired one, but for a whole block of code points adjacent to that one.
2767 * For binary properties on ASCII machines, the block is usually for 64 code
2768 * points, starting with a code point evenly divisible by 64. Thus if the
2769 * property value for code point 257 is requested, the code goes out and
2770 * calculates the property values for all 64 code points between 256 and 319,
2771 * and stores these as a single 64-bit long bit vector, called a "swatch",
2772 * under the key for code point 256. The key is the UTF-8 encoding for code
2773 * point 256, minus the final byte. Thus, if the length of the UTF-8 encoding
2774 * for a code point is 13 bytes, the key will be 12 bytes long. If the value
2775 * for code point 258 is then requested, this code realizes that it would be
2776 * stored under the key for 256, and would find that value and extract the
2777 * relevant bit, offset from 256.
2778 *
2779 * Non-binary properties are stored in as many bits as necessary to represent
2780 * their values (32 currently, though the code is more general than that), not
fc273927 2781 * as single bits, but the principle is the same: the value for each key is a
af2af982
KW
2782 * vector that encompasses the property values for all code points whose UTF-8
2783 * representations are represented by the key. That is, for all code points
2784 * whose UTF-8 representations are length N bytes, and the key is the first N-1
2785 * bytes of that.
680c470c 2786 */
a0ed51b3 2787UV
680c470c 2788Perl_swash_fetch(pTHX_ SV *swash, const U8 *ptr, bool do_utf8)
a0ed51b3 2789{
ef8f7699 2790 HV *const hv = MUTABLE_HV(SvRV(swash));
3568d838
JH
2791 U32 klen;
2792 U32 off;
9b56a019 2793 STRLEN slen = 0;
7d85a32c 2794 STRLEN needents;
cfd0369c 2795 const U8 *tmps = NULL;
979f2922 2796 SV *swatch;
08fb1ac5 2797 const U8 c = *ptr;
3568d838 2798
7918f24d
NC
2799 PERL_ARGS_ASSERT_SWASH_FETCH;
2800
87367d5f
KW
2801 /* If it really isn't a hash, it isn't really swash; must be an inversion
2802 * list */
2803 if (SvTYPE(hv) != SVt_PVHV) {
2804 return _invlist_contains_cp((SV*)hv,
2805 (do_utf8)
2806 ? valid_utf8_to_uvchr(ptr, NULL)
2807 : c);
2808 }
2809
08fb1ac5
KW
2810 /* We store the values in a "swatch" which is a vec() value in a swash
2811 * hash. Code points 0-255 are a single vec() stored with key length
2812 * (klen) 0. All other code points have a UTF-8 representation
2813 * 0xAA..0xYY,0xZZ. A vec() is constructed containing all of them which
2814 * share 0xAA..0xYY, which is the key in the hash to that vec. So the key
2815 * length for them is the length of the encoded char - 1. ptr[klen] is the
2816 * final byte in the sequence representing the character */
2817 if (!do_utf8 || UTF8_IS_INVARIANT(c)) {
2818 klen = 0;
2819 needents = 256;
2820 off = c;
3568d838 2821 }
08fb1ac5
KW
2822 else if (UTF8_IS_DOWNGRADEABLE_START(c)) {
2823 klen = 0;
2824 needents = 256;
a62b247b 2825 off = EIGHT_BIT_UTF8_TO_NATIVE(c, *(ptr + 1));
979f2922
ST
2826 }
2827 else {
08fb1ac5
KW
2828 klen = UTF8SKIP(ptr) - 1;
2829
2830 /* Each vec() stores 2**UTF_ACCUMULATION_SHIFT values. The offset into
2831 * the vec is the final byte in the sequence. (In EBCDIC this is
2832 * converted to I8 to get consecutive values.) To help you visualize
2833 * all this:
2834 * Straight 1047 After final byte
2835 * UTF-8 UTF-EBCDIC I8 transform
2836 * U+0400: \xD0\x80 \xB8\x41\x41 \xB8\x41\xA0
2837 * U+0401: \xD0\x81 \xB8\x41\x42 \xB8\x41\xA1
2838 * ...
2839 * U+0409: \xD0\x89 \xB8\x41\x4A \xB8\x41\xA9
2840 * U+040A: \xD0\x8A \xB8\x41\x51 \xB8\x41\xAA
2841 * ...
2842 * U+0412: \xD0\x92 \xB8\x41\x59 \xB8\x41\xB2
2843 * U+0413: \xD0\x93 \xB8\x41\x62 \xB8\x41\xB3
2844 * ...
2845 * U+041B: \xD0\x9B \xB8\x41\x6A \xB8\x41\xBB
2846 * U+041C: \xD0\x9C \xB8\x41\x70 \xB8\x41\xBC
2847 * ...
2848 * U+041F: \xD0\x9F \xB8\x41\x73 \xB8\x41\xBF
2849 * U+0420: \xD0\xA0 \xB8\x42\x41 \xB8\x42\x41
2850 *
2851 * (There are no discontinuities in the elided (...) entries.)
2852 * The UTF-8 key for these 33 code points is '\xD0' (which also is the
2853 * key for the next 31, up through U+043F, whose UTF-8 final byte is
2854 * \xBF). Thus in UTF-8, each key is for a vec() for 64 code points.
2855 * The final UTF-8 byte, which ranges between \x80 and \xBF, is an
2856 * index into the vec() swatch (after subtracting 0x80, which we
2857 * actually do with an '&').
2858 * In UTF-EBCDIC, each key is for a 32 code point vec(). The first 32
2859 * code points above have key '\xB8\x41'. The final UTF-EBCDIC byte has
2860 * dicontinuities which go away by transforming it into I8, and we
2861 * effectively subtract 0xA0 to get the index. */
979f2922 2862 needents = (1 << UTF_ACCUMULATION_SHIFT);
bc3632a8 2863 off = NATIVE_UTF8_TO_I8(ptr[klen]) & UTF_CONTINUATION_MASK;
979f2922 2864 }
7d85a32c 2865
a0ed51b3 2866 /*
4a4088c4 2867 * This single-entry cache saves about 1/3 of the UTF-8 overhead in test
a0ed51b3
LW
2868 * suite. (That is, only 7-8% overall over just a hash cache. Still,
2869 * it's nothing to sniff at.) Pity we usually come through at least
2870 * two function calls to get here...
2871 *
2872 * NB: this code assumes that swatches are never modified, once generated!
2873 */
2874
3568d838 2875 if (hv == PL_last_swash_hv &&
a0ed51b3 2876 klen == PL_last_swash_klen &&
27da23d5 2877 (!klen || memEQ((char *)ptr, (char *)PL_last_swash_key, klen)) )
a0ed51b3
LW
2878 {
2879 tmps = PL_last_swash_tmps;
2880 slen = PL_last_swash_slen;
2881 }
2882 else {
2883 /* Try our second-level swatch cache, kept in a hash. */
e1ec3a88 2884 SV** svp = hv_fetch(hv, (const char*)ptr, klen, FALSE);
a0ed51b3 2885
b0e3252e 2886 /* If not cached, generate it via swatch_get */
979f2922 2887 if (!svp || !SvPOK(*svp)
08fb1ac5
KW
2888 || !(tmps = (const U8*)SvPV_const(*svp, slen)))
2889 {
2890 if (klen) {
2891 const UV code_point = valid_utf8_to_uvchr(ptr, NULL);
2892 swatch = swatch_get(swash,
2893 code_point & ~((UV)needents - 1),
2894 needents);
2895 }
2896 else { /* For the first 256 code points, the swatch has a key of
2897 length 0 */
2898 swatch = swatch_get(swash, 0, needents);
2899 }
979f2922 2900
923e4eb5 2901 if (IN_PERL_COMPILETIME)
623e6609 2902 CopHINTS_set(PL_curcop, PL_hints);
a0ed51b3 2903
979f2922 2904 svp = hv_store(hv, (const char *)ptr, klen, swatch, 0);
a0ed51b3 2905
979f2922
ST
2906 if (!svp || !(tmps = (U8*)SvPV(*svp, slen))
2907 || (slen << 3) < needents)
5637ef5b
NC
2908 Perl_croak(aTHX_ "panic: swash_fetch got improper swatch, "
2909 "svp=%p, tmps=%p, slen=%"UVuf", needents=%"UVuf,
2910 svp, tmps, (UV)slen, (UV)needents);
a0ed51b3
LW
2911 }
2912
2913 PL_last_swash_hv = hv;
16d8f38a 2914 assert(klen <= sizeof(PL_last_swash_key));
eac04b2e 2915 PL_last_swash_klen = (U8)klen;
cfd0369c
NC
2916 /* FIXME change interpvar.h? */
2917 PL_last_swash_tmps = (U8 *) tmps;
a0ed51b3
LW
2918 PL_last_swash_slen = slen;
2919 if (klen)
2920 Copy(ptr, PL_last_swash_key, klen, U8);
2921 }
2922
9faf8d75 2923 switch ((int)((slen << 3) / needents)) {
a0ed51b3 2924 case 1:
e7aca353 2925 return ((UV) tmps[off >> 3] & (1 << (off & 7))) != 0;
a0ed51b3 2926 case 8:
e7aca353 2927 return ((UV) tmps[off]);
a0ed51b3
LW
2928 case 16:
2929 off <<= 1;
e7aca353
JH
2930 return
2931 ((UV) tmps[off ] << 8) +
2932 ((UV) tmps[off + 1]);
a0ed51b3
LW
2933 case 32:
2934 off <<= 2;
e7aca353
JH
2935 return
2936 ((UV) tmps[off ] << 24) +
2937 ((UV) tmps[off + 1] << 16) +
2938 ((UV) tmps[off + 2] << 8) +
2939 ((UV) tmps[off + 3]);
a0ed51b3 2940 }
5637ef5b
NC
2941 Perl_croak(aTHX_ "panic: swash_fetch got swatch of unexpected bit width, "
2942 "slen=%"UVuf", needents=%"UVuf, (UV)slen, (UV)needents);
670f1322 2943 NORETURN_FUNCTION_END;
a0ed51b3 2944}
2b9d42f0 2945
319009ee
KW
2946/* Read a single line of the main body of the swash input text. These are of
2947 * the form:
2948 * 0053 0056 0073
2949 * where each number is hex. The first two numbers form the minimum and
2950 * maximum of a range, and the third is the value associated with the range.
2951 * Not all swashes should have a third number
2952 *
2953 * On input: l points to the beginning of the line to be examined; it points
2954 * to somewhere in the string of the whole input text, and is
2955 * terminated by a \n or the null string terminator.
2956 * lend points to the null terminator of that string
2957 * wants_value is non-zero if the swash expects a third number
2958 * typestr is the name of the swash's mapping, like 'ToLower'
2959 * On output: *min, *max, and *val are set to the values read from the line.
2960 * returns a pointer just beyond the line examined. If there was no
2961 * valid min number on the line, returns lend+1
2962 */
2963
2964STATIC U8*
2965S_swash_scan_list_line(pTHX_ U8* l, U8* const lend, UV* min, UV* max, UV* val,
2966 const bool wants_value, const U8* const typestr)
2967{
2968 const int typeto = typestr[0] == 'T' && typestr[1] == 'o';
2969 STRLEN numlen; /* Length of the number */
02470786
KW
2970 I32 flags = PERL_SCAN_SILENT_ILLDIGIT
2971 | PERL_SCAN_DISALLOW_PREFIX
2972 | PERL_SCAN_SILENT_NON_PORTABLE;
319009ee
KW
2973
2974 /* nl points to the next \n in the scan */
2975 U8* const nl = (U8*)memchr(l, '\n', lend - l);
2976
95543e92
KW
2977 PERL_ARGS_ASSERT_SWASH_SCAN_LIST_LINE;
2978
319009ee
KW
2979 /* Get the first number on the line: the range minimum */
2980 numlen = lend - l;
2981 *min = grok_hex((char *)l, &numlen, &flags, NULL);
c88850db 2982 *max = *min; /* So can never return without setting max */
319009ee
KW
2983 if (numlen) /* If found a hex number, position past it */
2984 l += numlen;
2985 else if (nl) { /* Else, go handle next line, if any */
2986 return nl + 1; /* 1 is length of "\n" */
2987 }
2988 else { /* Else, no next line */
2989 return lend + 1; /* to LIST's end at which \n is not found */
2990 }
2991
2992 /* The max range value follows, separated by a BLANK */
2993 if (isBLANK(*l)) {
2994 ++l;
02470786
KW
2995 flags = PERL_SCAN_SILENT_ILLDIGIT
2996 | PERL_SCAN_DISALLOW_PREFIX
2997 | PERL_SCAN_SILENT_NON_PORTABLE;
319009ee
KW
2998 numlen = lend - l;
2999 *max = grok_hex((char *)l, &numlen, &flags, NULL);
3000 if (numlen)
3001 l += numlen;
3002 else /* If no value here, it is a single element range */
3003 *max = *min;
3004
3005 /* Non-binary tables have a third entry: what the first element of the
24303724 3006 * range maps to. The map for those currently read here is in hex */
319009ee
KW
3007 if (wants_value) {
3008 if (isBLANK(*l)) {
3009 ++l;
f2a7d0fc
KW
3010 flags = PERL_SCAN_SILENT_ILLDIGIT
3011 | PERL_SCAN_DISALLOW_PREFIX
3012 | PERL_SCAN_SILENT_NON_PORTABLE;
3013 numlen = lend - l;
3014 *val = grok_hex((char *)l, &numlen, &flags, NULL);
3015 if (numlen)
3016 l += numlen;
3017 else
3018 *val = 0;
319009ee
KW
3019 }
3020 else {
3021 *val = 0;
3022 if (typeto) {
dcbac5bb 3023 /* diag_listed_as: To%s: illegal mapping '%s' */
319009ee
KW
3024 Perl_croak(aTHX_ "%s: illegal mapping '%s'",
3025 typestr, l);
3026 }
3027 }
3028 }
3029 else
3030 *val = 0; /* bits == 1, then any val should be ignored */
3031 }
3032 else { /* Nothing following range min, should be single element with no
3033 mapping expected */
319009ee
KW
3034 if (wants_value) {
3035 *val = 0;
3036 if (typeto) {
dcbac5bb 3037 /* diag_listed_as: To%s: illegal mapping '%s' */
319009ee
KW
3038 Perl_croak(aTHX_ "%s: illegal mapping '%s'", typestr, l);
3039 }
3040 }
3041 else
3042 *val = 0; /* bits == 1, then val should be ignored */
3043 }
3044
3045 /* Position to next line if any, or EOF */
3046 if (nl)
3047 l = nl + 1;
3048 else
3049 l = lend;
3050
3051 return l;
3052}
3053
979f2922
ST
3054/* Note:
3055 * Returns a swatch (a bit vector string) for a code point sequence
3056 * that starts from the value C<start> and comprises the number C<span>.
3057 * A C<swash> must be an object created by SWASHNEW (see lib/utf8_heavy.pl).
3058 * Should be used via swash_fetch, which will cache the swatch in C<swash>.
3059 */
3060STATIC SV*
b0e3252e 3061S_swatch_get(pTHX_ SV* swash, UV start, UV span)
979f2922
ST
3062{
3063 SV *swatch;
77f9f126 3064 U8 *l, *lend, *x, *xend, *s, *send;
979f2922 3065 STRLEN lcur, xcur, scur;
ef8f7699 3066 HV *const hv = MUTABLE_HV(SvRV(swash));
5c9f4bd2 3067 SV** const invlistsvp = hv_fetchs(hv, "V", FALSE);
36eb48b4 3068
88d45d28
KW
3069 SV** listsvp = NULL; /* The string containing the main body of the table */
3070 SV** extssvp = NULL;
3071 SV** invert_it_svp = NULL;
3072 U8* typestr = NULL;
786861f5
KW
3073 STRLEN bits;
3074 STRLEN octets; /* if bits == 1, then octets == 0 */
3075 UV none;
3076 UV end = start + span;
972dd592 3077
36eb48b4 3078 if (invlistsvp == NULL) {
786861f5
KW
3079 SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3080 SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3081 SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3082 extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
3083 listsvp = hv_fetchs(hv, "LIST", FALSE);
3084 invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
3085
3086 bits = SvUV(*bitssvp);
3087 none = SvUV(*nonesvp);
3088 typestr = (U8*)SvPV_nolen(*typesvp);
3089 }
36eb48b4
KW
3090 else {
3091 bits = 1;
3092 none = 0;
3093 }
786861f5 3094 octets = bits >> 3; /* if bits == 1, then octets == 0 */
979f2922 3095
b0e3252e 3096 PERL_ARGS_ASSERT_SWATCH_GET;
7918f24d 3097
979f2922 3098 if (bits != 1 && bits != 8 && bits != 16 && bits != 32) {
b0e3252e 3099 Perl_croak(aTHX_ "panic: swatch_get doesn't expect bits %"UVuf,
660a4616 3100 (UV)bits);
979f2922
ST
3101 }
3102
84ea5ef6
KW
3103 /* If overflowed, use the max possible */
3104 if (end < start) {
3105 end = UV_MAX;
3106 span = end - start;
3107 }
3108
979f2922 3109 /* create and initialize $swatch */
979f2922 3110 scur = octets ? (span * octets) : (span + 7) / 8;
e524fe40
NC
3111 swatch = newSV(scur);
3112 SvPOK_on(swatch);
979f2922
ST
3113 s = (U8*)SvPVX(swatch);
3114 if (octets && none) {
0bd48802 3115 const U8* const e = s + scur;
979f2922
ST
3116 while (s < e) {
3117 if (bits == 8)
3118 *s++ = (U8)(none & 0xff);
3119 else if (bits == 16) {
3120 *s++ = (U8)((none >> 8) & 0xff);
3121 *s++ = (U8)( none & 0xff);
3122 }
3123 else if (bits == 32) {
3124 *s++ = (U8)((none >> 24) & 0xff);
3125 *s++ = (U8)((none >> 16) & 0xff);
3126 *s++ = (U8)((none >> 8) & 0xff);
3127 *s++ = (U8)( none & 0xff);
3128 }
3129 }
3130 *s = '\0';
3131 }
3132 else {
3133 (void)memzero((U8*)s, scur + 1);
3134 }
3135 SvCUR_set(swatch, scur);
3136 s = (U8*)SvPVX(swatch);
3137
36eb48b4
KW
3138 if (invlistsvp) { /* If has an inversion list set up use that */
3139 _invlist_populate_swatch(*invlistsvp, start, end, s);
3140 return swatch;
3141 }
3142
3143 /* read $swash->{LIST} */
979f2922
ST
3144 l = (U8*)SvPV(*listsvp, lcur);
3145 lend = l + lcur;
3146 while (l < lend) {
8ed25d53 3147 UV min, max, val, upper;
95543e92
KW
3148 l = swash_scan_list_line(l, lend, &min, &max, &val,
3149 cBOOL(octets), typestr);
319009ee 3150 if (l > lend) {
979f2922
ST
3151 break;
3152 }
3153
972dd592 3154 /* If looking for something beyond this range, go try the next one */
979f2922
ST
3155 if (max < start)
3156 continue;
3157
8ed25d53
KW
3158 /* <end> is generally 1 beyond where we want to set things, but at the
3159 * platform's infinity, where we can't go any higher, we want to
3160 * include the code point at <end> */
3161 upper = (max < end)
3162 ? max
3163 : (max != UV_MAX || end != UV_MAX)
3164 ? end - 1
3165 : end;
3166
979f2922 3167 if (octets) {
35da51f7 3168 UV key;
979f2922
ST
3169 if (min < start) {
3170 if (!none || val < none) {
3171 val += start - min;
3172 }
3173 min = start;
3174 }
8ed25d53 3175 for (key = min; key <= upper; key++) {
979f2922 3176 STRLEN offset;
979f2922
ST
3177 /* offset must be non-negative (start <= min <= key < end) */
3178 offset = octets * (key - start);
3179 if (bits == 8)
3180 s[offset] = (U8)(val & 0xff);
3181 else if (bits == 16) {
3182 s[offset ] = (U8)((val >> 8) & 0xff);
3183 s[offset + 1] = (U8)( val & 0xff);
3184 }
3185 else if (bits == 32) {
3186 s[offset ] = (U8)((val >> 24) & 0xff);
3187 s[offset + 1] = (U8)((val >> 16) & 0xff);
3188 s[offset + 2] = (U8)((val >> 8) & 0xff);
3189 s[offset + 3] = (U8)( val & 0xff);
3190 }
3191
3192 if (!none || val < none)
3193 ++val;
3194 }
3195 }
711a919c 3196 else { /* bits == 1, then val should be ignored */
35da51f7 3197 UV key;
979f2922
ST
3198 if (min < start)
3199 min = start;
6cb05c12 3200
8ed25d53 3201 for (key = min; key <= upper; key++) {
0bd48802 3202 const STRLEN offset = (STRLEN)(key - start);
979f2922
ST
3203 s[offset >> 3] |= 1 << (offset & 7);
3204 }
3205 }
3206 } /* while */
979f2922 3207
9479a769 3208 /* Invert if the data says it should be. Assumes that bits == 1 */
77f9f126 3209 if (invert_it_svp && SvUV(*invert_it_svp)) {
0bda3001
KW
3210
3211 /* Unicode properties should come with all bits above PERL_UNICODE_MAX
3212 * be 0, and their inversion should also be 0, as we don't succeed any
3213 * Unicode property matches for non-Unicode code points */
3214 if (start <= PERL_UNICODE_MAX) {
3215
3216 /* The code below assumes that we never cross the
3217 * Unicode/above-Unicode boundary in a range, as otherwise we would
3218 * have to figure out where to stop flipping the bits. Since this
3219 * boundary is divisible by a large power of 2, and swatches comes
3220 * in small powers of 2, this should be a valid assumption */
3221 assert(start + span - 1 <= PERL_UNICODE_MAX);
3222
507a8485
KW
3223 send = s + scur;
3224 while (s < send) {
3225 *s = ~(*s);
3226 s++;
3227 }
0bda3001 3228 }
77f9f126
KW
3229 }
3230
d73c39c5
KW
3231 /* read $swash->{EXTRAS}
3232 * This code also copied to swash_to_invlist() below */
979f2922
ST
3233 x = (U8*)SvPV(*extssvp, xcur);
3234 xend = x + xcur;
3235 while (x < xend) {
3236 STRLEN namelen;
3237 U8 *namestr;
3238 SV** othersvp;
3239 HV* otherhv;
3240 STRLEN otherbits;
3241 SV **otherbitssvp, *other;
711a919c 3242 U8 *s, *o, *nl;
979f2922
ST
3243 STRLEN slen, olen;
3244
35da51f7 3245 const U8 opc = *x++;
979f2922
ST
3246 if (opc == '\n')
3247 continue;
3248
3249 nl = (U8*)memchr(x, '\n', xend - x);
3250
3251 if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
3252 if (nl) {
3253 x = nl + 1; /* 1 is length of "\n" */
3254 continue;
3255 }
3256 else {
3257 x = xend; /* to EXTRAS' end at which \n is not found */
3258 break;
3259 }
3260 }
3261
3262 namestr = x;
3263 if (nl) {
3264 namelen = nl - namestr;
3265 x = nl + 1;
3266 }
3267 else {
3268 namelen = xend - namestr;
3269 x = xend;
3270 }
3271
3272 othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
ef8f7699 3273 otherhv = MUTABLE_HV(SvRV(*othersvp));
017a3ce5 3274 otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
979f2922
ST
3275 otherbits = (STRLEN)SvUV(*otherbitssvp);
3276 if (bits < otherbits)
5637ef5b
NC
3277 Perl_croak(aTHX_ "panic: swatch_get found swatch size mismatch, "
3278 "bits=%"UVuf", otherbits=%"UVuf, (UV)bits, (UV)otherbits);
979f2922
ST
3279
3280 /* The "other" swatch must be destroyed after. */
b0e3252e 3281 other = swatch_get(*othersvp, start, span);
979f2922
ST
3282 o = (U8*)SvPV(other, olen);
3283
3284 if (!olen)
b0e3252e 3285 Perl_croak(aTHX_ "panic: swatch_get got improper swatch");
979f2922
ST
3286
3287 s = (U8*)SvPV(swatch, slen);
3288 if (bits == 1 && otherbits == 1) {
3289 if (slen != olen)
5637ef5b
NC
3290 Perl_croak(aTHX_ "panic: swatch_get found swatch length "
3291 "mismatch, slen=%"UVuf", olen=%"UVuf,
3292 (UV)slen, (UV)olen);
979f2922
ST
3293
3294 switch (opc) {
3295 case '+':
3296 while (slen--)
3297 *s++ |= *o++;
3298 break;
3299 case '!':
3300 while (slen--)
3301 *s++ |= ~*o++;
3302 break;
3303 case '-':
3304 while (slen--)
3305 *s++ &= ~*o++;
3306 break;
3307 case '&':
3308 while (slen--)
3309 *s++ &= *o++;
3310 break;
3311 default:
3312 break;
3313 }
3314 }
711a919c 3315 else {
979f2922
ST
3316 STRLEN otheroctets = otherbits >> 3;
3317 STRLEN offset = 0;
35da51f7 3318 U8* const send = s + slen;
979f2922
ST
3319
3320 while (s < send) {
3321 UV otherval = 0;
3322
3323 if (otherbits == 1) {
3324 otherval = (o[offset >> 3] >> (offset & 7)) & 1;
3325 ++offset;
3326 }
3327 else {
3328 STRLEN vlen = otheroctets;
3329 otherval = *o++;
3330 while (--vlen) {
3331 otherval <<= 8;
3332 otherval |= *o++;
3333 }
3334 }
3335
711a919c 3336 if (opc == '+' && otherval)
6f207bd3 3337 NOOP; /* replace with otherval */
979f2922
ST
3338 else if (opc == '!' && !otherval)
3339 otherval = 1;
3340 else if (opc == '-' && otherval)
3341 otherval = 0;
3342 else if (opc == '&' && !otherval)
3343 otherval = 0;
3344 else {
711a919c 3345 s += octets; /* no replacement */
979f2922
ST
3346 continue;
3347 }
3348
3349 if (bits == 8)
3350 *s++ = (U8)( otherval & 0xff);
3351 else if (bits == 16) {
3352 *s++ = (U8)((otherval >> 8) & 0xff);
3353 *s++ = (U8)( otherval & 0xff);
3354 }
3355 else if (bits == 32) {
3356 *s++ = (U8)((otherval >> 24) & 0xff);
3357 *s++ = (U8)((otherval >> 16) & 0xff);
3358 *s++ = (U8)((otherval >> 8) & 0xff);
3359 *s++ = (U8)( otherval & 0xff);
3360 }
3361 }
3362 }
3363 sv_free(other); /* through with it! */
3364 } /* while */
3365 return swatch;
3366}
3367
064c021d 3368HV*
4c2e1131 3369Perl__swash_inversion_hash(pTHX_ SV* const swash)
064c021d
KW
3370{
3371
79a2a0e8 3372 /* Subject to change or removal. For use only in regcomp.c and regexec.c
5662e334
KW
3373 * Can't be used on a property that is subject to user override, as it
3374 * relies on the value of SPECIALS in the swash which would be set by
3375 * utf8_heavy.pl to the hash in the non-overriden file, and hence is not set
3376 * for overridden properties
064c021d
KW
3377 *
3378 * Returns a hash which is the inversion and closure of a swash mapping.
3379 * For example, consider the input lines:
3380 * 004B 006B
3381 * 004C 006C
3382 * 212A 006B
3383 *
4a4088c4 3384 * The returned hash would have two keys, the UTF-8 for 006B and the UTF-8 for
064c021d 3385 * 006C. The value for each key is an array. For 006C, the array would
4a4088c4
KW
3386 * have two elements, the UTF-8 for itself, and for 004C. For 006B, there
3387 * would be three elements in its array, the UTF-8 for 006B, 004B and 212A.
064c021d 3388 *
538e84ed
KW
3389 * Note that there are no elements in the hash for 004B, 004C, 212A. The
3390 * keys are only code points that are folded-to, so it isn't a full closure.
3391 *
064c021d
KW
3392 * Essentially, for any code point, it gives all the code points that map to
3393 * it, or the list of 'froms' for that point.
3394 *
5662e334
KW
3395 * Currently it ignores any additions or deletions from other swashes,
3396 * looking at just the main body of the swash, and if there are SPECIALS
3397 * in the swash, at that hash
3398 *
3399 * The specials hash can be extra code points, and most likely consists of
3400 * maps from single code points to multiple ones (each expressed as a string
4a4088c4 3401 * of UTF-8 characters). This function currently returns only 1-1 mappings.
5662e334
KW
3402 * However consider this possible input in the specials hash:
3403 * "\xEF\xAC\x85" => "\x{0073}\x{0074}", # U+FB05 => 0073 0074
3404 * "\xEF\xAC\x86" => "\x{0073}\x{0074}", # U+FB06 => 0073 0074
3405 *
3406 * Both FB05 and FB06 map to the same multi-char sequence, which we don't
3407 * currently handle. But it also means that FB05 and FB06 are equivalent in
3408 * a 1-1 mapping which we should handle, and this relationship may not be in
3409 * the main table. Therefore this function examines all the multi-char
74894415
KW
3410 * sequences and adds the 1-1 mappings that come out of that.
3411 *
3412 * XXX This function was originally intended to be multipurpose, but its
3413 * only use is quite likely to remain for constructing the inversion of
3414 * the CaseFolding (//i) property. If it were more general purpose for
3415 * regex patterns, it would have to do the FB05/FB06 game for simple folds,
3416 * because certain folds are prohibited under /iaa and /il. As an example,
3417 * in Unicode 3.0.1 both U+0130 and U+0131 fold to 'i', and hence are both
3418 * equivalent under /i. But under /iaa and /il, the folds to 'i' are
3419 * prohibited, so we would not figure out that they fold to each other.
3420 * Code could be written to automatically figure this out, similar to the
3421 * code that does this for multi-character folds, but this is the only case
3422 * where something like this is ever likely to happen, as all the single
7ee537e6 3423 * char folds to the 0-255 range are now quite settled. Instead there is a
74894415
KW
3424 * little special code that is compiled only for this Unicode version. This
3425 * is smaller and didn't require much coding time to do. But this makes
3426 * this routine strongly tied to being used just for CaseFolding. If ever
3427 * it should be generalized, this would have to be fixed */
064c021d
KW
3428
3429 U8 *l, *lend;
3430 STRLEN lcur;
3431 HV *const hv = MUTABLE_HV(SvRV(swash));
3432
923b6d4e
KW
3433 /* The string containing the main body of the table. This will have its
3434 * assertion fail if the swash has been converted to its inversion list */
064c021d
KW
3435 SV** const listsvp = hv_fetchs(hv, "LIST", FALSE);
3436
3437 SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3438 SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3439 SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3440 /*SV** const extssvp = hv_fetchs(hv, "EXTRAS", FALSE);*/
3441 const U8* const typestr = (U8*)SvPV_nolen(*typesvp);
3442 const STRLEN bits = SvUV(*bitssvp);
3443 const STRLEN octets = bits >> 3; /* if bits == 1, then octets == 0 */
3444 const UV none = SvUV(*nonesvp);
5662e334 3445 SV **specials_p = hv_fetchs(hv, "SPECIALS", 0);
064c021d
KW
3446
3447 HV* ret = newHV();
3448
3449 PERL_ARGS_ASSERT__SWASH_INVERSION_HASH;
3450
3451 /* Must have at least 8 bits to get the mappings */
3452 if (bits != 8 && bits != 16 && bits != 32) {
3453 Perl_croak(aTHX_ "panic: swash_inversion_hash doesn't expect bits %"UVuf,
3454 (UV)bits);
3455 }
3456
5662e334
KW
3457 if (specials_p) { /* It might be "special" (sometimes, but not always, a
3458 mapping to more than one character */
3459
3460 /* Construct an inverse mapping hash for the specials */
3461 HV * const specials_hv = MUTABLE_HV(SvRV(*specials_p));
3462 HV * specials_inverse = newHV();
3463 char *char_from; /* the lhs of the map */
3464 I32 from_len; /* its byte length */
3465 char *char_to; /* the rhs of the map */
3466 I32 to_len; /* its byte length */
3467 SV *sv_to; /* and in a sv */
3468 AV* from_list; /* list of things that map to each 'to' */
3469
3470 hv_iterinit(specials_hv);
3471
4a4088c4
KW
3472 /* The keys are the characters (in UTF-8) that map to the corresponding
3473 * UTF-8 string value. Iterate through the list creating the inverse
5662e334
KW
3474 * list. */
3475 while ((sv_to = hv_iternextsv(specials_hv, &char_from, &from_len))) {
3476 SV** listp;
3477 if (! SvPOK(sv_to)) {
5637ef5b
NC
3478 Perl_croak(aTHX_ "panic: value returned from hv_iternextsv() "
3479 "unexpectedly is not a string, flags=%lu",
3480 (unsigned long)SvFLAGS(sv_to));
5662e334 3481 }
4b88fb76 3482 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "Found mapping from %"UVXf", First char of to is %"UVXf"\n", valid_utf8_to_uvchr((U8*) char_from, 0), valid_utf8_to_uvchr((U8*) SvPVX(sv_to), 0)));*/
5662e334
KW
3483
3484 /* Each key in the inverse list is a mapped-to value, and the key's
4a4088c4 3485 * hash value is a list of the strings (each in UTF-8) that map to
5662e334
KW
3486 * it. Those strings are all one character long */
3487 if ((listp = hv_fetch(specials_inverse,
3488 SvPVX(sv_to),
3489 SvCUR(sv_to), 0)))
3490 {
3491 from_list = (AV*) *listp;
3492 }
3493 else { /* No entry yet for it: create one */
3494 from_list = newAV();
3495 if (! hv_store(specials_inverse,
3496 SvPVX(sv_to),
3497 SvCUR(sv_to),
3498 (SV*) from_list, 0))
3499 {
3500 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3501 }
3502 }
3503
3504 /* Here have the list associated with this 'to' (perhaps newly
3505 * created and empty). Just add to it. Note that we ASSUME that
3506 * the input is guaranteed to not have duplications, so we don't
3507 * check for that. Duplications just slow down execution time. */
3508 av_push(from_list, newSVpvn_utf8(char_from, from_len, TRUE));
3509 }
3510
3511 /* Here, 'specials_inverse' contains the inverse mapping. Go through
3512 * it looking for cases like the FB05/FB06 examples above. There would
3513 * be an entry in the hash like
3514 * 'st' => [ FB05, FB06 ]
3515 * In this example we will create two lists that get stored in the
3516 * returned hash, 'ret':
3517 * FB05 => [ FB05, FB06 ]
3518 * FB06 => [ FB05, FB06 ]
3519 *
3520 * Note that there is nothing to do if the array only has one element.
3521 * (In the normal 1-1 case handled below, we don't have to worry about
3522 * two lists, as everything gets tied to the single list that is
3523 * generated for the single character 'to'. But here, we are omitting
3524 * that list, ('st' in the example), so must have multiple lists.) */
3525 while ((from_list = (AV *) hv_iternextsv(specials_inverse,
3526 &char_to, &to_len)))
3527 {
7e13d567 3528 if (av_tindex_nomg(from_list) > 0) {
c70927a6 3529 SSize_t i;
5662e334
KW
3530
3531 /* We iterate over all combinations of i,j to place each code
3532 * point on each list */
7e13d567 3533 for (i = 0; i <= av_tindex_nomg(from_list); i++) {
c70927a6 3534 SSize_t j;
5662e334
KW
3535 AV* i_list = newAV();
3536 SV** entryp = av_fetch(from_list, i, FALSE);
3537 if (entryp == NULL) {
3538 Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3539 }
3540 if (hv_fetch(ret, SvPVX(*entryp), SvCUR(*entryp), FALSE)) {
3541 Perl_croak(aTHX_ "panic: unexpected entry for %s", SvPVX(*entryp));
3542 }
3543 if (! hv_store(ret, SvPVX(*entryp), SvCUR(*entryp),
3544 (SV*) i_list, FALSE))
3545 {
3546 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3547 }
3548
538e84ed 3549 /* For DEBUG_U: UV u = valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0);*/
7e13d567 3550 for (j = 0; j <= av_tindex_nomg(from_list); j++) {
5662e334
KW
3551 entryp = av_fetch(from_list, j, FALSE);
3552 if (entryp == NULL) {
3553 Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3554 }
3555
3556 /* When i==j this adds itself to the list */
4b88fb76
KW
3557 av_push(i_list, newSVuv(utf8_to_uvchr_buf(
3558 (U8*) SvPVX(*entryp),
3559 (U8*) SvPVX(*entryp) + SvCUR(*entryp),
3560 0)));
4637d003 3561 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0), u));*/
5662e334
KW
3562 }
3563 }
3564 }
3565 }
3566 SvREFCNT_dec(specials_inverse); /* done with it */
3567 } /* End of specials */
3568
064c021d 3569 /* read $swash->{LIST} */
74894415
KW
3570
3571#if UNICODE_MAJOR_VERSION == 3 \
3572 && UNICODE_DOT_VERSION == 0 \
3573 && UNICODE_DOT_DOT_VERSION == 1
3574
3575 /* For this version only U+130 and U+131 are equivalent under qr//i. Add a
3576 * rule so that things work under /iaa and /il */
3577
3578 SV * mod_listsv = sv_mortalcopy(*listsvp);
3579 sv_catpv(mod_listsv, "130\t130\t131\n");
3580 l = (U8*)SvPV(mod_listsv, lcur);
3581
3582#else
3583
064c021d 3584 l = (U8*)SvPV(*listsvp, lcur);
74894415
KW
3585
3586#endif
3587
064c021d
KW
3588 lend = l + lcur;
3589
3590 /* Go through each input line */
3591 while (l < lend) {
3592 UV min, max, val;
3593 UV inverse;
95543e92
KW
3594 l = swash_scan_list_line(l, lend, &min, &max, &val,
3595 cBOOL(octets), typestr);
064c021d
KW
3596 if (l > lend) {
3597 break;
3598 }
3599
3600 /* Each element in the range is to be inverted */
3601 for (inverse = min; inverse <= max; inverse++) {
3602 AV* list;
064c021d
KW
3603 SV** listp;
3604 IV i;
3605 bool found_key = FALSE;
5662e334 3606 bool found_inverse = FALSE;
064c021d
KW
3607
3608 /* The key is the inverse mapping */
3609 char key[UTF8_MAXBYTES+1];
c80e42f3 3610 char* key_end = (char *) uvchr_to_utf8((U8*) key, val);
064c021d
KW
3611 STRLEN key_len = key_end - key;
3612
064c021d
KW
3613 /* Get the list for the map */
3614 if ((listp = hv_fetch(ret, key, key_len, FALSE))) {
3615 list = (AV*) *listp;
3616 }
3617 else { /* No entry yet for it: create one */
3618 list = newAV();
3619 if (! hv_store(ret, key, key_len, (SV*) list, FALSE)) {
3620 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3621 }
3622 }
3623
5662e334
KW
3624 /* Look through list to see if this inverse mapping already is
3625 * listed, or if there is a mapping to itself already */
7e13d567 3626 for (i = 0; i <= av_tindex_nomg(list); i++) {
064c021d
KW
3627 SV** entryp = av_fetch(list, i, FALSE);
3628 SV* entry;
414db8a1 3629 UV uv;
064c021d
KW
3630 if (entryp == NULL) {
3631 Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3632 }
3633 entry = *entryp;
414db8a1
DM
3634 uv = SvUV(entry);
3635 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "list for %"UVXf" contains %"UVXf"\n", val, uv));*/
3636 if (uv == val) {
064c021d 3637 found_key = TRUE;
5662e334 3638 }
414db8a1 3639 if (uv == inverse) {
5662e334
KW
3640 found_inverse = TRUE;
3641 }
3642
3643 /* No need to continue searching if found everything we are
3644 * looking for */
3645 if (found_key && found_inverse) {
064c021d
KW
3646 break;
3647 }
3648 }
56ca34ca
KW
3649
3650 /* Make sure there is a mapping to itself on the list */
064c021d 3651 if (! found_key) {
d397ff6a 3652 av_push(list, newSVuv(val));
4637d003 3653 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, val, val));*/
064c021d
KW
3654 }
3655
3656
3657 /* Simply add the value to the list */
5662e334
KW
3658 if (! found_inverse) {
3659 av_push(list, newSVuv(inverse));
4637d003 3660 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, inverse, val));*/
5662e334 3661 }
064c021d 3662
b0e3252e 3663 /* swatch_get() increments the value of val for each element in the
064c021d
KW
3664 * range. That makes more compact tables possible. You can
3665 * express the capitalization, for example, of all consecutive
3666 * letters with a single line: 0061\t007A\t0041 This maps 0061 to
3667 * 0041, 0062 to 0042, etc. I (khw) have never understood 'none',
bd3f2f94 3668 * and it's not documented; it appears to be used only in
b0e3252e 3669 * implementing tr//; I copied the semantics from swatch_get(), just
bd3f2f94 3670 * in case */
064c021d
KW
3671 if (!none || val < none) {
3672 ++val;
3673 }
3674 }
3675 }
3676
3677 return ret;
3678}
3679
a25abddc 3680SV*
d764b54e
KW
3681Perl__swash_to_invlist(pTHX_ SV* const swash)