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