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