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