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