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