]> perl5.git.perl.org Git - perl5.git/blob - doop.c This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Deparse: exclude two new test files
[perl5.git] / doop.c
1 /*    doop.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2004, 2005, 2006, 2007, 2008, 2009 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  *  'So that was the job I felt I had to do when I started,' thought Sam.
13  *
14  *     [p.934 of _The Lord of the Rings_, VI/iii: "Mount Doom"]
15  */
16
17 /* This file contains some common functions needed to carry out certain
18  * ops. For example, both pp_sprintf() and pp_prtf() call the function
19  * do_sprintf() found in this file.
20  */
21
22 #include "EXTERN.h"
23 #define PERL_IN_DOOP_C
24 #include "perl.h"
25 #include "invlist_inline.h"
26
27 #include <signal.h>
28
29
30 /* Helper function for do_trans().
31  * Handles cases where the search and replacement charlists aren't UTF-8,
32  * aren't identical, and neither the /d nor /s flag is present.
33  *
34  * sv may or may not be utf8.  Note that no code point above 255 can possibly
35  * be in the to-translate set
36  */
37
38 STATIC Size_t
39 S_do_trans_simple(pTHX_ SV * const sv, const OPtrans_map * const tbl)
40 {
41     Size_t matches = 0;
42     STRLEN len;
43     U8 *s = (U8*)SvPV_nomg(sv,len);
44     U8 * const send = s+len;
45
46     PERL_ARGS_ASSERT_DO_TRANS_SIMPLE;
47     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: entering do_trans_simple:"
48                                           " input sv:\n",
49                                           __FILE__, __LINE__));
50     DEBUG_y(sv_dump(sv));
51
52     /* First, take care of input strings where UTF8ness doesn't matter */
53     if (   ! SvUTF8(sv)
54         || (PL_op->op_private & OPpTRANS_MASK) == OPpTRANS_ONLY_UTF8_INVARIANTS)
55     {
56         while (s < send) {
57             const short ch = tbl->map[*s];
58             if (ch >= 0) {
59                 matches++;
60                 *s = (U8)ch;
61             }
62             s++;
63         }
64         SvSETMAGIC(sv);
65     }
66     else {
67         const bool grows = (PL_op->op_private & OPpTRANS_MASK) == OPpTRANS_GROWS;
68         U8 *d;
69         U8 *dstart;
70
71         /* Allow for worst-case expansion: Each input byte can become 2.  For a
72          * given input character, this happens when it occupies a single byte
73          * under UTF-8, but is to be translated to something that occupies two:
74          * $_="a".chr(400); tr/a/\xFE/, FE needs encoding. */
75         if (grows)
76             Newx(d, len*2+1, U8);
77         else
78             d = s;
79         dstart = d;
80         while (s < send) {
81             STRLEN ulen;
82             short ch;
83
84             /* Need to check this, otherwise 128..255 won't match */
85             const UV c = utf8_to_uv_or_die(s, send, &ulen);
86             if (c < 0x100 && (ch = tbl->map[c]) >= 0) {
87                 matches++;
88                 d = uv_to_utf8(d, (UV)ch);
89                 s += ulen;
90             }
91             else { /* No match -> copy */
92                 Move(s, d, ulen, U8);
93                 d += ulen;
94                 s += ulen;
95             }
96         }
97         if (grows) {
98             sv_setpvn(sv, (char*)dstart, d - dstart);
99             Safefree(dstart);
100         }
101         else {
102             *d = '\0';
103             SvCUR_set(sv, d - dstart);
104         }
105         SvUTF8_on(sv);
106         SvSETMAGIC(sv);
107     }
108     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: returning %zu\n",
109                                           __FILE__, __LINE__, matches));
110     DEBUG_y(sv_dump(sv));
111     return matches;
112 }
113
114
115 /* Helper function for do_trans().
116  * Handles cases where the search and replacement charlists are identical and
117  * non-utf8: so the string isn't modified, and only a count of modifiable
118  * chars is needed.
119  *
120  * Note that it doesn't handle /d or /s, since these modify the string even if
121  * the replacement list is empty.
122  *
123  * sv may or may not be utf8.  Note that no code point above 255 can possibly
124  * be in the to-translate set
125  */
126
127 STATIC Size_t
128 S_do_trans_count(pTHX_ SV * const sv, const OPtrans_map * const tbl)
129 {
130     STRLEN len;
131     const U8 *s = (const U8*)SvPV_nomg_const(sv, len);
132     const U8 * const send = s + len;
133     Size_t matches = 0;
134
135     PERL_ARGS_ASSERT_DO_TRANS_COUNT;
136
137     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: entering do_trans_count:"
138                                           " input sv:\n",
139                                           __FILE__, __LINE__));
140     DEBUG_y(sv_dump(sv));
141
142     if (!SvUTF8(sv)) {
143         while (s < send) {
144             if (tbl->map[*s++] >= 0)
145                 matches++;
146         }
147     }
148     else {
149         const bool complement = cBOOL(PL_op->op_private & OPpTRANS_COMPLEMENT);
150         while (s < send) {
151             STRLEN ulen;
152             const UV c = utf8_to_uv_or_die(s, send, &ulen);
153             if (c < 0x100) {
154                 if (tbl->map[c] >= 0)
155                     matches++;
156             } else if (complement)
157                 matches++;
158             s += ulen;
159         }
160     }
161
162     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: count returning %zu\n",
163                                           __FILE__, __LINE__, matches));
164     return matches;
165 }
166
167
168 /* Helper function for do_trans().
169  * Handles cases where the search and replacement charlists aren't identical
170  * and both are non-utf8, and one or both of /d, /s is specified.
171  *
172  * sv may or may not be utf8.  Note that no code point above 255 can possibly
173  * be in the to-translate set
174  */
175
176 STATIC Size_t
177 S_do_trans_complex(pTHX_ SV * const sv, const OPtrans_map * const tbl)
178 {
179     STRLEN len;
180     U8 *s = (U8*)SvPV_nomg(sv, len);
181     U8 * const send = s+len;
182     Size_t matches = 0;
183     const bool complement = cBOOL(PL_op->op_private & OPpTRANS_COMPLEMENT);
184
185     PERL_ARGS_ASSERT_DO_TRANS_COMPLEX;
186
187     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: entering do_trans_complex:"
188                                           " input sv:\n",
189                                           __FILE__, __LINE__));
190     DEBUG_y(sv_dump(sv));
191
192     if (   ! SvUTF8(sv)
193         || (PL_op->op_private & OPpTRANS_MASK) == OPpTRANS_ONLY_UTF8_INVARIANTS)
194     {
195         U8 *d = s;
196         U8 * const dstart = d;
197
198         if (PL_op->op_private & OPpTRANS_SQUASH) {
199
200             /* What the mapping of the previous character was to.  If the new
201              * character has the same mapping, it is squashed from the output
202              * (but still is included in the count) */
203             short previous_map = (short) TR_OOB;
204
205             while (s < send) {
206                 const short this_map = tbl->map[*s];
207                 if (this_map >= 0) {
208                     matches++;
209                     if (this_map != previous_map) {
210                         *d++ = (U8)this_map;
211                         previous_map = this_map;
212                     }
213                 }
214                 else {
215                     if (this_map == (short) TR_UNMAPPED) {
216                         *d++ = *s;
217                         previous_map = (short) TR_OOB;
218                     }
219                     else {
220                         assert(this_map == (short) TR_DELETE);
221                         matches++;
222                     }
223                 }
224
225                 s++;
226             }
227         }
228         else {  /* Not to squash */
229             while (s < send) {
230                 const short this_map = tbl->map[*s];
231                 if (this_map >= 0) {
232                     matches++;
233                     *d++ = (U8)this_map;
234                 }
235                 else if (this_map == (short) TR_UNMAPPED)
236                     *d++ = *s;
237                 else if (this_map == (short) TR_DELETE)
238                     matches++;
239                 s++;
240             }
241         }
242         *d = '\0';
243         SvCUR_set(sv, d - dstart);
244     }
245     else { /* is utf8 */
246         const bool squash = cBOOL(PL_op->op_private & OPpTRANS_SQUASH);
247         const bool grows = (PL_op->op_private & OPpTRANS_MASK) == OPpTRANS_GROWS;
248         U8 *d;
249         U8 *dstart;
250         Size_t size = tbl->size;
251
252         /* What the mapping of the previous character was to.  If the new
253          * character has the same mapping, it is squashed from the output (but
254          * still is included in the count) */
255         UV pch = TR_OOB;
256
257         if (grows)
258             /* Allow for worst-case expansion: Each input byte can become 2.
259              * For a given input character, this happens when it occupies a
260              * single byte under UTF-8, but is to be translated to something
261              * that occupies two: */
262             Newx(d, len*2+1, U8);
263         else
264             d = s;
265         dstart = d;
266
267         while (s < send) {
268             STRLEN len;
269             const UV comp = utf8_to_uv_or_die(s, send, &len);
270             UV     ch;
271             short sch;
272
273             sch = (comp < size)
274                   ? tbl->map[comp]
275                   : (! complement)
276                     ? (short) TR_UNMAPPED
277                     : tbl->map[size];
278
279             if (sch >= 0) {
280                 ch = (UV)sch;
281               replace:
282                 matches++;
283                 if (LIKELY(!squash || ch != pch)) {
284                     d = uv_to_utf8(d, ch);
285                     pch = ch;
286                 }
287                 s += len;
288                 continue;
289             }
290             else if (sch == (short) TR_UNMAPPED) {
291                 Move(s, d, len, U8);
292                 d += len;
293                 pch = TR_OOB;
294             }
295             else if (sch == (short) TR_DELETE)
296                 matches++;
297             else {
298                 assert(sch == (short) TR_R_EMPTY);  /* empty replacement */
299                 ch = comp;
300                 goto replace;
301             }
302
303             s += len;
304         }
305
306         if (grows) {
307             sv_setpvn(sv, (char*)dstart, d - dstart);
308             Safefree(dstart);
309         }
310         else {
311             *d = '\0';
312             SvCUR_set(sv, d - dstart);
313         }
314         SvUTF8_on(sv);
315     }
316     SvSETMAGIC(sv);
317     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: returning %zu\n",
318                                           __FILE__, __LINE__, matches));
319     DEBUG_y(sv_dump(sv));
320     return matches;
321 }
322
323
324 /* Helper function for do_trans().
325  * Handles cases where an inversion map implementation is to be used and the
326  * search and replacement charlists are identical: so the string isn't
327  * modified, and only a count of modifiable chars is needed.
328  *
329  * Note that it doesn't handle /d nor /s, since these modify the string
330  * even if the replacement charlist is empty.
331  *
332  * sv may or may not be utf8.
333  */
334
335 STATIC Size_t
336 S_do_trans_count_invmap(pTHX_ SV * const sv, AV * const invmap)
337 {
338     U8 *s;
339     U8 *send;
340     Size_t matches = 0;
341     STRLEN len;
342     SV** const from_invlist_ptr = av_fetch(invmap, 0, TRUE);
343     SV** const to_invmap_ptr = av_fetch(invmap, 1, TRUE);
344     SV* from_invlist = *from_invlist_ptr;
345     SV* to_invmap_sv = *to_invmap_ptr;
346     UV* map = (UV *) SvPVX(to_invmap_sv);
347
348     PERL_ARGS_ASSERT_DO_TRANS_COUNT_INVMAP;
349
350     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:"
351                                           "entering do_trans_count_invmap:"
352                                           " input sv:\n",
353                                           __FILE__, __LINE__));
354     DEBUG_y(sv_dump(sv));
355     DEBUG_y(PerlIO_printf(Perl_debug_log, "mapping:\n"));
356     DEBUG_y(invmap_dump(from_invlist, (UV *) SvPVX(to_invmap_sv)));
357
358     s = (U8*)SvPV_nomg(sv, len);
359
360     send = s + len;
361
362     while (s < send) {
363         UV from;
364         SSize_t i;
365         STRLEN s_len;
366
367         /* Get the code point of the next character in the string */
368         if (! SvUTF8(sv) || UTF8_IS_INVARIANT(*s)) {
369             from = *s;
370             s_len = 1;
371         }
372         else {
373             from = utf8_to_uv_or_die(s, send, &s_len);
374         }
375
376         /* Look the code point up in the data structure for this tr/// to get
377          * what it maps to */
378         i = _invlist_search(from_invlist, from);
379         assert(i >= 0);
380
381         if (map[i] != (UV) TR_UNLISTED) {
382             matches++;
383         }
384
385         s += s_len;
386     }
387
388     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: returning %zu\n",
389                                           __FILE__, __LINE__, matches));
390     return matches;
391 }
392
393 /* Helper function for do_trans().
394  * Handles cases where an inversion map implementation is to be used and the
395  * search and replacement charlists are either not identical or flags are
396  * present.
397  *
398  * sv may or may not be utf8.
399  */
400
401 STATIC Size_t
402 S_do_trans_invmap(pTHX_ SV * const sv, AV * const invmap)
403 {
404     U8 *s;
405     U8 *send;
406     U8 *d;
407     U8 *s0;
408     U8 *d0;
409     Size_t matches = 0;
410     STRLEN len;
411     SV** const from_invlist_ptr = av_fetch(invmap, 0, TRUE);
412     SV** const to_invmap_ptr = av_fetch(invmap, 1, TRUE);
413     SV** const to_expansion_ptr = av_fetch(invmap, 2, TRUE);
414     NV max_expansion = SvNV(*to_expansion_ptr);
415     SV* from_invlist = *from_invlist_ptr;
416     SV* to_invmap_sv = *to_invmap_ptr;
417     UV* map = (UV *) SvPVX(to_invmap_sv);
418     UV previous_map = TR_OOB;
419     const bool squash         = cBOOL(PL_op->op_private & OPpTRANS_SQUASH);
420     const bool delete_unfound = cBOOL(PL_op->op_private & OPpTRANS_DELETE);
421     bool inplace = (PL_op->op_private & OPpTRANS_MASK) != OPpTRANS_GROWS;
422     const UV* from_array = invlist_array(from_invlist);
423     UV final_map = TR_OOB;
424     bool out_is_utf8 = cBOOL(SvUTF8(sv));
425     STRLEN s_len;
426
427     PERL_ARGS_ASSERT_DO_TRANS_INVMAP;
428
429     /* A third element in the array indicates that the replacement list was
430      * shorter than the search list, and this element contains the value to use
431      * for the items that don't correspond */
432     if (av_top_index(invmap) >= 3) {
433         SV** const final_map_ptr = av_fetch(invmap, 3, TRUE);
434         SV*  const final_map_sv = *final_map_ptr;
435         final_map = SvUV(final_map_sv);
436     }
437
438     /* If there is something in the transliteration that could force the input
439      * to be changed to UTF-8, we don't know if we can do it in place, so
440      * assume cannot */
441     if (   ! out_is_utf8
442         && (PL_op->op_private & OPpTRANS_MASK) == OPpTRANS_CAN_FORCE_UTF8)
443     {
444         inplace = FALSE;
445     }
446
447     s = (U8*)SvPV_nomg(sv, len);
448     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: entering do_trans_invmap:"
449                                           " input sv:\n",
450                                           __FILE__, __LINE__));
451     DEBUG_y(sv_dump(sv));
452     DEBUG_y(PerlIO_printf(Perl_debug_log, "mapping:\n"));
453     DEBUG_y(invmap_dump(from_invlist, map));
454
455     send = s + len;
456     s0 = s;
457
458     /* We know by now if there are some possible input strings whose
459      * transliterations are longer than the input.  If none can, we just edit
460      * in place. */
461     if (inplace) {
462         d0 = d = s;
463     }
464     else {
465         /* Here, we can't edit in place.  We have no idea how much, if any,
466          * this particular input string will grow.  However, the compilation
467          * calculated the maximum expansion possible.  Use that to allocate
468          * based on the worst case scenario.  (First +1 is to round up; 2nd is
469          * for \0) */
470         Newx(d, (STRLEN) (len * max_expansion + 1 + 1), U8);
471         d0 = d;
472     }
473
474   restart:
475
476     /* Do the actual transliteration */
477     while (s < send) {
478         UV from;
479         UV to;
480         SSize_t i;
481         STRLEN s_len;
482
483         /* Get the code point of the next character in the string */
484         if (! SvUTF8(sv) || UTF8_IS_INVARIANT(*s)) {
485             from = *s;
486             s_len = 1;
487         }
488         else {
489             from = utf8_to_uv_or_die(s, send, &s_len);
490         }
491
492         /* Look the code point up in the data structure for this tr/// to get
493          * what it maps to */
494         i = _invlist_search(from_invlist, from);
495         assert(i >= 0);
496
497         to = map[i];
498
499         if (to == (UV) TR_UNLISTED) { /* Just copy the unreplaced character */
500             if (UVCHR_IS_INVARIANT(from) || ! out_is_utf8) {
501                 *d++ = (U8) from;
502             }
503             else if (SvUTF8(sv)) {
504                 Move(s, d, s_len, U8);
505                 d += s_len;
506             }
507             else {  /* Convert to UTF-8 */
508                 append_utf8_from_native_byte(*s, &d);
509             }
510
511             previous_map = to;
512             s += s_len;
513             continue;
514         }
515
516         /* Everything else is counted as a match */
517         matches++;
518
519         if (to == (UV) TR_SPECIAL_HANDLING) {
520             if (delete_unfound) {
521                 s += s_len;
522                 continue;
523             }
524
525             /* Use the final character in the replacement list */
526             to = final_map;
527         }
528         else { /* Here the input code point is to be remapped.  The actual
529                   value is offset from the base of this entry */
530             to += from - from_array[i];
531         }
532
533         /* If copying all occurrences, or this is the first occurrence, copy it
534          * to the output */
535         if (! squash || to != previous_map) {
536             if (out_is_utf8) {
537                 d = uv_to_utf8(d, to);
538             }
539             else {
540                 if (to >= 256) {    /* If need to convert to UTF-8, restart */
541                     out_is_utf8 = TRUE;
542                     s = s0;
543                     d = d0;
544                     matches = 0;
545                     goto restart;
546                 }
547                 *d++ = (U8) to;
548             }
549         }
550
551         previous_map = to;
552         s += s_len;
553     }
554
555     s_len = 0;
556     s += s_len;
557     if (! inplace) {
558         sv_setpvn(sv, (char*)d0, d - d0);
559         Safefree(d0);
560     }
561     else {
562         *d = '\0';
563         SvCUR_set(sv, d - d0);
564     }
565
566     if (! SvUTF8(sv) && out_is_utf8) {
567         SvUTF8_on(sv);
568     }
569     SvSETMAGIC(sv);
570
571     DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d: returning %zu\n",
572                                           __FILE__, __LINE__, matches));
573     DEBUG_y(sv_dump(sv));
574     return matches;
575 }
576
577 /* Execute a tr//. sv is the value to be translated, while PL_op
578  * should be an OP_TRANS or OP_TRANSR op, whose op_pv field contains a
579  * translation table or whose op_sv field contains an inversion map.
580  *
581  * Returns a count of number of characters translated
582  */
583
584 Size_t
585 Perl_do_trans(pTHX_ SV *sv)
586 {
587     STRLEN len;
588     const U8 flags = PL_op->op_private;
589     bool use_utf8_fcns = cBOOL(flags & OPpTRANS_USE_SVOP);
590     bool identical     = cBOOL(flags & OPpTRANS_IDENTICAL);
591
592     PERL_ARGS_ASSERT_DO_TRANS;
593
594     if (SvREADONLY(sv) && ! identical) {
595         croak_no_modify();
596     }
597     (void)SvPV_const(sv, len);
598     if (!len)
599         return 0;
600     if (! identical) {
601         if (!SvPOKp(sv) || SvTHINKFIRST(sv))
602             (void)SvPV_force_nomg(sv, len);
603         (void)SvPOK_only_UTF8(sv);
604     }
605
606     if (use_utf8_fcns) {
607         SV* const map =
608 #ifdef USE_ITHREADS
609                         PAD_SVl(cPADOP->op_padix);
610 #else
611                         MUTABLE_SV(cSVOP->op_sv);
612 #endif
613
614         if (identical) {
615             return do_trans_count_invmap(sv, (AV *) map);
616         }
617         else {
618             return do_trans_invmap(sv, (AV *) map);
619         }
620     }
621     else {
622         const OPtrans_map * const map = (OPtrans_map*)cPVOP->op_pv;
623
624         if (identical) {
625             return do_trans_count(sv, map);
626         }
627         else if (flags & (OPpTRANS_SQUASH|OPpTRANS_DELETE|OPpTRANS_COMPLEMENT)) {
628             return do_trans_complex(sv, map);
629         }
630         else
631             return do_trans_simple(sv, map);
632     }
633 }
634
635 #ifdef DEBUGGING
636 /* make it small to exercise the logic */
637 #  define JOIN_DELIM_BUFSIZE 2
638 #else
639 #  define JOIN_DELIM_BUFSIZE 40
640 #endif
641
642 /*
643 =for apidoc_section $string
644 =for apidoc do_join
645
646 This performs a Perl L<C<join>|perlfunc/join>, placing the joined output
647 into C<sv>.
648
649 The elements to join are in SVs, stored in a C array of pointers to SVs, from
650 C<**mark> to S<C<**sp - 1>>.  Hence C<*mark> is a reference to the first SV.
651 Each SV will be coerced into a PV if not one already.
652
653 C<delim> contains the string (or coerced into a string) that is to separate
654 each of the joined elements.
655
656 If any component is in UTF-8, the result will be as well, and all non-UTF-8
657 components will be converted to UTF-8 as necessary.
658
659 Magic and tainting are handled.
660
661 =cut
662 */
663
664 void
665 Perl_do_join(pTHX_ SV *sv, SV *delim, SV **mark, SV **sp)
666 {
667     PERL_ARGS_ASSERT_DO_JOIN;
668
669     SV ** const oldmark = mark;
670     SSize_t items = sp - mark;
671     STRLEN len;
672     STRLEN delimlen;
673     const char * delimpv = SvPV_const(delim, delimlen);
674     char delim_buf[JOIN_DELIM_BUFSIZE];
675     bool delim_do_utf8 = DO_UTF8(delim);
676
677     if (items >= 2) {
678         /* Make a copy of the delim, since G or A magic may modify the delim SV.
679            Use a local buffer if possible to avoid the cost of allocation and
680            clean up.
681         */
682         if (delimlen <= JOIN_DELIM_BUFSIZE) {
683             Copy(delimpv, delim_buf, delimlen, char);
684             delimpv = delim_buf;
685         }
686         else {
687             delimpv = savepvn(delimpv, delimlen);
688             SAVEFREEPV(delimpv);
689         }
690     }
691
692     mark++;
693     len = (items > 0 ? (delimlen * (items - 1) ) : 0);
694     SvUPGRADE(sv, SVt_PV);
695     if (SvLEN(sv) < len + items) {      /* current length is way too short */
696         while (items-- > 0) {
697             if (*mark && !SvGAMAGIC(*mark) && SvOK(*mark)) {
698                 STRLEN tmplen;
699                 SvPV_const(*mark, tmplen);
700                 len += tmplen;
701             }
702             mark++;
703         }
704         SvGROW(sv, len + 1);            /* so try to pre-extend */
705
706         mark = oldmark;
707         items = sp - mark;
708         ++mark;
709     }
710
711     SvPVCLEAR(sv);
712     /* sv_setpv retains old UTF8ness [perl #24846] */
713     SvUTF8_off(sv);
714
715     if (TAINTING_get && SvMAGICAL(sv))
716         SvTAINTED_off(sv);
717
718     if (items-- > 0) {
719         if (*mark)
720             sv_catsv(sv, *mark);
721         mark++;
722     }
723
724     if (delimlen) {
725         const U32 delimflag = delim_do_utf8 ? SV_CATUTF8 : SV_CATBYTES;
726         for (; items > 0; items--,mark++) {
727             STRLEN len;
728             const char *s;
729             sv_catpvn_flags(sv, delimpv, delimlen, delimflag);
730             s = SvPV_const(*mark,len);
731             sv_catpvn_flags(sv,s,len,
732                             DO_UTF8(*mark) ? SV_CATUTF8 : SV_CATBYTES);
733         }
734     }
735     else {
736         for (; items > 0; items--,mark++)
737         {
738             STRLEN len;
739             const char *s = SvPV_const(*mark,len);
740             sv_catpvn_flags(sv,s,len,
741                             DO_UTF8(*mark) ? SV_CATUTF8 : SV_CATBYTES);
742         }
743     }
744     SvSETMAGIC(sv);
745 }
746
747 /*
748 =for apidoc_section $string
749 =for apidoc do_sprintf
750
751 This performs a Perl L<C<sprintf>|perlfunc/sprintf> placing the string output
752 into C<sv>.
753
754 The elements to format are in SVs, stored in a C array of pointers to SVs of
755 length C<len>> and beginning at C<**sarg>.  The element referenced by C<*sarg>
756 is the format.
757
758 Magic and tainting are handled.
759
760 =cut
761 */
762
763 void
764 Perl_do_sprintf(pTHX_ SV *sv, SSize_t len, SV **sarg)
765 {
766     STRLEN patlen;
767     const char * const pat = SvPV_const(*sarg, patlen);
768     bool do_taint = FALSE;
769
770     PERL_ARGS_ASSERT_DO_SPRINTF;
771     assert(len >= 1);
772
773     if (SvTAINTED(*sarg))
774         TAINT_PROPER(
775                 (PL_op && PL_op->op_type < OP_max)
776                     ? (PL_op->op_type == OP_PRTF)
777                         ? "printf"
778                         : PL_op_name[PL_op->op_type]
779                     : "(unknown)"
780         );
781     SvUTF8_off(sv);
782     if (DO_UTF8(*sarg))
783         SvUTF8_on(sv);
784     sv_vsetpvfn(sv, pat, patlen, NULL, sarg + 1, (Size_t)(len - 1), &do_taint);
785     SvSETMAGIC(sv);
786     if (do_taint)
787         SvTAINTED_on(sv);
788 }
789
790 UV
791 Perl_do_vecget(pTHX_ SV *sv, STRLEN offset, int size)
792 {
793     STRLEN srclen;
794     const I32 svpv_flags = ((PL_op->op_flags & OPf_MOD || LVRET)
795                                           ? SV_UNDEF_RETURNS_NULL : 0);
796     unsigned char *s = (unsigned char *)
797                             SvPV_flags(sv, srclen, (svpv_flags|SV_GMAGIC));
798     UV retnum = 0;
799
800     if (!s) {
801       s = (unsigned char *)"";
802     }
803
804     PERL_ARGS_ASSERT_DO_VECGET;
805
806     if (size < 1 || ! isPOWER_OF_2(size))
807         croak("Illegal number of bits in vec");
808
809     if (SvUTF8(sv)) {
810         if (Perl_sv_utf8_downgrade_flags(aTHX_ sv, TRUE, 0)) {
811             /* PVX may have changed */
812             s = (unsigned char *) SvPV_flags(sv, srclen, svpv_flags);
813         }
814         else {
815             croak("Use of strings with code points over 0xFF"
816                              " as arguments to vec is forbidden");
817         }
818     }
819
820     if (size <= 8) {
821         STRLEN bitoffs = ((offset % 8) * size) % 8;
822         STRLEN uoffset = offset / (8 / size);
823
824         if (uoffset >= srclen)
825             return 0;
826
827         retnum = (s[uoffset] >> bitoffs) & nBIT_MASK(size);
828     }
829     else {
830         int n = size / 8;            /* required number of bytes */
831         SSize_t uoffset;
832
833 #ifdef UV_IS_QUAD
834
835         if (size == 64) {
836             ck_warner(packWARN(WARN_PORTABLE),
837                       "Bit vector size > 32 non-portable");
838         }
839 #endif
840         if (offset > Size_t_MAX / n - 1) /* would overflow */
841             return 0;
842
843         uoffset = offset * n;
844
845         /* Switch on the number of bytes available, but no more than the number
846          * required */
847         switch (MIN(n, (SSize_t) srclen - uoffset)) {
848
849 #ifdef UV_IS_QUAD
850
851           case 8:
852             retnum += ((UV) s[uoffset + 7]);
853             /* FALLTHROUGH */
854           case 7:
855             retnum += ((UV) s[uoffset + 6] <<  8);  /* = size - 56 */
856             /* FALLTHROUGH */
857           case 6:
858             retnum += ((UV) s[uoffset + 5] << 16);  /* = size - 48 */
859             /* FALLTHROUGH */
860           case 5:
861             retnum += ((UV) s[uoffset + 4] << 24);  /* = size - 40 */
862 #endif
863             /* FALLTHROUGH */
864           case 4:
865             retnum += ((UV) s[uoffset + 3] << (size - 32));
866             /* FALLTHROUGH */
867           case 3:
868             retnum += ((UV) s[uoffset + 2] << (size - 24));
869             /* FALLTHROUGH */
870           case 2:
871             retnum += ((UV) s[uoffset + 1] << (size - 16));
872             /* FALLTHROUGH */
873           case 1:
874             retnum += ((UV) s[uoffset    ] << (size - 8));
875             break;
876
877           default:
878             return 0;
879         }
880     }
881
882     return retnum;
883 }
884
885 /* currently converts input to bytes if possible but doesn't sweat failures,
886  * although it does ensure that the string it clobbers is not marked as
887  * utf8-valid any more
888  */
889 void
890 Perl_do_vecset(pTHX_ SV *sv)
891 {
892     STRLEN offset, bitoffs = 0;
893     int size;
894     unsigned char *s;
895     UV lval;
896     I32 mask;
897     STRLEN targlen;
898     STRLEN len;
899     SV * const targ = LvTARG(sv);
900     char errflags = LvFLAGS(sv);
901
902     PERL_ARGS_ASSERT_DO_VECSET;
903
904     /* some out-of-range errors have been deferred if/until the LV is
905      * actually written to: f(vec($s,-1,8)) is not always fatal */
906     if (errflags) {
907         assert(!(errflags & ~(LVf_NEG_OFF|LVf_OUT_OF_RANGE)));
908         if (errflags & LVf_NEG_OFF)
909             croak("Negative offset to vec in lvalue context");
910         croak("Out of memory during vec in lvalue context");
911     }
912
913     if (!targ)
914         return;
915     s = (unsigned char*)SvPV_force_flags(targ, targlen,
916                                          SV_GMAGIC | SV_UNDEF_RETURNS_NULL);
917     if (SvUTF8(targ)) {
918         /* This is handled by the SvPOK_only below...
919         if (!Perl_sv_utf8_downgrade_flags(aTHX_ targ, TRUE, 0))
920             SvUTF8_off(targ);
921          */
922         (void) Perl_sv_utf8_downgrade_flags(aTHX_ targ, TRUE, 0);
923     }
924
925     (void)SvPOK_only(targ);
926     lval = SvUV(sv);
927     offset = LvTARGOFF(sv);
928     size = LvTARGLEN(sv);
929
930     if (size < 1 || (size & (size-1))) /* size < 1 or not a power of two */
931         croak("Illegal number of bits in vec");
932
933     if (size < 8) {
934         bitoffs = ((offset%8)*size)%8;
935         offset /= 8/size;
936     }
937     else if (size > 8) {
938         int n = size/8;
939         if (offset > Size_t_MAX / n - 1) /* would overflow */
940             croak("Out of memory during vec in lvalue context");
941         offset *= n;
942     }
943
944     len = (bitoffs + size + 7)/8;       /* required number of bytes */
945     if (targlen < offset || targlen - offset < len) {
946         STRLEN newlen = offset > Size_t_MAX - len - 1 ? /* avoid overflow */
947                                         Size_t_MAX : offset + len + 1;
948         s = (unsigned char*)SvGROW(targ, newlen);
949         (void)memzero((char *)(s + targlen), newlen - targlen);
950         SvCUR_set(targ, newlen - 1);
951     }
952
953     if (size < 8) {
954         mask = nBIT_MASK(size);
955         lval &= mask;
956         s[offset] &= ~(mask << bitoffs);
957         s[offset] |= lval << bitoffs;
958     }
959     else switch (size) {
960
961 #ifdef UV_IS_QUAD
962
963       case 64:
964         ck_warner(packWARN(WARN_PORTABLE),
965                   "Bit vector size > 32 non-portable");
966         s[offset+7] = (U8)( lval      );    /* = size - 64 */
967         s[offset+6] = (U8)( lval >>  8);    /* = size - 56 */
968         s[offset+5] = (U8)( lval >> 16);    /* = size - 48 */
969         s[offset+4] = (U8)( lval >> 24);    /* = size - 40 */
970 #endif
971         /* FALLTHROUGH */
972       case 32:
973         s[offset+3] = (U8)( lval >> (size - 32));
974         s[offset+2] = (U8)( lval >> (size - 24));
975         /* FALLTHROUGH */
976       case 16:
977         s[offset+1] = (U8)( lval >> (size - 16));
978         /* FALLTHROUGH */
979       case 8:
980         s[offset  ] = (U8)( lval >> (size - 8));
981     }
982     SvSETMAGIC(targ);
983 }
984
985 void
986 Perl_do_vop(pTHX_ I32 optype, SV *sv, SV *left, SV *right)
987 {
988     long *dl;
989     long *ll;
990     long *rl;
991     char *dc;
992     STRLEN leftlen;
993     STRLEN rightlen;
994     const char *lc;
995     const char *rc;
996     STRLEN len = 0;
997     STRLEN lensave;
998     const char *lsave;
999     const char *rsave;
1000     STRLEN needlen = 0;
1001     bool result_needs_to_be_utf8 = FALSE;
1002     bool left_utf8 = FALSE;
1003     bool right_utf8 = FALSE;
1004
1005     PERL_ARGS_ASSERT_DO_VOP;
1006
1007     if (sv != left || (optype != OP_BIT_AND && !SvOK(sv)))
1008         SvPVCLEAR(sv);        /* avoid undef warning on |= and ^= */
1009     if (sv == left) {
1010         lc = SvPV_force_nomg(left, leftlen);
1011     }
1012     else {
1013         lc = SvPV_nomg_const(left, leftlen);
1014         SvPV_force_nomg_nolen(sv);
1015     }
1016     rc = SvPV_nomg_const(right, rightlen);
1017
1018     /* This needs to come after SvPV to ensure that string overloading has
1019        fired off.  */
1020
1021     /* Create downgraded temporaries of any UTF-8 encoded operands.  As of
1022      * perl-5.32, we no longer accept above-FF code points at all */
1023     if (DO_UTF8(left)) {
1024         result_needs_to_be_utf8 = TRUE;
1025         left_utf8 = ! utf8_to_bytes_temp_pv((const U8 **) &lc, &leftlen);
1026     }
1027     if (DO_UTF8(right)) {
1028         result_needs_to_be_utf8 = TRUE;
1029         right_utf8 = ! utf8_to_bytes_temp_pv((const U8 **) &rc, &rightlen);
1030     }
1031
1032     /* We set 'len' to the length that the operation actually operates on.  The
1033      * dangling part of the longer operand doesn't actually participate in the
1034      * operation.  What happens is that we pretend that the shorter operand has
1035      * been extended to the right by enough imaginary zeros to match the length
1036      * of the longer one.  But we know in advance the result of the operation
1037      * on zeros without having to do it.  In the case of '&', the result is
1038      * zero, and the dangling portion is simply discarded.  For '|' and '^', the
1039      * result is the same as the other operand, so the dangling part is just
1040      * appended to the final result, unchanged. */
1041     if (left_utf8 || right_utf8) {
1042         croak(FATAL_ABOVE_FF_MSG, PL_op_desc[optype]);
1043     }
1044     else {  /* Neither is UTF-8 */
1045         len = MIN(leftlen, rightlen);
1046     }
1047
1048     lensave = len;
1049     lsave = lc;
1050     rsave = rc;
1051
1052     (void)SvPOK_only(sv);
1053     if (SvOK(sv) || SvTYPE(sv) > SVt_PVMG) {
1054         dc = SvPV_force_nomg_nolen(sv);
1055         if (SvLEN(sv) < len + 1) {
1056             dc = SvGROW(sv, len + 1);
1057             (void)memzero(dc + SvCUR(sv), len - SvCUR(sv) + 1);
1058         }
1059     }
1060     else {
1061         needlen = optype == OP_BIT_AND
1062                     ? len : (leftlen > rightlen ? leftlen : rightlen);
1063         Newxz(dc, needlen + 1, char);
1064         sv_usepvn_flags(sv, dc, needlen, SV_HAS_TRAILING_NUL);
1065         dc = SvPVX(sv);         /* sv_usepvn() calls Renew() */
1066     }
1067     SvCUR_set(sv, len);
1068
1069     if (len >= sizeof(long)*4 &&
1070         !(PTR2nat(dc) % sizeof(long)) &&
1071         !(PTR2nat(lc) % sizeof(long)) &&
1072         !(PTR2nat(rc) % sizeof(long)))  /* It's almost always aligned... */
1073     {
1074         const STRLEN remainder = len % (sizeof(long)*4);
1075         len /= (sizeof(long)*4);
1076
1077         dl = (long*)dc;
1078         ll = (long*)lc;
1079         rl = (long*)rc;
1080
1081         switch (optype) {
1082         case OP_BIT_AND:
1083             while (len--) {
1084                 *dl++ = *ll++ & *rl++;
1085                 *dl++ = *ll++ & *rl++;
1086                 *dl++ = *ll++ & *rl++;
1087                 *dl++ = *ll++ & *rl++;
1088             }
1089             break;
1090         case OP_BIT_XOR:
1091             while (len--) {
1092                 *dl++ = *ll++ ^ *rl++;
1093                 *dl++ = *ll++ ^ *rl++;
1094                 *dl++ = *ll++ ^ *rl++;
1095                 *dl++ = *ll++ ^ *rl++;
1096             }
1097             break;
1098         case OP_BIT_OR:
1099             while (len--) {
1100                 *dl++ = *ll++ | *rl++;
1101                 *dl++ = *ll++ | *rl++;
1102                 *dl++ = *ll++ | *rl++;
1103                 *dl++ = *ll++ | *rl++;
1104             }
1105         }
1106
1107         dc = (char*)dl;
1108         lc = (char*)ll;
1109         rc = (char*)rl;
1110
1111         len = remainder;
1112     }
1113
1114     switch (optype) {
1115     case OP_BIT_AND:
1116         while (len--)
1117             *dc++ = *lc++ & *rc++;
1118         *dc = '\0';
1119         break;
1120     case OP_BIT_XOR:
1121         while (len--)
1122             *dc++ = *lc++ ^ *rc++;
1123         goto mop_up;
1124     case OP_BIT_OR:
1125         while (len--)
1126             *dc++ = *lc++ | *rc++;
1127       mop_up:
1128         len = lensave;
1129         if (rightlen > len) {
1130             if (dc == rc)
1131                 SvCUR_set(sv, rightlen);
1132             else
1133                 sv_catpvn_nomg(sv, rsave + len, rightlen - len);
1134         }
1135         else if (leftlen > len) {
1136             if (dc == lc)
1137                 SvCUR_set(sv, leftlen);
1138             else
1139                 sv_catpvn_nomg(sv, lsave + len, leftlen - len);
1140         }
1141         *SvEND(sv) = '\0';
1142         break;
1143     }
1144
1145     if (result_needs_to_be_utf8) {
1146         sv_utf8_upgrade_nomg(sv);
1147     }
1148
1149     SvTAINT(sv);
1150 }
1151
1152
1153 /* Perl_do_kv() may be:
1154  *  * called directly as the pp function for pp_keys() and pp_values();
1155  *  * It may also be called directly when the op is OP_AVHVSWITCH, to
1156  *       implement CORE::keys(), CORE::values().
1157  *
1158  * In all cases it expects an HV on the stack and returns a list of keys,
1159  * values, or key-value pairs, depending on PL_op.
1160  */
1161
1162 PP(do_kv)
1163 {
1164     HV * const keys = MUTABLE_HV(*PL_stack_sp);
1165     const U8 gimme = GIMME_V;
1166
1167     const I32 dokeys   =     (PL_op->op_type == OP_KEYS)
1168                           || (    PL_op->op_type == OP_AVHVSWITCH
1169                               && (PL_op->op_private & OPpAVHVSWITCH_MASK)
1170                                     + OP_EACH == OP_KEYS);
1171
1172     const I32 dovalues =     (PL_op->op_type == OP_VALUES)
1173                           || (    PL_op->op_type == OP_AVHVSWITCH
1174                               && (PL_op->op_private & OPpAVHVSWITCH_MASK)
1175                                      + OP_EACH == OP_VALUES);
1176
1177     assert(   PL_op->op_type == OP_KEYS
1178            || PL_op->op_type == OP_VALUES
1179            || PL_op->op_type == OP_AVHVSWITCH);
1180
1181     assert(!(    PL_op->op_type == OP_VALUES
1182              && (PL_op->op_private & OPpMAYBE_LVSUB)));
1183
1184     (void)hv_iterinit(keys);    /* always reset iterator regardless */
1185
1186     if (gimme == G_VOID) {
1187         rpp_popfree_1();
1188         return NORMAL;
1189     }
1190
1191     if (gimme == G_SCALAR) {
1192         if (PL_op->op_flags & OPf_MOD || LVRET) {       /* lvalue */
1193             SV * const ret = newSV_type_mortal(SVt_PVLV);  /* Not TARG RT#67838 */
1194             sv_magic(ret, NULL, PERL_MAGIC_nkeys, NULL, 0);
1195             LvTYPE(ret) = 'k';
1196             LvTARG(ret) = SvREFCNT_inc_simple(keys);
1197             rpp_replace_1_1(ret);
1198         }
1199         else {
1200             IV i;
1201             dTARGET;
1202
1203             /* note that in 'scalar(keys %h)' the OP_KEYS is usually
1204              * optimised away and the action is performed directly by the
1205              * padhv or rv2hv op. We now only get here via OP_AVHVSWITCH
1206              * and \&CORE::keys
1207              */
1208             if (! SvTIED_mg((const SV *)keys, PERL_MAGIC_tied) ) {
1209                 i = HvUSEDKEYS(keys);
1210             }
1211             else {
1212                 i = 0;
1213                 while (hv_iternext(keys)) i++;
1214             }
1215             TARGi(i,1);
1216             rpp_replace_1_1(targ);
1217         }
1218         return NORMAL;
1219     }
1220
1221     /* list context only here */
1222
1223     if (UNLIKELY(PL_op->op_private & OPpMAYBE_LVSUB)) {
1224         const I32 flags = is_lvalue_sub();
1225         if (flags && !(flags & OPpENTERSUB_INARGS))
1226             /* diag_listed_as: Can't modify %s in %s */
1227             croak("Can't modify keys in list assignment");
1228     }
1229
1230     /* push all keys and/or values onto stack */
1231 #ifdef PERL_RC_STACK
1232     SSize_t sp_base = PL_stack_sp - PL_stack_base;
1233     hv_pushkv(keys, (dokeys | (dovalues << 1)));
1234     /* Now safe to free the original arg on the stack and shuffle
1235      * down one place anything pushed on top of it */
1236     SSize_t nitems = PL_stack_sp - (PL_stack_base + sp_base);
1237     SV *old_sv = PL_stack_sp[-nitems];
1238     if (nitems)
1239         Move(PL_stack_sp - nitems + 1,
1240              PL_stack_sp - nitems,    nitems, SV*);
1241     PL_stack_sp--;
1242     SvREFCNT_dec_NN(old_sv);
1243 #else
1244     rpp_popfree_1();
1245     hv_pushkv(keys, (dokeys | (dovalues << 1)));
1246 #endif
1247     return NORMAL;
1248 }
1249
1250 /*
1251  * ex: set ts=8 sts=4 sw=4 et:
1252  */