This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
write_buildcustomize.pl: Setup $^O to be the target os when building Core.
[perl5.git] / utf8.c
1 /*    utf8.c
2  *
3  *    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4  *    by Larry Wall and others
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 /*
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  *
16  *     [p.603 of _The Lord of the Rings_, IV/I: "The Taming of Sméagol"]
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,
20  *  as is the custom in the West, if you wish to be answered?'
21  *                           --Gandalf, addressing Théoden's door wardens
22  *
23  *     [p.508 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
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.
27  *
28  *     [p.512 of _The Lord of the Rings_, III/vi: "The King of the Golden Hall"]
29  */
30
31 #include "EXTERN.h"
32 #define PERL_IN_UTF8_C
33 #include "perl.h"
34 #include "inline_invlist.c"
35 #include "charclass_invlists.h"
36
37 static const char unees[] =
38     "Malformed UTF-8 character (unexpected end of string)";
39
40 /*
41 =head1 Unicode Support
42
43 This file contains various utility functions for manipulating UTF8-encoded
44 strings.  For the uninitiated, this is a method of representing arbitrary
45 Unicode characters as a variable number of bytes, in such a way that
46 characters in the ASCII range are unmodified, and a zero byte never appears
47 within non-zero characters.
48
49 =cut
50 */
51
52 /*
53 =for apidoc is_ascii_string
54
55 Returns true if the first C<len> bytes of the string C<s> are the same whether
56 or not the string is encoded in UTF-8 (or UTF-EBCDIC on EBCDIC machines).  That
57 is, if they are invariant.  On ASCII-ish machines, only ASCII characters
58 fit this definition, hence the function's name.
59
60 If C<len> is 0, it will be calculated using C<strlen(s)>.  
61
62 See also L</is_utf8_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
63
64 =cut
65 */
66
67 bool
68 Perl_is_ascii_string(const U8 *s, STRLEN len)
69 {
70     const U8* const send = s + (len ? len : strlen((const char *)s));
71     const U8* x = s;
72
73     PERL_ARGS_ASSERT_IS_ASCII_STRING;
74
75     for (; x < send; ++x) {
76         if (!UTF8_IS_INVARIANT(*x))
77             break;
78     }
79
80     return x == send;
81 }
82
83 /*
84 =for apidoc uvoffuni_to_utf8_flags
85
86 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
87 Instead, B<Almost all code should use L</uvchr_to_utf8> or
88 L</uvchr_to_utf8_flags>>.
89
90 This function is like them, but the input is a strict Unicode
91 (as opposed to native) code point.  Only in very rare circumstances should code
92 not be using the native code point.
93
94 For details, see the description for L</uvchr_to_utf8_flags>>.
95
96 =cut
97 */
98
99 U8 *
100 Perl_uvoffuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
101 {
102     PERL_ARGS_ASSERT_UVOFFUNI_TO_UTF8_FLAGS;
103
104     if (UNI_IS_INVARIANT(uv)) {
105         *d++ = (U8) LATIN1_TO_NATIVE(uv);
106         return d;
107     }
108
109     /* The first problematic code point is the first surrogate */
110     if (uv >= UNICODE_SURROGATE_FIRST
111         && ckWARN3_d(WARN_SURROGATE, WARN_NON_UNICODE, WARN_NONCHAR))
112     {
113         if (UNICODE_IS_SURROGATE(uv)) {
114             if (flags & UNICODE_WARN_SURROGATE) {
115                 Perl_ck_warner_d(aTHX_ packWARN(WARN_SURROGATE),
116                                             "UTF-16 surrogate U+%04"UVXf, uv);
117             }
118             if (flags & UNICODE_DISALLOW_SURROGATE) {
119                 return NULL;
120             }
121         }
122         else if (UNICODE_IS_SUPER(uv)) {
123             if (flags & UNICODE_WARN_SUPER
124                 || (UNICODE_IS_FE_FF(uv) && (flags & UNICODE_WARN_FE_FF)))
125             {
126                 Perl_ck_warner_d(aTHX_ packWARN(WARN_NON_UNICODE),
127                           "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv);
128             }
129             if (flags & UNICODE_DISALLOW_SUPER
130                 || (UNICODE_IS_FE_FF(uv) && (flags & UNICODE_DISALLOW_FE_FF)))
131             {
132                 return NULL;
133             }
134         }
135         else if (UNICODE_IS_NONCHAR(uv)) {
136             if (flags & UNICODE_WARN_NONCHAR) {
137                 Perl_ck_warner_d(aTHX_ packWARN(WARN_NONCHAR),
138                  "Unicode non-character U+%04"UVXf" is illegal for open interchange",
139                  uv);
140             }
141             if (flags & UNICODE_DISALLOW_NONCHAR) {
142                 return NULL;
143             }
144         }
145     }
146
147 #if defined(EBCDIC)
148     {
149         STRLEN len  = OFFUNISKIP(uv);
150         U8 *p = d+len-1;
151         while (p > d) {
152             *p-- = (U8) I8_TO_NATIVE_UTF8((uv & UTF_CONTINUATION_MASK) | UTF_CONTINUATION_MARK);
153             uv >>= UTF_ACCUMULATION_SHIFT;
154         }
155         *p = (U8) I8_TO_NATIVE_UTF8((uv & UTF_START_MASK(len)) | UTF_START_MARK(len));
156         return d+len;
157     }
158 #else /* Non loop style */
159     if (uv < 0x800) {
160         *d++ = (U8)(( uv >>  6)         | 0xc0);
161         *d++ = (U8)(( uv        & 0x3f) | 0x80);
162         return d;
163     }
164     if (uv < 0x10000) {
165         *d++ = (U8)(( uv >> 12)         | 0xe0);
166         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
167         *d++ = (U8)(( uv        & 0x3f) | 0x80);
168         return d;
169     }
170     if (uv < 0x200000) {
171         *d++ = (U8)(( uv >> 18)         | 0xf0);
172         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
173         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
174         *d++ = (U8)(( uv        & 0x3f) | 0x80);
175         return d;
176     }
177     if (uv < 0x4000000) {
178         *d++ = (U8)(( uv >> 24)         | 0xf8);
179         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
180         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
181         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
182         *d++ = (U8)(( uv        & 0x3f) | 0x80);
183         return d;
184     }
185     if (uv < 0x80000000) {
186         *d++ = (U8)(( uv >> 30)         | 0xfc);
187         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
188         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
189         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
190         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
191         *d++ = (U8)(( uv        & 0x3f) | 0x80);
192         return d;
193     }
194 #ifdef UTF8_QUAD_MAX
195     if (uv < UTF8_QUAD_MAX)
196 #endif
197     {
198         *d++ =                            0xfe; /* Can't match U+FEFF! */
199         *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
200         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
201         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
202         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
203         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
204         *d++ = (U8)(( uv        & 0x3f) | 0x80);
205         return d;
206     }
207 #ifdef UTF8_QUAD_MAX
208     {
209         *d++ =                            0xff;         /* Can't match U+FFFE! */
210         *d++ =                            0x80;         /* 6 Reserved bits */
211         *d++ = (U8)(((uv >> 60) & 0x0f) | 0x80);        /* 2 Reserved bits */
212         *d++ = (U8)(((uv >> 54) & 0x3f) | 0x80);
213         *d++ = (U8)(((uv >> 48) & 0x3f) | 0x80);
214         *d++ = (U8)(((uv >> 42) & 0x3f) | 0x80);
215         *d++ = (U8)(((uv >> 36) & 0x3f) | 0x80);
216         *d++ = (U8)(((uv >> 30) & 0x3f) | 0x80);
217         *d++ = (U8)(((uv >> 24) & 0x3f) | 0x80);
218         *d++ = (U8)(((uv >> 18) & 0x3f) | 0x80);
219         *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
220         *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
221         *d++ = (U8)(( uv        & 0x3f) | 0x80);
222         return d;
223     }
224 #endif
225 #endif /* Non loop style */
226 }
227 /*
228 =for apidoc uvchr_to_utf8
229
230 Adds the UTF-8 representation of the native code point C<uv> to the end
231 of the string C<d>; C<d> should have at least C<UTF8_MAXBYTES+1> free
232 bytes available.  The return value is the pointer to the byte after the
233 end of the new character.  In other words,
234
235     d = uvchr_to_utf8(d, uv);
236
237 is the recommended wide native character-aware way of saying
238
239     *(d++) = uv;
240
241 This function accepts any UV as input.  To forbid or warn on non-Unicode code
242 points, or those that may be problematic, see L</uvchr_to_utf8_flags>.
243
244 =cut
245 */
246
247 /* This is also a macro */
248 PERL_CALLCONV U8*       Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv);
249
250 U8 *
251 Perl_uvchr_to_utf8(pTHX_ U8 *d, UV uv)
252 {
253     return uvchr_to_utf8(d, uv);
254 }
255
256 /*
257 =for apidoc uvchr_to_utf8_flags
258
259 Adds the UTF-8 representation of the native code point C<uv> to the end
260 of the string C<d>; C<d> should have at least C<UTF8_MAXBYTES+1> free
261 bytes available.  The return value is the pointer to the byte after the
262 end of the new character.  In other words,
263
264     d = uvchr_to_utf8_flags(d, uv, flags);
265
266 or, in most cases,
267
268     d = uvchr_to_utf8_flags(d, uv, 0);
269
270 This is the Unicode-aware way of saying
271
272     *(d++) = uv;
273
274 This function will convert to UTF-8 (and not warn) even code points that aren't
275 legal Unicode or are problematic, unless C<flags> contains one or more of the
276 following flags:
277
278 If C<uv> is a Unicode surrogate code point and UNICODE_WARN_SURROGATE is set,
279 the function will raise a warning, provided UTF8 warnings are enabled.  If instead
280 UNICODE_DISALLOW_SURROGATE is set, the function will fail and return NULL.
281 If both flags are set, the function will both warn and return NULL.
282
283 The UNICODE_WARN_NONCHAR and UNICODE_DISALLOW_NONCHAR flags
284 affect how the function handles a Unicode non-character.  And likewise, the
285 UNICODE_WARN_SUPER and UNICODE_DISALLOW_SUPER flags affect the handling of
286 code points that are
287 above the Unicode maximum of 0x10FFFF.  Code points above 0x7FFF_FFFF (which are
288 even less portable) can be warned and/or disallowed even if other above-Unicode
289 code points are accepted, by the UNICODE_WARN_FE_FF and UNICODE_DISALLOW_FE_FF
290 flags.
291
292 And finally, the flag UNICODE_WARN_ILLEGAL_INTERCHANGE selects all four of the
293 above WARN flags; and UNICODE_DISALLOW_ILLEGAL_INTERCHANGE selects all four
294 DISALLOW flags.
295
296 =cut
297 */
298
299 /* This is also a macro */
300 PERL_CALLCONV U8*       Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags);
301
302 U8 *
303 Perl_uvchr_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
304 {
305     return uvchr_to_utf8_flags(d, uv, flags);
306 }
307
308 /*
309
310 Tests if the first C<len> bytes of string C<s> form a valid UTF-8
311 character.  Note that an INVARIANT (i.e. ASCII on non-EBCDIC) character is a
312 valid UTF-8 character.  The number of bytes in the UTF-8 character
313 will be returned if it is valid, otherwise 0.
314
315 This is the "slow" version as opposed to the "fast" version which is
316 the "unrolled" IS_UTF8_CHAR().  E.g. for t/uni/class.t the speed
317 difference is a factor of 2 to 3.  For lengths (UTF8SKIP(s)) of four
318 or less you should use the IS_UTF8_CHAR(), for lengths of five or more
319 you should use the _slow().  In practice this means that the _slow()
320 will be used very rarely, since the maximum Unicode code point (as of
321 Unicode 4.1) is U+10FFFF, which encodes in UTF-8 to four bytes.  Only
322 the "Perl extended UTF-8" (e.g, the infamous 'v-strings') will encode into
323 five bytes or more.
324
325 =cut */
326 PERL_STATIC_INLINE STRLEN
327 S_is_utf8_char_slow(const U8 *s, const STRLEN len)
328 {
329     dTHX;   /* The function called below requires thread context */
330
331     STRLEN actual_len;
332
333     PERL_ARGS_ASSERT_IS_UTF8_CHAR_SLOW;
334
335     utf8n_to_uvchr(s, len, &actual_len, UTF8_CHECK_ONLY);
336
337     return (actual_len == (STRLEN) -1) ? 0 : actual_len;
338 }
339
340 /*
341 =for apidoc is_utf8_char_buf
342
343 Returns the number of bytes that comprise the first UTF-8 encoded character in
344 buffer C<buf>.  C<buf_end> should point to one position beyond the end of the
345 buffer.  0 is returned if C<buf> does not point to a complete, valid UTF-8
346 encoded character.
347
348 Note that an INVARIANT character (i.e. ASCII on non-EBCDIC
349 machines) is a valid UTF-8 character.
350
351 =cut */
352
353 STRLEN
354 Perl_is_utf8_char_buf(const U8 *buf, const U8* buf_end)
355 {
356
357     STRLEN len;
358
359     PERL_ARGS_ASSERT_IS_UTF8_CHAR_BUF;
360
361     if (buf_end <= buf) {
362         return 0;
363     }
364
365     len = buf_end - buf;
366     if (len > UTF8SKIP(buf)) {
367         len = UTF8SKIP(buf);
368     }
369
370     if (IS_UTF8_CHAR_FAST(len))
371         return IS_UTF8_CHAR(buf, len) ? len : 0;
372     return is_utf8_char_slow(buf, len);
373 }
374
375 /*
376 =for apidoc is_utf8_char
377
378 Tests if some arbitrary number of bytes begins in a valid UTF-8
379 character.  Note that an INVARIANT (i.e. ASCII on non-EBCDIC machines)
380 character is a valid UTF-8 character.  The actual number of bytes in the UTF-8
381 character will be returned if it is valid, otherwise 0.
382
383 This function is deprecated due to the possibility that malformed input could
384 cause reading beyond the end of the input buffer.  Use L</is_utf8_char_buf>
385 instead.
386
387 =cut */
388
389 STRLEN
390 Perl_is_utf8_char(const U8 *s)
391 {
392     PERL_ARGS_ASSERT_IS_UTF8_CHAR;
393
394     /* Assumes we have enough space, which is why this is deprecated */
395     return is_utf8_char_buf(s, s + UTF8SKIP(s));
396 }
397
398
399 /*
400 =for apidoc is_utf8_string
401
402 Returns true if the first C<len> bytes of string C<s> form a valid
403 UTF-8 string, false otherwise.  If C<len> is 0, it will be calculated
404 using C<strlen(s)> (which means if you use this option, that C<s> has to have a
405 terminating NUL byte).  Note that all characters being ASCII constitute 'a
406 valid UTF-8 string'.
407
408 See also L</is_ascii_string>(), L</is_utf8_string_loclen>(), and L</is_utf8_string_loc>().
409
410 =cut
411 */
412
413 bool
414 Perl_is_utf8_string(const U8 *s, STRLEN len)
415 {
416     const U8* const send = s + (len ? len : strlen((const char *)s));
417     const U8* x = s;
418
419     PERL_ARGS_ASSERT_IS_UTF8_STRING;
420
421     while (x < send) {
422          /* Inline the easy bits of is_utf8_char() here for speed... */
423          if (UTF8_IS_INVARIANT(*x)) {
424             x++;
425          }
426          else {
427               /* ... and call is_utf8_char() only if really needed. */
428              const STRLEN c = UTF8SKIP(x);
429              const U8* const next_char_ptr = x + c;
430
431              if (next_char_ptr > send) {
432                  return FALSE;
433              }
434
435              if (IS_UTF8_CHAR_FAST(c)) {
436                  if (!IS_UTF8_CHAR(x, c))
437                      return FALSE;
438              }
439              else if (! is_utf8_char_slow(x, c)) {
440                  return FALSE;
441              }
442              x = next_char_ptr;
443          }
444     }
445
446     return TRUE;
447 }
448
449 /*
450 Implemented as a macro in utf8.h
451
452 =for apidoc is_utf8_string_loc
453
454 Like L</is_utf8_string> but stores the location of the failure (in the
455 case of "utf8ness failure") or the location C<s>+C<len> (in the case of
456 "utf8ness success") in the C<ep>.
457
458 See also L</is_utf8_string_loclen>() and L</is_utf8_string>().
459
460 =for apidoc is_utf8_string_loclen
461
462 Like L</is_utf8_string>() but stores the location of the failure (in the
463 case of "utf8ness failure") or the location C<s>+C<len> (in the case of
464 "utf8ness success") in the C<ep>, and the number of UTF-8
465 encoded characters in the C<el>.
466
467 See also L</is_utf8_string_loc>() and L</is_utf8_string>().
468
469 =cut
470 */
471
472 bool
473 Perl_is_utf8_string_loclen(const U8 *s, STRLEN len, const U8 **ep, STRLEN *el)
474 {
475     const U8* const send = s + (len ? len : strlen((const char *)s));
476     const U8* x = s;
477     STRLEN c;
478     STRLEN outlen = 0;
479
480     PERL_ARGS_ASSERT_IS_UTF8_STRING_LOCLEN;
481
482     while (x < send) {
483          const U8* next_char_ptr;
484
485          /* Inline the easy bits of is_utf8_char() here for speed... */
486          if (UTF8_IS_INVARIANT(*x))
487              next_char_ptr = x + 1;
488          else {
489              /* ... and call is_utf8_char() only if really needed. */
490              c = UTF8SKIP(x);
491              next_char_ptr = c + x;
492              if (next_char_ptr > send) {
493                  goto out;
494              }
495              if (IS_UTF8_CHAR_FAST(c)) {
496                  if (!IS_UTF8_CHAR(x, c))
497                      c = 0;
498              } else
499                  c = is_utf8_char_slow(x, c);
500              if (!c)
501                  goto out;
502          }
503          x = next_char_ptr;
504          outlen++;
505     }
506
507  out:
508     if (el)
509         *el = outlen;
510
511     if (ep)
512         *ep = x;
513     return (x == send);
514 }
515
516 /*
517
518 =for apidoc utf8n_to_uvchr
519
520 THIS FUNCTION SHOULD BE USED IN ONLY VERY SPECIALIZED CIRCUMSTANCES.
521 Most code should use L</utf8_to_uvchr_buf>() rather than call this directly.
522
523 Bottom level UTF-8 decode routine.
524 Returns the native code point value of the first character in the string C<s>,
525 which is assumed to be in UTF-8 (or UTF-EBCDIC) encoding, and no longer than
526 C<curlen> bytes; C<*retlen> (if C<retlen> isn't NULL) will be set to
527 the length, in bytes, of that character.
528
529 The value of C<flags> determines the behavior when C<s> does not point to a
530 well-formed UTF-8 character.  If C<flags> is 0, when a malformation is found,
531 zero is returned and C<*retlen> is set so that (S<C<s> + C<*retlen>>) is the
532 next possible position in C<s> that could begin a non-malformed character.
533 Also, if UTF-8 warnings haven't been lexically disabled, a warning is raised.
534
535 Various ALLOW flags can be set in C<flags> to allow (and not warn on)
536 individual types of malformations, such as the sequence being overlong (that
537 is, when there is a shorter sequence that can express the same code point;
538 overlong sequences are expressly forbidden in the UTF-8 standard due to
539 potential security issues).  Another malformation example is the first byte of
540 a character not being a legal first byte.  See F<utf8.h> for the list of such
541 flags.  For allowed 0 length strings, this function returns 0; for allowed
542 overlong sequences, the computed code point is returned; for all other allowed
543 malformations, the Unicode REPLACEMENT CHARACTER is returned, as these have no
544 determinable reasonable value.
545
546 The UTF8_CHECK_ONLY flag overrides the behavior when a non-allowed (by other
547 flags) malformation is found.  If this flag is set, the routine assumes that
548 the caller will raise a warning, and this function will silently just set
549 C<retlen> to C<-1> (cast to C<STRLEN>) and return zero.
550
551 Note that this API requires disambiguation between successful decoding a NUL
552 character, and an error return (unless the UTF8_CHECK_ONLY flag is set), as
553 in both cases, 0 is returned.  To disambiguate, upon a zero return, see if the
554 first byte of C<s> is 0 as well.  If so, the input was a NUL; if not, the input
555 had an error.
556
557 Certain code points are considered problematic.  These are Unicode surrogates,
558 Unicode non-characters, and code points above the Unicode maximum of 0x10FFFF.
559 By default these are considered regular code points, but certain situations
560 warrant special handling for them.  If C<flags> contains
561 UTF8_DISALLOW_ILLEGAL_INTERCHANGE, all three classes are treated as
562 malformations and handled as such.  The flags UTF8_DISALLOW_SURROGATE,
563 UTF8_DISALLOW_NONCHAR, and UTF8_DISALLOW_SUPER (meaning above the legal Unicode
564 maximum) can be set to disallow these categories individually.
565
566 The flags UTF8_WARN_ILLEGAL_INTERCHANGE, UTF8_WARN_SURROGATE,
567 UTF8_WARN_NONCHAR, and UTF8_WARN_SUPER will cause warning messages to be raised
568 for their respective categories, but otherwise the code points are considered
569 valid (not malformations).  To get a category to both be treated as a
570 malformation and raise a warning, specify both the WARN and DISALLOW flags.
571 (But note that warnings are not raised if lexically disabled nor if
572 UTF8_CHECK_ONLY is also specified.)
573
574 Very large code points (above 0x7FFF_FFFF) are considered more problematic than
575 the others that are above the Unicode legal maximum.  There are several
576 reasons: they requre at least 32 bits to represent them on ASCII platforms, are
577 not representable at all on EBCDIC platforms, and the original UTF-8
578 specification never went above this number (the current 0x10FFFF limit was
579 imposed later).  (The smaller ones, those that fit into 32 bits, are
580 representable by a UV on ASCII platforms, but not by an IV, which means that
581 the number of operations that can be performed on them is quite restricted.)
582 The UTF-8 encoding on ASCII platforms for these large code points begins with a
583 byte containing 0xFE or 0xFF.  The UTF8_DISALLOW_FE_FF flag will cause them to
584 be treated as malformations, while allowing smaller above-Unicode code points.
585 (Of course UTF8_DISALLOW_SUPER will treat all above-Unicode code points,
586 including these, as malformations.)
587 Similarly, UTF8_WARN_FE_FF acts just like
588 the other WARN flags, but applies just to these code points.
589
590 All other code points corresponding to Unicode characters, including private
591 use and those yet to be assigned, are never considered malformed and never
592 warn.
593
594 =cut
595 */
596
597 UV
598 Perl_utf8n_to_uvchr(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
599 {
600     dVAR;
601     const U8 * const s0 = s;
602     U8 overflow_byte = '\0';    /* Save byte in case of overflow */
603     U8 * send;
604     UV uv = *s;
605     STRLEN expectlen;
606     SV* sv = NULL;
607     UV outlier_ret = 0; /* return value when input is in error or problematic
608                          */
609     UV pack_warn = 0;   /* Save result of packWARN() for later */
610     bool unexpected_non_continuation = FALSE;
611     bool overflowed = FALSE;
612     bool do_overlong_test = TRUE;   /* May have to skip this test */
613
614     const char* const malformed_text = "Malformed UTF-8 character";
615
616     PERL_ARGS_ASSERT_UTF8N_TO_UVCHR;
617
618     /* The order of malformation tests here is important.  We should consume as
619      * few bytes as possible in order to not skip any valid character.  This is
620      * required by the Unicode Standard (section 3.9 of Unicode 6.0); see also
621      * http://unicode.org/reports/tr36 for more discussion as to why.  For
622      * example, once we've done a UTF8SKIP, we can tell the expected number of
623      * bytes, and could fail right off the bat if the input parameters indicate
624      * that there are too few available.  But it could be that just that first
625      * byte is garbled, and the intended character occupies fewer bytes.  If we
626      * blindly assumed that the first byte is correct, and skipped based on
627      * that number, we could skip over a valid input character.  So instead, we
628      * always examine the sequence byte-by-byte.
629      *
630      * We also should not consume too few bytes, otherwise someone could inject
631      * things.  For example, an input could be deliberately designed to
632      * overflow, and if this code bailed out immediately upon discovering that,
633      * returning to the caller C<*retlen> pointing to the very next byte (one
634      * which is actually part of of the overflowing sequence), that could look
635      * legitimate to the caller, which could discard the initial partial
636      * sequence and process the rest, inappropriately */
637
638     /* Zero length strings, if allowed, of necessity are zero */
639     if (UNLIKELY(curlen == 0)) {
640         if (retlen) {
641             *retlen = 0;
642         }
643
644         if (flags & UTF8_ALLOW_EMPTY) {
645             return 0;
646         }
647         if (! (flags & UTF8_CHECK_ONLY)) {
648             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (empty string)", malformed_text));
649         }
650         goto malformed;
651     }
652
653     expectlen = UTF8SKIP(s);
654
655     /* A well-formed UTF-8 character, as the vast majority of calls to this
656      * function will be for, has this expected length.  For efficiency, set
657      * things up here to return it.  It will be overriden only in those rare
658      * cases where a malformation is found */
659     if (retlen) {
660         *retlen = expectlen;
661     }
662
663     /* An invariant is trivially well-formed */
664     if (UTF8_IS_INVARIANT(uv)) {
665         return uv;
666     }
667
668     /* A continuation character can't start a valid sequence */
669     if (UNLIKELY(UTF8_IS_CONTINUATION(uv))) {
670         if (flags & UTF8_ALLOW_CONTINUATION) {
671             if (retlen) {
672                 *retlen = 1;
673             }
674             return UNICODE_REPLACEMENT;
675         }
676
677         if (! (flags & UTF8_CHECK_ONLY)) {
678             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected continuation byte 0x%02x, with no preceding start byte)", malformed_text, *s0));
679         }
680         curlen = 1;
681         goto malformed;
682     }
683
684     /* Here is not a continuation byte, nor an invariant.  The only thing left
685      * is a start byte (possibly for an overlong) */
686
687 #ifdef EBCDIC
688     uv = NATIVE_UTF8_TO_I8(uv);
689 #endif
690
691     /* Remove the leading bits that indicate the number of bytes in the
692      * character's whole UTF-8 sequence, leaving just the bits that are part of
693      * the value */
694     uv &= UTF_START_MASK(expectlen);
695
696     /* Now, loop through the remaining bytes in the character's sequence,
697      * accumulating each into the working value as we go.  Be sure to not look
698      * past the end of the input string */
699     send =  (U8*) s0 + ((expectlen <= curlen) ? expectlen : curlen);
700
701     for (s = s0 + 1; s < send; s++) {
702         if (LIKELY(UTF8_IS_CONTINUATION(*s))) {
703 #ifndef EBCDIC  /* Can't overflow in EBCDIC */
704             if (uv & UTF_ACCUMULATION_OVERFLOW_MASK) {
705
706                 /* The original implementors viewed this malformation as more
707                  * serious than the others (though I, khw, don't understand
708                  * why, since other malformations also give very very wrong
709                  * results), so there is no way to turn off checking for it.
710                  * Set a flag, but keep going in the loop, so that we absorb
711                  * the rest of the bytes that comprise the character. */
712                 overflowed = TRUE;
713                 overflow_byte = *s; /* Save for warning message's use */
714             }
715 #endif
716             uv = UTF8_ACCUMULATE(uv, *s);
717         }
718         else {
719             /* Here, found a non-continuation before processing all expected
720              * bytes.  This byte begins a new character, so quit, even if
721              * allowing this malformation. */
722             unexpected_non_continuation = TRUE;
723             break;
724         }
725     } /* End of loop through the character's bytes */
726
727     /* Save how many bytes were actually in the character */
728     curlen = s - s0;
729
730     /* The loop above finds two types of malformations: non-continuation and/or
731      * overflow.  The non-continuation malformation is really a too-short
732      * malformation, as it means that the current character ended before it was
733      * expected to (being terminated prematurely by the beginning of the next
734      * character, whereas in the too-short malformation there just are too few
735      * bytes available to hold the character.  In both cases, the check below
736      * that we have found the expected number of bytes would fail if executed.)
737      * Thus the non-continuation malformation is really unnecessary, being a
738      * subset of the too-short malformation.  But there may be existing
739      * applications that are expecting the non-continuation type, so we retain
740      * it, and return it in preference to the too-short malformation.  (If this
741      * code were being written from scratch, the two types might be collapsed
742      * into one.)  I, khw, am also giving priority to returning the
743      * non-continuation and too-short malformations over overflow when multiple
744      * ones are present.  I don't know of any real reason to prefer one over
745      * the other, except that it seems to me that multiple-byte errors trumps
746      * errors from a single byte */
747     if (UNLIKELY(unexpected_non_continuation)) {
748         if (!(flags & UTF8_ALLOW_NON_CONTINUATION)) {
749             if (! (flags & UTF8_CHECK_ONLY)) {
750                 if (curlen == 1) {
751                     sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (unexpected non-continuation byte 0x%02x, immediately after start byte 0x%02x)", malformed_text, *s, *s0));
752                 }
753                 else {
754                     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));
755                 }
756             }
757             goto malformed;
758         }
759         uv = UNICODE_REPLACEMENT;
760
761         /* Skip testing for overlongs, as the REPLACEMENT may not be the same
762          * as what the original expectations were. */
763         do_overlong_test = FALSE;
764         if (retlen) {
765             *retlen = curlen;
766         }
767     }
768     else if (UNLIKELY(curlen < expectlen)) {
769         if (! (flags & UTF8_ALLOW_SHORT)) {
770             if (! (flags & UTF8_CHECK_ONLY)) {
771                 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));
772             }
773             goto malformed;
774         }
775         uv = UNICODE_REPLACEMENT;
776         do_overlong_test = FALSE;
777         if (retlen) {
778             *retlen = curlen;
779         }
780     }
781
782 #ifndef EBCDIC  /* EBCDIC can't overflow */
783     if (UNLIKELY(overflowed)) {
784         sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (overflow at byte 0x%02x, after start byte 0x%02x)", malformed_text, overflow_byte, *s0));
785         goto malformed;
786     }
787 #endif
788
789     if (do_overlong_test
790         && expectlen > (STRLEN) OFFUNISKIP(uv)
791         && ! (flags & UTF8_ALLOW_LONG))
792     {
793         /* The overlong malformation has lower precedence than the others.
794          * Note that if this malformation is allowed, we return the actual
795          * value, instead of the replacement character.  This is because this
796          * value is actually well-defined. */
797         if (! (flags & UTF8_CHECK_ONLY)) {
798             sv = sv_2mortal(Perl_newSVpvf(aTHX_ "%s (%d byte%s, need %d, after start byte 0x%02x)", malformed_text, (int)expectlen, expectlen == 1 ? "": "s", OFFUNISKIP(uv), *s0));
799         }
800         goto malformed;
801     }
802
803     /* Here, the input is considered to be well-formed, but it still could be a
804      * problematic code point that is not allowed by the input parameters. */
805     if (uv >= UNICODE_SURROGATE_FIRST /* isn't problematic if < this */
806         && (flags & (UTF8_DISALLOW_ILLEGAL_INTERCHANGE
807                      |UTF8_WARN_ILLEGAL_INTERCHANGE)))
808     {
809         if (UNICODE_IS_SURROGATE(uv)) {
810
811             /* By adding UTF8_CHECK_ONLY to the test, we avoid unnecessary
812              * generation of the sv, since no warnings are raised under CHECK */
813             if ((flags & (UTF8_WARN_SURROGATE|UTF8_CHECK_ONLY)) == UTF8_WARN_SURROGATE
814                 && ckWARN_d(WARN_SURROGATE))
815             {
816                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "UTF-16 surrogate U+%04"UVXf"", uv));
817                 pack_warn = packWARN(WARN_SURROGATE);
818             }
819             if (flags & UTF8_DISALLOW_SURROGATE) {
820                 goto disallowed;
821             }
822         }
823         else if ((uv > PERL_UNICODE_MAX)) {
824             if ((flags & (UTF8_WARN_SUPER|UTF8_CHECK_ONLY)) == UTF8_WARN_SUPER
825                 && ckWARN_d(WARN_NON_UNICODE))
826             {
827                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv));
828                 pack_warn = packWARN(WARN_NON_UNICODE);
829             }
830 #ifndef EBCDIC  /* EBCDIC always allows FE, FF */
831
832             /* The first byte being 0xFE or 0xFF is a subset of the SUPER code
833              * points.  We test for these after the regular SUPER ones, and
834              * before possibly bailing out, so that the more dire warning
835              * overrides the regular one, if applicable */
836             if ((*s0 & 0xFE) == 0xFE    /* matches both FE, FF */
837                 && (flags & (UTF8_WARN_FE_FF|UTF8_DISALLOW_FE_FF)))
838             {
839                 if ((flags & (UTF8_WARN_FE_FF|UTF8_CHECK_ONLY))
840                                                             == UTF8_WARN_FE_FF
841                     && ckWARN_d(WARN_UTF8))
842                 {
843                     sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Code point 0x%"UVXf" is not Unicode, and not portable", uv));
844                     pack_warn = packWARN(WARN_UTF8);
845                 }
846                 if (flags & UTF8_DISALLOW_FE_FF) {
847                     goto disallowed;
848                 }
849             }
850 #endif
851             if (flags & UTF8_DISALLOW_SUPER) {
852                 goto disallowed;
853             }
854         }
855         else if (UNICODE_IS_NONCHAR(uv)) {
856             if ((flags & (UTF8_WARN_NONCHAR|UTF8_CHECK_ONLY)) == UTF8_WARN_NONCHAR
857                 && ckWARN_d(WARN_NONCHAR))
858             {
859                 sv = sv_2mortal(Perl_newSVpvf(aTHX_ "Unicode non-character U+%04"UVXf" is illegal for open interchange", uv));
860                 pack_warn = packWARN(WARN_NONCHAR);
861             }
862             if (flags & UTF8_DISALLOW_NONCHAR) {
863                 goto disallowed;
864             }
865         }
866
867         if (sv) {
868             outlier_ret = uv;   /* Note we don't bother to convert to native,
869                                    as all the outlier code points are the same
870                                    in both ASCII and EBCDIC */
871             goto do_warn;
872         }
873
874         /* Here, this is not considered a malformed character, so drop through
875          * to return it */
876     }
877
878     return UNI_TO_NATIVE(uv);
879
880     /* There are three cases which get to beyond this point.  In all 3 cases:
881      * <sv>         if not null points to a string to print as a warning.
882      * <curlen>     is what <*retlen> should be set to if UTF8_CHECK_ONLY isn't
883      *              set.
884      * <outlier_ret> is what return value to use if UTF8_CHECK_ONLY isn't set.
885      *              This is done by initializing it to 0, and changing it only
886      *              for case 1).
887      * The 3 cases are:
888      * 1)   The input is valid but problematic, and to be warned about.  The
889      *      return value is the resultant code point; <*retlen> is set to
890      *      <curlen>, the number of bytes that comprise the code point.
891      *      <pack_warn> contains the result of packWARN() for the warning
892      *      types.  The entry point for this case is the label <do_warn>;
893      * 2)   The input is a valid code point but disallowed by the parameters to
894      *      this function.  The return value is 0.  If UTF8_CHECK_ONLY is set,
895      *      <*relen> is -1; otherwise it is <curlen>, the number of bytes that
896      *      comprise the code point.  <pack_warn> contains the result of
897      *      packWARN() for the warning types.  The entry point for this case is
898      *      the label <disallowed>.
899      * 3)   The input is malformed.  The return value is 0.  If UTF8_CHECK_ONLY
900      *      is set, <*relen> is -1; otherwise it is <curlen>, the number of
901      *      bytes that comprise the malformation.  All such malformations are
902      *      assumed to be warning type <utf8>.  The entry point for this case
903      *      is the label <malformed>.
904      */
905
906 malformed:
907
908     if (sv && ckWARN_d(WARN_UTF8)) {
909         pack_warn = packWARN(WARN_UTF8);
910     }
911
912 disallowed:
913
914     if (flags & UTF8_CHECK_ONLY) {
915         if (retlen)
916             *retlen = ((STRLEN) -1);
917         return 0;
918     }
919
920 do_warn:
921
922     if (pack_warn) {    /* <pack_warn> was initialized to 0, and changed only
923                            if warnings are to be raised. */
924         const char * const string = SvPVX_const(sv);
925
926         if (PL_op)
927             Perl_warner(aTHX_ pack_warn, "%s in %s", string,  OP_DESC(PL_op));
928         else
929             Perl_warner(aTHX_ pack_warn, "%s", string);
930     }
931
932     if (retlen) {
933         *retlen = curlen;
934     }
935
936     return outlier_ret;
937 }
938
939 /*
940 =for apidoc utf8_to_uvchr_buf
941
942 Returns the native code point of the first character in the string C<s> which
943 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
944 C<*retlen> will be set to the length, in bytes, of that character.
945
946 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
947 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
948 NULL) to -1.  If those warnings are off, the computed value, if well-defined
949 (or the Unicode REPLACEMENT CHARACTER if not), is silently returned, and
950 C<*retlen> is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is
951 the next possible position in C<s> that could begin a non-malformed character.
952 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is
953 returned.
954
955 =cut
956 */
957
958
959 UV
960 Perl_utf8_to_uvchr_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
961 {
962     assert(s < send);
963
964     return utf8n_to_uvchr(s, send - s, retlen,
965                           ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY);
966 }
967
968 /* Like L</utf8_to_uvchr_buf>(), but should only be called when it is known that
969  * there are no malformations in the input UTF-8 string C<s>.  surrogates,
970  * non-character code points, and non-Unicode code points are allowed. */
971
972 UV
973 Perl_valid_utf8_to_uvchr(pTHX_ const U8 *s, STRLEN *retlen)
974 {
975     UV expectlen = UTF8SKIP(s);
976     const U8* send = s + expectlen;
977     UV uv = *s;
978
979     PERL_ARGS_ASSERT_VALID_UTF8_TO_UVCHR;
980
981     if (retlen) {
982         *retlen = expectlen;
983     }
984
985     /* An invariant is trivially returned */
986     if (expectlen == 1) {
987         return uv;
988     }
989
990 #ifdef EBCDIC
991     uv = NATIVE_UTF8_TO_I8(uv);
992 #endif
993
994     /* Remove the leading bits that indicate the number of bytes, leaving just
995      * the bits that are part of the value */
996     uv &= UTF_START_MASK(expectlen);
997
998     /* Now, loop through the remaining bytes, accumulating each into the
999      * working total as we go.  (I khw tried unrolling the loop for up to 4
1000      * bytes, but there was no performance improvement) */
1001     for (++s; s < send; s++) {
1002         uv = UTF8_ACCUMULATE(uv, *s);
1003     }
1004
1005     return UNI_TO_NATIVE(uv);
1006
1007 }
1008
1009 /*
1010 =for apidoc utf8_to_uvchr
1011
1012 Returns the native code point of the first character in the string C<s>
1013 which is assumed to be in UTF-8 encoding; C<retlen> will be set to the
1014 length, in bytes, of that character.
1015
1016 Some, but not all, UTF-8 malformations are detected, and in fact, some
1017 malformed input could cause reading beyond the end of the input buffer, which
1018 is why this function is deprecated.  Use L</utf8_to_uvchr_buf> instead.
1019
1020 If C<s> points to one of the detected malformations, and UTF8 warnings are
1021 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
1022 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1023 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1024 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1025 next possible position in C<s> that could begin a non-malformed character.
1026 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1027
1028 =cut
1029 */
1030
1031 UV
1032 Perl_utf8_to_uvchr(pTHX_ const U8 *s, STRLEN *retlen)
1033 {
1034     PERL_ARGS_ASSERT_UTF8_TO_UVCHR;
1035
1036     return utf8_to_uvchr_buf(s, s + UTF8_MAXBYTES, retlen);
1037 }
1038
1039 /*
1040 =for apidoc utf8_to_uvuni_buf
1041
1042 Only in very rare circumstances should code need to be dealing in Unicode
1043 (as opposed to native) code points.  In those few cases, use
1044 C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>> instead.
1045
1046 Returns the Unicode (not-native) code point of the first character in the
1047 string C<s> which
1048 is assumed to be in UTF-8 encoding; C<send> points to 1 beyond the end of C<s>.
1049 C<retlen> will be set to the length, in bytes, of that character.
1050
1051 If C<s> does not point to a well-formed UTF-8 character and UTF8 warnings are
1052 enabled, zero is returned and C<*retlen> is set (if C<retlen> isn't
1053 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1054 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1055 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1056 next possible position in C<s> that could begin a non-malformed character.
1057 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1058
1059 =cut
1060 */
1061
1062 UV
1063 Perl_utf8_to_uvuni_buf(pTHX_ const U8 *s, const U8 *send, STRLEN *retlen)
1064 {
1065     PERL_ARGS_ASSERT_UTF8_TO_UVUNI_BUF;
1066
1067     assert(send > s);
1068
1069     /* Call the low level routine asking for checks */
1070     return NATIVE_TO_UNI(Perl_utf8n_to_uvchr(aTHX_ s, send -s, retlen,
1071                                ckWARN_d(WARN_UTF8) ? 0 : UTF8_ALLOW_ANY));
1072 }
1073
1074 /* DEPRECATED!
1075  * Like L</utf8_to_uvuni_buf>(), but should only be called when it is known that
1076  * there are no malformations in the input UTF-8 string C<s>.  Surrogates,
1077  * non-character code points, and non-Unicode code points are allowed */
1078
1079 UV
1080 Perl_valid_utf8_to_uvuni(pTHX_ const U8 *s, STRLEN *retlen)
1081 {
1082     PERL_ARGS_ASSERT_VALID_UTF8_TO_UVUNI;
1083
1084     return NATIVE_TO_UNI(valid_utf8_to_uvchr(s, retlen));
1085 }
1086
1087 /*
1088 =for apidoc utf8_to_uvuni
1089
1090 Returns the Unicode code point of the first character in the string C<s>
1091 which is assumed to be in UTF-8 encoding; C<retlen> will be set to the
1092 length, in bytes, of that character.
1093
1094 Some, but not all, UTF-8 malformations are detected, and in fact, some
1095 malformed input could cause reading beyond the end of the input buffer, which
1096 is one reason why this function is deprecated.  The other is that only in
1097 extremely limited circumstances should the Unicode versus native code point be
1098 of any interest to you.  See L</utf8_to_uvuni_buf> for alternatives.
1099
1100 If C<s> points to one of the detected malformations, and UTF8 warnings are
1101 enabled, zero is returned and C<*retlen> is set (if C<retlen> doesn't point to
1102 NULL) to -1.  If those warnings are off, the computed value if well-defined (or
1103 the Unicode REPLACEMENT CHARACTER, if not) is silently returned, and C<*retlen>
1104 is set (if C<retlen> isn't NULL) so that (S<C<s> + C<*retlen>>) is the
1105 next possible position in C<s> that could begin a non-malformed character.
1106 See L</utf8n_to_uvchr> for details on when the REPLACEMENT CHARACTER is returned.
1107
1108 =cut
1109 */
1110
1111 UV
1112 Perl_utf8_to_uvuni(pTHX_ const U8 *s, STRLEN *retlen)
1113 {
1114     PERL_ARGS_ASSERT_UTF8_TO_UVUNI;
1115
1116     return NATIVE_TO_UNI(valid_utf8_to_uvchr(s, retlen));
1117 }
1118
1119 /*
1120 =for apidoc utf8_length
1121
1122 Return the length of the UTF-8 char encoded string C<s> in characters.
1123 Stops at C<e> (inclusive).  If C<e E<lt> s> or if the scan would end
1124 up past C<e>, croaks.
1125
1126 =cut
1127 */
1128
1129 STRLEN
1130 Perl_utf8_length(pTHX_ const U8 *s, const U8 *e)
1131 {
1132     dVAR;
1133     STRLEN len = 0;
1134
1135     PERL_ARGS_ASSERT_UTF8_LENGTH;
1136
1137     /* Note: cannot use UTF8_IS_...() too eagerly here since e.g.
1138      * the bitops (especially ~) can create illegal UTF-8.
1139      * In other words: in Perl UTF-8 is not just for Unicode. */
1140
1141     if (e < s)
1142         goto warn_and_return;
1143     while (s < e) {
1144         s += UTF8SKIP(s);
1145         len++;
1146     }
1147
1148     if (e != s) {
1149         len--;
1150         warn_and_return:
1151         if (PL_op)
1152             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1153                              "%s in %s", unees, OP_DESC(PL_op));
1154         else
1155             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
1156     }
1157
1158     return len;
1159 }
1160
1161 /*
1162 =for apidoc utf8_distance
1163
1164 Returns the number of UTF-8 characters between the UTF-8 pointers C<a>
1165 and C<b>.
1166
1167 WARNING: use only if you *know* that the pointers point inside the
1168 same UTF-8 buffer.
1169
1170 =cut
1171 */
1172
1173 IV
1174 Perl_utf8_distance(pTHX_ const U8 *a, const U8 *b)
1175 {
1176     PERL_ARGS_ASSERT_UTF8_DISTANCE;
1177
1178     return (a < b) ? -1 * (IV) utf8_length(a, b) : (IV) utf8_length(b, a);
1179 }
1180
1181 /*
1182 =for apidoc utf8_hop
1183
1184 Return the UTF-8 pointer C<s> displaced by C<off> characters, either
1185 forward or backward.
1186
1187 WARNING: do not use the following unless you *know* C<off> is within
1188 the UTF-8 data pointed to by C<s> *and* that on entry C<s> is aligned
1189 on the first byte of character or just after the last byte of a character.
1190
1191 =cut
1192 */
1193
1194 U8 *
1195 Perl_utf8_hop(pTHX_ const U8 *s, I32 off)
1196 {
1197     PERL_ARGS_ASSERT_UTF8_HOP;
1198
1199     PERL_UNUSED_CONTEXT;
1200     /* Note: cannot use UTF8_IS_...() too eagerly here since e.g
1201      * the bitops (especially ~) can create illegal UTF-8.
1202      * In other words: in Perl UTF-8 is not just for Unicode. */
1203
1204     if (off >= 0) {
1205         while (off--)
1206             s += UTF8SKIP(s);
1207     }
1208     else {
1209         while (off++) {
1210             s--;
1211             while (UTF8_IS_CONTINUATION(*s))
1212                 s--;
1213         }
1214     }
1215     return (U8 *)s;
1216 }
1217
1218 /*
1219 =for apidoc bytes_cmp_utf8
1220
1221 Compares the sequence of characters (stored as octets) in C<b>, C<blen> with the
1222 sequence of characters (stored as UTF-8)
1223 in C<u>, C<ulen>.  Returns 0 if they are
1224 equal, -1 or -2 if the first string is less than the second string, +1 or +2
1225 if the first string is greater than the second string.
1226
1227 -1 or +1 is returned if the shorter string was identical to the start of the
1228 longer string.  -2 or +2 is returned if
1229 there was a difference between characters
1230 within the strings.
1231
1232 =cut
1233 */
1234
1235 int
1236 Perl_bytes_cmp_utf8(pTHX_ const U8 *b, STRLEN blen, const U8 *u, STRLEN ulen)
1237 {
1238     const U8 *const bend = b + blen;
1239     const U8 *const uend = u + ulen;
1240
1241     PERL_ARGS_ASSERT_BYTES_CMP_UTF8;
1242
1243     PERL_UNUSED_CONTEXT;
1244
1245     while (b < bend && u < uend) {
1246         U8 c = *u++;
1247         if (!UTF8_IS_INVARIANT(c)) {
1248             if (UTF8_IS_DOWNGRADEABLE_START(c)) {
1249                 if (u < uend) {
1250                     U8 c1 = *u++;
1251                     if (UTF8_IS_CONTINUATION(c1)) {
1252                         c = TWO_BYTE_UTF8_TO_NATIVE(c, c1);
1253                     } else {
1254                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1255                                          "Malformed UTF-8 character "
1256                                          "(unexpected non-continuation byte 0x%02x"
1257                                          ", immediately after start byte 0x%02x)"
1258                                          /* Dear diag.t, it's in the pod.  */
1259                                          "%s%s", c1, c,
1260                                          PL_op ? " in " : "",
1261                                          PL_op ? OP_DESC(PL_op) : "");
1262                         return -2;
1263                     }
1264                 } else {
1265                     if (PL_op)
1266                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
1267                                          "%s in %s", unees, OP_DESC(PL_op));
1268                     else
1269                         Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8), "%s", unees);
1270                     return -2; /* Really want to return undef :-)  */
1271                 }
1272             } else {
1273                 return -2;
1274             }
1275         }
1276         if (*b != c) {
1277             return *b < c ? -2 : +2;
1278         }
1279         ++b;
1280     }
1281
1282     if (b == bend && u == uend)
1283         return 0;
1284
1285     return b < bend ? +1 : -1;
1286 }
1287
1288 /*
1289 =for apidoc utf8_to_bytes
1290
1291 Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
1292 Unlike L</bytes_to_utf8>, this over-writes the original string, and
1293 updates C<len> to contain the new length.
1294 Returns zero on failure, setting C<len> to -1.
1295
1296 If you need a copy of the string, see L</bytes_from_utf8>.
1297
1298 =cut
1299 */
1300
1301 U8 *
1302 Perl_utf8_to_bytes(pTHX_ U8 *s, STRLEN *len)
1303 {
1304     U8 * const save = s;
1305     U8 * const send = s + *len;
1306     U8 *d;
1307
1308     PERL_ARGS_ASSERT_UTF8_TO_BYTES;
1309
1310     /* ensure valid UTF-8 and chars < 256 before updating string */
1311     while (s < send) {
1312         if (! UTF8_IS_INVARIANT(*s)) {
1313             if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1314                 *len = ((STRLEN) -1);
1315                 return 0;
1316             }
1317             s++;
1318         }
1319         s++;
1320     }
1321
1322     d = s = save;
1323     while (s < send) {
1324         U8 c = *s++;
1325         if (! UTF8_IS_INVARIANT(c)) {
1326             /* Then it is two-byte encoded */
1327             c = TWO_BYTE_UTF8_TO_NATIVE(c, *s);
1328             s++;
1329         }
1330         *d++ = c;
1331     }
1332     *d = '\0';
1333     *len = d - save;
1334     return save;
1335 }
1336
1337 /*
1338 =for apidoc bytes_from_utf8
1339
1340 Converts a string C<s> of length C<len> from UTF-8 into native byte encoding.
1341 Unlike L</utf8_to_bytes> but like L</bytes_to_utf8>, returns a pointer to
1342 the newly-created string, and updates C<len> to contain the new
1343 length.  Returns the original string if no conversion occurs, C<len>
1344 is unchanged.  Do nothing if C<is_utf8> points to 0.  Sets C<is_utf8> to
1345 0 if C<s> is converted or consisted entirely of characters that are invariant
1346 in utf8 (i.e., US-ASCII on non-EBCDIC machines).
1347
1348 =cut
1349 */
1350
1351 U8 *
1352 Perl_bytes_from_utf8(pTHX_ const U8 *s, STRLEN *len, bool *is_utf8)
1353 {
1354     U8 *d;
1355     const U8 *start = s;
1356     const U8 *send;
1357     I32 count = 0;
1358
1359     PERL_ARGS_ASSERT_BYTES_FROM_UTF8;
1360
1361     PERL_UNUSED_CONTEXT;
1362     if (!*is_utf8)
1363         return (U8 *)start;
1364
1365     /* ensure valid UTF-8 and chars < 256 before converting string */
1366     for (send = s + *len; s < send;) {
1367         if (! UTF8_IS_INVARIANT(*s)) {
1368             if (! UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(s, send)) {
1369                 return (U8 *)start;
1370             }
1371             count++;
1372             s++;
1373         }
1374         s++;
1375     }
1376
1377     *is_utf8 = FALSE;
1378
1379     Newx(d, (*len) - count + 1, U8);
1380     s = start; start = d;
1381     while (s < send) {
1382         U8 c = *s++;
1383         if (! UTF8_IS_INVARIANT(c)) {
1384             /* Then it is two-byte encoded */
1385             c = TWO_BYTE_UTF8_TO_NATIVE(c, *s);
1386             s++;
1387         }
1388         *d++ = c;
1389     }
1390     *d = '\0';
1391     *len = d - start;
1392     return (U8 *)start;
1393 }
1394
1395 /*
1396 =for apidoc bytes_to_utf8
1397
1398 Converts a string C<s> of length C<len> bytes from the native encoding into
1399 UTF-8.
1400 Returns a pointer to the newly-created string, and sets C<len> to
1401 reflect the new length in bytes.
1402
1403 A NUL character will be written after the end of the string.
1404
1405 If you want to convert to UTF-8 from encodings other than
1406 the native (Latin1 or EBCDIC),
1407 see L</sv_recode_to_utf8>().
1408
1409 =cut
1410 */
1411
1412 /* This logic is duplicated in sv_catpvn_flags, so any bug fixes will
1413    likewise need duplication. */
1414
1415 U8*
1416 Perl_bytes_to_utf8(pTHX_ const U8 *s, STRLEN *len)
1417 {
1418     const U8 * const send = s + (*len);
1419     U8 *d;
1420     U8 *dst;
1421
1422     PERL_ARGS_ASSERT_BYTES_TO_UTF8;
1423     PERL_UNUSED_CONTEXT;
1424
1425     Newx(d, (*len) * 2 + 1, U8);
1426     dst = d;
1427
1428     while (s < send) {
1429         append_utf8_from_native_byte(*s, &d);
1430         s++;
1431     }
1432     *d = '\0';
1433     *len = d-dst;
1434     return dst;
1435 }
1436
1437 /*
1438  * Convert native (big-endian) or reversed (little-endian) UTF-16 to UTF-8.
1439  *
1440  * Destination must be pre-extended to 3/2 source.  Do not use in-place.
1441  * We optimize for native, for obvious reasons. */
1442
1443 U8*
1444 Perl_utf16_to_utf8(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
1445 {
1446     U8* pend;
1447     U8* dstart = d;
1448
1449     PERL_ARGS_ASSERT_UTF16_TO_UTF8;
1450
1451     if (bytelen & 1)
1452         Perl_croak(aTHX_ "panic: utf16_to_utf8: odd bytelen %"UVuf, (UV)bytelen);
1453
1454     pend = p + bytelen;
1455
1456     while (p < pend) {
1457         UV uv = (p[0] << 8) + p[1]; /* UTF-16BE */
1458         p += 2;
1459         if (UNI_IS_INVARIANT(uv)) {
1460             *d++ = LATIN1_TO_NATIVE((U8) uv);
1461             continue;
1462         }
1463         if (uv <= MAX_UTF8_TWO_BYTE) {
1464             *d++ = UTF8_TWO_BYTE_HI(UNI_TO_NATIVE(uv));
1465             *d++ = UTF8_TWO_BYTE_LO(UNI_TO_NATIVE(uv));
1466             continue;
1467         }
1468 #define FIRST_HIGH_SURROGATE UNICODE_SURROGATE_FIRST
1469 #define LAST_HIGH_SURROGATE  0xDBFF
1470 #define FIRST_LOW_SURROGATE  0xDC00
1471 #define LAST_LOW_SURROGATE   UNICODE_SURROGATE_LAST
1472         if (uv >= FIRST_HIGH_SURROGATE && uv <= LAST_HIGH_SURROGATE) {
1473             if (p >= pend) {
1474                 Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1475             } else {
1476                 UV low = (p[0] << 8) + p[1];
1477                 p += 2;
1478                 if (low < FIRST_LOW_SURROGATE || low > LAST_LOW_SURROGATE)
1479                     Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1480                 uv = ((uv - FIRST_HIGH_SURROGATE) << 10)
1481                                        + (low - FIRST_LOW_SURROGATE) + 0x10000;
1482             }
1483         } else if (uv >= FIRST_LOW_SURROGATE && uv <= LAST_LOW_SURROGATE) {
1484             Perl_croak(aTHX_ "Malformed UTF-16 surrogate");
1485         }
1486 #ifdef EBCDIC
1487         d = uvoffuni_to_utf8_flags(d, uv, 0);
1488 #else
1489         if (uv < 0x10000) {
1490             *d++ = (U8)(( uv >> 12)         | 0xe0);
1491             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
1492             *d++ = (U8)(( uv        & 0x3f) | 0x80);
1493             continue;
1494         }
1495         else {
1496             *d++ = (U8)(( uv >> 18)         | 0xf0);
1497             *d++ = (U8)(((uv >> 12) & 0x3f) | 0x80);
1498             *d++ = (U8)(((uv >>  6) & 0x3f) | 0x80);
1499             *d++ = (U8)(( uv        & 0x3f) | 0x80);
1500             continue;
1501         }
1502 #endif
1503     }
1504     *newlen = d - dstart;
1505     return d;
1506 }
1507
1508 /* Note: this one is slightly destructive of the source. */
1509
1510 U8*
1511 Perl_utf16_to_utf8_reversed(pTHX_ U8* p, U8* d, I32 bytelen, I32 *newlen)
1512 {
1513     U8* s = (U8*)p;
1514     U8* const send = s + bytelen;
1515
1516     PERL_ARGS_ASSERT_UTF16_TO_UTF8_REVERSED;
1517
1518     if (bytelen & 1)
1519         Perl_croak(aTHX_ "panic: utf16_to_utf8_reversed: odd bytelen %"UVuf,
1520                    (UV)bytelen);
1521
1522     while (s < send) {
1523         const U8 tmp = s[0];
1524         s[0] = s[1];
1525         s[1] = tmp;
1526         s += 2;
1527     }
1528     return utf16_to_utf8(p, d, bytelen, newlen);
1529 }
1530
1531 bool
1532 Perl__is_uni_FOO(pTHX_ const U8 classnum, const UV c)
1533 {
1534     U8 tmpbuf[UTF8_MAXBYTES+1];
1535     uvchr_to_utf8(tmpbuf, c);
1536     return _is_utf8_FOO(classnum, tmpbuf);
1537 }
1538
1539 /* Internal function so we can deprecate the external one, and call
1540    this one from other deprecated functions in this file */
1541
1542 PERL_STATIC_INLINE bool
1543 S_is_utf8_idfirst(pTHX_ const U8 *p)
1544 {
1545     dVAR;
1546
1547     if (*p == '_')
1548         return TRUE;
1549     /* is_utf8_idstart would be more logical. */
1550     return is_utf8_common(p, &PL_utf8_idstart, "IdStart", NULL);
1551 }
1552
1553 bool
1554 Perl_is_uni_idfirst(pTHX_ UV c)
1555 {
1556     U8 tmpbuf[UTF8_MAXBYTES+1];
1557     uvchr_to_utf8(tmpbuf, c);
1558     return S_is_utf8_idfirst(aTHX_ tmpbuf);
1559 }
1560
1561 bool
1562 Perl__is_uni_perl_idcont(pTHX_ UV c)
1563 {
1564     U8 tmpbuf[UTF8_MAXBYTES+1];
1565     uvchr_to_utf8(tmpbuf, c);
1566     return _is_utf8_perl_idcont(tmpbuf);
1567 }
1568
1569 bool
1570 Perl__is_uni_perl_idstart(pTHX_ UV c)
1571 {
1572     U8 tmpbuf[UTF8_MAXBYTES+1];
1573     uvchr_to_utf8(tmpbuf, c);
1574     return _is_utf8_perl_idstart(tmpbuf);
1575 }
1576
1577 UV
1578 Perl__to_upper_title_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const char S_or_s)
1579 {
1580     /* We have the latin1-range values compiled into the core, so just use
1581      * those, converting the result to utf8.  The only difference between upper
1582      * and title case in this range is that LATIN_SMALL_LETTER_SHARP_S is
1583      * either "SS" or "Ss".  Which one to use is passed into the routine in
1584      * 'S_or_s' to avoid a test */
1585
1586     UV converted = toUPPER_LATIN1_MOD(c);
1587
1588     PERL_ARGS_ASSERT__TO_UPPER_TITLE_LATIN1;
1589
1590     assert(S_or_s == 'S' || S_or_s == 's');
1591
1592     if (UVCHR_IS_INVARIANT(converted)) { /* No difference between the two for
1593                                              characters in this range */
1594         *p = (U8) converted;
1595         *lenp = 1;
1596         return converted;
1597     }
1598
1599     /* toUPPER_LATIN1_MOD gives the correct results except for three outliers,
1600      * which it maps to one of them, so as to only have to have one check for
1601      * it in the main case */
1602     if (UNLIKELY(converted == LATIN_SMALL_LETTER_Y_WITH_DIAERESIS)) {
1603         switch (c) {
1604             case LATIN_SMALL_LETTER_Y_WITH_DIAERESIS:
1605                 converted = LATIN_CAPITAL_LETTER_Y_WITH_DIAERESIS;
1606                 break;
1607             case MICRO_SIGN:
1608                 converted = GREEK_CAPITAL_LETTER_MU;
1609                 break;
1610             case LATIN_SMALL_LETTER_SHARP_S:
1611                 *(p)++ = 'S';
1612                 *p = S_or_s;
1613                 *lenp = 2;
1614                 return 'S';
1615             default:
1616                 Perl_croak(aTHX_ "panic: to_upper_title_latin1 did not expect '%c' to map to '%c'", c, LATIN_SMALL_LETTER_Y_WITH_DIAERESIS);
1617                 assert(0); /* NOTREACHED */
1618         }
1619     }
1620
1621     *(p)++ = UTF8_TWO_BYTE_HI(converted);
1622     *p = UTF8_TWO_BYTE_LO(converted);
1623     *lenp = 2;
1624
1625     return converted;
1626 }
1627
1628 /* Call the function to convert a UTF-8 encoded character to the specified case.
1629  * Note that there may be more than one character in the result.
1630  * INP is a pointer to the first byte of the input character
1631  * OUTP will be set to the first byte of the string of changed characters.  It
1632  *      needs to have space for UTF8_MAXBYTES_CASE+1 bytes
1633  * LENP will be set to the length in bytes of the string of changed characters
1634  *
1635  * The functions return the ordinal of the first character in the string of OUTP */
1636 #define CALL_UPPER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_toupper, "ToUc", "")
1637 #define CALL_TITLE_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_totitle, "ToTc", "")
1638 #define CALL_LOWER_CASE(INP, OUTP, LENP) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tolower, "ToLc", "")
1639
1640 /* This additionally has the input parameter SPECIALS, which if non-zero will
1641  * cause this to use the SPECIALS hash for folding (meaning get full case
1642  * folding); otherwise, when zero, this implies a simple case fold */
1643 #define CALL_FOLD_CASE(INP, OUTP, LENP, SPECIALS) Perl_to_utf8_case(aTHX_ INP, OUTP, LENP, &PL_utf8_tofold, "ToCf", (SPECIALS) ? "" : NULL)
1644
1645 UV
1646 Perl_to_uni_upper(pTHX_ UV c, U8* p, STRLEN *lenp)
1647 {
1648     dVAR;
1649
1650     /* Convert the Unicode character whose ordinal is <c> to its uppercase
1651      * version and store that in UTF-8 in <p> and its length in bytes in <lenp>.
1652      * Note that the <p> needs to be at least UTF8_MAXBYTES_CASE+1 bytes since
1653      * the changed version may be longer than the original character.
1654      *
1655      * The ordinal of the first character of the changed version is returned
1656      * (but note, as explained above, that there may be more.) */
1657
1658     PERL_ARGS_ASSERT_TO_UNI_UPPER;
1659
1660     if (c < 256) {
1661         return _to_upper_title_latin1((U8) c, p, lenp, 'S');
1662     }
1663
1664     uvchr_to_utf8(p, c);
1665     return CALL_UPPER_CASE(p, p, lenp);
1666 }
1667
1668 UV
1669 Perl_to_uni_title(pTHX_ UV c, U8* p, STRLEN *lenp)
1670 {
1671     dVAR;
1672
1673     PERL_ARGS_ASSERT_TO_UNI_TITLE;
1674
1675     if (c < 256) {
1676         return _to_upper_title_latin1((U8) c, p, lenp, 's');
1677     }
1678
1679     uvchr_to_utf8(p, c);
1680     return CALL_TITLE_CASE(p, p, lenp);
1681 }
1682
1683 STATIC U8
1684 S_to_lower_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp)
1685 {
1686     /* We have the latin1-range values compiled into the core, so just use
1687      * those, converting the result to utf8.  Since the result is always just
1688      * one character, we allow <p> to be NULL */
1689
1690     U8 converted = toLOWER_LATIN1(c);
1691
1692     if (p != NULL) {
1693         if (NATIVE_BYTE_IS_INVARIANT(converted)) {
1694             *p = converted;
1695             *lenp = 1;
1696         }
1697         else {
1698             *p = UTF8_TWO_BYTE_HI(converted);
1699             *(p+1) = UTF8_TWO_BYTE_LO(converted);
1700             *lenp = 2;
1701         }
1702     }
1703     return converted;
1704 }
1705
1706 UV
1707 Perl_to_uni_lower(pTHX_ UV c, U8* p, STRLEN *lenp)
1708 {
1709     dVAR;
1710
1711     PERL_ARGS_ASSERT_TO_UNI_LOWER;
1712
1713     if (c < 256) {
1714         return to_lower_latin1((U8) c, p, lenp);
1715     }
1716
1717     uvchr_to_utf8(p, c);
1718     return CALL_LOWER_CASE(p, p, lenp);
1719 }
1720
1721 UV
1722 Perl__to_fold_latin1(pTHX_ const U8 c, U8* p, STRLEN *lenp, const unsigned int flags)
1723 {
1724     /* Corresponds to to_lower_latin1(); <flags> bits meanings:
1725      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1726      *      FOLD_FLAGS_FULL  iff full folding is to be used;
1727      *
1728      *  Not to be used for locale folds
1729      */
1730
1731     UV converted;
1732
1733     PERL_ARGS_ASSERT__TO_FOLD_LATIN1;
1734
1735     assert (! (flags & FOLD_FLAGS_LOCALE));
1736
1737     if (c == MICRO_SIGN) {
1738         converted = GREEK_SMALL_LETTER_MU;
1739     }
1740     else if ((flags & FOLD_FLAGS_FULL) && c == LATIN_SMALL_LETTER_SHARP_S) {
1741
1742         /* If can't cross 127/128 boundary, can't return "ss"; instead return
1743          * two U+017F characters, as fc("\df") should eq fc("\x{17f}\x{17f}")
1744          * under those circumstances. */
1745         if (flags & FOLD_FLAGS_NOMIX_ASCII) {
1746             *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
1747             Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
1748                  p, *lenp, U8);
1749             return LATIN_SMALL_LETTER_LONG_S;
1750         }
1751         else {
1752             *(p)++ = 's';
1753             *p = 's';
1754             *lenp = 2;
1755             return 's';
1756         }
1757     }
1758     else { /* In this range the fold of all other characters is their lower
1759               case */
1760         converted = toLOWER_LATIN1(c);
1761     }
1762
1763     if (UVCHR_IS_INVARIANT(converted)) {
1764         *p = (U8) converted;
1765         *lenp = 1;
1766     }
1767     else {
1768         *(p)++ = UTF8_TWO_BYTE_HI(converted);
1769         *p = UTF8_TWO_BYTE_LO(converted);
1770         *lenp = 2;
1771     }
1772
1773     return converted;
1774 }
1775
1776 UV
1777 Perl__to_uni_fold_flags(pTHX_ UV c, U8* p, STRLEN *lenp, const U8 flags)
1778 {
1779
1780     /* Not currently externally documented, and subject to change
1781      *  <flags> bits meanings:
1782      *      FOLD_FLAGS_FULL  iff full folding is to be used;
1783      *      FOLD_FLAGS_LOCALE iff in locale
1784      *      FOLD_FLAGS_NOMIX_ASCII iff non-ASCII to ASCII folds are prohibited
1785      */
1786
1787     PERL_ARGS_ASSERT__TO_UNI_FOLD_FLAGS;
1788
1789     if (c < 256) {
1790         UV result = _to_fold_latin1((U8) c, p, lenp,
1791                               flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
1792         /* It is illegal for the fold to cross the 255/256 boundary under
1793          * locale; in this case return the original */
1794         return (result > 256 && flags & FOLD_FLAGS_LOCALE)
1795                ? c
1796                : result;
1797     }
1798
1799     /* If no special needs, just use the macro */
1800     if ( ! (flags & (FOLD_FLAGS_LOCALE|FOLD_FLAGS_NOMIX_ASCII))) {
1801         uvchr_to_utf8(p, c);
1802         return CALL_FOLD_CASE(p, p, lenp, flags & FOLD_FLAGS_FULL);
1803     }
1804     else {  /* Otherwise, _to_utf8_fold_flags has the intelligence to deal with
1805                the special flags. */
1806         U8 utf8_c[UTF8_MAXBYTES + 1];
1807         uvchr_to_utf8(utf8_c, c);
1808         return _to_utf8_fold_flags(utf8_c, p, lenp, flags, NULL);
1809     }
1810 }
1811
1812 PERL_STATIC_INLINE bool
1813 S_is_utf8_common(pTHX_ const U8 *const p, SV **swash,
1814                  const char *const swashname, SV* const invlist)
1815 {
1816     /* returns a boolean giving whether or not the UTF8-encoded character that
1817      * starts at <p> is in the swash indicated by <swashname>.  <swash>
1818      * contains a pointer to where the swash indicated by <swashname>
1819      * is to be stored; which this routine will do, so that future calls will
1820      * look at <*swash> and only generate a swash if it is not null.  <invlist>
1821      * is NULL or an inversion list that defines the swash.  If not null, it
1822      * saves time during initialization of the swash.
1823      *
1824      * Note that it is assumed that the buffer length of <p> is enough to
1825      * contain all the bytes that comprise the character.  Thus, <*p> should
1826      * have been checked before this call for mal-formedness enough to assure
1827      * that. */
1828
1829     dVAR;
1830
1831     PERL_ARGS_ASSERT_IS_UTF8_COMMON;
1832
1833     /* The API should have included a length for the UTF-8 character in <p>,
1834      * but it doesn't.  We therefore assume that p has been validated at least
1835      * as far as there being enough bytes available in it to accommodate the
1836      * character without reading beyond the end, and pass that number on to the
1837      * validating routine */
1838     if (! is_utf8_char_buf(p, p + UTF8SKIP(p))) {
1839         if (ckWARN_d(WARN_UTF8)) {
1840             Perl_warner(aTHX_ packWARN2(WARN_DEPRECATED,WARN_UTF8),
1841                     "Passing malformed UTF-8 to \"%s\" is deprecated", swashname);
1842             if (ckWARN(WARN_UTF8)) {    /* This will output details as to the
1843                                            what the malformation is */
1844                 utf8_to_uvchr_buf(p, p + UTF8SKIP(p), NULL);
1845             }
1846         }
1847         return FALSE;
1848     }
1849     if (!*swash) {
1850         U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
1851         *swash = _core_swash_init("utf8",
1852
1853                                   /* Only use the name if there is no inversion
1854                                    * list; otherwise will go out to disk */
1855                                   (invlist) ? "" : swashname,
1856
1857                                   &PL_sv_undef, 1, 0, invlist, &flags);
1858     }
1859
1860     return swash_fetch(*swash, p, TRUE) != 0;
1861 }
1862
1863 bool
1864 Perl__is_utf8_FOO(pTHX_ const U8 classnum, const U8 *p)
1865 {
1866     dVAR;
1867
1868     PERL_ARGS_ASSERT__IS_UTF8_FOO;
1869
1870     assert(classnum < _FIRST_NON_SWASH_CC);
1871
1872     return is_utf8_common(p,
1873                           &PL_utf8_swash_ptrs[classnum],
1874                           swash_property_names[classnum],
1875                           PL_XPosix_ptrs[classnum]);
1876 }
1877
1878 bool
1879 Perl_is_utf8_idfirst(pTHX_ const U8 *p) /* The naming is historical. */
1880 {
1881     dVAR;
1882
1883     PERL_ARGS_ASSERT_IS_UTF8_IDFIRST;
1884
1885     return S_is_utf8_idfirst(aTHX_ p);
1886 }
1887
1888 bool
1889 Perl_is_utf8_xidfirst(pTHX_ const U8 *p) /* The naming is historical. */
1890 {
1891     dVAR;
1892
1893     PERL_ARGS_ASSERT_IS_UTF8_XIDFIRST;
1894
1895     if (*p == '_')
1896         return TRUE;
1897     /* is_utf8_idstart would be more logical. */
1898     return is_utf8_common(p, &PL_utf8_xidstart, "XIdStart", NULL);
1899 }
1900
1901 bool
1902 Perl__is_utf8_perl_idstart(pTHX_ const U8 *p)
1903 {
1904     dVAR;
1905     SV* invlist = NULL;
1906
1907     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDSTART;
1908
1909     if (! PL_utf8_perl_idstart) {
1910         invlist = _new_invlist_C_array(_Perl_IDStart_invlist);
1911     }
1912     return is_utf8_common(p, &PL_utf8_perl_idstart, "", invlist);
1913 }
1914
1915 bool
1916 Perl__is_utf8_perl_idcont(pTHX_ const U8 *p)
1917 {
1918     dVAR;
1919     SV* invlist = NULL;
1920
1921     PERL_ARGS_ASSERT__IS_UTF8_PERL_IDCONT;
1922
1923     if (! PL_utf8_perl_idcont) {
1924         invlist = _new_invlist_C_array(_Perl_IDCont_invlist);
1925     }
1926     return is_utf8_common(p, &PL_utf8_perl_idcont, "", invlist);
1927 }
1928
1929
1930 bool
1931 Perl_is_utf8_idcont(pTHX_ const U8 *p)
1932 {
1933     dVAR;
1934
1935     PERL_ARGS_ASSERT_IS_UTF8_IDCONT;
1936
1937     return is_utf8_common(p, &PL_utf8_idcont, "IdContinue", NULL);
1938 }
1939
1940 bool
1941 Perl_is_utf8_xidcont(pTHX_ const U8 *p)
1942 {
1943     dVAR;
1944
1945     PERL_ARGS_ASSERT_IS_UTF8_XIDCONT;
1946
1947     return is_utf8_common(p, &PL_utf8_idcont, "XIdContinue", NULL);
1948 }
1949
1950 bool
1951 Perl__is_utf8_mark(pTHX_ const U8 *p)
1952 {
1953     dVAR;
1954
1955     PERL_ARGS_ASSERT__IS_UTF8_MARK;
1956
1957     return is_utf8_common(p, &PL_utf8_mark, "IsM", NULL);
1958 }
1959
1960 /*
1961 =for apidoc to_utf8_case
1962
1963 C<p> contains the pointer to the UTF-8 string encoding
1964 the character that is being converted.  This routine assumes that the character
1965 at C<p> is well-formed.
1966
1967 C<ustrp> is a pointer to the character buffer to put the
1968 conversion result to.  C<lenp> is a pointer to the length
1969 of the result.
1970
1971 C<swashp> is a pointer to the swash to use.
1972
1973 Both the special and normal mappings are stored in F<lib/unicore/To/Foo.pl>,
1974 and loaded by SWASHNEW, using F<lib/utf8_heavy.pl>.  C<special> (usually,
1975 but not always, a multicharacter mapping), is tried first.
1976
1977 C<special> is a string, normally C<NULL> or C<"">.  C<NULL> means to not use
1978 any special mappings; C<""> means to use the special mappings.  Values other
1979 than these two are treated as the name of the hash containing the special
1980 mappings, like C<"utf8::ToSpecLower">.
1981
1982 C<normal> is a string like "ToLower" which means the swash
1983 %utf8::ToLower.
1984
1985 =cut */
1986
1987 UV
1988 Perl_to_utf8_case(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp,
1989                         SV **swashp, const char *normal, const char *special)
1990 {
1991     dVAR;
1992     STRLEN len = 0;
1993     const UV uv1 = valid_utf8_to_uvchr(p, NULL);
1994
1995     PERL_ARGS_ASSERT_TO_UTF8_CASE;
1996
1997     /* Note that swash_fetch() doesn't output warnings for these because it
1998      * assumes we will */
1999     if (uv1 >= UNICODE_SURROGATE_FIRST) {
2000         if (uv1 <= UNICODE_SURROGATE_LAST) {
2001             if (ckWARN_d(WARN_SURROGATE)) {
2002                 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
2003                 Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
2004                     "Operation \"%s\" returns its argument for UTF-16 surrogate U+%04"UVXf"", desc, uv1);
2005             }
2006         }
2007         else if (UNICODE_IS_SUPER(uv1)) {
2008             if (ckWARN_d(WARN_NON_UNICODE)) {
2009                 const char* desc = (PL_op) ? OP_DESC(PL_op) : normal;
2010                 Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
2011                     "Operation \"%s\" returns its argument for non-Unicode code point 0x%04"UVXf"", desc, uv1);
2012             }
2013         }
2014
2015         /* Note that non-characters are perfectly legal, so no warning should
2016          * be given */
2017     }
2018
2019     if (!*swashp) /* load on-demand */
2020          *swashp = _core_swash_init("utf8", normal, &PL_sv_undef, 4, 0, NULL, NULL);
2021
2022     if (special) {
2023          /* It might be "special" (sometimes, but not always,
2024           * a multicharacter mapping) */
2025          HV *hv = NULL;
2026          SV **svp;
2027
2028          /* If passed in the specials name, use that; otherwise use any
2029           * given in the swash */
2030          if (*special != '\0') {
2031             hv = get_hv(special, 0);
2032         }
2033         else {
2034             svp = hv_fetchs(MUTABLE_HV(SvRV(*swashp)), "SPECIALS", 0);
2035             if (svp) {
2036                 hv = MUTABLE_HV(SvRV(*svp));
2037             }
2038         }
2039
2040          if (hv
2041              && (svp = hv_fetch(hv, (const char*)p, UNISKIP(uv1), FALSE))
2042              && (*svp))
2043          {
2044              const char *s;
2045
2046               s = SvPV_const(*svp, len);
2047               if (len == 1)
2048                   /* EIGHTBIT */
2049                    len = uvchr_to_utf8(ustrp, *(U8*)s) - ustrp;
2050               else {
2051                    Copy(s, ustrp, len, U8);
2052               }
2053          }
2054     }
2055
2056     if (!len && *swashp) {
2057         const UV uv2 = swash_fetch(*swashp, p, TRUE /* => is utf8 */);
2058
2059          if (uv2) {
2060               /* It was "normal" (a single character mapping). */
2061               len = uvchr_to_utf8(ustrp, uv2) - ustrp;
2062          }
2063     }
2064
2065     if (len) {
2066         if (lenp) {
2067             *lenp = len;
2068         }
2069         return valid_utf8_to_uvchr(ustrp, 0);
2070     }
2071
2072     /* Here, there was no mapping defined, which means that the code point maps
2073      * to itself.  Return the inputs */
2074     len = UTF8SKIP(p);
2075     if (p != ustrp) {   /* Don't copy onto itself */
2076         Copy(p, ustrp, len, U8);
2077     }
2078
2079     if (lenp)
2080          *lenp = len;
2081
2082     return uv1;
2083
2084 }
2085
2086 STATIC UV
2087 S_check_locale_boundary_crossing(pTHX_ const U8* const p, const UV result, U8* const ustrp, STRLEN *lenp)
2088 {
2089     /* This is called when changing the case of a utf8-encoded character above
2090      * the Latin1 range, and the operation is in locale.  If the result
2091      * contains a character that crosses the 255/256 boundary, disallow the
2092      * change, and return the original code point.  See L<perlfunc/lc> for why;
2093      *
2094      * p        points to the original string whose case was changed; assumed
2095      *          by this routine to be well-formed
2096      * result   the code point of the first character in the changed-case string
2097      * ustrp    points to the changed-case string (<result> represents its first char)
2098      * lenp     points to the length of <ustrp> */
2099
2100     UV original;    /* To store the first code point of <p> */
2101
2102     PERL_ARGS_ASSERT_CHECK_LOCALE_BOUNDARY_CROSSING;
2103
2104     assert(UTF8_IS_ABOVE_LATIN1(*p));
2105
2106     /* We know immediately if the first character in the string crosses the
2107      * boundary, so can skip */
2108     if (result > 255) {
2109
2110         /* Look at every character in the result; if any cross the
2111         * boundary, the whole thing is disallowed */
2112         U8* s = ustrp + UTF8SKIP(ustrp);
2113         U8* e = ustrp + *lenp;
2114         while (s < e) {
2115             if (! UTF8_IS_ABOVE_LATIN1(*s)) {
2116                 goto bad_crossing;
2117             }
2118             s += UTF8SKIP(s);
2119         }
2120
2121         /* Here, no characters crossed, result is ok as-is */
2122         return result;
2123     }
2124
2125 bad_crossing:
2126
2127     /* Failed, have to return the original */
2128     original = valid_utf8_to_uvchr(p, lenp);
2129     Copy(p, ustrp, *lenp, char);
2130     return original;
2131 }
2132
2133 /*
2134 =for apidoc to_utf8_upper
2135
2136 Instead use L</toUPPER_utf8>.
2137
2138 =cut */
2139
2140 /* Not currently externally documented, and subject to change:
2141  * <flags> is set iff locale semantics are to be used for code points < 256
2142  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2143  *               were used in the calculation; otherwise unchanged. */
2144
2145 UV
2146 Perl__to_utf8_upper_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2147 {
2148     dVAR;
2149
2150     UV result;
2151
2152     PERL_ARGS_ASSERT__TO_UTF8_UPPER_FLAGS;
2153
2154     if (UTF8_IS_INVARIANT(*p)) {
2155         if (flags) {
2156             result = toUPPER_LC(*p);
2157         }
2158         else {
2159             return _to_upper_title_latin1(*p, ustrp, lenp, 'S');
2160         }
2161     }
2162     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2163         if (flags) {
2164             U8 c = TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1));
2165             result = toUPPER_LC(c);
2166         }
2167         else {
2168             return _to_upper_title_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2169                                           ustrp, lenp, 'S');
2170         }
2171     }
2172     else {  /* utf8, ord above 255 */
2173         result = CALL_UPPER_CASE(p, ustrp, lenp);
2174
2175         if (flags) {
2176             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2177         }
2178         return result;
2179     }
2180
2181     /* Here, used locale rules.  Convert back to utf8 */
2182     if (UTF8_IS_INVARIANT(result)) {
2183         *ustrp = (U8) result;
2184         *lenp = 1;
2185     }
2186     else {
2187         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2188         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
2189         *lenp = 2;
2190     }
2191
2192     if (tainted_ptr) {
2193         *tainted_ptr = TRUE;
2194     }
2195     return result;
2196 }
2197
2198 /*
2199 =for apidoc to_utf8_title
2200
2201 Instead use L</toTITLE_utf8>.
2202
2203 =cut */
2204
2205 /* Not currently externally documented, and subject to change:
2206  * <flags> is set iff locale semantics are to be used for code points < 256
2207  *         Since titlecase is not defined in POSIX, uppercase is used instead
2208  *         for these/
2209  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2210  *               were used in the calculation; otherwise unchanged. */
2211
2212 UV
2213 Perl__to_utf8_title_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2214 {
2215     dVAR;
2216
2217     UV result;
2218
2219     PERL_ARGS_ASSERT__TO_UTF8_TITLE_FLAGS;
2220
2221     if (UTF8_IS_INVARIANT(*p)) {
2222         if (flags) {
2223             result = toUPPER_LC(*p);
2224         }
2225         else {
2226             return _to_upper_title_latin1(*p, ustrp, lenp, 's');
2227         }
2228     }
2229     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2230         if (flags) {
2231             U8 c = TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1));
2232             result = toUPPER_LC(c);
2233         }
2234         else {
2235             return _to_upper_title_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2236                                           ustrp, lenp, 's');
2237         }
2238     }
2239     else {  /* utf8, ord above 255 */
2240         result = CALL_TITLE_CASE(p, ustrp, lenp);
2241
2242         if (flags) {
2243             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2244         }
2245         return result;
2246     }
2247
2248     /* Here, used locale rules.  Convert back to utf8 */
2249     if (UTF8_IS_INVARIANT(result)) {
2250         *ustrp = (U8) result;
2251         *lenp = 1;
2252     }
2253     else {
2254         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2255         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
2256         *lenp = 2;
2257     }
2258
2259     if (tainted_ptr) {
2260         *tainted_ptr = TRUE;
2261     }
2262     return result;
2263 }
2264
2265 /*
2266 =for apidoc to_utf8_lower
2267
2268 Instead use L</toLOWER_utf8>.
2269
2270 =cut */
2271
2272 /* Not currently externally documented, and subject to change:
2273  * <flags> is set iff locale semantics are to be used for code points < 256
2274  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2275  *               were used in the calculation; otherwise unchanged. */
2276
2277 UV
2278 Perl__to_utf8_lower_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, const bool flags, bool* tainted_ptr)
2279 {
2280     UV result;
2281
2282     dVAR;
2283
2284     PERL_ARGS_ASSERT__TO_UTF8_LOWER_FLAGS;
2285
2286     if (UTF8_IS_INVARIANT(*p)) {
2287         if (flags) {
2288             result = toLOWER_LC(*p);
2289         }
2290         else {
2291             return to_lower_latin1(*p, ustrp, lenp);
2292         }
2293     }
2294     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2295         if (flags) {
2296             U8 c = TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1));
2297             result = toLOWER_LC(c);
2298         }
2299         else {
2300             return to_lower_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2301                                    ustrp, lenp);
2302         }
2303     }
2304     else {  /* utf8, ord above 255 */
2305         result = CALL_LOWER_CASE(p, ustrp, lenp);
2306
2307         if (flags) {
2308             result = check_locale_boundary_crossing(p, result, ustrp, lenp);
2309         }
2310
2311         return result;
2312     }
2313
2314     /* Here, used locale rules.  Convert back to utf8 */
2315     if (UTF8_IS_INVARIANT(result)) {
2316         *ustrp = (U8) result;
2317         *lenp = 1;
2318     }
2319     else {
2320         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2321         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
2322         *lenp = 2;
2323     }
2324
2325     if (tainted_ptr) {
2326         *tainted_ptr = TRUE;
2327     }
2328     return result;
2329 }
2330
2331 /*
2332 =for apidoc to_utf8_fold
2333
2334 Instead use L</toFOLD_utf8>.
2335
2336 =cut */
2337
2338 /* Not currently externally documented, and subject to change,
2339  * in <flags>
2340  *      bit FOLD_FLAGS_LOCALE is set iff locale semantics are to be used for code
2341  *                            points < 256.  Since foldcase is not defined in
2342  *                            POSIX, lowercase is used instead
2343  *      bit FOLD_FLAGS_FULL   is set iff full case folds are to be used;
2344  *                            otherwise simple folds
2345  *      bit FOLD_FLAGS_NOMIX_ASCII is set iff folds of non-ASCII to ASCII are
2346  *                            prohibited
2347  * <tainted_ptr> if non-null, *tainted_ptr will be set TRUE iff locale rules
2348  *               were used in the calculation; otherwise unchanged. */
2349
2350 UV
2351 Perl__to_utf8_fold_flags(pTHX_ const U8 *p, U8* ustrp, STRLEN *lenp, U8 flags, bool* tainted_ptr)
2352 {
2353     dVAR;
2354
2355     UV result;
2356
2357     PERL_ARGS_ASSERT__TO_UTF8_FOLD_FLAGS;
2358
2359     /* These are mutually exclusive */
2360     assert (! ((flags & FOLD_FLAGS_LOCALE) && (flags & FOLD_FLAGS_NOMIX_ASCII)));
2361
2362     assert(p != ustrp); /* Otherwise overwrites */
2363
2364     if (UTF8_IS_INVARIANT(*p)) {
2365         if (flags & FOLD_FLAGS_LOCALE) {
2366             result = toFOLD_LC(*p);
2367         }
2368         else {
2369             return _to_fold_latin1(*p, ustrp, lenp,
2370                             flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
2371         }
2372     }
2373     else if UTF8_IS_DOWNGRADEABLE_START(*p) {
2374         if (flags & FOLD_FLAGS_LOCALE) {
2375             U8 c = TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1));
2376             result = toFOLD_LC(c);
2377         }
2378         else {
2379             return _to_fold_latin1(TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1)),
2380                             ustrp, lenp,
2381                             flags & (FOLD_FLAGS_FULL | FOLD_FLAGS_NOMIX_ASCII));
2382         }
2383     }
2384     else {  /* utf8, ord above 255 */
2385         result = CALL_FOLD_CASE(p, ustrp, lenp, flags & FOLD_FLAGS_FULL);
2386
2387         if (flags & FOLD_FLAGS_LOCALE) {
2388
2389             /* Special case these characters, as what normally gets returned
2390              * under locale doesn't work */
2391             if (UTF8SKIP(p) == sizeof(LATIN_CAPITAL_LETTER_SHARP_S_UTF8) - 1
2392                 && memEQ((char *) p, LATIN_CAPITAL_LETTER_SHARP_S_UTF8,
2393                           sizeof(LATIN_CAPITAL_LETTER_SHARP_S_UTF8) - 1))
2394             {
2395                 goto return_long_s;
2396             }
2397             else if (UTF8SKIP(p) == sizeof(LATIN_SMALL_LIGATURE_LONG_S_T) - 1
2398                 && memEQ((char *) p, LATIN_SMALL_LIGATURE_LONG_S_T_UTF8,
2399                           sizeof(LATIN_SMALL_LIGATURE_LONG_S_T_UTF8) - 1))
2400             {
2401                 goto return_ligature_st;
2402             }
2403             return check_locale_boundary_crossing(p, result, ustrp, lenp);
2404         }
2405         else if (! (flags & FOLD_FLAGS_NOMIX_ASCII)) {
2406             return result;
2407         }
2408         else {
2409             /* This is called when changing the case of a utf8-encoded
2410              * character above the ASCII range, and the result should not
2411              * contain an ASCII character. */
2412
2413             UV original;    /* To store the first code point of <p> */
2414
2415             /* Look at every character in the result; if any cross the
2416             * boundary, the whole thing is disallowed */
2417             U8* s = ustrp;
2418             U8* e = ustrp + *lenp;
2419             while (s < e) {
2420                 if (isASCII(*s)) {
2421                     /* Crossed, have to return the original */
2422                     original = valid_utf8_to_uvchr(p, lenp);
2423
2424                     /* But in these instances, there is an alternative we can
2425                      * return that is valid */
2426                     if (original == LATIN_CAPITAL_LETTER_SHARP_S
2427                         || original == LATIN_SMALL_LETTER_SHARP_S)
2428                     {
2429                         goto return_long_s;
2430                     }
2431                     else if (original == LATIN_SMALL_LIGATURE_LONG_S_T) {
2432                         goto return_ligature_st;
2433                     }
2434                     Copy(p, ustrp, *lenp, char);
2435                     return original;
2436                 }
2437                 s += UTF8SKIP(s);
2438             }
2439
2440             /* Here, no characters crossed, result is ok as-is */
2441             return result;
2442         }
2443     }
2444
2445     /* Here, used locale rules.  Convert back to utf8 */
2446     if (UTF8_IS_INVARIANT(result)) {
2447         *ustrp = (U8) result;
2448         *lenp = 1;
2449     }
2450     else {
2451         *ustrp = UTF8_EIGHT_BIT_HI((U8) result);
2452         *(ustrp + 1) = UTF8_EIGHT_BIT_LO((U8) result);
2453         *lenp = 2;
2454     }
2455
2456     if (tainted_ptr) {
2457         *tainted_ptr = TRUE;
2458     }
2459     return result;
2460
2461   return_long_s:
2462     /* Certain folds to 'ss' are prohibited by the options, but they do allow
2463      * folds to a string of two of these characters.  By returning this
2464      * instead, then, e.g.,
2465      *      fc("\x{1E9E}") eq fc("\x{17F}\x{17F}")
2466      * works. */
2467
2468     *lenp = 2 * sizeof(LATIN_SMALL_LETTER_LONG_S_UTF8) - 2;
2469     Copy(LATIN_SMALL_LETTER_LONG_S_UTF8 LATIN_SMALL_LETTER_LONG_S_UTF8,
2470         ustrp, *lenp, U8);
2471     return LATIN_SMALL_LETTER_LONG_S;
2472
2473   return_ligature_st:
2474     /* Two folds to 'st' are prohibited by the options; instead we pick one and
2475      * have the other one fold to it */
2476
2477     *lenp = sizeof(LATIN_SMALL_LIGATURE_ST_UTF8) - 1;
2478     Copy(LATIN_SMALL_LIGATURE_ST_UTF8, ustrp, *lenp, U8);
2479     return LATIN_SMALL_LIGATURE_ST;
2480 }
2481
2482 /* Note:
2483  * Returns a "swash" which is a hash described in utf8.c:Perl_swash_fetch().
2484  * C<pkg> is a pointer to a package name for SWASHNEW, should be "utf8".
2485  * For other parameters, see utf8::SWASHNEW in lib/utf8_heavy.pl.
2486  */
2487
2488 SV*
2489 Perl_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none)
2490 {
2491     PERL_ARGS_ASSERT_SWASH_INIT;
2492
2493     /* Returns a copy of a swash initiated by the called function.  This is the
2494      * public interface, and returning a copy prevents others from doing
2495      * mischief on the original */
2496
2497     return newSVsv(_core_swash_init(pkg, name, listsv, minbits, none, NULL, NULL));
2498 }
2499
2500 SV*
2501 Perl__core_swash_init(pTHX_ const char* pkg, const char* name, SV *listsv, I32 minbits, I32 none, SV* invlist, U8* const flags_p)
2502 {
2503     /* Initialize and return a swash, creating it if necessary.  It does this
2504      * by calling utf8_heavy.pl in the general case.  The returned value may be
2505      * the swash's inversion list instead if the input parameters allow it.
2506      * Which is returned should be immaterial to callers, as the only
2507      * operations permitted on a swash, swash_fetch(), _get_swash_invlist(),
2508      * and swash_to_invlist() handle both these transparently.
2509      *
2510      * This interface should only be used by functions that won't destroy or
2511      * adversely change the swash, as doing so affects all other uses of the
2512      * swash in the program; the general public should use 'Perl_swash_init'
2513      * instead.
2514      *
2515      * pkg  is the name of the package that <name> should be in.
2516      * name is the name of the swash to find.  Typically it is a Unicode
2517      *      property name, including user-defined ones
2518      * listsv is a string to initialize the swash with.  It must be of the form
2519      *      documented as the subroutine return value in
2520      *      L<perlunicode/User-Defined Character Properties>
2521      * minbits is the number of bits required to represent each data element.
2522      *      It is '1' for binary properties.
2523      * none I (khw) do not understand this one, but it is used only in tr///.
2524      * invlist is an inversion list to initialize the swash with (or NULL)
2525      * flags_p if non-NULL is the address of various input and output flag bits
2526      *      to the routine, as follows:  ('I' means is input to the routine;
2527      *      'O' means output from the routine.  Only flags marked O are
2528      *      meaningful on return.)
2529      *  _CORE_SWASH_INIT_USER_DEFINED_PROPERTY indicates if the swash
2530      *      came from a user-defined property.  (I O)
2531      *  _CORE_SWASH_INIT_RETURN_IF_UNDEF indicates that instead of croaking
2532      *      when the swash cannot be located, to simply return NULL. (I)
2533      *  _CORE_SWASH_INIT_ACCEPT_INVLIST indicates that the caller will accept a
2534      *      return of an inversion list instead of a swash hash if this routine
2535      *      thinks that would result in faster execution of swash_fetch() later
2536      *      on. (I)
2537      *
2538      * Thus there are three possible inputs to find the swash: <name>,
2539      * <listsv>, and <invlist>.  At least one must be specified.  The result
2540      * will be the union of the specified ones, although <listsv>'s various
2541      * actions can intersect, etc. what <name> gives.  To avoid going out to
2542      * disk at all, <invlist> should specify completely what the swash should
2543      * have, and <listsv> should be &PL_sv_undef and <name> should be "".
2544      *
2545      * <invlist> is only valid for binary properties */
2546
2547     dVAR;
2548     SV* retval = &PL_sv_undef;
2549     HV* swash_hv = NULL;
2550     const int invlist_swash_boundary =
2551         (flags_p && *flags_p & _CORE_SWASH_INIT_ACCEPT_INVLIST)
2552         ? 512    /* Based on some benchmarking, but not extensive, see commit
2553                     message */
2554         : -1;   /* Never return just an inversion list */
2555
2556     assert(listsv != &PL_sv_undef || strNE(name, "") || invlist);
2557     assert(! invlist || minbits == 1);
2558
2559     /* If data was passed in to go out to utf8_heavy to find the swash of, do
2560      * so */
2561     if (listsv != &PL_sv_undef || strNE(name, "")) {
2562         dSP;
2563         const size_t pkg_len = strlen(pkg);
2564         const size_t name_len = strlen(name);
2565         HV * const stash = gv_stashpvn(pkg, pkg_len, 0);
2566         SV* errsv_save;
2567         GV *method;
2568
2569         PERL_ARGS_ASSERT__CORE_SWASH_INIT;
2570
2571         PUSHSTACKi(PERLSI_MAGIC);
2572         ENTER;
2573         SAVEHINTS();
2574         save_re_context();
2575         /* We might get here via a subroutine signature which uses a utf8
2576          * parameter name, at which point PL_subname will have been set
2577          * but not yet used. */
2578         save_item(PL_subname);
2579         if (PL_parser && PL_parser->error_count)
2580             SAVEI8(PL_parser->error_count), PL_parser->error_count = 0;
2581         method = gv_fetchmeth(stash, "SWASHNEW", 8, -1);
2582         if (!method) {  /* demand load utf8 */
2583             ENTER;
2584             if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2585             GvSV(PL_errgv) = NULL;
2586             /* It is assumed that callers of this routine are not passing in
2587              * any user derived data.  */
2588             /* Need to do this after save_re_context() as it will set
2589              * PL_tainted to 1 while saving $1 etc (see the code after getrx:
2590              * in Perl_magic_get).  Even line to create errsv_save can turn on
2591              * PL_tainted.  */
2592 #ifndef NO_TAINT_SUPPORT
2593             SAVEBOOL(TAINT_get);
2594             TAINT_NOT;
2595 #endif
2596             Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT, newSVpvn(pkg,pkg_len),
2597                              NULL);
2598             {
2599                 /* Not ERRSV, as there is no need to vivify a scalar we are
2600                    about to discard. */
2601                 SV * const errsv = GvSV(PL_errgv);
2602                 if (!SvTRUE(errsv)) {
2603                     GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2604                     SvREFCNT_dec(errsv);
2605                 }
2606             }
2607             LEAVE;
2608         }
2609         SPAGAIN;
2610         PUSHMARK(SP);
2611         EXTEND(SP,5);
2612         mPUSHp(pkg, pkg_len);
2613         mPUSHp(name, name_len);
2614         PUSHs(listsv);
2615         mPUSHi(minbits);
2616         mPUSHi(none);
2617         PUTBACK;
2618         if ((errsv_save = GvSV(PL_errgv))) SAVEFREESV(errsv_save);
2619         GvSV(PL_errgv) = NULL;
2620         /* If we already have a pointer to the method, no need to use
2621          * call_method() to repeat the lookup.  */
2622         if (method
2623             ? call_sv(MUTABLE_SV(method), G_SCALAR)
2624             : call_sv(newSVpvs_flags("SWASHNEW", SVs_TEMP), G_SCALAR | G_METHOD))
2625         {
2626             retval = *PL_stack_sp--;
2627             SvREFCNT_inc(retval);
2628         }
2629         {
2630             /* Not ERRSV.  See above. */
2631             SV * const errsv = GvSV(PL_errgv);
2632             if (!SvTRUE(errsv)) {
2633                 GvSV(PL_errgv) = SvREFCNT_inc_simple(errsv_save);
2634                 SvREFCNT_dec(errsv);
2635             }
2636         }
2637         LEAVE;
2638         POPSTACK;
2639         if (IN_PERL_COMPILETIME) {
2640             CopHINTS_set(PL_curcop, PL_hints);
2641         }
2642         if (!SvROK(retval) || SvTYPE(SvRV(retval)) != SVt_PVHV) {
2643             if (SvPOK(retval))
2644
2645                 /* If caller wants to handle missing properties, let them */
2646                 if (flags_p && *flags_p & _CORE_SWASH_INIT_RETURN_IF_UNDEF) {
2647                     return NULL;
2648                 }
2649                 Perl_croak(aTHX_
2650                            "Can't find Unicode property definition \"%"SVf"\"",
2651                            SVfARG(retval));
2652             Perl_croak(aTHX_ "SWASHNEW didn't return an HV ref");
2653         }
2654     } /* End of calling the module to find the swash */
2655
2656     /* If this operation fetched a swash, and we will need it later, get it */
2657     if (retval != &PL_sv_undef
2658         && (minbits == 1 || (flags_p
2659                             && ! (*flags_p
2660                                   & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY))))
2661     {
2662         swash_hv = MUTABLE_HV(SvRV(retval));
2663
2664         /* If we don't already know that there is a user-defined component to
2665          * this swash, and the user has indicated they wish to know if there is
2666          * one (by passing <flags_p>), find out */
2667         if (flags_p && ! (*flags_p & _CORE_SWASH_INIT_USER_DEFINED_PROPERTY)) {
2668             SV** user_defined = hv_fetchs(swash_hv, "USER_DEFINED", FALSE);
2669             if (user_defined && SvUV(*user_defined)) {
2670                 *flags_p |= _CORE_SWASH_INIT_USER_DEFINED_PROPERTY;
2671             }
2672         }
2673     }
2674
2675     /* Make sure there is an inversion list for binary properties */
2676     if (minbits == 1) {
2677         SV** swash_invlistsvp = NULL;
2678         SV* swash_invlist = NULL;
2679         bool invlist_in_swash_is_valid = FALSE;
2680         bool swash_invlist_unclaimed = FALSE; /* whether swash_invlist has
2681                                             an unclaimed reference count */
2682
2683         /* If this operation fetched a swash, get its already existing
2684          * inversion list, or create one for it */
2685
2686         if (swash_hv) {
2687             swash_invlistsvp = hv_fetchs(swash_hv, "V", FALSE);
2688             if (swash_invlistsvp) {
2689                 swash_invlist = *swash_invlistsvp;
2690                 invlist_in_swash_is_valid = TRUE;
2691             }
2692             else {
2693                 swash_invlist = _swash_to_invlist(retval);
2694                 swash_invlist_unclaimed = TRUE;
2695             }
2696         }
2697
2698         /* If an inversion list was passed in, have to include it */
2699         if (invlist) {
2700
2701             /* Any fetched swash will by now have an inversion list in it;
2702              * otherwise <swash_invlist>  will be NULL, indicating that we
2703              * didn't fetch a swash */
2704             if (swash_invlist) {
2705
2706                 /* Add the passed-in inversion list, which invalidates the one
2707                  * already stored in the swash */
2708                 invlist_in_swash_is_valid = FALSE;
2709                 _invlist_union(invlist, swash_invlist, &swash_invlist);
2710             }
2711             else {
2712
2713                 /* Here, there is no swash already.  Set up a minimal one, if
2714                  * we are going to return a swash */
2715                 if ((int) _invlist_len(invlist) > invlist_swash_boundary) {
2716                     swash_hv = newHV();
2717                     retval = newRV_noinc(MUTABLE_SV(swash_hv));
2718                 }
2719                 swash_invlist = invlist;
2720             }
2721         }
2722
2723         /* Here, we have computed the union of all the passed-in data.  It may
2724          * be that there was an inversion list in the swash which didn't get
2725          * touched; otherwise save the one computed one */
2726         if (! invlist_in_swash_is_valid
2727             && (int) _invlist_len(swash_invlist) > invlist_swash_boundary)
2728         {
2729             if (! hv_stores(MUTABLE_HV(SvRV(retval)), "V", swash_invlist))
2730             {
2731                 Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
2732             }
2733             /* We just stole a reference count. */
2734             if (swash_invlist_unclaimed) swash_invlist_unclaimed = FALSE;
2735             else SvREFCNT_inc_simple_void_NN(swash_invlist);
2736         }
2737
2738         SvREADONLY_on(swash_invlist);
2739
2740         /* Use the inversion list stand-alone if small enough */
2741         if ((int) _invlist_len(swash_invlist) <= invlist_swash_boundary) {
2742             SvREFCNT_dec(retval);
2743             if (!swash_invlist_unclaimed)
2744                 SvREFCNT_inc_simple_void_NN(swash_invlist);
2745             retval = newRV_noinc(swash_invlist);
2746         }
2747     }
2748
2749     return retval;
2750 }
2751
2752
2753 /* This API is wrong for special case conversions since we may need to
2754  * return several Unicode characters for a single Unicode character
2755  * (see lib/unicore/SpecCase.txt) The SWASHGET in lib/utf8_heavy.pl is
2756  * the lower-level routine, and it is similarly broken for returning
2757  * multiple values.  --jhi
2758  * For those, you should use to_utf8_case() instead */
2759 /* Now SWASHGET is recasted into S_swatch_get in this file. */
2760
2761 /* Note:
2762  * Returns the value of property/mapping C<swash> for the first character
2763  * of the string C<ptr>. If C<do_utf8> is true, the string C<ptr> is
2764  * assumed to be in well-formed utf8. If C<do_utf8> is false, the string C<ptr>
2765  * is assumed to be in native 8-bit encoding. Caches the swatch in C<swash>.
2766  *
2767  * A "swash" is a hash which contains initially the keys/values set up by
2768  * SWASHNEW.  The purpose is to be able to completely represent a Unicode
2769  * property for all possible code points.  Things are stored in a compact form
2770  * (see utf8_heavy.pl) so that calculation is required to find the actual
2771  * property value for a given code point.  As code points are looked up, new
2772  * key/value pairs are added to the hash, so that the calculation doesn't have
2773  * to ever be re-done.  Further, each calculation is done, not just for the
2774  * desired one, but for a whole block of code points adjacent to that one.
2775  * For binary properties on ASCII machines, the block is usually for 64 code
2776  * points, starting with a code point evenly divisible by 64.  Thus if the
2777  * property value for code point 257 is requested, the code goes out and
2778  * calculates the property values for all 64 code points between 256 and 319,
2779  * and stores these as a single 64-bit long bit vector, called a "swatch",
2780  * under the key for code point 256.  The key is the UTF-8 encoding for code
2781  * point 256, minus the final byte.  Thus, if the length of the UTF-8 encoding
2782  * for a code point is 13 bytes, the key will be 12 bytes long.  If the value
2783  * for code point 258 is then requested, this code realizes that it would be
2784  * stored under the key for 256, and would find that value and extract the
2785  * relevant bit, offset from 256.
2786  *
2787  * Non-binary properties are stored in as many bits as necessary to represent
2788  * their values (32 currently, though the code is more general than that), not
2789  * as single bits, but the principal is the same: the value for each key is a
2790  * vector that encompasses the property values for all code points whose UTF-8
2791  * representations are represented by the key.  That is, for all code points
2792  * whose UTF-8 representations are length N bytes, and the key is the first N-1
2793  * bytes of that.
2794  */
2795 UV
2796 Perl_swash_fetch(pTHX_ SV *swash, const U8 *ptr, bool do_utf8)
2797 {
2798     dVAR;
2799     HV *const hv = MUTABLE_HV(SvRV(swash));
2800     U32 klen;
2801     U32 off;
2802     STRLEN slen;
2803     STRLEN needents;
2804     const U8 *tmps = NULL;
2805     U32 bit;
2806     SV *swatch;
2807     const U8 c = *ptr;
2808
2809     PERL_ARGS_ASSERT_SWASH_FETCH;
2810
2811     /* If it really isn't a hash, it isn't really swash; must be an inversion
2812      * list */
2813     if (SvTYPE(hv) != SVt_PVHV) {
2814         return _invlist_contains_cp((SV*)hv,
2815                                     (do_utf8)
2816                                      ? valid_utf8_to_uvchr(ptr, NULL)
2817                                      : c);
2818     }
2819
2820     /* We store the values in a "swatch" which is a vec() value in a swash
2821      * hash.  Code points 0-255 are a single vec() stored with key length
2822      * (klen) 0.  All other code points have a UTF-8 representation
2823      * 0xAA..0xYY,0xZZ.  A vec() is constructed containing all of them which
2824      * share 0xAA..0xYY, which is the key in the hash to that vec.  So the key
2825      * length for them is the length of the encoded char - 1.  ptr[klen] is the
2826      * final byte in the sequence representing the character */
2827     if (!do_utf8 || UTF8_IS_INVARIANT(c)) {
2828         klen = 0;
2829         needents = 256;
2830         off = c;
2831     }
2832     else if (UTF8_IS_DOWNGRADEABLE_START(c)) {
2833         klen = 0;
2834         needents = 256;
2835         off = TWO_BYTE_UTF8_TO_NATIVE(c, *(ptr + 1));
2836     }
2837     else {
2838         klen = UTF8SKIP(ptr) - 1;
2839
2840         /* Each vec() stores 2**UTF_ACCUMULATION_SHIFT values.  The offset into
2841          * the vec is the final byte in the sequence.  (In EBCDIC this is
2842          * converted to I8 to get consecutive values.)  To help you visualize
2843          * all this:
2844          *                       Straight 1047   After final byte
2845          *             UTF-8      UTF-EBCDIC     I8 transform
2846          *  U+0400:  \xD0\x80    \xB8\x41\x41    \xB8\x41\xA0
2847          *  U+0401:  \xD0\x81    \xB8\x41\x42    \xB8\x41\xA1
2848          *    ...
2849          *  U+0409:  \xD0\x89    \xB8\x41\x4A    \xB8\x41\xA9
2850          *  U+040A:  \xD0\x8A    \xB8\x41\x51    \xB8\x41\xAA
2851          *    ...
2852          *  U+0412:  \xD0\x92    \xB8\x41\x59    \xB8\x41\xB2
2853          *  U+0413:  \xD0\x93    \xB8\x41\x62    \xB8\x41\xB3
2854          *    ...
2855          *  U+041B:  \xD0\x9B    \xB8\x41\x6A    \xB8\x41\xBB
2856          *  U+041C:  \xD0\x9C    \xB8\x41\x70    \xB8\x41\xBC
2857          *    ...
2858          *  U+041F:  \xD0\x9F    \xB8\x41\x73    \xB8\x41\xBF
2859          *  U+0420:  \xD0\xA0    \xB8\x42\x41    \xB8\x42\x41
2860          *
2861          * (There are no discontinuities in the elided (...) entries.)
2862          * The UTF-8 key for these 33 code points is '\xD0' (which also is the
2863          * key for the next 31, up through U+043F, whose UTF-8 final byte is
2864          * \xBF).  Thus in UTF-8, each key is for a vec() for 64 code points.
2865          * The final UTF-8 byte, which ranges between \x80 and \xBF, is an
2866          * index into the vec() swatch (after subtracting 0x80, which we
2867          * actually do with an '&').
2868          * In UTF-EBCDIC, each key is for a 32 code point vec().  The first 32
2869          * code points above have key '\xB8\x41'. The final UTF-EBCDIC byte has
2870          * dicontinuities which go away by transforming it into I8, and we
2871          * effectively subtract 0xA0 to get the index. */
2872         needents = (1 << UTF_ACCUMULATION_SHIFT);
2873         off      = NATIVE_UTF8_TO_I8(ptr[klen]) & UTF_CONTINUATION_MASK;
2874     }
2875
2876     /*
2877      * This single-entry cache saves about 1/3 of the utf8 overhead in test
2878      * suite.  (That is, only 7-8% overall over just a hash cache.  Still,
2879      * it's nothing to sniff at.)  Pity we usually come through at least
2880      * two function calls to get here...
2881      *
2882      * NB: this code assumes that swatches are never modified, once generated!
2883      */
2884
2885     if (hv   == PL_last_swash_hv &&
2886         klen == PL_last_swash_klen &&
2887         (!klen || memEQ((char *)ptr, (char *)PL_last_swash_key, klen)) )
2888     {
2889         tmps = PL_last_swash_tmps;
2890         slen = PL_last_swash_slen;
2891     }
2892     else {
2893         /* Try our second-level swatch cache, kept in a hash. */
2894         SV** svp = hv_fetch(hv, (const char*)ptr, klen, FALSE);
2895
2896         /* If not cached, generate it via swatch_get */
2897         if (!svp || !SvPOK(*svp)
2898                  || !(tmps = (const U8*)SvPV_const(*svp, slen)))
2899         {
2900             if (klen) {
2901                 const UV code_point = valid_utf8_to_uvchr(ptr, NULL);
2902                 swatch = swatch_get(swash,
2903                                     code_point & ~((UV)needents - 1),
2904                                     needents);
2905             }
2906             else {  /* For the first 256 code points, the swatch has a key of
2907                        length 0 */
2908                 swatch = swatch_get(swash, 0, needents);
2909             }
2910
2911             if (IN_PERL_COMPILETIME)
2912                 CopHINTS_set(PL_curcop, PL_hints);
2913
2914             svp = hv_store(hv, (const char *)ptr, klen, swatch, 0);
2915
2916             if (!svp || !(tmps = (U8*)SvPV(*svp, slen))
2917                      || (slen << 3) < needents)
2918                 Perl_croak(aTHX_ "panic: swash_fetch got improper swatch, "
2919                            "svp=%p, tmps=%p, slen=%"UVuf", needents=%"UVuf,
2920                            svp, tmps, (UV)slen, (UV)needents);
2921         }
2922
2923         PL_last_swash_hv = hv;
2924         assert(klen <= sizeof(PL_last_swash_key));
2925         PL_last_swash_klen = (U8)klen;
2926         /* FIXME change interpvar.h?  */
2927         PL_last_swash_tmps = (U8 *) tmps;
2928         PL_last_swash_slen = slen;
2929         if (klen)
2930             Copy(ptr, PL_last_swash_key, klen, U8);
2931     }
2932
2933     switch ((int)((slen << 3) / needents)) {
2934     case 1:
2935         bit = 1 << (off & 7);
2936         off >>= 3;
2937         return (tmps[off] & bit) != 0;
2938     case 8:
2939         return tmps[off];
2940     case 16:
2941         off <<= 1;
2942         return (tmps[off] << 8) + tmps[off + 1] ;
2943     case 32:
2944         off <<= 2;
2945         return (tmps[off] << 24) + (tmps[off+1] << 16) + (tmps[off+2] << 8) + tmps[off + 3] ;
2946     }
2947     Perl_croak(aTHX_ "panic: swash_fetch got swatch of unexpected bit width, "
2948                "slen=%"UVuf", needents=%"UVuf, (UV)slen, (UV)needents);
2949     NORETURN_FUNCTION_END;
2950 }
2951
2952 /* Read a single line of the main body of the swash input text.  These are of
2953  * the form:
2954  * 0053 0056    0073
2955  * where each number is hex.  The first two numbers form the minimum and
2956  * maximum of a range, and the third is the value associated with the range.
2957  * Not all swashes should have a third number
2958  *
2959  * On input: l    points to the beginning of the line to be examined; it points
2960  *                to somewhere in the string of the whole input text, and is
2961  *                terminated by a \n or the null string terminator.
2962  *           lend   points to the null terminator of that string
2963  *           wants_value    is non-zero if the swash expects a third number
2964  *           typestr is the name of the swash's mapping, like 'ToLower'
2965  * On output: *min, *max, and *val are set to the values read from the line.
2966  *            returns a pointer just beyond the line examined.  If there was no
2967  *            valid min number on the line, returns lend+1
2968  */
2969
2970 STATIC U8*
2971 S_swash_scan_list_line(pTHX_ U8* l, U8* const lend, UV* min, UV* max, UV* val,
2972                              const bool wants_value, const U8* const typestr)
2973 {
2974     const int  typeto  = typestr[0] == 'T' && typestr[1] == 'o';
2975     STRLEN numlen;          /* Length of the number */
2976     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
2977                 | PERL_SCAN_DISALLOW_PREFIX
2978                 | PERL_SCAN_SILENT_NON_PORTABLE;
2979
2980     /* nl points to the next \n in the scan */
2981     U8* const nl = (U8*)memchr(l, '\n', lend - l);
2982
2983     /* Get the first number on the line: the range minimum */
2984     numlen = lend - l;
2985     *min = grok_hex((char *)l, &numlen, &flags, NULL);
2986     if (numlen)     /* If found a hex number, position past it */
2987         l += numlen;
2988     else if (nl) {          /* Else, go handle next line, if any */
2989         return nl + 1;  /* 1 is length of "\n" */
2990     }
2991     else {              /* Else, no next line */
2992         return lend + 1;        /* to LIST's end at which \n is not found */
2993     }
2994
2995     /* The max range value follows, separated by a BLANK */
2996     if (isBLANK(*l)) {
2997         ++l;
2998         flags = PERL_SCAN_SILENT_ILLDIGIT
2999                 | PERL_SCAN_DISALLOW_PREFIX
3000                 | PERL_SCAN_SILENT_NON_PORTABLE;
3001         numlen = lend - l;
3002         *max = grok_hex((char *)l, &numlen, &flags, NULL);
3003         if (numlen)
3004             l += numlen;
3005         else    /* If no value here, it is a single element range */
3006             *max = *min;
3007
3008         /* Non-binary tables have a third entry: what the first element of the
3009          * range maps to.  The map for those currently read here is in hex */
3010         if (wants_value) {
3011             if (isBLANK(*l)) {
3012                 ++l;
3013                 flags = PERL_SCAN_SILENT_ILLDIGIT
3014                     | PERL_SCAN_DISALLOW_PREFIX
3015                     | PERL_SCAN_SILENT_NON_PORTABLE;
3016                 numlen = lend - l;
3017                 *val = grok_hex((char *)l, &numlen, &flags, NULL);
3018                 if (numlen)
3019                     l += numlen;
3020                 else
3021                     *val = 0;
3022             }
3023             else {
3024                 *val = 0;
3025                 if (typeto) {
3026                     /* diag_listed_as: To%s: illegal mapping '%s' */
3027                     Perl_croak(aTHX_ "%s: illegal mapping '%s'",
3028                                      typestr, l);
3029                 }
3030             }
3031         }
3032         else
3033             *val = 0; /* bits == 1, then any val should be ignored */
3034     }
3035     else { /* Nothing following range min, should be single element with no
3036               mapping expected */
3037         *max = *min;
3038         if (wants_value) {
3039             *val = 0;
3040             if (typeto) {
3041                 /* diag_listed_as: To%s: illegal mapping '%s' */
3042                 Perl_croak(aTHX_ "%s: illegal mapping '%s'", typestr, l);
3043             }
3044         }
3045         else
3046             *val = 0; /* bits == 1, then val should be ignored */
3047     }
3048
3049     /* Position to next line if any, or EOF */
3050     if (nl)
3051         l = nl + 1;
3052     else
3053         l = lend;
3054
3055     return l;
3056 }
3057
3058 /* Note:
3059  * Returns a swatch (a bit vector string) for a code point sequence
3060  * that starts from the value C<start> and comprises the number C<span>.
3061  * A C<swash> must be an object created by SWASHNEW (see lib/utf8_heavy.pl).
3062  * Should be used via swash_fetch, which will cache the swatch in C<swash>.
3063  */
3064 STATIC SV*
3065 S_swatch_get(pTHX_ SV* swash, UV start, UV span)
3066 {
3067     SV *swatch;
3068     U8 *l, *lend, *x, *xend, *s, *send;
3069     STRLEN lcur, xcur, scur;
3070     HV *const hv = MUTABLE_HV(SvRV(swash));
3071     SV** const invlistsvp = hv_fetchs(hv, "V", FALSE);
3072
3073     SV** listsvp = NULL; /* The string containing the main body of the table */
3074     SV** extssvp = NULL;
3075     SV** invert_it_svp = NULL;
3076     U8* typestr = NULL;
3077     STRLEN bits;
3078     STRLEN octets; /* if bits == 1, then octets == 0 */
3079     UV  none;
3080     UV  end = start + span;
3081
3082     if (invlistsvp == NULL) {
3083         SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3084         SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3085         SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3086         extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
3087         listsvp = hv_fetchs(hv, "LIST", FALSE);
3088         invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
3089
3090         bits  = SvUV(*bitssvp);
3091         none  = SvUV(*nonesvp);
3092         typestr = (U8*)SvPV_nolen(*typesvp);
3093     }
3094     else {
3095         bits = 1;
3096         none = 0;
3097     }
3098     octets = bits >> 3; /* if bits == 1, then octets == 0 */
3099
3100     PERL_ARGS_ASSERT_SWATCH_GET;
3101
3102     if (bits != 1 && bits != 8 && bits != 16 && bits != 32) {
3103         Perl_croak(aTHX_ "panic: swatch_get doesn't expect bits %"UVuf,
3104                                                  (UV)bits);
3105     }
3106
3107     /* If overflowed, use the max possible */
3108     if (end < start) {
3109         end = UV_MAX;
3110         span = end - start;
3111     }
3112
3113     /* create and initialize $swatch */
3114     scur   = octets ? (span * octets) : (span + 7) / 8;
3115     swatch = newSV(scur);
3116     SvPOK_on(swatch);
3117     s = (U8*)SvPVX(swatch);
3118     if (octets && none) {
3119         const U8* const e = s + scur;
3120         while (s < e) {
3121             if (bits == 8)
3122                 *s++ = (U8)(none & 0xff);
3123             else if (bits == 16) {
3124                 *s++ = (U8)((none >>  8) & 0xff);
3125                 *s++ = (U8)( none        & 0xff);
3126             }
3127             else if (bits == 32) {
3128                 *s++ = (U8)((none >> 24) & 0xff);
3129                 *s++ = (U8)((none >> 16) & 0xff);
3130                 *s++ = (U8)((none >>  8) & 0xff);
3131                 *s++ = (U8)( none        & 0xff);
3132             }
3133         }
3134         *s = '\0';
3135     }
3136     else {
3137         (void)memzero((U8*)s, scur + 1);
3138     }
3139     SvCUR_set(swatch, scur);
3140     s = (U8*)SvPVX(swatch);
3141
3142     if (invlistsvp) {   /* If has an inversion list set up use that */
3143         _invlist_populate_swatch(*invlistsvp, start, end, s);
3144         return swatch;
3145     }
3146
3147     /* read $swash->{LIST} */
3148     l = (U8*)SvPV(*listsvp, lcur);
3149     lend = l + lcur;
3150     while (l < lend) {
3151         UV min, max, val, upper;
3152         l = S_swash_scan_list_line(aTHX_ l, lend, &min, &max, &val,
3153                                          cBOOL(octets), typestr);
3154         if (l > lend) {
3155             break;
3156         }
3157
3158         /* If looking for something beyond this range, go try the next one */
3159         if (max < start)
3160             continue;
3161
3162         /* <end> is generally 1 beyond where we want to set things, but at the
3163          * platform's infinity, where we can't go any higher, we want to
3164          * include the code point at <end> */
3165         upper = (max < end)
3166                 ? max
3167                 : (max != UV_MAX || end != UV_MAX)
3168                   ? end - 1
3169                   : end;
3170
3171         if (octets) {
3172             UV key;
3173             if (min < start) {
3174                 if (!none || val < none) {
3175                     val += start - min;
3176                 }
3177                 min = start;
3178             }
3179             for (key = min; key <= upper; key++) {
3180                 STRLEN offset;
3181                 /* offset must be non-negative (start <= min <= key < end) */
3182                 offset = octets * (key - start);
3183                 if (bits == 8)
3184                     s[offset] = (U8)(val & 0xff);
3185                 else if (bits == 16) {
3186                     s[offset    ] = (U8)((val >>  8) & 0xff);
3187                     s[offset + 1] = (U8)( val        & 0xff);
3188                 }
3189                 else if (bits == 32) {
3190                     s[offset    ] = (U8)((val >> 24) & 0xff);
3191                     s[offset + 1] = (U8)((val >> 16) & 0xff);
3192                     s[offset + 2] = (U8)((val >>  8) & 0xff);
3193                     s[offset + 3] = (U8)( val        & 0xff);
3194                 }
3195
3196                 if (!none || val < none)
3197                     ++val;
3198             }
3199         }
3200         else { /* bits == 1, then val should be ignored */
3201             UV key;
3202             if (min < start)
3203                 min = start;
3204
3205             for (key = min; key <= upper; key++) {
3206                 const STRLEN offset = (STRLEN)(key - start);
3207                 s[offset >> 3] |= 1 << (offset & 7);
3208             }
3209         }
3210     } /* while */
3211
3212     /* Invert if the data says it should be.  Assumes that bits == 1 */
3213     if (invert_it_svp && SvUV(*invert_it_svp)) {
3214
3215         /* Unicode properties should come with all bits above PERL_UNICODE_MAX
3216          * be 0, and their inversion should also be 0, as we don't succeed any
3217          * Unicode property matches for non-Unicode code points */
3218         if (start <= PERL_UNICODE_MAX) {
3219
3220             /* The code below assumes that we never cross the
3221              * Unicode/above-Unicode boundary in a range, as otherwise we would
3222              * have to figure out where to stop flipping the bits.  Since this
3223              * boundary is divisible by a large power of 2, and swatches comes
3224              * in small powers of 2, this should be a valid assumption */
3225             assert(start + span - 1 <= PERL_UNICODE_MAX);
3226
3227             send = s + scur;
3228             while (s < send) {
3229                 *s = ~(*s);
3230                 s++;
3231             }
3232         }
3233     }
3234
3235     /* read $swash->{EXTRAS}
3236      * This code also copied to swash_to_invlist() below */
3237     x = (U8*)SvPV(*extssvp, xcur);
3238     xend = x + xcur;
3239     while (x < xend) {
3240         STRLEN namelen;
3241         U8 *namestr;
3242         SV** othersvp;
3243         HV* otherhv;
3244         STRLEN otherbits;
3245         SV **otherbitssvp, *other;
3246         U8 *s, *o, *nl;
3247         STRLEN slen, olen;
3248
3249         const U8 opc = *x++;
3250         if (opc == '\n')
3251             continue;
3252
3253         nl = (U8*)memchr(x, '\n', xend - x);
3254
3255         if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
3256             if (nl) {
3257                 x = nl + 1; /* 1 is length of "\n" */
3258                 continue;
3259             }
3260             else {
3261                 x = xend; /* to EXTRAS' end at which \n is not found */
3262                 break;
3263             }
3264         }
3265
3266         namestr = x;
3267         if (nl) {
3268             namelen = nl - namestr;
3269             x = nl + 1;
3270         }
3271         else {
3272             namelen = xend - namestr;
3273             x = xend;
3274         }
3275
3276         othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
3277         otherhv = MUTABLE_HV(SvRV(*othersvp));
3278         otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
3279         otherbits = (STRLEN)SvUV(*otherbitssvp);
3280         if (bits < otherbits)
3281             Perl_croak(aTHX_ "panic: swatch_get found swatch size mismatch, "
3282                        "bits=%"UVuf", otherbits=%"UVuf, (UV)bits, (UV)otherbits);
3283
3284         /* The "other" swatch must be destroyed after. */
3285         other = swatch_get(*othersvp, start, span);
3286         o = (U8*)SvPV(other, olen);
3287
3288         if (!olen)
3289             Perl_croak(aTHX_ "panic: swatch_get got improper swatch");
3290
3291         s = (U8*)SvPV(swatch, slen);
3292         if (bits == 1 && otherbits == 1) {
3293             if (slen != olen)
3294                 Perl_croak(aTHX_ "panic: swatch_get found swatch length "
3295                            "mismatch, slen=%"UVuf", olen=%"UVuf,
3296                            (UV)slen, (UV)olen);
3297
3298             switch (opc) {
3299             case '+':
3300                 while (slen--)
3301                     *s++ |= *o++;
3302                 break;
3303             case '!':
3304                 while (slen--)
3305                     *s++ |= ~*o++;
3306                 break;
3307             case '-':
3308                 while (slen--)
3309                     *s++ &= ~*o++;
3310                 break;
3311             case '&':
3312                 while (slen--)
3313                     *s++ &= *o++;
3314                 break;
3315             default:
3316                 break;
3317             }
3318         }
3319         else {
3320             STRLEN otheroctets = otherbits >> 3;
3321             STRLEN offset = 0;
3322             U8* const send = s + slen;
3323
3324             while (s < send) {
3325                 UV otherval = 0;
3326
3327                 if (otherbits == 1) {
3328                     otherval = (o[offset >> 3] >> (offset & 7)) & 1;
3329                     ++offset;
3330                 }
3331                 else {
3332                     STRLEN vlen = otheroctets;
3333                     otherval = *o++;
3334                     while (--vlen) {
3335                         otherval <<= 8;
3336                         otherval |= *o++;
3337                     }
3338                 }
3339
3340                 if (opc == '+' && otherval)
3341                     NOOP;   /* replace with otherval */
3342                 else if (opc == '!' && !otherval)
3343                     otherval = 1;
3344                 else if (opc == '-' && otherval)
3345                     otherval = 0;
3346                 else if (opc == '&' && !otherval)
3347                     otherval = 0;
3348                 else {
3349                     s += octets; /* no replacement */
3350                     continue;
3351                 }
3352
3353                 if (bits == 8)
3354                     *s++ = (U8)( otherval & 0xff);
3355                 else if (bits == 16) {
3356                     *s++ = (U8)((otherval >>  8) & 0xff);
3357                     *s++ = (U8)( otherval        & 0xff);
3358                 }
3359                 else if (bits == 32) {
3360                     *s++ = (U8)((otherval >> 24) & 0xff);
3361                     *s++ = (U8)((otherval >> 16) & 0xff);
3362                     *s++ = (U8)((otherval >>  8) & 0xff);
3363                     *s++ = (U8)( otherval        & 0xff);
3364                 }
3365             }
3366         }
3367         sv_free(other); /* through with it! */
3368     } /* while */
3369     return swatch;
3370 }
3371
3372 HV*
3373 Perl__swash_inversion_hash(pTHX_ SV* const swash)
3374 {
3375
3376    /* Subject to change or removal.  For use only in regcomp.c and regexec.c
3377     * Can't be used on a property that is subject to user override, as it
3378     * relies on the value of SPECIALS in the swash which would be set by
3379     * utf8_heavy.pl to the hash in the non-overriden file, and hence is not set
3380     * for overridden properties
3381     *
3382     * Returns a hash which is the inversion and closure of a swash mapping.
3383     * For example, consider the input lines:
3384     * 004B              006B
3385     * 004C              006C
3386     * 212A              006B
3387     *
3388     * The returned hash would have two keys, the utf8 for 006B and the utf8 for
3389     * 006C.  The value for each key is an array.  For 006C, the array would
3390     * have two elements, the utf8 for itself, and for 004C.  For 006B, there
3391     * would be three elements in its array, the utf8 for 006B, 004B and 212A.
3392     *
3393     * Essentially, for any code point, it gives all the code points that map to
3394     * it, or the list of 'froms' for that point.
3395     *
3396     * Currently it ignores any additions or deletions from other swashes,
3397     * looking at just the main body of the swash, and if there are SPECIALS
3398     * in the swash, at that hash
3399     *
3400     * The specials hash can be extra code points, and most likely consists of
3401     * maps from single code points to multiple ones (each expressed as a string
3402     * of utf8 characters).   This function currently returns only 1-1 mappings.
3403     * However consider this possible input in the specials hash:
3404     * "\xEF\xAC\x85" => "\x{0073}\x{0074}",         # U+FB05 => 0073 0074
3405     * "\xEF\xAC\x86" => "\x{0073}\x{0074}",         # U+FB06 => 0073 0074
3406     *
3407     * Both FB05 and FB06 map to the same multi-char sequence, which we don't
3408     * currently handle.  But it also means that FB05 and FB06 are equivalent in
3409     * a 1-1 mapping which we should handle, and this relationship may not be in
3410     * the main table.  Therefore this function examines all the multi-char
3411     * sequences and adds the 1-1 mappings that come out of that.  */
3412
3413     U8 *l, *lend;
3414     STRLEN lcur;
3415     HV *const hv = MUTABLE_HV(SvRV(swash));
3416
3417     /* The string containing the main body of the table.  This will have its
3418      * assertion fail if the swash has been converted to its inversion list */
3419     SV** const listsvp = hv_fetchs(hv, "LIST", FALSE);
3420
3421     SV** const typesvp = hv_fetchs(hv, "TYPE", FALSE);
3422     SV** const bitssvp = hv_fetchs(hv, "BITS", FALSE);
3423     SV** const nonesvp = hv_fetchs(hv, "NONE", FALSE);
3424     /*SV** const extssvp = hv_fetchs(hv, "EXTRAS", FALSE);*/
3425     const U8* const typestr = (U8*)SvPV_nolen(*typesvp);
3426     const STRLEN bits  = SvUV(*bitssvp);
3427     const STRLEN octets = bits >> 3; /* if bits == 1, then octets == 0 */
3428     const UV     none  = SvUV(*nonesvp);
3429     SV **specials_p = hv_fetchs(hv, "SPECIALS", 0);
3430
3431     HV* ret = newHV();
3432
3433     PERL_ARGS_ASSERT__SWASH_INVERSION_HASH;
3434
3435     /* Must have at least 8 bits to get the mappings */
3436     if (bits != 8 && bits != 16 && bits != 32) {
3437         Perl_croak(aTHX_ "panic: swash_inversion_hash doesn't expect bits %"UVuf,
3438                                                  (UV)bits);
3439     }
3440
3441     if (specials_p) { /* It might be "special" (sometimes, but not always, a
3442                         mapping to more than one character */
3443
3444         /* Construct an inverse mapping hash for the specials */
3445         HV * const specials_hv = MUTABLE_HV(SvRV(*specials_p));
3446         HV * specials_inverse = newHV();
3447         char *char_from; /* the lhs of the map */
3448         I32 from_len;   /* its byte length */
3449         char *char_to;  /* the rhs of the map */
3450         I32 to_len;     /* its byte length */
3451         SV *sv_to;      /* and in a sv */
3452         AV* from_list;  /* list of things that map to each 'to' */
3453
3454         hv_iterinit(specials_hv);
3455
3456         /* The keys are the characters (in utf8) that map to the corresponding
3457          * utf8 string value.  Iterate through the list creating the inverse
3458          * list. */
3459         while ((sv_to = hv_iternextsv(specials_hv, &char_from, &from_len))) {
3460             SV** listp;
3461             if (! SvPOK(sv_to)) {
3462                 Perl_croak(aTHX_ "panic: value returned from hv_iternextsv() "
3463                            "unexpectedly is not a string, flags=%lu",
3464                            (unsigned long)SvFLAGS(sv_to));
3465             }
3466             /*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)));*/
3467
3468             /* Each key in the inverse list is a mapped-to value, and the key's
3469              * hash value is a list of the strings (each in utf8) that map to
3470              * it.  Those strings are all one character long */
3471             if ((listp = hv_fetch(specials_inverse,
3472                                     SvPVX(sv_to),
3473                                     SvCUR(sv_to), 0)))
3474             {
3475                 from_list = (AV*) *listp;
3476             }
3477             else { /* No entry yet for it: create one */
3478                 from_list = newAV();
3479                 if (! hv_store(specials_inverse,
3480                                 SvPVX(sv_to),
3481                                 SvCUR(sv_to),
3482                                 (SV*) from_list, 0))
3483                 {
3484                     Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3485                 }
3486             }
3487
3488             /* Here have the list associated with this 'to' (perhaps newly
3489              * created and empty).  Just add to it.  Note that we ASSUME that
3490              * the input is guaranteed to not have duplications, so we don't
3491              * check for that.  Duplications just slow down execution time. */
3492             av_push(from_list, newSVpvn_utf8(char_from, from_len, TRUE));
3493         }
3494
3495         /* Here, 'specials_inverse' contains the inverse mapping.  Go through
3496          * it looking for cases like the FB05/FB06 examples above.  There would
3497          * be an entry in the hash like
3498         *       'st' => [ FB05, FB06 ]
3499         * In this example we will create two lists that get stored in the
3500         * returned hash, 'ret':
3501         *       FB05 => [ FB05, FB06 ]
3502         *       FB06 => [ FB05, FB06 ]
3503         *
3504         * Note that there is nothing to do if the array only has one element.
3505         * (In the normal 1-1 case handled below, we don't have to worry about
3506         * two lists, as everything gets tied to the single list that is
3507         * generated for the single character 'to'.  But here, we are omitting
3508         * that list, ('st' in the example), so must have multiple lists.) */
3509         while ((from_list = (AV *) hv_iternextsv(specials_inverse,
3510                                                  &char_to, &to_len)))
3511         {
3512             if (av_len(from_list) > 0) {
3513                 SSize_t i;
3514
3515                 /* We iterate over all combinations of i,j to place each code
3516                  * point on each list */
3517                 for (i = 0; i <= av_len(from_list); i++) {
3518                     SSize_t j;
3519                     AV* i_list = newAV();
3520                     SV** entryp = av_fetch(from_list, i, FALSE);
3521                     if (entryp == NULL) {
3522                         Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3523                     }
3524                     if (hv_fetch(ret, SvPVX(*entryp), SvCUR(*entryp), FALSE)) {
3525                         Perl_croak(aTHX_ "panic: unexpected entry for %s", SvPVX(*entryp));
3526                     }
3527                     if (! hv_store(ret, SvPVX(*entryp), SvCUR(*entryp),
3528                                    (SV*) i_list, FALSE))
3529                     {
3530                         Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3531                     }
3532
3533                     /* For debugging: UV u = valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0);*/
3534                     for (j = 0; j <= av_len(from_list); j++) {
3535                         entryp = av_fetch(from_list, j, FALSE);
3536                         if (entryp == NULL) {
3537                             Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3538                         }
3539
3540                         /* When i==j this adds itself to the list */
3541                         av_push(i_list, newSVuv(utf8_to_uvchr_buf(
3542                                         (U8*) SvPVX(*entryp),
3543                                         (U8*) SvPVX(*entryp) + SvCUR(*entryp),
3544                                         0)));
3545                         /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, valid_utf8_to_uvchr((U8*) SvPVX(*entryp), 0), u));*/
3546                     }
3547                 }
3548             }
3549         }
3550         SvREFCNT_dec(specials_inverse); /* done with it */
3551     } /* End of specials */
3552
3553     /* read $swash->{LIST} */
3554     l = (U8*)SvPV(*listsvp, lcur);
3555     lend = l + lcur;
3556
3557     /* Go through each input line */
3558     while (l < lend) {
3559         UV min, max, val;
3560         UV inverse;
3561         l = S_swash_scan_list_line(aTHX_ l, lend, &min, &max, &val,
3562                                          cBOOL(octets), typestr);
3563         if (l > lend) {
3564             break;
3565         }
3566
3567         /* Each element in the range is to be inverted */
3568         for (inverse = min; inverse <= max; inverse++) {
3569             AV* list;
3570             SV** listp;
3571             IV i;
3572             bool found_key = FALSE;
3573             bool found_inverse = FALSE;
3574
3575             /* The key is the inverse mapping */
3576             char key[UTF8_MAXBYTES+1];
3577             char* key_end = (char *) uvchr_to_utf8((U8*) key, val);
3578             STRLEN key_len = key_end - key;
3579
3580             /* Get the list for the map */
3581             if ((listp = hv_fetch(ret, key, key_len, FALSE))) {
3582                 list = (AV*) *listp;
3583             }
3584             else { /* No entry yet for it: create one */
3585                 list = newAV();
3586                 if (! hv_store(ret, key, key_len, (SV*) list, FALSE)) {
3587                     Perl_croak(aTHX_ "panic: hv_store() unexpectedly failed");
3588                 }
3589             }
3590
3591             /* Look through list to see if this inverse mapping already is
3592              * listed, or if there is a mapping to itself already */
3593             for (i = 0; i <= av_len(list); i++) {
3594                 SV** entryp = av_fetch(list, i, FALSE);
3595                 SV* entry;
3596                 if (entryp == NULL) {
3597                     Perl_croak(aTHX_ "panic: av_fetch() unexpectedly failed");
3598                 }
3599                 entry = *entryp;
3600                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "list for %"UVXf" contains %"UVXf"\n", val, SvUV(entry)));*/
3601                 if (SvUV(entry) == val) {
3602                     found_key = TRUE;
3603                 }
3604                 if (SvUV(entry) == inverse) {
3605                     found_inverse = TRUE;
3606                 }
3607
3608                 /* No need to continue searching if found everything we are
3609                  * looking for */
3610                 if (found_key && found_inverse) {
3611                     break;
3612                 }
3613             }
3614
3615             /* Make sure there is a mapping to itself on the list */
3616             if (! found_key) {
3617                 av_push(list, newSVuv(val));
3618                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, val, val));*/
3619             }
3620
3621
3622             /* Simply add the value to the list */
3623             if (! found_inverse) {
3624                 av_push(list, newSVuv(inverse));
3625                 /*DEBUG_U(PerlIO_printf(Perl_debug_log, "%s: %d: Adding %"UVXf" to list for %"UVXf"\n", __FILE__, __LINE__, inverse, val));*/
3626             }
3627
3628             /* swatch_get() increments the value of val for each element in the
3629              * range.  That makes more compact tables possible.  You can
3630              * express the capitalization, for example, of all consecutive
3631              * letters with a single line: 0061\t007A\t0041 This maps 0061 to
3632              * 0041, 0062 to 0042, etc.  I (khw) have never understood 'none',
3633              * and it's not documented; it appears to be used only in
3634              * implementing tr//; I copied the semantics from swatch_get(), just
3635              * in case */
3636             if (!none || val < none) {
3637                 ++val;
3638             }
3639         }
3640     }
3641
3642     return ret;
3643 }
3644
3645 SV*
3646 Perl__swash_to_invlist(pTHX_ SV* const swash)
3647 {
3648
3649    /* Subject to change or removal.  For use only in one place in regcomp.c.
3650     * Ownership is given to one reference count in the returned SV* */
3651
3652     U8 *l, *lend;
3653     char *loc;
3654     STRLEN lcur;
3655     HV *const hv = MUTABLE_HV(SvRV(swash));
3656     UV elements = 0;    /* Number of elements in the inversion list */
3657     U8 empty[] = "";
3658     SV** listsvp;
3659     SV** typesvp;
3660     SV** bitssvp;
3661     SV** extssvp;
3662     SV** invert_it_svp;
3663
3664     U8* typestr;
3665     STRLEN bits;
3666     STRLEN octets; /* if bits == 1, then octets == 0 */
3667     U8 *x, *xend;
3668     STRLEN xcur;
3669
3670     SV* invlist;
3671
3672     PERL_ARGS_ASSERT__SWASH_TO_INVLIST;
3673
3674     /* If not a hash, it must be the swash's inversion list instead */
3675     if (SvTYPE(hv) != SVt_PVHV) {
3676         return SvREFCNT_inc_simple_NN((SV*) hv);
3677     }
3678
3679     /* The string containing the main body of the table */
3680     listsvp = hv_fetchs(hv, "LIST", FALSE);
3681     typesvp = hv_fetchs(hv, "TYPE", FALSE);
3682     bitssvp = hv_fetchs(hv, "BITS", FALSE);
3683     extssvp = hv_fetchs(hv, "EXTRAS", FALSE);
3684     invert_it_svp = hv_fetchs(hv, "INVERT_IT", FALSE);
3685
3686     typestr = (U8*)SvPV_nolen(*typesvp);
3687     bits  = SvUV(*bitssvp);
3688     octets = bits >> 3; /* if bits == 1, then octets == 0 */
3689
3690     /* read $swash->{LIST} */
3691     if (SvPOK(*listsvp)) {
3692         l = (U8*)SvPV(*listsvp, lcur);
3693     }
3694     else {
3695         /* LIST legitimately doesn't contain a string during compilation phases
3696          * of Perl itself, before the Unicode tables are generated.  In this
3697          * case, just fake things up by creating an empty list */
3698         l = empty;
3699         lcur = 0;
3700     }
3701     loc = (char *) l;
3702     lend = l + lcur;
3703
3704     if (*l == 'V') {    /*  Inversion list format */
3705         char *after_strtol = (char *) lend;
3706         UV element0;
3707         UV* other_elements_ptr;
3708
3709         /* The first number is a count of the rest */
3710         l++;
3711         elements = Strtoul((char *)l, &after_strtol, 10);
3712         l = (U8 *) after_strtol;
3713
3714         /* Get the 0th element, which is needed to setup the inversion list */
3715         element0 = (UV) Strtoul((char *)l, &after_strtol, 10);
3716         l = (U8 *) after_strtol;
3717         invlist = _setup_canned_invlist(elements, element0, &other_elements_ptr);
3718         elements--;
3719
3720         /* Then just populate the rest of the input */
3721         while (elements-- > 0) {
3722             if (l > lend) {
3723                 Perl_croak(aTHX_ "panic: Expecting %"UVuf" more elements than available", elements);
3724             }
3725             *other_elements_ptr++ = (UV) Strtoul((char *)l, &after_strtol, 10);
3726             l = (U8 *) after_strtol;
3727         }
3728     }
3729     else {
3730
3731         /* Scan the input to count the number of lines to preallocate array
3732          * size based on worst possible case, which is each line in the input
3733          * creates 2 elements in the inversion list: 1) the beginning of a
3734          * range in the list; 2) the beginning of a range not in the list.  */
3735         while ((loc = (strchr(loc, '\n'))) != NULL) {
3736             elements += 2;
3737             loc++;
3738         }
3739
3740         /* If the ending is somehow corrupt and isn't a new line, add another
3741          * element for the final range that isn't in the inversion list */
3742         if (! (*lend == '\n'
3743             || (*lend == '\0' && (lcur == 0 || *(lend - 1) == '\n'))))
3744         {
3745             elements++;
3746         }
3747
3748         invlist = _new_invlist(elements);
3749
3750         /* Now go through the input again, adding each range to the list */
3751         while (l < lend) {
3752             UV start, end;
3753             UV val;             /* Not used by this function */
3754
3755             l = S_swash_scan_list_line(aTHX_ l, lend, &start, &end, &val,
3756                                             cBOOL(octets), typestr);
3757
3758             if (l > lend) {
3759                 break;
3760             }
3761
3762             invlist = _add_range_to_invlist(invlist, start, end);
3763         }
3764     }
3765
3766     /* Invert if the data says it should be */
3767     if (invert_it_svp && SvUV(*invert_it_svp)) {
3768         _invlist_invert(invlist);
3769     }
3770
3771     /* This code is copied from swatch_get()
3772      * read $swash->{EXTRAS} */
3773     x = (U8*)SvPV(*extssvp, xcur);
3774     xend = x + xcur;
3775     while (x < xend) {
3776         STRLEN namelen;
3777         U8 *namestr;
3778         SV** othersvp;
3779         HV* otherhv;
3780         STRLEN otherbits;
3781         SV **otherbitssvp, *other;
3782         U8 *nl;
3783
3784         const U8 opc = *x++;
3785         if (opc == '\n')
3786             continue;
3787
3788         nl = (U8*)memchr(x, '\n', xend - x);
3789
3790         if (opc != '-' && opc != '+' && opc != '!' && opc != '&') {
3791             if (nl) {
3792                 x = nl + 1; /* 1 is length of "\n" */
3793                 continue;
3794             }
3795             else {
3796                 x = xend; /* to EXTRAS' end at which \n is not found */
3797                 break;
3798             }
3799         }
3800
3801         namestr = x;
3802         if (nl) {
3803             namelen = nl - namestr;
3804             x = nl + 1;
3805         }
3806         else {
3807             namelen = xend - namestr;
3808             x = xend;
3809         }
3810
3811         othersvp = hv_fetch(hv, (char *)namestr, namelen, FALSE);
3812         otherhv = MUTABLE_HV(SvRV(*othersvp));
3813         otherbitssvp = hv_fetchs(otherhv, "BITS", FALSE);
3814         otherbits = (STRLEN)SvUV(*otherbitssvp);
3815
3816         if (bits != otherbits || bits != 1) {
3817             Perl_croak(aTHX_ "panic: _swash_to_invlist only operates on boolean "
3818                        "properties, bits=%"UVuf", otherbits=%"UVuf,
3819                        (UV)bits, (UV)otherbits);
3820         }
3821
3822         /* The "other" swatch must be destroyed after. */
3823         other = _swash_to_invlist((SV *)*othersvp);
3824
3825         /* End of code copied from swatch_get() */
3826         switch (opc) {
3827         case '+':
3828             _invlist_union(invlist, other, &invlist);
3829             break;
3830         case '!':
3831             _invlist_union_maybe_complement_2nd(invlist, other, TRUE, &invlist);
3832             break;
3833         case '-':
3834             _invlist_subtract(invlist, other, &invlist);
3835             break;
3836         case '&':
3837             _invlist_intersection(invlist, other, &invlist);
3838             break;
3839         default:
3840             break;
3841         }
3842         sv_free(other); /* through with it! */
3843     }
3844
3845     SvREADONLY_on(invlist);
3846     return invlist;
3847 }
3848
3849 SV*
3850 Perl__get_swash_invlist(pTHX_ SV* const swash)
3851 {
3852     SV** ptr;
3853
3854     PERL_ARGS_ASSERT__GET_SWASH_INVLIST;
3855
3856     if (! SvROK(swash)) {
3857         return NULL;
3858     }
3859
3860     /* If it really isn't a hash, it isn't really swash; must be an inversion
3861      * list */
3862     if (SvTYPE(SvRV(swash)) != SVt_PVHV) {
3863         return SvRV(swash);
3864     }
3865
3866     ptr = hv_fetchs(MUTABLE_HV(SvRV(swash)), "V", FALSE);
3867     if (! ptr) {
3868         return NULL;
3869     }
3870
3871     return *ptr;
3872 }
3873
3874 bool
3875 Perl_check_utf8_print(pTHX_ const U8* s, const STRLEN len)
3876 {
3877     /* May change: warns if surrogates, non-character code points, or
3878      * non-Unicode code points are in s which has length len bytes.  Returns
3879      * TRUE if none found; FALSE otherwise.  The only other validity check is
3880      * to make sure that this won't exceed the string's length */
3881
3882     const U8* const e = s + len;
3883     bool ok = TRUE;
3884
3885     PERL_ARGS_ASSERT_CHECK_UTF8_PRINT;
3886
3887     while (s < e) {
3888         if (UTF8SKIP(s) > len) {
3889             Perl_ck_warner_d(aTHX_ packWARN(WARN_UTF8),
3890                            "%s in %s", unees, PL_op ? OP_DESC(PL_op) : "print");
3891             return FALSE;
3892         }
3893         if (UNLIKELY(*s >= UTF8_FIRST_PROBLEMATIC_CODE_POINT_FIRST_BYTE)) {
3894             STRLEN char_len;
3895             if (UTF8_IS_SUPER(s)) {
3896                 if (ckWARN_d(WARN_NON_UNICODE)) {
3897                     UV uv = utf8_to_uvchr_buf(s, e, &char_len);
3898                     Perl_warner(aTHX_ packWARN(WARN_NON_UNICODE),
3899                         "Code point 0x%04"UVXf" is not Unicode, may not be portable", uv);
3900                     ok = FALSE;
3901                 }
3902             }
3903             else if (UTF8_IS_SURROGATE(s)) {
3904                 if (ckWARN_d(WARN_SURROGATE)) {
3905                     UV uv = utf8_to_uvchr_buf(s, e, &char_len);
3906                     Perl_warner(aTHX_ packWARN(WARN_SURROGATE),
3907                         "Unicode surrogate U+%04"UVXf" is illegal in UTF-8", uv);
3908                     ok = FALSE;
3909                 }
3910             }
3911             else if
3912                 ((UTF8_IS_NONCHAR_GIVEN_THAT_NON_SUPER_AND_GE_PROBLEMATIC(s))
3913                  && (ckWARN_d(WARN_NONCHAR)))
3914             {
3915                 UV uv = utf8_to_uvchr_buf(s, e, &char_len);
3916                 Perl_warner(aTHX_ packWARN(WARN_NONCHAR),
3917                     "Unicode non-character U+%04"UVXf" is illegal for open interchange", uv);
3918                 ok = FALSE;
3919             }
3920         }
3921         s += UTF8SKIP(s);
3922     }
3923
3924     return ok;
3925 }
3926
3927 /*
3928 =for apidoc pv_uni_display
3929
3930 Build to the scalar C<dsv> a displayable version of the string C<spv>,
3931 length C<len>, the displayable version being at most C<pvlim> bytes long
3932 (if longer, the rest is truncated and "..." will be appended).
3933
3934 The C<flags> argument can have UNI_DISPLAY_ISPRINT set to display
3935 isPRINT()able characters as themselves, UNI_DISPLAY_BACKSLASH
3936 to display the \\[nrfta\\] as the backslashed versions (like '\n')
3937 (UNI_DISPLAY_BACKSLASH is preferred over UNI_DISPLAY_ISPRINT for \\).
3938 UNI_DISPLAY_QQ (and its alias UNI_DISPLAY_REGEX) have both
3939 UNI_DISPLAY_BACKSLASH and UNI_DISPLAY_ISPRINT turned on.
3940
3941 The pointer to the PV of the C<dsv> is returned.
3942
3943 =cut */
3944 char *
3945 Perl_pv_uni_display(pTHX_ SV *dsv, const U8 *spv, STRLEN len, STRLEN pvlim, UV flags)
3946 {
3947     int truncated = 0;
3948     const char *s, *e;
3949
3950     PERL_ARGS_ASSERT_PV_UNI_DISPLAY;
3951
3952     sv_setpvs(dsv, "");
3953     SvUTF8_off(dsv);
3954     for (s = (const char *)spv, e = s + len; s < e; s += UTF8SKIP(s)) {
3955          UV u;
3956           /* This serves double duty as a flag and a character to print after
3957              a \ when flags & UNI_DISPLAY_BACKSLASH is true.
3958           */
3959          char ok = 0;
3960
3961          if (pvlim && SvCUR(dsv) >= pvlim) {
3962               truncated++;
3963               break;
3964          }
3965          u = utf8_to_uvchr_buf((U8*)s, (U8*)e, 0);
3966          if (u < 256) {
3967              const unsigned char c = (unsigned char)u & 0xFF;
3968              if (flags & UNI_DISPLAY_BACKSLASH) {
3969                  switch (c) {
3970                  case '\n':
3971                      ok = 'n'; break;
3972                  case '\r':
3973                      ok = 'r'; break;
3974                  case '\t':
3975                      ok = 't'; break;
3976                  case '\f':
3977                      ok = 'f'; break;
3978                  case '\a':
3979                      ok = 'a'; break;
3980                  case '\\':
3981                      ok = '\\'; break;
3982                  default: break;
3983                  }
3984                  if (ok) {
3985                      const char string = ok;
3986                      sv_catpvs(dsv, "\\");
3987                      sv_catpvn(dsv, &string, 1);
3988                  }
3989              }
3990              /* isPRINT() is the locale-blind version. */
3991              if (!ok && (flags & UNI_DISPLAY_ISPRINT) && isPRINT(c)) {
3992                  const char string = c;
3993                  sv_catpvn(dsv, &string, 1);
3994                  ok = 1;
3995              }
3996          }
3997          if (!ok)
3998              Perl_sv_catpvf(aTHX_ dsv, "\\x{%"UVxf"}", u);
3999     }
4000     if (truncated)
4001          sv_catpvs(dsv, "...");
4002
4003     return SvPVX(dsv);
4004 }
4005
4006 /*
4007 =for apidoc sv_uni_display
4008
4009 Build to the scalar C<dsv> a displayable version of the scalar C<sv>,
4010 the displayable version being at most C<pvlim> bytes long
4011 (if longer, the rest is truncated and "..." will be appended).
4012
4013 The C<flags> argument is as in L</pv_uni_display>().
4014
4015 The pointer to the PV of the C<dsv> is returned.
4016
4017 =cut
4018 */
4019 char *
4020 Perl_sv_uni_display(pTHX_ SV *dsv, SV *ssv, STRLEN pvlim, UV flags)
4021 {
4022     const char * const ptr =
4023         isREGEXP(ssv) ? RX_WRAPPED((REGEXP*)ssv) : SvPVX_const(ssv);
4024
4025     PERL_ARGS_ASSERT_SV_UNI_DISPLAY;
4026
4027     return Perl_pv_uni_display(aTHX_ dsv, (const U8*)ptr,
4028                                 SvCUR(ssv), pvlim, flags);
4029 }
4030
4031 /*
4032 =for apidoc foldEQ_utf8
4033
4034 Returns true if the leading portions of the strings C<s1> and C<s2> (either or both
4035 of which may be in UTF-8) are the same case-insensitively; false otherwise.
4036 How far into the strings to compare is determined by other input parameters.
4037
4038 If C<u1> is true, the string C<s1> is assumed to be in UTF-8-encoded Unicode;
4039 otherwise it is assumed to be in native 8-bit encoding.  Correspondingly for C<u2>
4040 with respect to C<s2>.
4041
4042 If the byte length C<l1> is non-zero, it says how far into C<s1> to check for fold
4043 equality.  In other words, C<s1>+C<l1> will be used as a goal to reach.  The
4044 scan will not be considered to be a match unless the goal is reached, and
4045 scanning won't continue past that goal.  Correspondingly for C<l2> with respect to
4046 C<s2>.
4047
4048 If C<pe1> is non-NULL and the pointer it points to is not NULL, that pointer is
4049 considered an end pointer to the position 1 byte past the maximum point
4050 in C<s1> beyond which scanning will not continue under any circumstances.
4051 (This routine assumes that UTF-8 encoded input strings are not malformed;
4052 malformed input can cause it to read past C<pe1>).
4053 This means that if both C<l1> and C<pe1> are specified, and C<pe1>
4054 is less than C<s1>+C<l1>, the match will never be successful because it can
4055 never
4056 get as far as its goal (and in fact is asserted against).  Correspondingly for
4057 C<pe2> with respect to C<s2>.
4058
4059 At least one of C<s1> and C<s2> must have a goal (at least one of C<l1> and
4060 C<l2> must be non-zero), and if both do, both have to be
4061 reached for a successful match.   Also, if the fold of a character is multiple
4062 characters, all of them must be matched (see tr21 reference below for
4063 'folding').
4064
4065 Upon a successful match, if C<pe1> is non-NULL,
4066 it will be set to point to the beginning of the I<next> character of C<s1>
4067 beyond what was matched.  Correspondingly for C<pe2> and C<s2>.
4068
4069 For case-insensitiveness, the "casefolding" of Unicode is used
4070 instead of upper/lowercasing both the characters, see
4071 L<http://www.unicode.org/unicode/reports/tr21/> (Case Mappings).
4072
4073 =cut */
4074
4075 /* A flags parameter has been added which may change, and hence isn't
4076  * externally documented.  Currently it is:
4077  *  0 for as-documented above
4078  *  FOLDEQ_UTF8_NOMIX_ASCII meaning that if a non-ASCII character folds to an
4079                             ASCII one, to not match
4080  *  FOLDEQ_UTF8_LOCALE      meaning that locale rules are to be used for code
4081  *                          points below 256; unicode rules for above 255; and
4082  *                          folds that cross those boundaries are disallowed,
4083  *                          like the NOMIX_ASCII option
4084  *  FOLDEQ_S1_ALREADY_FOLDED s1 has already been folded before calling this
4085  *                           routine.  This allows that step to be skipped.
4086  *  FOLDEQ_S2_ALREADY_FOLDED   Similarly.
4087  */
4088 I32
4089 Perl_foldEQ_utf8_flags(pTHX_ const char *s1, char **pe1, UV l1, bool u1, const char *s2, char **pe2, UV l2, bool u2, U32 flags)
4090 {
4091     dVAR;
4092     const U8 *p1  = (const U8*)s1; /* Point to current char */
4093     const U8 *p2  = (const U8*)s2;
4094     const U8 *g1 = NULL;       /* goal for s1 */
4095     const U8 *g2 = NULL;
4096     const U8 *e1 = NULL;       /* Don't scan s1 past this */
4097     U8 *f1 = NULL;             /* Point to current folded */
4098     const U8 *e2 = NULL;
4099     U8 *f2 = NULL;
4100     STRLEN n1 = 0, n2 = 0;              /* Number of bytes in current char */
4101     U8 foldbuf1[UTF8_MAXBYTES_CASE+1];
4102     U8 foldbuf2[UTF8_MAXBYTES_CASE+1];
4103
4104     PERL_ARGS_ASSERT_FOLDEQ_UTF8_FLAGS;
4105
4106     assert( ! ((flags & (FOLDEQ_UTF8_NOMIX_ASCII | FOLDEQ_UTF8_LOCALE))
4107            && (flags & (FOLDEQ_S1_ALREADY_FOLDED | FOLDEQ_S2_ALREADY_FOLDED))));
4108     /* The algorithm is to trial the folds without regard to the flags on
4109      * the first line of the above assert(), and then see if the result
4110      * violates them.  This means that the inputs can't be pre-folded to a
4111      * violating result, hence the assert.  This could be changed, with the
4112      * addition of extra tests here for the already-folded case, which would
4113      * slow it down.  That cost is more than any possible gain for when these
4114      * flags are specified, as the flags indicate /il or /iaa matching which
4115      * is less common than /iu, and I (khw) also believe that real-world /il
4116      * and /iaa matches are most likely to involve code points 0-255, and this
4117      * function only under rare conditions gets called for 0-255. */
4118
4119     if (pe1) {
4120         e1 = *(U8**)pe1;
4121     }
4122
4123     if (l1) {
4124         g1 = (const U8*)s1 + l1;
4125     }
4126
4127     if (pe2) {
4128         e2 = *(U8**)pe2;
4129     }
4130
4131     if (l2) {
4132         g2 = (const U8*)s2 + l2;
4133     }
4134
4135     /* Must have at least one goal */
4136     assert(g1 || g2);
4137
4138     if (g1) {
4139
4140         /* Will never match if goal is out-of-bounds */
4141         assert(! e1  || e1 >= g1);
4142
4143         /* Here, there isn't an end pointer, or it is beyond the goal.  We
4144         * only go as far as the goal */
4145         e1 = g1;
4146     }
4147     else {
4148         assert(e1);    /* Must have an end for looking at s1 */
4149     }
4150
4151     /* Same for goal for s2 */
4152     if (g2) {
4153         assert(! e2  || e2 >= g2);
4154         e2 = g2;
4155     }
4156     else {
4157         assert(e2);
4158     }
4159
4160     /* If both operands are already folded, we could just do a memEQ on the
4161      * whole strings at once, but it would be better if the caller realized
4162      * this and didn't even call us */
4163
4164     /* Look through both strings, a character at a time */
4165     while (p1 < e1 && p2 < e2) {
4166
4167         /* If at the beginning of a new character in s1, get its fold to use
4168          * and the length of the fold.  (exception: locale rules just get the
4169          * character to a single byte) */
4170         if (n1 == 0) {
4171             if (flags & FOLDEQ_S1_ALREADY_FOLDED) {
4172                 f1 = (U8 *) p1;
4173                 n1 = UTF8SKIP(f1);
4174             }
4175             else {
4176                 /* If in locale matching, we use two sets of rules, depending
4177                  * on if the code point is above or below 255.  Here, we test
4178                  * for and handle locale rules */
4179                 if ((flags & FOLDEQ_UTF8_LOCALE)
4180                     && (! u1 || ! UTF8_IS_ABOVE_LATIN1(*p1)))
4181                 {
4182                     /* There is no mixing of code points above and below 255. */
4183                     if (u2 && UTF8_IS_ABOVE_LATIN1(*p2)) {
4184                         return 0;
4185                     }
4186
4187                     /* We handle locale rules by converting, if necessary, the
4188                      * code point to a single byte. */
4189                     if (! u1 || UTF8_IS_INVARIANT(*p1)) {
4190                         *foldbuf1 = *p1;
4191                     }
4192                     else {
4193                         *foldbuf1 = TWO_BYTE_UTF8_TO_NATIVE(*p1, *(p1 + 1));
4194                     }
4195                     n1 = 1;
4196                 }
4197                 else if (isASCII(*p1)) {    /* Note, that here won't be both
4198                                                ASCII and using locale rules */
4199
4200                     /* If trying to mix non- with ASCII, and not supposed to,
4201                      * fail */
4202                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p2)) {
4203                         return 0;
4204                     }
4205                     n1 = 1;
4206                     *foldbuf1 = toFOLD(*p1);
4207                 }
4208                 else if (u1) {
4209                     to_utf8_fold(p1, foldbuf1, &n1);
4210                 }
4211                 else {  /* Not utf8, get utf8 fold */
4212                     to_uni_fold(*p1, foldbuf1, &n1);
4213                 }
4214                 f1 = foldbuf1;
4215             }
4216         }
4217
4218         if (n2 == 0) {    /* Same for s2 */
4219             if (flags & FOLDEQ_S2_ALREADY_FOLDED) {
4220                 f2 = (U8 *) p2;
4221                 n2 = UTF8SKIP(f2);
4222             }
4223             else {
4224                 if ((flags & FOLDEQ_UTF8_LOCALE)
4225                     && (! u2 || ! UTF8_IS_ABOVE_LATIN1(*p2)))
4226                 {
4227                     /* Here, the next char in s2 is < 256.  We've already
4228                      * worked on s1, and if it isn't also < 256, can't match */
4229                     if (u1 && UTF8_IS_ABOVE_LATIN1(*p1)) {
4230                         return 0;
4231                     }
4232                     if (! u2 || UTF8_IS_INVARIANT(*p2)) {
4233                         *foldbuf2 = *p2;
4234                     }
4235                     else {
4236                         *foldbuf2 = TWO_BYTE_UTF8_TO_NATIVE(*p2, *(p2 + 1));
4237                     }
4238
4239                     /* Use another function to handle locale rules.  We've made
4240                      * sure that both characters to compare are single bytes */
4241                     if (! foldEQ_locale((char *) f1, (char *) foldbuf2, 1)) {
4242                         return 0;
4243                     }
4244                     n1 = n2 = 0;
4245                 }
4246                 else if (isASCII(*p2)) {
4247                     if ((flags & FOLDEQ_UTF8_NOMIX_ASCII) && ! isASCII(*p1)) {
4248                         return 0;
4249                     }
4250                     n2 = 1;
4251                     *foldbuf2 = toFOLD(*p2);
4252                 }
4253                 else if (u2) {
4254                     to_utf8_fold(p2, foldbuf2, &n2);
4255                 }
4256                 else {
4257                     to_uni_fold(*p2, foldbuf2, &n2);
4258                 }
4259                 f2 = foldbuf2;
4260             }
4261         }
4262
4263         /* Here f1 and f2 point to the beginning of the strings to compare.
4264          * These strings are the folds of the next character from each input
4265          * string, stored in utf8. */
4266
4267         /* While there is more to look for in both folds, see if they
4268         * continue to match */
4269         while (n1 && n2) {
4270             U8 fold_length = UTF8SKIP(f1);
4271             if (fold_length != UTF8SKIP(f2)
4272                 || (fold_length == 1 && *f1 != *f2) /* Short circuit memNE
4273                                                        function call for single
4274                                                        byte */
4275                 || memNE((char*)f1, (char*)f2, fold_length))
4276             {
4277                 return 0; /* mismatch */
4278             }
4279
4280             /* Here, they matched, advance past them */
4281             n1 -= fold_length;
4282             f1 += fold_length;
4283             n2 -= fold_length;
4284             f2 += fold_length;
4285         }
4286
4287         /* When reach the end of any fold, advance the input past it */
4288         if (n1 == 0) {
4289             p1 += u1 ? UTF8SKIP(p1) : 1;
4290         }
4291         if (n2 == 0) {
4292             p2 += u2 ? UTF8SKIP(p2) : 1;
4293         }
4294     } /* End of loop through both strings */
4295
4296     /* A match is defined by each scan that specified an explicit length
4297     * reaching its final goal, and the other not having matched a partial
4298     * character (which can happen when the fold of a character is more than one
4299     * character). */
4300     if (! ((g1 == 0 || p1 == g1) && (g2 == 0 || p2 == g2)) || n1 || n2) {
4301         return 0;
4302     }
4303
4304     /* Successful match.  Set output pointers */
4305     if (pe1) {
4306         *pe1 = (char*)p1;
4307     }
4308     if (pe2) {
4309         *pe2 = (char*)p2;
4310     }
4311     return 1;
4312 }
4313
4314 /* XXX The next four functions should likely be moved to mathoms.c once all
4315  * occurrences of them are removed from the core; some cpan-upstream modules
4316  * still use them */
4317
4318 U8 *
4319 Perl_uvuni_to_utf8(pTHX_ U8 *d, UV uv)
4320 {
4321     PERL_ARGS_ASSERT_UVUNI_TO_UTF8;
4322
4323     return Perl_uvoffuni_to_utf8_flags(aTHX_ d, uv, 0);
4324 }
4325
4326 UV
4327 Perl_utf8n_to_uvuni(pTHX_ const U8 *s, STRLEN curlen, STRLEN *retlen, U32 flags)
4328 {
4329     PERL_ARGS_ASSERT_UTF8N_TO_UVUNI;
4330
4331     return NATIVE_TO_UNI(utf8n_to_uvchr(s, curlen, retlen, flags));
4332 }
4333
4334 /*
4335 =for apidoc uvuni_to_utf8_flags
4336
4337 Instead you almost certainly want to use L</uvchr_to_utf8> or
4338 L</uvchr_to_utf8_flags>>.
4339
4340 This function is a deprecated synonym for L</uvoffuni_to_utf8_flags>,
4341 which itself, while not deprecated, should be used only in isolated
4342 circumstances.  These functions were useful for code that wanted to handle
4343 both EBCDIC and ASCII platforms with Unicode properties, but starting in Perl
4344 v5.20, the distinctions between the platforms have mostly been made invisible
4345 to most code, so this function is quite unlikely to be what you want.
4346
4347 =cut
4348 */
4349
4350 U8 *
4351 Perl_uvuni_to_utf8_flags(pTHX_ U8 *d, UV uv, UV flags)
4352 {
4353     PERL_ARGS_ASSERT_UVUNI_TO_UTF8_FLAGS;
4354
4355     return uvoffuni_to_utf8_flags(d, uv, flags);
4356 }
4357
4358 /*
4359 =for apidoc utf8n_to_uvuni
4360
4361 Instead use L</utf8_to_uvchr_buf>, or rarely, L</utf8n_to_uvchr>.
4362
4363 This function was useful for code that wanted to handle both EBCDIC and
4364 ASCII platforms with Unicode properties, but starting in Perl v5.20, the
4365 distinctions between the platforms have mostly been made invisible to most
4366 code, so this function is quite unlikely to be what you want.  If you do need
4367 this precise functionality, use instead
4368 C<L<NATIVE_TO_UNI(utf8_to_uvchr_buf(...))|/utf8_to_uvchr_buf>>
4369 or C<L<NATIVE_TO_UNI(utf8n_to_uvchr(...))|/utf8n_to_uvchr>>.
4370
4371 =cut
4372 */
4373
4374 /*
4375  * Local variables:
4376  * c-indentation-style: bsd
4377  * c-basic-offset: 4
4378  * indent-tabs-mode: nil
4379  * End:
4380  *
4381  * ex: set ts=8 sts=4 sw=4 et:
4382  */