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