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