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