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