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