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