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