This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
op.c: White-space only
[perl5.git] / op.c
1 #line 2 "op.c"
2 /*    op.c
3  *
4  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
5  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
6  *
7  *    You may distribute under the terms of either the GNU General Public
8  *    License or the Artistic License, as specified in the README file.
9  *
10  */
11
12 /*
13  * 'You see: Mr. Drogo, he married poor Miss Primula Brandybuck.  She was
14  *  our Mr. Bilbo's first cousin on the mother's side (her mother being the
15  *  youngest of the Old Took's daughters); and Mr. Drogo was his second
16  *  cousin.  So Mr. Frodo is his first *and* second cousin, once removed
17  *  either way, as the saying is, if you follow me.'       --the Gaffer
18  *
19  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
20  */
21
22 /* This file contains the functions that create, manipulate and optimize
23  * the OP structures that hold a compiled perl program.
24  *
25  * A Perl program is compiled into a tree of OPs. Each op contains
26  * structural pointers (eg to its siblings and the next op in the
27  * execution sequence), a pointer to the function that would execute the
28  * op, plus any data specific to that op. For example, an OP_CONST op
29  * points to the pp_const() function and to an SV containing the constant
30  * value. When pp_const() is executed, its job is to push that SV onto the
31  * stack.
32  *
33  * OPs are mainly created by the newFOO() functions, which are mainly
34  * called from the parser (in perly.y) as the code is parsed. For example
35  * the Perl code $a + $b * $c would cause the equivalent of the following
36  * to be called (oversimplifying a bit):
37  *
38  *  newBINOP(OP_ADD, flags,
39  *      newSVREF($a),
40  *      newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
41  *  )
42  *
43  * Note that during the build of miniperl, a temporary copy of this file
44  * is made, called opmini.c.
45  */
46
47 /*
48 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
49
50     A bottom-up pass
51     A top-down pass
52     An execution-order pass
53
54 The bottom-up pass is represented by all the "newOP" routines and
55 the ck_ routines.  The bottom-upness is actually driven by yacc.
56 So at the point that a ck_ routine fires, we have no idea what the
57 context is, either upward in the syntax tree, or either forward or
58 backward in the execution order.  (The bottom-up parser builds that
59 part of the execution order it knows about, but if you follow the "next"
60 links around, you'll find it's actually a closed loop through the
61 top level node.)
62
63 Whenever the bottom-up parser gets to a node that supplies context to
64 its components, it invokes that portion of the top-down pass that applies
65 to that part of the subtree (and marks the top node as processed, so
66 if a node further up supplies context, it doesn't have to take the
67 plunge again).  As a particular subcase of this, as the new node is
68 built, it takes all the closed execution loops of its subcomponents
69 and links them into a new closed loop for the higher level node.  But
70 it's still not the real execution order.
71
72 The actual execution order is not known till we get a grammar reduction
73 to a top-level unit like a subroutine or file that will be called by
74 "name" rather than via a "next" pointer.  At that point, we can call
75 into peep() to do that code's portion of the 3rd pass.  It has to be
76 recursive, but it's recursive on basic blocks, not on tree nodes.
77 */
78
79 /* To implement user lexical pragmas, there needs to be a way at run time to
80    get the compile time state of %^H for that block.  Storing %^H in every
81    block (or even COP) would be very expensive, so a different approach is
82    taken.  The (running) state of %^H is serialised into a tree of HE-like
83    structs.  Stores into %^H are chained onto the current leaf as a struct
84    refcounted_he * with the key and the value.  Deletes from %^H are saved
85    with a value of PL_sv_placeholder.  The state of %^H at any point can be
86    turned back into a regular HV by walking back up the tree from that point's
87    leaf, ignoring any key you've already seen (placeholder or not), storing
88    the rest into the HV structure, then removing the placeholders. Hence
89    memory is only used to store the %^H deltas from the enclosing COP, rather
90    than the entire %^H on each COP.
91
92    To cause actions on %^H to write out the serialisation records, it has
93    magic type 'H'. This magic (itself) does nothing, but its presence causes
94    the values to gain magic type 'h', which has entries for set and clear.
95    C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
96    record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
97    saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
98    it will be correctly restored when any inner compiling scope is exited.
99 */
100
101 #include "EXTERN.h"
102 #define PERL_IN_OP_C
103 #include "perl.h"
104 #include "keywords.h"
105 #include "feature.h"
106 #include "regcomp.h"
107
108 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
109 #define CALL_RPEEP(o) PL_rpeepp(aTHX_ o)
110 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
111
112 /* See the explanatory comments above struct opslab in op.h. */
113
114 #ifdef PERL_DEBUG_READONLY_OPS
115 #  define PERL_SLAB_SIZE 128
116 #  define PERL_MAX_SLAB_SIZE 4096
117 #  include <sys/mman.h>
118 #endif
119
120 #ifndef PERL_SLAB_SIZE
121 #  define PERL_SLAB_SIZE 64
122 #endif
123 #ifndef PERL_MAX_SLAB_SIZE
124 #  define PERL_MAX_SLAB_SIZE 2048
125 #endif
126
127 /* rounds up to nearest pointer */
128 #define SIZE_TO_PSIZE(x)        (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
129 #define DIFF(o,p)               ((size_t)((I32 **)(p) - (I32**)(o)))
130
131 static OPSLAB *
132 S_new_slab(pTHX_ size_t sz)
133 {
134 #ifdef PERL_DEBUG_READONLY_OPS
135     OPSLAB *slab = (OPSLAB *) mmap(0, sz * sizeof(I32 *),
136                                    PROT_READ|PROT_WRITE,
137                                    MAP_ANON|MAP_PRIVATE, -1, 0);
138     DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
139                           (unsigned long) sz, slab));
140     if (slab == MAP_FAILED) {
141         perror("mmap failed");
142         abort();
143     }
144     slab->opslab_size = (U16)sz;
145 #else
146     OPSLAB *slab = (OPSLAB *)PerlMemShared_calloc(sz, sizeof(I32 *));
147 #endif
148     slab->opslab_first = (OPSLOT *)((I32 **)slab + sz - 1);
149     return slab;
150 }
151
152 /* requires double parens and aTHX_ */
153 #define DEBUG_S_warn(args)                                             \
154     DEBUG_S(                                                            \
155         PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
156     )
157
158 void *
159 Perl_Slab_Alloc(pTHX_ size_t sz)
160 {
161     dVAR;
162     OPSLAB *slab;
163     OPSLAB *slab2;
164     OPSLOT *slot;
165     OP *o;
166     size_t opsz, space;
167
168     /* We only allocate ops from the slab during subroutine compilation.
169        We find the slab via PL_compcv, hence that must be non-NULL. It could
170        also be pointing to a subroutine which is now fully set up (CvROOT()
171        pointing to the top of the optree for that sub), or a subroutine
172        which isn't using the slab allocator. If our sanity checks aren't met,
173        don't use a slab, but allocate the OP directly from the heap.  */
174     if (!PL_compcv || CvROOT(PL_compcv)
175      || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
176         return PerlMemShared_calloc(1, sz);
177
178 #if defined(USE_ITHREADS) && IVSIZE > U32SIZE && IVSIZE > PTRSIZE
179     /* Work around a goof with alignment on our part. For sparc32 (and
180        possibly other architectures), if built with -Duse64bitint, the IV
181        op_pmoffset in struct pmop should be 8 byte aligned, but the slab
182        allocator is only providing 4 byte alignment. The real fix is to change
183        the IV to a type the same size as a pointer, such as size_t, but we
184        can't do that without breaking the ABI, which is a no-no in a maint
185        release. So instead, simply allocate struct pmop directly, which will be
186        suitably aligned:  */
187     if (sz == sizeof(struct pmop))
188         return PerlMemShared_calloc(1, sz);
189 #endif
190
191     /* While the subroutine is under construction, the slabs are accessed via
192        CvSTART(), to avoid needing to expand PVCV by one pointer for something
193        unneeded at runtime. Once a subroutine is constructed, the slabs are
194        accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
195        allocated yet.  See the commit message for 8be227ab5eaa23f2 for more
196        details.  */
197     if (!CvSTART(PL_compcv)) {
198         CvSTART(PL_compcv) =
199             (OP *)(slab = S_new_slab(aTHX_ PERL_SLAB_SIZE));
200         CvSLABBED_on(PL_compcv);
201         slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
202     }
203     else ++(slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
204
205     opsz = SIZE_TO_PSIZE(sz);
206     sz = opsz + OPSLOT_HEADER_P;
207
208     /* The slabs maintain a free list of OPs. In particular, constant folding
209        will free up OPs, so it makes sense to re-use them where possible. A
210        freed up slot is used in preference to a new allocation.  */
211     if (slab->opslab_freed) {
212         OP **too = &slab->opslab_freed;
213         o = *too;
214         DEBUG_S_warn((aTHX_ "found free op at %p, slab %p", o, slab));
215         while (o && DIFF(OpSLOT(o), OpSLOT(o)->opslot_next) < sz) {
216             DEBUG_S_warn((aTHX_ "Alas! too small"));
217             o = *(too = &o->op_next);
218             if (o) { DEBUG_S_warn((aTHX_ "found another free op at %p", o)); }
219         }
220         if (o) {
221             *too = o->op_next;
222             Zero(o, opsz, I32 *);
223             o->op_slabbed = 1;
224             return (void *)o;
225         }
226     }
227
228 #define INIT_OPSLOT \
229             slot->opslot_slab = slab;                   \
230             slot->opslot_next = slab2->opslab_first;    \
231             slab2->opslab_first = slot;                 \
232             o = &slot->opslot_op;                       \
233             o->op_slabbed = 1
234
235     /* The partially-filled slab is next in the chain. */
236     slab2 = slab->opslab_next ? slab->opslab_next : slab;
237     if ((space = DIFF(&slab2->opslab_slots, slab2->opslab_first)) < sz) {
238         /* Remaining space is too small. */
239
240         /* If we can fit a BASEOP, add it to the free chain, so as not
241            to waste it. */
242         if (space >= SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P) {
243             slot = &slab2->opslab_slots;
244             INIT_OPSLOT;
245             o->op_type = OP_FREED;
246             o->op_next = slab->opslab_freed;
247             slab->opslab_freed = o;
248         }
249
250         /* Create a new slab.  Make this one twice as big. */
251         slot = slab2->opslab_first;
252         while (slot->opslot_next) slot = slot->opslot_next;
253         slab2 = S_new_slab(aTHX_
254                             (DIFF(slab2, slot)+1)*2 > PERL_MAX_SLAB_SIZE
255                                         ? PERL_MAX_SLAB_SIZE
256                                         : (DIFF(slab2, slot)+1)*2);
257         slab2->opslab_next = slab->opslab_next;
258         slab->opslab_next = slab2;
259     }
260     assert(DIFF(&slab2->opslab_slots, slab2->opslab_first) >= sz);
261
262     /* Create a new op slot */
263     slot = (OPSLOT *)((I32 **)slab2->opslab_first - sz);
264     assert(slot >= &slab2->opslab_slots);
265     if (DIFF(&slab2->opslab_slots, slot)
266          < SIZE_TO_PSIZE(sizeof(OP)) + OPSLOT_HEADER_P)
267         slot = &slab2->opslab_slots;
268     INIT_OPSLOT;
269     DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p", o, slab));
270     return (void *)o;
271 }
272
273 #undef INIT_OPSLOT
274
275 #ifdef PERL_DEBUG_READONLY_OPS
276 void
277 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
278 {
279     PERL_ARGS_ASSERT_SLAB_TO_RO;
280
281     if (slab->opslab_readonly) return;
282     slab->opslab_readonly = 1;
283     for (; slab; slab = slab->opslab_next) {
284         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
285                               (unsigned long) slab->opslab_size, slab));*/
286         if (mprotect(slab, slab->opslab_size * sizeof(I32 *), PROT_READ))
287             Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", slab,
288                              (unsigned long)slab->opslab_size, errno);
289     }
290 }
291
292 void
293 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
294 {
295     OPSLAB *slab2;
296
297     PERL_ARGS_ASSERT_SLAB_TO_RW;
298
299     if (!slab->opslab_readonly) return;
300     slab2 = slab;
301     for (; slab2; slab2 = slab2->opslab_next) {
302         /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
303                               (unsigned long) size, slab2));*/
304         if (mprotect((void *)slab2, slab2->opslab_size * sizeof(I32 *),
305                      PROT_READ|PROT_WRITE)) {
306             Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", slab,
307                              (unsigned long)slab2->opslab_size, errno);
308         }
309     }
310     slab->opslab_readonly = 0;
311 }
312
313 #else
314 #  define Slab_to_rw(op)    NOOP
315 #endif
316
317 /* This cannot possibly be right, but it was copied from the old slab
318    allocator, to which it was originally added, without explanation, in
319    commit 083fcd5. */
320 #ifdef NETWARE
321 #    define PerlMemShared PerlMem
322 #endif
323
324 void
325 Perl_Slab_Free(pTHX_ void *op)
326 {
327     dVAR;
328     OP * const o = (OP *)op;
329     OPSLAB *slab;
330
331     PERL_ARGS_ASSERT_SLAB_FREE;
332
333     if (!o->op_slabbed) {
334         if (!o->op_static)
335             PerlMemShared_free(op);
336         return;
337     }
338
339     slab = OpSLAB(o);
340     /* If this op is already freed, our refcount will get screwy. */
341     assert(o->op_type != OP_FREED);
342     o->op_type = OP_FREED;
343     o->op_next = slab->opslab_freed;
344     slab->opslab_freed = o;
345     DEBUG_S_warn((aTHX_ "free op at %p, recorded in slab %p", o, slab));
346     OpslabREFCNT_dec_padok(slab);
347 }
348
349 void
350 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
351 {
352     dVAR;
353     const bool havepad = !!PL_comppad;
354     PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
355     if (havepad) {
356         ENTER;
357         PAD_SAVE_SETNULLPAD();
358     }
359     opslab_free(slab);
360     if (havepad) LEAVE;
361 }
362
363 void
364 Perl_opslab_free(pTHX_ OPSLAB *slab)
365 {
366     dVAR;
367     OPSLAB *slab2;
368     PERL_ARGS_ASSERT_OPSLAB_FREE;
369     DEBUG_S_warn((aTHX_ "freeing slab %p", slab));
370     assert(slab->opslab_refcnt == 1);
371     for (; slab; slab = slab2) {
372         slab2 = slab->opslab_next;
373 #ifdef DEBUGGING
374         slab->opslab_refcnt = ~(size_t)0;
375 #endif
376 #ifdef PERL_DEBUG_READONLY_OPS
377         DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
378                                                slab));
379         if (munmap(slab, slab->opslab_size * sizeof(I32 *))) {
380             perror("munmap failed");
381             abort();
382         }
383 #else
384         PerlMemShared_free(slab);
385 #endif
386     }
387 }
388
389 void
390 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
391 {
392     OPSLAB *slab2;
393     OPSLOT *slot;
394 #ifdef DEBUGGING
395     size_t savestack_count = 0;
396 #endif
397     PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
398     slab2 = slab;
399     do {
400         for (slot = slab2->opslab_first;
401              slot->opslot_next;
402              slot = slot->opslot_next) {
403             if (slot->opslot_op.op_type != OP_FREED
404              && !(slot->opslot_op.op_savefree
405 #ifdef DEBUGGING
406                   && ++savestack_count
407 #endif
408                  )
409             ) {
410                 assert(slot->opslot_op.op_slabbed);
411                 op_free(&slot->opslot_op);
412                 if (slab->opslab_refcnt == 1) goto free;
413             }
414         }
415     } while ((slab2 = slab2->opslab_next));
416     /* > 1 because the CV still holds a reference count. */
417     if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
418 #ifdef DEBUGGING
419         assert(savestack_count == slab->opslab_refcnt-1);
420 #endif
421         /* Remove the CV’s reference count. */
422         slab->opslab_refcnt--;
423         return;
424     }
425    free:
426     opslab_free(slab);
427 }
428
429 #ifdef PERL_DEBUG_READONLY_OPS
430 OP *
431 Perl_op_refcnt_inc(pTHX_ OP *o)
432 {
433     if(o) {
434         OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
435         if (slab && slab->opslab_readonly) {
436             Slab_to_rw(slab);
437             ++o->op_targ;
438             Slab_to_ro(slab);
439         } else {
440             ++o->op_targ;
441         }
442     }
443     return o;
444
445 }
446
447 PADOFFSET
448 Perl_op_refcnt_dec(pTHX_ OP *o)
449 {
450     PADOFFSET result;
451     OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
452
453     PERL_ARGS_ASSERT_OP_REFCNT_DEC;
454
455     if (slab && slab->opslab_readonly) {
456         Slab_to_rw(slab);
457         result = --o->op_targ;
458         Slab_to_ro(slab);
459     } else {
460         result = --o->op_targ;
461     }
462     return result;
463 }
464 #endif
465 /*
466  * In the following definition, the ", (OP*)0" is just to make the compiler
467  * think the expression is of the right type: croak actually does a Siglongjmp.
468  */
469 #define CHECKOP(type,o) \
470     ((PL_op_mask && PL_op_mask[type])                           \
471      ? ( op_free((OP*)o),                                       \
472          Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]),  \
473          (OP*)0 )                                               \
474      : PL_check[type](aTHX_ (OP*)o))
475
476 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
477
478 #define CHANGE_TYPE(o,type) \
479     STMT_START {                                \
480         o->op_type = (OPCODE)type;              \
481         o->op_ppaddr = PL_ppaddr[type];         \
482     } STMT_END
483
484 STATIC SV*
485 S_gv_ename(pTHX_ GV *gv)
486 {
487     SV* const tmpsv = sv_newmortal();
488
489     PERL_ARGS_ASSERT_GV_ENAME;
490
491     gv_efullname3(tmpsv, gv, NULL);
492     return tmpsv;
493 }
494
495 STATIC OP *
496 S_no_fh_allowed(pTHX_ OP *o)
497 {
498     PERL_ARGS_ASSERT_NO_FH_ALLOWED;
499
500     yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
501                  OP_DESC(o)));
502     return o;
503 }
504
505 STATIC OP *
506 S_too_few_arguments_sv(pTHX_ OP *o, SV *namesv, U32 flags)
507 {
508     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_SV;
509     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %"SVf, namesv),
510                                     SvUTF8(namesv) | flags);
511     return o;
512 }
513
514 STATIC OP *
515 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
516 {
517     PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
518     yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
519     return o;
520 }
521  
522 STATIC OP *
523 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
524 {
525     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
526
527     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
528     return o;
529 }
530
531 STATIC OP *
532 S_too_many_arguments_sv(pTHX_ OP *o, SV *namesv, U32 flags)
533 {
534     PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_SV;
535
536     yyerror_pv(Perl_form(aTHX_ "Too many arguments for %"SVf, SVfARG(namesv)),
537                 SvUTF8(namesv) | flags);
538     return o;
539 }
540
541 STATIC void
542 S_bad_type_pv(pTHX_ I32 n, const char *t, const char *name, U32 flags, const OP *kid)
543 {
544     PERL_ARGS_ASSERT_BAD_TYPE_PV;
545
546     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
547                  (int)n, name, t, OP_DESC(kid)), flags);
548 }
549
550 STATIC void
551 S_bad_type_gv(pTHX_ I32 n, const char *t, GV *gv, U32 flags, const OP *kid)
552 {
553     SV * const namesv = gv_ename(gv);
554     PERL_ARGS_ASSERT_BAD_TYPE_GV;
555  
556     yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %"SVf" must be %s (not %s)",
557                  (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv) | flags);
558 }
559
560 STATIC void
561 S_no_bareword_allowed(pTHX_ OP *o)
562 {
563     PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
564
565     if (PL_madskills)
566         return;         /* various ok barewords are hidden in extra OP_NULL */
567     qerror(Perl_mess(aTHX_
568                      "Bareword \"%"SVf"\" not allowed while \"strict subs\" in use",
569                      SVfARG(cSVOPo_sv)));
570     o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
571 }
572
573 /* "register" allocation */
574
575 PADOFFSET
576 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
577 {
578     dVAR;
579     PADOFFSET off;
580     const bool is_our = (PL_parser->in_my == KEY_our);
581
582     PERL_ARGS_ASSERT_ALLOCMY;
583
584     if (flags & ~SVf_UTF8)
585         Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
586                    (UV)flags);
587
588     /* Until we're using the length for real, cross check that we're being
589        told the truth.  */
590     assert(strlen(name) == len);
591
592     /* complain about "my $<special_var>" etc etc */
593     if (len &&
594         !(is_our ||
595           isALPHA(name[1]) ||
596           ((flags & SVf_UTF8) && isIDFIRST_utf8((U8 *)name+1)) ||
597           (name[1] == '_' && (*name == '$' || len > 2))))
598     {
599         /* name[2] is true if strlen(name) > 2  */
600         if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
601          && (!isPRINT(name[1]) || strchr("\t\n\r\f", name[1]))) {
602             yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in \"%s\"",
603                               name[0], toCTRL(name[1]), (int)(len - 2), name + 2,
604                               PL_parser->in_my == KEY_state ? "state" : "my"));
605         } else {
606             yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in \"%s\"", (int) len, name,
607                               PL_parser->in_my == KEY_state ? "state" : "my"), flags & SVf_UTF8);
608         }
609     }
610     else if (len == 2 && name[1] == '_' && !is_our)
611         /* diag_listed_as: Use of my $_ is experimental */
612         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__LEXICAL_TOPIC),
613                               "Use of %s $_ is experimental",
614                                PL_parser->in_my == KEY_state
615                                  ? "state"
616                                  : "my");
617
618     /* allocate a spare slot and store the name in that slot */
619
620     off = pad_add_name_pvn(name, len,
621                        (is_our ? padadd_OUR :
622                         PL_parser->in_my == KEY_state ? padadd_STATE : 0)
623                             | ( flags & SVf_UTF8 ? SVf_UTF8 : 0 ),
624                     PL_parser->in_my_stash,
625                     (is_our
626                         /* $_ is always in main::, even with our */
627                         ? (PL_curstash && !strEQ(name,"$_") ? PL_curstash : PL_defstash)
628                         : NULL
629                     )
630     );
631     /* anon sub prototypes contains state vars should always be cloned,
632      * otherwise the state var would be shared between anon subs */
633
634     if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
635         CvCLONE_on(PL_compcv);
636
637     return off;
638 }
639
640 /*
641 =for apidoc alloccopstash
642
643 Available only under threaded builds, this function allocates an entry in
644 C<PL_stashpad> for the stash passed to it.
645
646 =cut
647 */
648
649 #ifdef USE_ITHREADS
650 PADOFFSET
651 Perl_alloccopstash(pTHX_ HV *hv)
652 {
653     PADOFFSET off = 0, o = 1;
654     bool found_slot = FALSE;
655
656     PERL_ARGS_ASSERT_ALLOCCOPSTASH;
657
658     if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
659
660     for (; o < PL_stashpadmax; ++o) {
661         if (PL_stashpad[o] == hv) return PL_stashpadix = o;
662         if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
663             found_slot = TRUE, off = o;
664     }
665     if (!found_slot) {
666         Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
667         Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
668         off = PL_stashpadmax;
669         PL_stashpadmax += 10;
670     }
671
672     PL_stashpad[PL_stashpadix = off] = hv;
673     return off;
674 }
675 #endif
676
677 /* free the body of an op without examining its contents.
678  * Always use this rather than FreeOp directly */
679
680 static void
681 S_op_destroy(pTHX_ OP *o)
682 {
683     FreeOp(o);
684 }
685
686 /* Destructor */
687
688 void
689 Perl_op_free(pTHX_ OP *o)
690 {
691     dVAR;
692     OPCODE type;
693
694     /* Though ops may be freed twice, freeing the op after its slab is a
695        big no-no. */
696     assert(!o || !o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0); 
697     /* During the forced freeing of ops after compilation failure, kidops
698        may be freed before their parents. */
699     if (!o || o->op_type == OP_FREED)
700         return;
701
702     type = o->op_type;
703     if (o->op_private & OPpREFCOUNTED) {
704         switch (type) {
705         case OP_LEAVESUB:
706         case OP_LEAVESUBLV:
707         case OP_LEAVEEVAL:
708         case OP_LEAVE:
709         case OP_SCOPE:
710         case OP_LEAVEWRITE:
711             {
712             PADOFFSET refcnt;
713             OP_REFCNT_LOCK;
714             refcnt = OpREFCNT_dec(o);
715             OP_REFCNT_UNLOCK;
716             if (refcnt) {
717                 /* Need to find and remove any pattern match ops from the list
718                    we maintain for reset().  */
719                 find_and_forget_pmops(o);
720                 return;
721             }
722             }
723             break;
724         default:
725             break;
726         }
727     }
728
729     /* Call the op_free hook if it has been set. Do it now so that it's called
730      * at the right time for refcounted ops, but still before all of the kids
731      * are freed. */
732     CALL_OPFREEHOOK(o);
733
734     if (o->op_flags & OPf_KIDS) {
735         OP *kid, *nextkid;
736         for (kid = cUNOPo->op_first; kid; kid = nextkid) {
737             nextkid = kid->op_sibling; /* Get before next freeing kid */
738             op_free(kid);
739         }
740     }
741     if (type == OP_NULL)
742         type = (OPCODE)o->op_targ;
743
744     if (o->op_slabbed)
745         Slab_to_rw(OpSLAB(o));
746
747     /* COP* is not cleared by op_clear() so that we may track line
748      * numbers etc even after null() */
749     if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
750         cop_free((COP*)o);
751     }
752
753     op_clear(o);
754     FreeOp(o);
755 #ifdef DEBUG_LEAKING_SCALARS
756     if (PL_op == o)
757         PL_op = NULL;
758 #endif
759 }
760
761 void
762 Perl_op_clear(pTHX_ OP *o)
763 {
764
765     dVAR;
766
767     PERL_ARGS_ASSERT_OP_CLEAR;
768
769 #ifdef PERL_MAD
770     mad_free(o->op_madprop);
771     o->op_madprop = 0;
772 #endif    
773
774  retry:
775     switch (o->op_type) {
776     case OP_NULL:       /* Was holding old type, if any. */
777         if (PL_madskills && o->op_targ != OP_NULL) {
778             o->op_type = (Optype)o->op_targ;
779             o->op_targ = 0;
780             goto retry;
781         }
782     case OP_ENTERTRY:
783     case OP_ENTEREVAL:  /* Was holding hints. */
784         o->op_targ = 0;
785         break;
786     default:
787         if (!(o->op_flags & OPf_REF)
788             || (PL_check[o->op_type] != Perl_ck_ftst))
789             break;
790         /* FALL THROUGH */
791     case OP_GVSV:
792     case OP_GV:
793     case OP_AELEMFAST:
794         {
795             GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV)
796 #ifdef USE_ITHREADS
797                         && PL_curpad
798 #endif
799                         ? cGVOPo_gv : NULL;
800             /* It's possible during global destruction that the GV is freed
801                before the optree. Whilst the SvREFCNT_inc is happy to bump from
802                0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
803                will trigger an assertion failure, because the entry to sv_clear
804                checks that the scalar is not already freed.  A check of for
805                !SvIS_FREED(gv) turns out to be invalid, because during global
806                destruction the reference count can be forced down to zero
807                (with SVf_BREAK set).  In which case raising to 1 and then
808                dropping to 0 triggers cleanup before it should happen.  I
809                *think* that this might actually be a general, systematic,
810                weakness of the whole idea of SVf_BREAK, in that code *is*
811                allowed to raise and lower references during global destruction,
812                so any *valid* code that happens to do this during global
813                destruction might well trigger premature cleanup.  */
814             bool still_valid = gv && SvREFCNT(gv);
815
816             if (still_valid)
817                 SvREFCNT_inc_simple_void(gv);
818 #ifdef USE_ITHREADS
819             if (cPADOPo->op_padix > 0) {
820                 /* No GvIN_PAD_off(cGVOPo_gv) here, because other references
821                  * may still exist on the pad */
822                 pad_swipe(cPADOPo->op_padix, TRUE);
823                 cPADOPo->op_padix = 0;
824             }
825 #else
826             SvREFCNT_dec(cSVOPo->op_sv);
827             cSVOPo->op_sv = NULL;
828 #endif
829             if (still_valid) {
830                 int try_downgrade = SvREFCNT(gv) == 2;
831                 SvREFCNT_dec_NN(gv);
832                 if (try_downgrade)
833                     gv_try_downgrade(gv);
834             }
835         }
836         break;
837     case OP_METHOD_NAMED:
838     case OP_CONST:
839     case OP_HINTSEVAL:
840         SvREFCNT_dec(cSVOPo->op_sv);
841         cSVOPo->op_sv = NULL;
842 #ifdef USE_ITHREADS
843         /** Bug #15654
844           Even if op_clear does a pad_free for the target of the op,
845           pad_free doesn't actually remove the sv that exists in the pad;
846           instead it lives on. This results in that it could be reused as 
847           a target later on when the pad was reallocated.
848         **/
849         if(o->op_targ) {
850           pad_swipe(o->op_targ,1);
851           o->op_targ = 0;
852         }
853 #endif
854         break;
855     case OP_DUMP:
856     case OP_GOTO:
857     case OP_NEXT:
858     case OP_LAST:
859     case OP_REDO:
860         if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
861             break;
862         /* FALL THROUGH */
863     case OP_TRANS:
864     case OP_TRANSR:
865         if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
866             assert(o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
867 #ifdef USE_ITHREADS
868             if (cPADOPo->op_padix > 0) {
869                 pad_swipe(cPADOPo->op_padix, TRUE);
870                 cPADOPo->op_padix = 0;
871             }
872 #else
873             SvREFCNT_dec(cSVOPo->op_sv);
874             cSVOPo->op_sv = NULL;
875 #endif
876         }
877         else {
878             PerlMemShared_free(cPVOPo->op_pv);
879             cPVOPo->op_pv = NULL;
880         }
881         break;
882     case OP_SUBST:
883         op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
884         goto clear_pmop;
885     case OP_PUSHRE:
886 #ifdef USE_ITHREADS
887         if (cPMOPo->op_pmreplrootu.op_pmtargetoff) {
888             /* No GvIN_PAD_off here, because other references may still
889              * exist on the pad */
890             pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
891         }
892 #else
893         SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
894 #endif
895         /* FALL THROUGH */
896     case OP_MATCH:
897     case OP_QR:
898 clear_pmop:
899         if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
900             op_free(cPMOPo->op_code_list);
901         cPMOPo->op_code_list = NULL;
902         forget_pmop(cPMOPo);
903         cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
904         /* we use the same protection as the "SAFE" version of the PM_ macros
905          * here since sv_clean_all might release some PMOPs
906          * after PL_regex_padav has been cleared
907          * and the clearing of PL_regex_padav needs to
908          * happen before sv_clean_all
909          */
910 #ifdef USE_ITHREADS
911         if(PL_regex_pad) {        /* We could be in destruction */
912             const IV offset = (cPMOPo)->op_pmoffset;
913             ReREFCNT_dec(PM_GETRE(cPMOPo));
914             PL_regex_pad[offset] = &PL_sv_undef;
915             sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
916                            sizeof(offset));
917         }
918 #else
919         ReREFCNT_dec(PM_GETRE(cPMOPo));
920         PM_SETRE(cPMOPo, NULL);
921 #endif
922
923         break;
924     }
925
926     if (o->op_targ > 0) {
927         pad_free(o->op_targ);
928         o->op_targ = 0;
929     }
930 }
931
932 STATIC void
933 S_cop_free(pTHX_ COP* cop)
934 {
935     PERL_ARGS_ASSERT_COP_FREE;
936
937     CopFILE_free(cop);
938     if (! specialWARN(cop->cop_warnings))
939         PerlMemShared_free(cop->cop_warnings);
940     cophh_free(CopHINTHASH_get(cop));
941 }
942
943 STATIC void
944 S_forget_pmop(pTHX_ PMOP *const o
945               )
946 {
947     HV * const pmstash = PmopSTASH(o);
948
949     PERL_ARGS_ASSERT_FORGET_PMOP;
950
951     if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
952         MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
953         if (mg) {
954             PMOP **const array = (PMOP**) mg->mg_ptr;
955             U32 count = mg->mg_len / sizeof(PMOP**);
956             U32 i = count;
957
958             while (i--) {
959                 if (array[i] == o) {
960                     /* Found it. Move the entry at the end to overwrite it.  */
961                     array[i] = array[--count];
962                     mg->mg_len = count * sizeof(PMOP**);
963                     /* Could realloc smaller at this point always, but probably
964                        not worth it. Probably worth free()ing if we're the
965                        last.  */
966                     if(!count) {
967                         Safefree(mg->mg_ptr);
968                         mg->mg_ptr = NULL;
969                     }
970                     break;
971                 }
972             }
973         }
974     }
975     if (PL_curpm == o) 
976         PL_curpm = NULL;
977 }
978
979 STATIC void
980 S_find_and_forget_pmops(pTHX_ OP *o)
981 {
982     PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
983
984     if (o->op_flags & OPf_KIDS) {
985         OP *kid = cUNOPo->op_first;
986         while (kid) {
987             switch (kid->op_type) {
988             case OP_SUBST:
989             case OP_PUSHRE:
990             case OP_MATCH:
991             case OP_QR:
992                 forget_pmop((PMOP*)kid);
993             }
994             find_and_forget_pmops(kid);
995             kid = kid->op_sibling;
996         }
997     }
998 }
999
1000 void
1001 Perl_op_null(pTHX_ OP *o)
1002 {
1003     dVAR;
1004
1005     PERL_ARGS_ASSERT_OP_NULL;
1006
1007     if (o->op_type == OP_NULL)
1008         return;
1009     if (!PL_madskills)
1010         op_clear(o);
1011     o->op_targ = o->op_type;
1012     o->op_type = OP_NULL;
1013     o->op_ppaddr = PL_ppaddr[OP_NULL];
1014 }
1015
1016 void
1017 Perl_op_refcnt_lock(pTHX)
1018 {
1019     dVAR;
1020     PERL_UNUSED_CONTEXT;
1021     OP_REFCNT_LOCK;
1022 }
1023
1024 void
1025 Perl_op_refcnt_unlock(pTHX)
1026 {
1027     dVAR;
1028     PERL_UNUSED_CONTEXT;
1029     OP_REFCNT_UNLOCK;
1030 }
1031
1032 /* Contextualizers */
1033
1034 /*
1035 =for apidoc Am|OP *|op_contextualize|OP *o|I32 context
1036
1037 Applies a syntactic context to an op tree representing an expression.
1038 I<o> is the op tree, and I<context> must be C<G_SCALAR>, C<G_ARRAY>,
1039 or C<G_VOID> to specify the context to apply.  The modified op tree
1040 is returned.
1041
1042 =cut
1043 */
1044
1045 OP *
1046 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1047 {
1048     PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1049     switch (context) {
1050         case G_SCALAR: return scalar(o);
1051         case G_ARRAY:  return list(o);
1052         case G_VOID:   return scalarvoid(o);
1053         default:
1054             Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1055                        (long) context);
1056             return o;
1057     }
1058 }
1059
1060 /*
1061 =head1 Optree Manipulation Functions
1062
1063 =for apidoc Am|OP*|op_linklist|OP *o
1064 This function is the implementation of the L</LINKLIST> macro. It should
1065 not be called directly.
1066
1067 =cut
1068 */
1069
1070 OP *
1071 Perl_op_linklist(pTHX_ OP *o)
1072 {
1073     OP *first;
1074
1075     PERL_ARGS_ASSERT_OP_LINKLIST;
1076
1077     if (o->op_next)
1078         return o->op_next;
1079
1080     /* establish postfix order */
1081     first = cUNOPo->op_first;
1082     if (first) {
1083         OP *kid;
1084         o->op_next = LINKLIST(first);
1085         kid = first;
1086         for (;;) {
1087             if (kid->op_sibling) {
1088                 kid->op_next = LINKLIST(kid->op_sibling);
1089                 kid = kid->op_sibling;
1090             } else {
1091                 kid->op_next = o;
1092                 break;
1093             }
1094         }
1095     }
1096     else
1097         o->op_next = o;
1098
1099     return o->op_next;
1100 }
1101
1102 static OP *
1103 S_scalarkids(pTHX_ OP *o)
1104 {
1105     if (o && o->op_flags & OPf_KIDS) {
1106         OP *kid;
1107         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1108             scalar(kid);
1109     }
1110     return o;
1111 }
1112
1113 STATIC OP *
1114 S_scalarboolean(pTHX_ OP *o)
1115 {
1116     dVAR;
1117
1118     PERL_ARGS_ASSERT_SCALARBOOLEAN;
1119
1120     if (o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST
1121      && !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) {
1122         if (ckWARN(WARN_SYNTAX)) {
1123             const line_t oldline = CopLINE(PL_curcop);
1124
1125             if (PL_parser && PL_parser->copline != NOLINE) {
1126                 /* This ensures that warnings are reported at the first line
1127                    of the conditional, not the last.  */
1128                 CopLINE_set(PL_curcop, PL_parser->copline);
1129             }
1130             Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1131             CopLINE_set(PL_curcop, oldline);
1132         }
1133     }
1134     return scalar(o);
1135 }
1136
1137 OP *
1138 Perl_scalar(pTHX_ OP *o)
1139 {
1140     dVAR;
1141     OP *kid;
1142
1143     /* assumes no premature commitment */
1144     if (!o || (PL_parser && PL_parser->error_count)
1145          || (o->op_flags & OPf_WANT)
1146          || o->op_type == OP_RETURN)
1147     {
1148         return o;
1149     }
1150
1151     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1152
1153     switch (o->op_type) {
1154     case OP_REPEAT:
1155         scalar(cBINOPo->op_first);
1156         break;
1157     case OP_OR:
1158     case OP_AND:
1159     case OP_COND_EXPR:
1160         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1161             scalar(kid);
1162         break;
1163         /* FALL THROUGH */
1164     case OP_SPLIT:
1165     case OP_MATCH:
1166     case OP_QR:
1167     case OP_SUBST:
1168     case OP_NULL:
1169     default:
1170         if (o->op_flags & OPf_KIDS) {
1171             for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1172                 scalar(kid);
1173         }
1174         break;
1175     case OP_LEAVE:
1176     case OP_LEAVETRY:
1177         kid = cLISTOPo->op_first;
1178         scalar(kid);
1179         kid = kid->op_sibling;
1180     do_kids:
1181         while (kid) {
1182             OP *sib = kid->op_sibling;
1183             if (sib && kid->op_type != OP_LEAVEWHEN)
1184                 scalarvoid(kid);
1185             else
1186                 scalar(kid);
1187             kid = sib;
1188         }
1189         PL_curcop = &PL_compiling;
1190         break;
1191     case OP_SCOPE:
1192     case OP_LINESEQ:
1193     case OP_LIST:
1194         kid = cLISTOPo->op_first;
1195         goto do_kids;
1196     case OP_SORT:
1197         Perl_ck_warner(aTHX_ packWARN(WARN_VOID), "Useless use of sort in scalar context");
1198         break;
1199     }
1200     return o;
1201 }
1202
1203 OP *
1204 Perl_scalarvoid(pTHX_ OP *o)
1205 {
1206     dVAR;
1207     OP *kid;
1208     SV *useless_sv = NULL;
1209     const char* useless = NULL;
1210     SV* sv;
1211     U8 want;
1212
1213     PERL_ARGS_ASSERT_SCALARVOID;
1214
1215     /* trailing mad null ops don't count as "there" for void processing */
1216     if (PL_madskills &&
1217         o->op_type != OP_NULL &&
1218         o->op_sibling &&
1219         o->op_sibling->op_type == OP_NULL)
1220     {
1221         OP *sib;
1222         for (sib = o->op_sibling;
1223                 sib && sib->op_type == OP_NULL;
1224                 sib = sib->op_sibling) ;
1225         
1226         if (!sib)
1227             return o;
1228     }
1229
1230     if (o->op_type == OP_NEXTSTATE
1231         || o->op_type == OP_DBSTATE
1232         || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
1233                                       || o->op_targ == OP_DBSTATE)))
1234         PL_curcop = (COP*)o;            /* for warning below */
1235
1236     /* assumes no premature commitment */
1237     want = o->op_flags & OPf_WANT;
1238     if ((want && want != OPf_WANT_SCALAR)
1239          || (PL_parser && PL_parser->error_count)
1240          || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
1241     {
1242         return o;
1243     }
1244
1245     if ((o->op_private & OPpTARGET_MY)
1246         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1247     {
1248         return scalar(o);                       /* As if inside SASSIGN */
1249     }
1250
1251     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
1252
1253     switch (o->op_type) {
1254     default:
1255         if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
1256             break;
1257         /* FALL THROUGH */
1258     case OP_REPEAT:
1259         if (o->op_flags & OPf_STACKED)
1260             break;
1261         goto func_ops;
1262     case OP_SUBSTR:
1263         if (o->op_private == 4)
1264             break;
1265         /* FALL THROUGH */
1266     case OP_GVSV:
1267     case OP_WANTARRAY:
1268     case OP_GV:
1269     case OP_SMARTMATCH:
1270     case OP_PADSV:
1271     case OP_PADAV:
1272     case OP_PADHV:
1273     case OP_PADANY:
1274     case OP_AV2ARYLEN:
1275     case OP_REF:
1276     case OP_REFGEN:
1277     case OP_SREFGEN:
1278     case OP_DEFINED:
1279     case OP_HEX:
1280     case OP_OCT:
1281     case OP_LENGTH:
1282     case OP_VEC:
1283     case OP_INDEX:
1284     case OP_RINDEX:
1285     case OP_SPRINTF:
1286     case OP_AELEM:
1287     case OP_AELEMFAST:
1288     case OP_AELEMFAST_LEX:
1289     case OP_ASLICE:
1290     case OP_HELEM:
1291     case OP_HSLICE:
1292     case OP_UNPACK:
1293     case OP_PACK:
1294     case OP_JOIN:
1295     case OP_LSLICE:
1296     case OP_ANONLIST:
1297     case OP_ANONHASH:
1298     case OP_SORT:
1299     case OP_REVERSE:
1300     case OP_RANGE:
1301     case OP_FLIP:
1302     case OP_FLOP:
1303     case OP_CALLER:
1304     case OP_FILENO:
1305     case OP_EOF:
1306     case OP_TELL:
1307     case OP_GETSOCKNAME:
1308     case OP_GETPEERNAME:
1309     case OP_READLINK:
1310     case OP_TELLDIR:
1311     case OP_GETPPID:
1312     case OP_GETPGRP:
1313     case OP_GETPRIORITY:
1314     case OP_TIME:
1315     case OP_TMS:
1316     case OP_LOCALTIME:
1317     case OP_GMTIME:
1318     case OP_GHBYNAME:
1319     case OP_GHBYADDR:
1320     case OP_GHOSTENT:
1321     case OP_GNBYNAME:
1322     case OP_GNBYADDR:
1323     case OP_GNETENT:
1324     case OP_GPBYNAME:
1325     case OP_GPBYNUMBER:
1326     case OP_GPROTOENT:
1327     case OP_GSBYNAME:
1328     case OP_GSBYPORT:
1329     case OP_GSERVENT:
1330     case OP_GPWNAM:
1331     case OP_GPWUID:
1332     case OP_GGRNAM:
1333     case OP_GGRGID:
1334     case OP_GETLOGIN:
1335     case OP_PROTOTYPE:
1336     case OP_RUNCV:
1337       func_ops:
1338         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
1339             /* Otherwise it's "Useless use of grep iterator" */
1340             useless = OP_DESC(o);
1341         break;
1342
1343     case OP_SPLIT:
1344         kid = cLISTOPo->op_first;
1345         if (kid && kid->op_type == OP_PUSHRE
1346 #ifdef USE_ITHREADS
1347                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetoff)
1348 #else
1349                 && !((PMOP*)kid)->op_pmreplrootu.op_pmtargetgv)
1350 #endif
1351             useless = OP_DESC(o);
1352         break;
1353
1354     case OP_NOT:
1355        kid = cUNOPo->op_first;
1356        if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
1357            kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
1358                 goto func_ops;
1359        }
1360        useless = "negative pattern binding (!~)";
1361        break;
1362
1363     case OP_SUBST:
1364         if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
1365             useless = "non-destructive substitution (s///r)";
1366         break;
1367
1368     case OP_TRANSR:
1369         useless = "non-destructive transliteration (tr///r)";
1370         break;
1371
1372     case OP_RV2GV:
1373     case OP_RV2SV:
1374     case OP_RV2AV:
1375     case OP_RV2HV:
1376         if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
1377                 (!o->op_sibling || o->op_sibling->op_type != OP_READLINE))
1378             useless = "a variable";
1379         break;
1380
1381     case OP_CONST:
1382         sv = cSVOPo_sv;
1383         if (cSVOPo->op_private & OPpCONST_STRICT)
1384             no_bareword_allowed(o);
1385         else {
1386             if (ckWARN(WARN_VOID)) {
1387                 /* don't warn on optimised away booleans, eg 
1388                  * use constant Foo, 5; Foo || print; */
1389                 if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
1390                     useless = NULL;
1391                 /* the constants 0 and 1 are permitted as they are
1392                    conventionally used as dummies in constructs like
1393                         1 while some_condition_with_side_effects;  */
1394                 else if (SvNIOK(sv) && (SvNV(sv) == 0.0 || SvNV(sv) == 1.0))
1395                     useless = NULL;
1396                 else if (SvPOK(sv)) {
1397                     SV * const dsv = newSVpvs("");
1398                     useless_sv
1399                         = Perl_newSVpvf(aTHX_
1400                                         "a constant (%s)",
1401                                         pv_pretty(dsv, SvPVX_const(sv),
1402                                                   SvCUR(sv), 32, NULL, NULL,
1403                                                   PERL_PV_PRETTY_DUMP
1404                                                   | PERL_PV_ESCAPE_NOCLEAR
1405                                                   | PERL_PV_ESCAPE_UNI_DETECT));
1406                     SvREFCNT_dec_NN(dsv);
1407                 }
1408                 else if (SvOK(sv)) {
1409                     useless_sv = Perl_newSVpvf(aTHX_ "a constant (%"SVf")", sv);
1410                 }
1411                 else
1412                     useless = "a constant (undef)";
1413             }
1414         }
1415         op_null(o);             /* don't execute or even remember it */
1416         break;
1417
1418     case OP_POSTINC:
1419         o->op_type = OP_PREINC;         /* pre-increment is faster */
1420         o->op_ppaddr = PL_ppaddr[OP_PREINC];
1421         break;
1422
1423     case OP_POSTDEC:
1424         o->op_type = OP_PREDEC;         /* pre-decrement is faster */
1425         o->op_ppaddr = PL_ppaddr[OP_PREDEC];
1426         break;
1427
1428     case OP_I_POSTINC:
1429         o->op_type = OP_I_PREINC;       /* pre-increment is faster */
1430         o->op_ppaddr = PL_ppaddr[OP_I_PREINC];
1431         break;
1432
1433     case OP_I_POSTDEC:
1434         o->op_type = OP_I_PREDEC;       /* pre-decrement is faster */
1435         o->op_ppaddr = PL_ppaddr[OP_I_PREDEC];
1436         break;
1437
1438     case OP_SASSIGN: {
1439         OP *rv2gv;
1440         UNOP *refgen, *rv2cv;
1441         LISTOP *exlist;
1442
1443         if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
1444             break;
1445
1446         rv2gv = ((BINOP *)o)->op_last;
1447         if (!rv2gv || rv2gv->op_type != OP_RV2GV)
1448             break;
1449
1450         refgen = (UNOP *)((BINOP *)o)->op_first;
1451
1452         if (!refgen || refgen->op_type != OP_REFGEN)
1453             break;
1454
1455         exlist = (LISTOP *)refgen->op_first;
1456         if (!exlist || exlist->op_type != OP_NULL
1457             || exlist->op_targ != OP_LIST)
1458             break;
1459
1460         if (exlist->op_first->op_type != OP_PUSHMARK)
1461             break;
1462
1463         rv2cv = (UNOP*)exlist->op_last;
1464
1465         if (rv2cv->op_type != OP_RV2CV)
1466             break;
1467
1468         assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
1469         assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
1470         assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
1471
1472         o->op_private |= OPpASSIGN_CV_TO_GV;
1473         rv2gv->op_private |= OPpDONT_INIT_GV;
1474         rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
1475
1476         break;
1477     }
1478
1479     case OP_AASSIGN: {
1480         inplace_aassign(o);
1481         break;
1482     }
1483
1484     case OP_OR:
1485     case OP_AND:
1486         kid = cLOGOPo->op_first;
1487         if (kid->op_type == OP_NOT
1488             && (kid->op_flags & OPf_KIDS)
1489             && !PL_madskills) {
1490             if (o->op_type == OP_AND) {
1491                 o->op_type = OP_OR;
1492                 o->op_ppaddr = PL_ppaddr[OP_OR];
1493             } else {
1494                 o->op_type = OP_AND;
1495                 o->op_ppaddr = PL_ppaddr[OP_AND];
1496             }
1497             op_null(kid);
1498         }
1499
1500     case OP_DOR:
1501     case OP_COND_EXPR:
1502     case OP_ENTERGIVEN:
1503     case OP_ENTERWHEN:
1504         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1505             scalarvoid(kid);
1506         break;
1507
1508     case OP_NULL:
1509         if (o->op_flags & OPf_STACKED)
1510             break;
1511         /* FALL THROUGH */
1512     case OP_NEXTSTATE:
1513     case OP_DBSTATE:
1514     case OP_ENTERTRY:
1515     case OP_ENTER:
1516         if (!(o->op_flags & OPf_KIDS))
1517             break;
1518         /* FALL THROUGH */
1519     case OP_SCOPE:
1520     case OP_LEAVE:
1521     case OP_LEAVETRY:
1522     case OP_LEAVELOOP:
1523     case OP_LINESEQ:
1524     case OP_LIST:
1525     case OP_LEAVEGIVEN:
1526     case OP_LEAVEWHEN:
1527         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1528             scalarvoid(kid);
1529         break;
1530     case OP_ENTEREVAL:
1531         scalarkids(o);
1532         break;
1533     case OP_SCALAR:
1534         return scalar(o);
1535     }
1536
1537     if (useless_sv) {
1538         /* mortalise it, in case warnings are fatal.  */
1539         Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
1540                        "Useless use of %"SVf" in void context",
1541                        sv_2mortal(useless_sv));
1542     }
1543     else if (useless) {
1544        Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
1545                       "Useless use of %s in void context",
1546                       useless);
1547     }
1548     return o;
1549 }
1550
1551 static OP *
1552 S_listkids(pTHX_ OP *o)
1553 {
1554     if (o && o->op_flags & OPf_KIDS) {
1555         OP *kid;
1556         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1557             list(kid);
1558     }
1559     return o;
1560 }
1561
1562 OP *
1563 Perl_list(pTHX_ OP *o)
1564 {
1565     dVAR;
1566     OP *kid;
1567
1568     /* assumes no premature commitment */
1569     if (!o || (o->op_flags & OPf_WANT)
1570          || (PL_parser && PL_parser->error_count)
1571          || o->op_type == OP_RETURN)
1572     {
1573         return o;
1574     }
1575
1576     if ((o->op_private & OPpTARGET_MY)
1577         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1578     {
1579         return o;                               /* As if inside SASSIGN */
1580     }
1581
1582     o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
1583
1584     switch (o->op_type) {
1585     case OP_FLOP:
1586     case OP_REPEAT:
1587         list(cBINOPo->op_first);
1588         break;
1589     case OP_OR:
1590     case OP_AND:
1591     case OP_COND_EXPR:
1592         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
1593             list(kid);
1594         break;
1595     default:
1596     case OP_MATCH:
1597     case OP_QR:
1598     case OP_SUBST:
1599     case OP_NULL:
1600         if (!(o->op_flags & OPf_KIDS))
1601             break;
1602         if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
1603             list(cBINOPo->op_first);
1604             return gen_constant_list(o);
1605         }
1606     case OP_LIST:
1607         listkids(o);
1608         break;
1609     case OP_LEAVE:
1610     case OP_LEAVETRY:
1611         kid = cLISTOPo->op_first;
1612         list(kid);
1613         kid = kid->op_sibling;
1614     do_kids:
1615         while (kid) {
1616             OP *sib = kid->op_sibling;
1617             if (sib && kid->op_type != OP_LEAVEWHEN)
1618                 scalarvoid(kid);
1619             else
1620                 list(kid);
1621             kid = sib;
1622         }
1623         PL_curcop = &PL_compiling;
1624         break;
1625     case OP_SCOPE:
1626     case OP_LINESEQ:
1627         kid = cLISTOPo->op_first;
1628         goto do_kids;
1629     }
1630     return o;
1631 }
1632
1633 static OP *
1634 S_scalarseq(pTHX_ OP *o)
1635 {
1636     dVAR;
1637     if (o) {
1638         const OPCODE type = o->op_type;
1639
1640         if (type == OP_LINESEQ || type == OP_SCOPE ||
1641             type == OP_LEAVE || type == OP_LEAVETRY)
1642         {
1643             OP *kid;
1644             for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling) {
1645                 if (kid->op_sibling) {
1646                     scalarvoid(kid);
1647                 }
1648             }
1649             PL_curcop = &PL_compiling;
1650         }
1651         o->op_flags &= ~OPf_PARENS;
1652         if (PL_hints & HINT_BLOCK_SCOPE)
1653             o->op_flags |= OPf_PARENS;
1654     }
1655     else
1656         o = newOP(OP_STUB, 0);
1657     return o;
1658 }
1659
1660 STATIC OP *
1661 S_modkids(pTHX_ OP *o, I32 type)
1662 {
1663     if (o && o->op_flags & OPf_KIDS) {
1664         OP *kid;
1665         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
1666             op_lvalue(kid, type);
1667     }
1668     return o;
1669 }
1670
1671 /*
1672 =for apidoc finalize_optree
1673
1674 This function finalizes the optree. Should be called directly after
1675 the complete optree is built. It does some additional
1676 checking which can't be done in the normal ck_xxx functions and makes
1677 the tree thread-safe.
1678
1679 =cut
1680 */
1681 void
1682 Perl_finalize_optree(pTHX_ OP* o)
1683 {
1684     PERL_ARGS_ASSERT_FINALIZE_OPTREE;
1685
1686     ENTER;
1687     SAVEVPTR(PL_curcop);
1688
1689     finalize_op(o);
1690
1691     LEAVE;
1692 }
1693
1694 STATIC void
1695 S_finalize_op(pTHX_ OP* o)
1696 {
1697     PERL_ARGS_ASSERT_FINALIZE_OP;
1698
1699 #if defined(PERL_MAD) && defined(USE_ITHREADS)
1700     {
1701         /* Make sure mad ops are also thread-safe */
1702         MADPROP *mp = o->op_madprop;
1703         while (mp) {
1704             if (mp->mad_type == MAD_OP && mp->mad_vlen) {
1705                 OP *prop_op = (OP *) mp->mad_val;
1706                 /* We only need "Relocate sv to the pad for thread safety.", but this
1707                    easiest way to make sure it traverses everything */
1708                 if (prop_op->op_type == OP_CONST)
1709                     cSVOPx(prop_op)->op_private &= ~OPpCONST_STRICT;
1710                 finalize_op(prop_op);
1711             }
1712             mp = mp->mad_next;
1713         }
1714     }
1715 #endif
1716
1717     switch (o->op_type) {
1718     case OP_NEXTSTATE:
1719     case OP_DBSTATE:
1720         PL_curcop = ((COP*)o);          /* for warnings */
1721         break;
1722     case OP_EXEC:
1723         if ( o->op_sibling
1724             && (o->op_sibling->op_type == OP_NEXTSTATE || o->op_sibling->op_type == OP_DBSTATE)
1725             && ckWARN(WARN_EXEC))
1726             {
1727                 if (o->op_sibling->op_sibling) {
1728                     const OPCODE type = o->op_sibling->op_sibling->op_type;
1729                     if (type != OP_EXIT && type != OP_WARN && type != OP_DIE) {
1730                         const line_t oldline = CopLINE(PL_curcop);
1731                         CopLINE_set(PL_curcop, CopLINE((COP*)o->op_sibling));
1732                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
1733                             "Statement unlikely to be reached");
1734                         Perl_warner(aTHX_ packWARN(WARN_EXEC),
1735                             "\t(Maybe you meant system() when you said exec()?)\n");
1736                         CopLINE_set(PL_curcop, oldline);
1737                     }
1738                 }
1739             }
1740         break;
1741
1742     case OP_GV:
1743         if ((o->op_private & OPpEARLY_CV) && ckWARN(WARN_PROTOTYPE)) {
1744             GV * const gv = cGVOPo_gv;
1745             if (SvTYPE(gv) == SVt_PVGV && GvCV(gv) && SvPVX_const(GvCV(gv))) {
1746                 /* XXX could check prototype here instead of just carping */
1747                 SV * const sv = sv_newmortal();
1748                 gv_efullname3(sv, gv, NULL);
1749                 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
1750                     "%"SVf"() called too early to check prototype",
1751                     SVfARG(sv));
1752             }
1753         }
1754         break;
1755
1756     case OP_CONST:
1757         if (cSVOPo->op_private & OPpCONST_STRICT)
1758             no_bareword_allowed(o);
1759         /* FALLTHROUGH */
1760 #ifdef USE_ITHREADS
1761     case OP_HINTSEVAL:
1762     case OP_METHOD_NAMED:
1763         /* Relocate sv to the pad for thread safety.
1764          * Despite being a "constant", the SV is written to,
1765          * for reference counts, sv_upgrade() etc. */
1766         if (cSVOPo->op_sv) {
1767             const PADOFFSET ix = pad_alloc(OP_CONST, SVs_PADTMP);
1768             if (o->op_type != OP_METHOD_NAMED &&
1769                 (SvPADTMP(cSVOPo->op_sv) || SvPADMY(cSVOPo->op_sv)))
1770             {
1771                 /* If op_sv is already a PADTMP/MY then it is being used by
1772                  * some pad, so make a copy. */
1773                 sv_setsv(PAD_SVl(ix),cSVOPo->op_sv);
1774                 if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
1775                 SvREFCNT_dec(cSVOPo->op_sv);
1776             }
1777             else if (o->op_type != OP_METHOD_NAMED
1778                 && cSVOPo->op_sv == &PL_sv_undef) {
1779                 /* PL_sv_undef is hack - it's unsafe to store it in the
1780                    AV that is the pad, because av_fetch treats values of
1781                    PL_sv_undef as a "free" AV entry and will merrily
1782                    replace them with a new SV, causing pad_alloc to think
1783                    that this pad slot is free. (When, clearly, it is not)
1784                 */
1785                 SvOK_off(PAD_SVl(ix));
1786                 SvPADTMP_on(PAD_SVl(ix));
1787                 SvREADONLY_on(PAD_SVl(ix));
1788             }
1789             else {
1790                 SvREFCNT_dec(PAD_SVl(ix));
1791                 SvPADTMP_on(cSVOPo->op_sv);
1792                 PAD_SETSV(ix, cSVOPo->op_sv);
1793                 /* XXX I don't know how this isn't readonly already. */
1794                 if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
1795             }
1796             cSVOPo->op_sv = NULL;
1797             o->op_targ = ix;
1798         }
1799 #endif
1800         break;
1801
1802     case OP_HELEM: {
1803         UNOP *rop;
1804         SV *lexname;
1805         GV **fields;
1806         SV **svp, *sv;
1807         const char *key = NULL;
1808         STRLEN keylen;
1809
1810         if (((BINOP*)o)->op_last->op_type != OP_CONST)
1811             break;
1812
1813         /* Make the CONST have a shared SV */
1814         svp = cSVOPx_svp(((BINOP*)o)->op_last);
1815         if ((!SvIsCOW(sv = *svp))
1816             && SvTYPE(sv) < SVt_PVMG && !SvROK(sv)) {
1817             key = SvPV_const(sv, keylen);
1818             lexname = newSVpvn_share(key,
1819                 SvUTF8(sv) ? -(I32)keylen : (I32)keylen,
1820                 0);
1821             SvREFCNT_dec_NN(sv);
1822             *svp = lexname;
1823         }
1824
1825         if ((o->op_private & (OPpLVAL_INTRO)))
1826             break;
1827
1828         rop = (UNOP*)((BINOP*)o)->op_first;
1829         if (rop->op_type != OP_RV2HV || rop->op_first->op_type != OP_PADSV)
1830             break;
1831         lexname = *av_fetch(PL_comppad_name, rop->op_first->op_targ, TRUE);
1832         if (!SvPAD_TYPED(lexname))
1833             break;
1834         fields = (GV**)hv_fetchs(SvSTASH(lexname), "FIELDS", FALSE);
1835         if (!fields || !GvHV(*fields))
1836             break;
1837         key = SvPV_const(*svp, keylen);
1838         if (!hv_fetch(GvHV(*fields), key,
1839                 SvUTF8(*svp) ? -(I32)keylen : (I32)keylen, FALSE)) {
1840             Perl_croak(aTHX_ "No such class field \"%"SVf"\" " 
1841                            "in variable %"SVf" of type %"HEKf, 
1842                       SVfARG(*svp), SVfARG(lexname),
1843                       HEKfARG(HvNAME_HEK(SvSTASH(lexname))));
1844         }
1845         break;
1846     }
1847
1848     case OP_HSLICE: {
1849         UNOP *rop;
1850         SV *lexname;
1851         GV **fields;
1852         SV **svp;
1853         const char *key;
1854         STRLEN keylen;
1855         SVOP *first_key_op, *key_op;
1856
1857         if ((o->op_private & (OPpLVAL_INTRO))
1858             /* I bet there's always a pushmark... */
1859             || ((LISTOP*)o)->op_first->op_sibling->op_type != OP_LIST)
1860             /* hmmm, no optimization if list contains only one key. */
1861             break;
1862         rop = (UNOP*)((LISTOP*)o)->op_last;
1863         if (rop->op_type != OP_RV2HV)
1864             break;
1865         if (rop->op_first->op_type == OP_PADSV)
1866             /* @$hash{qw(keys here)} */
1867             rop = (UNOP*)rop->op_first;
1868         else {
1869             /* @{$hash}{qw(keys here)} */
1870             if (rop->op_first->op_type == OP_SCOPE
1871                 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
1872                 {
1873                     rop = (UNOP*)cLISTOPx(rop->op_first)->op_last;
1874                 }
1875             else
1876                 break;
1877         }
1878
1879         lexname = *av_fetch(PL_comppad_name, rop->op_targ, TRUE);
1880         if (!SvPAD_TYPED(lexname))
1881             break;
1882         fields = (GV**)hv_fetchs(SvSTASH(lexname), "FIELDS", FALSE);
1883         if (!fields || !GvHV(*fields))
1884             break;
1885         /* Again guessing that the pushmark can be jumped over.... */
1886         first_key_op = (SVOP*)((LISTOP*)((LISTOP*)o)->op_first->op_sibling)
1887             ->op_first->op_sibling;
1888         for (key_op = first_key_op; key_op;
1889              key_op = (SVOP*)key_op->op_sibling) {
1890             if (key_op->op_type != OP_CONST)
1891                 continue;
1892             svp = cSVOPx_svp(key_op);
1893             key = SvPV_const(*svp, keylen);
1894             if (!hv_fetch(GvHV(*fields), key,
1895                     SvUTF8(*svp) ? -(I32)keylen : (I32)keylen, FALSE)) {
1896                 Perl_croak(aTHX_ "No such class field \"%"SVf"\" " 
1897                            "in variable %"SVf" of type %"HEKf, 
1898                       SVfARG(*svp), SVfARG(lexname),
1899                       HEKfARG(HvNAME_HEK(SvSTASH(lexname))));
1900             }
1901         }
1902         break;
1903     }
1904
1905     case OP_SUBST: {
1906         if (cPMOPo->op_pmreplrootu.op_pmreplroot)
1907             finalize_op(cPMOPo->op_pmreplrootu.op_pmreplroot);
1908         break;
1909     }
1910     default:
1911         break;
1912     }
1913
1914     if (o->op_flags & OPf_KIDS) {
1915         OP *kid;
1916         for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling)
1917             finalize_op(kid);
1918     }
1919 }
1920
1921 /*
1922 =for apidoc Amx|OP *|op_lvalue|OP *o|I32 type
1923
1924 Propagate lvalue ("modifiable") context to an op and its children.
1925 I<type> represents the context type, roughly based on the type of op that
1926 would do the modifying, although C<local()> is represented by OP_NULL,
1927 because it has no op type of its own (it is signalled by a flag on
1928 the lvalue op).
1929
1930 This function detects things that can't be modified, such as C<$x+1>, and
1931 generates errors for them. For example, C<$x+1 = 2> would cause it to be
1932 called with an op of type OP_ADD and a C<type> argument of OP_SASSIGN.
1933
1934 It also flags things that need to behave specially in an lvalue context,
1935 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
1936
1937 =cut
1938 */
1939
1940 OP *
1941 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
1942 {
1943     dVAR;
1944     OP *kid;
1945     /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
1946     int localize = -1;
1947
1948     if (!o || (PL_parser && PL_parser->error_count))
1949         return o;
1950
1951     if ((o->op_private & OPpTARGET_MY)
1952         && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
1953     {
1954         return o;
1955     }
1956
1957     assert( (o->op_flags & OPf_WANT) != OPf_WANT_VOID );
1958
1959     if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
1960
1961     switch (o->op_type) {
1962     case OP_UNDEF:
1963         PL_modcount++;
1964         return o;
1965     case OP_STUB:
1966         if ((o->op_flags & OPf_PARENS) || PL_madskills)
1967             break;
1968         goto nomod;
1969     case OP_ENTERSUB:
1970         if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
1971             !(o->op_flags & OPf_STACKED)) {
1972             o->op_type = OP_RV2CV;              /* entersub => rv2cv */
1973             /* Both ENTERSUB and RV2CV use this bit, but for different pur-
1974                poses, so we need it clear.  */
1975             o->op_private &= ~1;
1976             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
1977             assert(cUNOPo->op_first->op_type == OP_NULL);
1978             op_null(((LISTOP*)cUNOPo->op_first)->op_first);/* disable pushmark */
1979             break;
1980         }
1981         else {                          /* lvalue subroutine call */
1982             o->op_private |= OPpLVAL_INTRO
1983                            |(OPpENTERSUB_INARGS * (type == OP_LEAVESUBLV));
1984             PL_modcount = RETURN_UNLIMITED_NUMBER;
1985             if (type == OP_GREPSTART || type == OP_ENTERSUB || type == OP_REFGEN) {
1986                 /* Potential lvalue context: */
1987                 o->op_private |= OPpENTERSUB_INARGS;
1988                 break;
1989             }
1990             else {                      /* Compile-time error message: */
1991                 OP *kid = cUNOPo->op_first;
1992                 CV *cv;
1993
1994                 if (kid->op_type != OP_PUSHMARK) {
1995                     if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
1996                         Perl_croak(aTHX_
1997                                 "panic: unexpected lvalue entersub "
1998                                 "args: type/targ %ld:%"UVuf,
1999                                 (long)kid->op_type, (UV)kid->op_targ);
2000                     kid = kLISTOP->op_first;
2001                 }
2002                 while (kid->op_sibling)
2003                     kid = kid->op_sibling;
2004                 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
2005                     break;      /* Postpone until runtime */
2006                 }
2007
2008                 kid = kUNOP->op_first;
2009                 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
2010                     kid = kUNOP->op_first;
2011                 if (kid->op_type == OP_NULL)
2012                     Perl_croak(aTHX_
2013                                "Unexpected constant lvalue entersub "
2014                                "entry via type/targ %ld:%"UVuf,
2015                                (long)kid->op_type, (UV)kid->op_targ);
2016                 if (kid->op_type != OP_GV) {
2017                     break;
2018                 }
2019
2020                 cv = GvCV(kGVOP_gv);
2021                 if (!cv)
2022                     break;
2023                 if (CvLVALUE(cv))
2024                     break;
2025             }
2026         }
2027         /* FALL THROUGH */
2028     default:
2029       nomod:
2030         if (flags & OP_LVALUE_NO_CROAK) return NULL;
2031         /* grep, foreach, subcalls, refgen */
2032         if (type == OP_GREPSTART || type == OP_ENTERSUB
2033          || type == OP_REFGEN    || type == OP_LEAVESUBLV)
2034             break;
2035         yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
2036                      (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
2037                       ? "do block"
2038                       : (o->op_type == OP_ENTERSUB
2039                         ? "non-lvalue subroutine call"
2040                         : OP_DESC(o))),
2041                      type ? PL_op_desc[type] : "local"));
2042         return o;
2043
2044     case OP_PREINC:
2045     case OP_PREDEC:
2046     case OP_POW:
2047     case OP_MULTIPLY:
2048     case OP_DIVIDE:
2049     case OP_MODULO:
2050     case OP_REPEAT:
2051     case OP_ADD:
2052     case OP_SUBTRACT:
2053     case OP_CONCAT:
2054     case OP_LEFT_SHIFT:
2055     case OP_RIGHT_SHIFT:
2056     case OP_BIT_AND:
2057     case OP_BIT_XOR:
2058     case OP_BIT_OR:
2059     case OP_I_MULTIPLY:
2060     case OP_I_DIVIDE:
2061     case OP_I_MODULO:
2062     case OP_I_ADD:
2063     case OP_I_SUBTRACT:
2064         if (!(o->op_flags & OPf_STACKED))
2065             goto nomod;
2066         PL_modcount++;
2067         break;
2068
2069     case OP_COND_EXPR:
2070         localize = 1;
2071         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
2072             op_lvalue(kid, type);
2073         break;
2074
2075     case OP_RV2AV:
2076     case OP_RV2HV:
2077         if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
2078            PL_modcount = RETURN_UNLIMITED_NUMBER;
2079             return o;           /* Treat \(@foo) like ordinary list. */
2080         }
2081         /* FALL THROUGH */
2082     case OP_RV2GV:
2083         if (scalar_mod_type(o, type))
2084             goto nomod;
2085         ref(cUNOPo->op_first, o->op_type);
2086         /* FALL THROUGH */
2087     case OP_ASLICE:
2088     case OP_HSLICE:
2089         localize = 1;
2090         /* FALL THROUGH */
2091     case OP_AASSIGN:
2092         if (type == OP_LEAVESUBLV)
2093             o->op_private |= OPpMAYBE_LVSUB;
2094         /* FALL THROUGH */
2095     case OP_NEXTSTATE:
2096     case OP_DBSTATE:
2097        PL_modcount = RETURN_UNLIMITED_NUMBER;
2098         break;
2099     case OP_AV2ARYLEN:
2100         PL_hints |= HINT_BLOCK_SCOPE;
2101         if (type == OP_LEAVESUBLV)
2102             o->op_private |= OPpMAYBE_LVSUB;
2103         PL_modcount++;
2104         break;
2105     case OP_RV2SV:
2106         ref(cUNOPo->op_first, o->op_type);
2107         localize = 1;
2108         /* FALL THROUGH */
2109     case OP_GV:
2110         PL_hints |= HINT_BLOCK_SCOPE;
2111     case OP_SASSIGN:
2112     case OP_ANDASSIGN:
2113     case OP_ORASSIGN:
2114     case OP_DORASSIGN:
2115         PL_modcount++;
2116         break;
2117
2118     case OP_AELEMFAST:
2119     case OP_AELEMFAST_LEX:
2120         localize = -1;
2121         PL_modcount++;
2122         break;
2123
2124     case OP_PADAV:
2125     case OP_PADHV:
2126        PL_modcount = RETURN_UNLIMITED_NUMBER;
2127         if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
2128             return o;           /* Treat \(@foo) like ordinary list. */
2129         if (scalar_mod_type(o, type))
2130             goto nomod;
2131         if (type == OP_LEAVESUBLV)
2132             o->op_private |= OPpMAYBE_LVSUB;
2133         /* FALL THROUGH */
2134     case OP_PADSV:
2135         PL_modcount++;
2136         if (!type) /* local() */
2137             Perl_croak(aTHX_ "Can't localize lexical variable %"SVf,
2138                  PAD_COMPNAME_SV(o->op_targ));
2139         break;
2140
2141     case OP_PUSHMARK:
2142         localize = 0;
2143         break;
2144
2145     case OP_KEYS:
2146     case OP_RKEYS:
2147         if (type != OP_SASSIGN && type != OP_LEAVESUBLV)
2148             goto nomod;
2149         goto lvalue_func;
2150     case OP_SUBSTR:
2151         if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
2152             goto nomod;
2153         /* FALL THROUGH */
2154     case OP_POS:
2155     case OP_VEC:
2156       lvalue_func:
2157         if (type == OP_LEAVESUBLV)
2158             o->op_private |= OPpMAYBE_LVSUB;
2159         if (o->op_flags & OPf_KIDS)
2160             op_lvalue(cBINOPo->op_first->op_sibling, type);
2161         break;
2162
2163     case OP_AELEM:
2164     case OP_HELEM:
2165         ref(cBINOPo->op_first, o->op_type);
2166         if (type == OP_ENTERSUB &&
2167              !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
2168             o->op_private |= OPpLVAL_DEFER;
2169         if (type == OP_LEAVESUBLV)
2170             o->op_private |= OPpMAYBE_LVSUB;
2171         localize = 1;
2172         PL_modcount++;
2173         break;
2174
2175     case OP_SCOPE:
2176     case OP_LEAVE:
2177     case OP_ENTER:
2178     case OP_LINESEQ:
2179         localize = 0;
2180         if (o->op_flags & OPf_KIDS)
2181             op_lvalue(cLISTOPo->op_last, type);
2182         break;
2183
2184     case OP_NULL:
2185         localize = 0;
2186         if (o->op_flags & OPf_SPECIAL)          /* do BLOCK */
2187             goto nomod;
2188         else if (!(o->op_flags & OPf_KIDS))
2189             break;
2190         if (o->op_targ != OP_LIST) {
2191             op_lvalue(cBINOPo->op_first, type);
2192             break;
2193         }
2194         /* FALL THROUGH */
2195     case OP_LIST:
2196         localize = 0;
2197         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2198             /* elements might be in void context because the list is
2199                in scalar context or because they are attribute sub calls */
2200             if ( (kid->op_flags & OPf_WANT) != OPf_WANT_VOID )
2201                 op_lvalue(kid, type);
2202         break;
2203
2204     case OP_RETURN:
2205         if (type != OP_LEAVESUBLV)
2206             goto nomod;
2207         break; /* op_lvalue()ing was handled by ck_return() */
2208
2209     case OP_COREARGS:
2210         return o;
2211     }
2212
2213     /* [20011101.069] File test operators interpret OPf_REF to mean that
2214        their argument is a filehandle; thus \stat(".") should not set
2215        it. AMS 20011102 */
2216     if (type == OP_REFGEN &&
2217         PL_check[o->op_type] == Perl_ck_ftst)
2218         return o;
2219
2220     if (type != OP_LEAVESUBLV)
2221         o->op_flags |= OPf_MOD;
2222
2223     if (type == OP_AASSIGN || type == OP_SASSIGN)
2224         o->op_flags |= OPf_SPECIAL|OPf_REF;
2225     else if (!type) { /* local() */
2226         switch (localize) {
2227         case 1:
2228             o->op_private |= OPpLVAL_INTRO;
2229             o->op_flags &= ~OPf_SPECIAL;
2230             PL_hints |= HINT_BLOCK_SCOPE;
2231             break;
2232         case 0:
2233             break;
2234         case -1:
2235             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
2236                            "Useless localization of %s", OP_DESC(o));
2237         }
2238     }
2239     else if (type != OP_GREPSTART && type != OP_ENTERSUB
2240              && type != OP_LEAVESUBLV)
2241         o->op_flags |= OPf_REF;
2242     return o;
2243 }
2244
2245 STATIC bool
2246 S_scalar_mod_type(const OP *o, I32 type)
2247 {
2248     switch (type) {
2249     case OP_POS:
2250     case OP_SASSIGN:
2251         if (o && o->op_type == OP_RV2GV)
2252             return FALSE;
2253         /* FALL THROUGH */
2254     case OP_PREINC:
2255     case OP_PREDEC:
2256     case OP_POSTINC:
2257     case OP_POSTDEC:
2258     case OP_I_PREINC:
2259     case OP_I_PREDEC:
2260     case OP_I_POSTINC:
2261     case OP_I_POSTDEC:
2262     case OP_POW:
2263     case OP_MULTIPLY:
2264     case OP_DIVIDE:
2265     case OP_MODULO:
2266     case OP_REPEAT:
2267     case OP_ADD:
2268     case OP_SUBTRACT:
2269     case OP_I_MULTIPLY:
2270     case OP_I_DIVIDE:
2271     case OP_I_MODULO:
2272     case OP_I_ADD:
2273     case OP_I_SUBTRACT:
2274     case OP_LEFT_SHIFT:
2275     case OP_RIGHT_SHIFT:
2276     case OP_BIT_AND:
2277     case OP_BIT_XOR:
2278     case OP_BIT_OR:
2279     case OP_CONCAT:
2280     case OP_SUBST:
2281     case OP_TRANS:
2282     case OP_TRANSR:
2283     case OP_READ:
2284     case OP_SYSREAD:
2285     case OP_RECV:
2286     case OP_ANDASSIGN:
2287     case OP_ORASSIGN:
2288     case OP_DORASSIGN:
2289         return TRUE;
2290     default:
2291         return FALSE;
2292     }
2293 }
2294
2295 STATIC bool
2296 S_is_handle_constructor(const OP *o, I32 numargs)
2297 {
2298     PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
2299
2300     switch (o->op_type) {
2301     case OP_PIPE_OP:
2302     case OP_SOCKPAIR:
2303         if (numargs == 2)
2304             return TRUE;
2305         /* FALL THROUGH */
2306     case OP_SYSOPEN:
2307     case OP_OPEN:
2308     case OP_SELECT:             /* XXX c.f. SelectSaver.pm */
2309     case OP_SOCKET:
2310     case OP_OPEN_DIR:
2311     case OP_ACCEPT:
2312         if (numargs == 1)
2313             return TRUE;
2314         /* FALLTHROUGH */
2315     default:
2316         return FALSE;
2317     }
2318 }
2319
2320 static OP *
2321 S_refkids(pTHX_ OP *o, I32 type)
2322 {
2323     if (o && o->op_flags & OPf_KIDS) {
2324         OP *kid;
2325         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2326             ref(kid, type);
2327     }
2328     return o;
2329 }
2330
2331 OP *
2332 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
2333 {
2334     dVAR;
2335     OP *kid;
2336
2337     PERL_ARGS_ASSERT_DOREF;
2338
2339     if (!o || (PL_parser && PL_parser->error_count))
2340         return o;
2341
2342     switch (o->op_type) {
2343     case OP_ENTERSUB:
2344         if ((type == OP_EXISTS || type == OP_DEFINED) &&
2345             !(o->op_flags & OPf_STACKED)) {
2346             o->op_type = OP_RV2CV;             /* entersub => rv2cv */
2347             o->op_ppaddr = PL_ppaddr[OP_RV2CV];
2348             assert(cUNOPo->op_first->op_type == OP_NULL);
2349             op_null(((LISTOP*)cUNOPo->op_first)->op_first);     /* disable pushmark */
2350             o->op_flags |= OPf_SPECIAL;
2351             o->op_private &= ~1;
2352         }
2353         else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
2354             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2355                               : type == OP_RV2HV ? OPpDEREF_HV
2356                               : OPpDEREF_SV);
2357             o->op_flags |= OPf_MOD;
2358         }
2359
2360         break;
2361
2362     case OP_COND_EXPR:
2363         for (kid = cUNOPo->op_first->op_sibling; kid; kid = kid->op_sibling)
2364             doref(kid, type, set_op_ref);
2365         break;
2366     case OP_RV2SV:
2367         if (type == OP_DEFINED)
2368             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2369         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2370         /* FALL THROUGH */
2371     case OP_PADSV:
2372         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2373             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2374                               : type == OP_RV2HV ? OPpDEREF_HV
2375                               : OPpDEREF_SV);
2376             o->op_flags |= OPf_MOD;
2377         }
2378         break;
2379
2380     case OP_RV2AV:
2381     case OP_RV2HV:
2382         if (set_op_ref)
2383             o->op_flags |= OPf_REF;
2384         /* FALL THROUGH */
2385     case OP_RV2GV:
2386         if (type == OP_DEFINED)
2387             o->op_flags |= OPf_SPECIAL;         /* don't create GV */
2388         doref(cUNOPo->op_first, o->op_type, set_op_ref);
2389         break;
2390
2391     case OP_PADAV:
2392     case OP_PADHV:
2393         if (set_op_ref)
2394             o->op_flags |= OPf_REF;
2395         break;
2396
2397     case OP_SCALAR:
2398     case OP_NULL:
2399         if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
2400             break;
2401         doref(cBINOPo->op_first, type, set_op_ref);
2402         break;
2403     case OP_AELEM:
2404     case OP_HELEM:
2405         doref(cBINOPo->op_first, o->op_type, set_op_ref);
2406         if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
2407             o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
2408                               : type == OP_RV2HV ? OPpDEREF_HV
2409                               : OPpDEREF_SV);
2410             o->op_flags |= OPf_MOD;
2411         }
2412         break;
2413
2414     case OP_SCOPE:
2415     case OP_LEAVE:
2416         set_op_ref = FALSE;
2417         /* FALL THROUGH */
2418     case OP_ENTER:
2419     case OP_LIST:
2420         if (!(o->op_flags & OPf_KIDS))
2421             break;
2422         doref(cLISTOPo->op_last, type, set_op_ref);
2423         break;
2424     default:
2425         break;
2426     }
2427     return scalar(o);
2428
2429 }
2430
2431 STATIC OP *
2432 S_dup_attrlist(pTHX_ OP *o)
2433 {
2434     dVAR;
2435     OP *rop;
2436
2437     PERL_ARGS_ASSERT_DUP_ATTRLIST;
2438
2439     /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
2440      * where the first kid is OP_PUSHMARK and the remaining ones
2441      * are OP_CONST.  We need to push the OP_CONST values.
2442      */
2443     if (o->op_type == OP_CONST)
2444         rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
2445 #ifdef PERL_MAD
2446     else if (o->op_type == OP_NULL)
2447         rop = NULL;
2448 #endif
2449     else {
2450         assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
2451         rop = NULL;
2452         for (o = cLISTOPo->op_first; o; o=o->op_sibling) {
2453             if (o->op_type == OP_CONST)
2454                 rop = op_append_elem(OP_LIST, rop,
2455                                   newSVOP(OP_CONST, o->op_flags,
2456                                           SvREFCNT_inc_NN(cSVOPo->op_sv)));
2457         }
2458     }
2459     return rop;
2460 }
2461
2462 STATIC void
2463 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
2464 {
2465     dVAR;
2466     SV * const stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2467
2468     PERL_ARGS_ASSERT_APPLY_ATTRS;
2469
2470     /* fake up C<use attributes $pkg,$rv,@attrs> */
2471     ENTER;              /* need to protect against side-effects of 'use' */
2472
2473 #define ATTRSMODULE "attributes"
2474 #define ATTRSMODULE_PM "attributes.pm"
2475
2476     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2477                          newSVpvs(ATTRSMODULE),
2478                          NULL,
2479                          op_prepend_elem(OP_LIST,
2480                                       newSVOP(OP_CONST, 0, stashsv),
2481                                       op_prepend_elem(OP_LIST,
2482                                                    newSVOP(OP_CONST, 0,
2483                                                            newRV(target)),
2484                                                    dup_attrlist(attrs))));
2485     LEAVE;
2486 }
2487
2488 STATIC void
2489 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
2490 {
2491     dVAR;
2492     OP *pack, *imop, *arg;
2493     SV *meth, *stashsv, **svp;
2494
2495     PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
2496
2497     if (!attrs)
2498         return;
2499
2500     assert(target->op_type == OP_PADSV ||
2501            target->op_type == OP_PADHV ||
2502            target->op_type == OP_PADAV);
2503
2504     /* Ensure that attributes.pm is loaded. */
2505     ENTER;              /* need to protect against side-effects of 'use' */
2506     /* Don't force the C<use> if we don't need it. */
2507     svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
2508     if (svp && *svp != &PL_sv_undef)
2509         NOOP;   /* already in %INC */
2510     else
2511         Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
2512                                newSVpvs(ATTRSMODULE), NULL);
2513     LEAVE;
2514
2515     /* Need package name for method call. */
2516     pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
2517
2518     /* Build up the real arg-list. */
2519     stashsv = stash ? newSVhek(HvNAME_HEK(stash)) : &PL_sv_no;
2520
2521     arg = newOP(OP_PADSV, 0);
2522     arg->op_targ = target->op_targ;
2523     arg = op_prepend_elem(OP_LIST,
2524                        newSVOP(OP_CONST, 0, stashsv),
2525                        op_prepend_elem(OP_LIST,
2526                                     newUNOP(OP_REFGEN, 0,
2527                                             op_lvalue(arg, OP_REFGEN)),
2528                                     dup_attrlist(attrs)));
2529
2530     /* Fake up a method call to import */
2531     meth = newSVpvs_share("import");
2532     imop = convert(OP_ENTERSUB, OPf_STACKED|OPf_SPECIAL|OPf_WANT_VOID,
2533                    op_append_elem(OP_LIST,
2534                                op_prepend_elem(OP_LIST, pack, list(arg)),
2535                                newSVOP(OP_METHOD_NAMED, 0, meth)));
2536
2537     /* Combine the ops. */
2538     *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
2539 }
2540
2541 /*
2542 =notfor apidoc apply_attrs_string
2543
2544 Attempts to apply a list of attributes specified by the C<attrstr> and
2545 C<len> arguments to the subroutine identified by the C<cv> argument which
2546 is expected to be associated with the package identified by the C<stashpv>
2547 argument (see L<attributes>).  It gets this wrong, though, in that it
2548 does not correctly identify the boundaries of the individual attribute
2549 specifications within C<attrstr>.  This is not really intended for the
2550 public API, but has to be listed here for systems such as AIX which
2551 need an explicit export list for symbols.  (It's called from XS code
2552 in support of the C<ATTRS:> keyword from F<xsubpp>.)  Patches to fix it
2553 to respect attribute syntax properly would be welcome.
2554
2555 =cut
2556 */
2557
2558 void
2559 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
2560                         const char *attrstr, STRLEN len)
2561 {
2562     OP *attrs = NULL;
2563
2564     PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
2565
2566     if (!len) {
2567         len = strlen(attrstr);
2568     }
2569
2570     while (len) {
2571         for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
2572         if (len) {
2573             const char * const sstr = attrstr;
2574             for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
2575             attrs = op_append_elem(OP_LIST, attrs,
2576                                 newSVOP(OP_CONST, 0,
2577                                         newSVpvn(sstr, attrstr-sstr)));
2578         }
2579     }
2580
2581     Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
2582                      newSVpvs(ATTRSMODULE),
2583                      NULL, op_prepend_elem(OP_LIST,
2584                                   newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
2585                                   op_prepend_elem(OP_LIST,
2586                                                newSVOP(OP_CONST, 0,
2587                                                        newRV(MUTABLE_SV(cv))),
2588                                                attrs)));
2589 }
2590
2591 STATIC OP *
2592 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
2593 {
2594     dVAR;
2595     I32 type;
2596     const bool stately = PL_parser && PL_parser->in_my == KEY_state;
2597
2598     PERL_ARGS_ASSERT_MY_KID;
2599
2600     if (!o || (PL_parser && PL_parser->error_count))
2601         return o;
2602
2603     type = o->op_type;
2604     if (PL_madskills && type == OP_NULL && o->op_flags & OPf_KIDS) {
2605         (void)my_kid(cUNOPo->op_first, attrs, imopsp);
2606         return o;
2607     }
2608
2609     if (type == OP_LIST) {
2610         OP *kid;
2611         for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling)
2612             my_kid(kid, attrs, imopsp);
2613         return o;
2614     } else if (type == OP_UNDEF || type == OP_STUB) {
2615         return o;
2616     } else if (type == OP_RV2SV ||      /* "our" declaration */
2617                type == OP_RV2AV ||
2618                type == OP_RV2HV) { /* XXX does this let anything illegal in? */
2619         if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
2620             yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
2621                         OP_DESC(o),
2622                         PL_parser->in_my == KEY_our
2623                             ? "our"
2624                             : PL_parser->in_my == KEY_state ? "state" : "my"));
2625         } else if (attrs) {
2626             GV * const gv = cGVOPx_gv(cUNOPo->op_first);
2627             PL_parser->in_my = FALSE;
2628             PL_parser->in_my_stash = NULL;
2629             apply_attrs(GvSTASH(gv),
2630                         (type == OP_RV2SV ? GvSV(gv) :
2631                          type == OP_RV2AV ? MUTABLE_SV(GvAV(gv)) :
2632                          type == OP_RV2HV ? MUTABLE_SV(GvHV(gv)) : MUTABLE_SV(gv)),
2633                         attrs);
2634         }
2635         o->op_private |= OPpOUR_INTRO;
2636         return o;
2637     }
2638     else if (type != OP_PADSV &&
2639              type != OP_PADAV &&
2640              type != OP_PADHV &&
2641              type != OP_PUSHMARK)
2642     {
2643         yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
2644                           OP_DESC(o),
2645                           PL_parser->in_my == KEY_our
2646                             ? "our"
2647                             : PL_parser->in_my == KEY_state ? "state" : "my"));
2648         return o;
2649     }
2650     else if (attrs && type != OP_PUSHMARK) {
2651         HV *stash;
2652
2653         PL_parser->in_my = FALSE;
2654         PL_parser->in_my_stash = NULL;
2655
2656         /* check for C<my Dog $spot> when deciding package */
2657         stash = PAD_COMPNAME_TYPE(o->op_targ);
2658         if (!stash)
2659             stash = PL_curstash;
2660         apply_attrs_my(stash, o, attrs, imopsp);
2661     }
2662     o->op_flags |= OPf_MOD;
2663     o->op_private |= OPpLVAL_INTRO;
2664     if (stately)
2665         o->op_private |= OPpPAD_STATE;
2666     return o;
2667 }
2668
2669 OP *
2670 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
2671 {
2672     dVAR;
2673     OP *rops;
2674     int maybe_scalar = 0;
2675
2676     PERL_ARGS_ASSERT_MY_ATTRS;
2677
2678 /* [perl #17376]: this appears to be premature, and results in code such as
2679    C< our(%x); > executing in list mode rather than void mode */
2680 #if 0
2681     if (o->op_flags & OPf_PARENS)
2682         list(o);
2683     else
2684         maybe_scalar = 1;
2685 #else
2686     maybe_scalar = 1;
2687 #endif
2688     if (attrs)
2689         SAVEFREEOP(attrs);
2690     rops = NULL;
2691     o = my_kid(o, attrs, &rops);
2692     if (rops) {
2693         if (maybe_scalar && o->op_type == OP_PADSV) {
2694             o = scalar(op_append_list(OP_LIST, rops, o));
2695             o->op_private |= OPpLVAL_INTRO;
2696         }
2697         else {
2698             /* The listop in rops might have a pushmark at the beginning,
2699                which will mess up list assignment. */
2700             LISTOP * const lrops = (LISTOP *)rops; /* for brevity */
2701             if (rops->op_type == OP_LIST && 
2702                 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
2703             {
2704                 OP * const pushmark = lrops->op_first;
2705                 lrops->op_first = pushmark->op_sibling;
2706                 op_free(pushmark);
2707             }
2708             o = op_append_list(OP_LIST, o, rops);
2709         }
2710     }
2711     PL_parser->in_my = FALSE;
2712     PL_parser->in_my_stash = NULL;
2713     return o;
2714 }
2715
2716 OP *
2717 Perl_sawparens(pTHX_ OP *o)
2718 {
2719     PERL_UNUSED_CONTEXT;
2720     if (o)
2721         o->op_flags |= OPf_PARENS;
2722     return o;
2723 }
2724
2725 OP *
2726 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
2727 {
2728     OP *o;
2729     bool ismatchop = 0;
2730     const OPCODE ltype = left->op_type;
2731     const OPCODE rtype = right->op_type;
2732
2733     PERL_ARGS_ASSERT_BIND_MATCH;
2734
2735     if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
2736           || ltype == OP_PADHV) && ckWARN(WARN_MISC))
2737     {
2738       const char * const desc
2739           = PL_op_desc[(
2740                           rtype == OP_SUBST || rtype == OP_TRANS
2741                        || rtype == OP_TRANSR
2742                        )
2743                        ? (int)rtype : OP_MATCH];
2744       const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
2745       GV *gv;
2746       SV * const name =
2747        (ltype == OP_RV2AV || ltype == OP_RV2HV)
2748         ?    cUNOPx(left)->op_first->op_type == OP_GV
2749           && (gv = cGVOPx_gv(cUNOPx(left)->op_first))
2750               ? varname(gv, isary ? '@' : '%', 0, NULL, 0, 1)
2751               : NULL
2752         : varname(
2753            (GV *)PL_compcv, isary ? '@' : '%', left->op_targ, NULL, 0, 1
2754           );
2755       if (name)
2756         Perl_warner(aTHX_ packWARN(WARN_MISC),
2757              "Applying %s to %"SVf" will act on scalar(%"SVf")",
2758              desc, name, name);
2759       else {
2760         const char * const sample = (isary
2761              ? "@array" : "%hash");
2762         Perl_warner(aTHX_ packWARN(WARN_MISC),
2763              "Applying %s to %s will act on scalar(%s)",
2764              desc, sample, sample);
2765       }
2766     }
2767
2768     if (rtype == OP_CONST &&
2769         cSVOPx(right)->op_private & OPpCONST_BARE &&
2770         cSVOPx(right)->op_private & OPpCONST_STRICT)
2771     {
2772         no_bareword_allowed(right);
2773     }
2774
2775     /* !~ doesn't make sense with /r, so error on it for now */
2776     if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
2777         type == OP_NOT)
2778         yyerror("Using !~ with s///r doesn't make sense");
2779     if (rtype == OP_TRANSR && type == OP_NOT)
2780         yyerror("Using !~ with tr///r doesn't make sense");
2781
2782     ismatchop = (rtype == OP_MATCH ||
2783                  rtype == OP_SUBST ||
2784                  rtype == OP_TRANS || rtype == OP_TRANSR)
2785              && !(right->op_flags & OPf_SPECIAL);
2786     if (ismatchop && right->op_private & OPpTARGET_MY) {
2787         right->op_targ = 0;
2788         right->op_private &= ~OPpTARGET_MY;
2789     }
2790     if (!(right->op_flags & OPf_STACKED) && ismatchop) {
2791         OP *newleft;
2792
2793         right->op_flags |= OPf_STACKED;
2794         if (rtype != OP_MATCH && rtype != OP_TRANSR &&
2795             ! (rtype == OP_TRANS &&
2796                right->op_private & OPpTRANS_IDENTICAL) &&
2797             ! (rtype == OP_SUBST &&
2798                (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
2799             newleft = op_lvalue(left, rtype);
2800         else
2801             newleft = left;
2802         if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
2803             o = newBINOP(OP_NULL, OPf_STACKED, scalar(newleft), right);
2804         else
2805             o = op_prepend_elem(rtype, scalar(newleft), right);
2806         if (type == OP_NOT)
2807             return newUNOP(OP_NOT, 0, scalar(o));
2808         return o;
2809     }
2810     else
2811         return bind_match(type, left,
2812                 pmruntime(newPMOP(OP_MATCH, 0), right, 0, 0));
2813 }
2814
2815 OP *
2816 Perl_invert(pTHX_ OP *o)
2817 {
2818     if (!o)
2819         return NULL;
2820     return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
2821 }
2822
2823 /*
2824 =for apidoc Amx|OP *|op_scope|OP *o
2825
2826 Wraps up an op tree with some additional ops so that at runtime a dynamic
2827 scope will be created.  The original ops run in the new dynamic scope,
2828 and then, provided that they exit normally, the scope will be unwound.
2829 The additional ops used to create and unwind the dynamic scope will
2830 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
2831 instead if the ops are simple enough to not need the full dynamic scope
2832 structure.
2833
2834 =cut
2835 */
2836
2837 OP *
2838 Perl_op_scope(pTHX_ OP *o)
2839 {
2840     dVAR;
2841     if (o) {
2842         if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
2843             o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
2844             o->op_type = OP_LEAVE;
2845             o->op_ppaddr = PL_ppaddr[OP_LEAVE];
2846         }
2847         else if (o->op_type == OP_LINESEQ) {
2848             OP *kid;
2849             o->op_type = OP_SCOPE;
2850             o->op_ppaddr = PL_ppaddr[OP_SCOPE];
2851             kid = ((LISTOP*)o)->op_first;
2852             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
2853                 op_null(kid);
2854
2855                 /* The following deals with things like 'do {1 for 1}' */
2856                 kid = kid->op_sibling;
2857                 if (kid &&
2858                     (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
2859                     op_null(kid);
2860             }
2861         }
2862         else
2863             o = newLISTOP(OP_SCOPE, 0, o, NULL);
2864     }
2865     return o;
2866 }
2867
2868 OP *
2869 Perl_op_unscope(pTHX_ OP *o)
2870 {
2871     if (o && o->op_type == OP_LINESEQ) {
2872         OP *kid = cLISTOPo->op_first;
2873         for(; kid; kid = kid->op_sibling)
2874             if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
2875                 op_null(kid);
2876     }
2877     return o;
2878 }
2879
2880 int
2881 Perl_block_start(pTHX_ int full)
2882 {
2883     dVAR;
2884     const int retval = PL_savestack_ix;
2885
2886     pad_block_start(full);
2887     SAVEHINTS();
2888     PL_hints &= ~HINT_BLOCK_SCOPE;
2889     SAVECOMPILEWARNINGS();
2890     PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
2891
2892     CALL_BLOCK_HOOKS(bhk_start, full);
2893
2894     return retval;
2895 }
2896
2897 OP*
2898 Perl_block_end(pTHX_ I32 floor, OP *seq)
2899 {
2900     dVAR;
2901     const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
2902     OP* retval = scalarseq(seq);
2903     OP *o;
2904
2905     CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
2906
2907     LEAVE_SCOPE(floor);
2908     CopHINTS_set(&PL_compiling, PL_hints);
2909     if (needblockscope)
2910         PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
2911     o = pad_leavemy();
2912
2913     if (o) {
2914         /* pad_leavemy has created a sequence of introcv ops for all my
2915            subs declared in the block.  We have to replicate that list with
2916            clonecv ops, to deal with this situation:
2917
2918                sub {
2919                    my sub s1;
2920                    my sub s2;
2921                    sub s1 { state sub foo { \&s2 } }
2922                }->()
2923
2924            Originally, I was going to have introcv clone the CV and turn
2925            off the stale flag.  Since &s1 is declared before &s2, the
2926            introcv op for &s1 is executed (on sub entry) before the one for
2927            &s2.  But the &foo sub inside &s1 (which is cloned when &s1 is
2928            cloned, since it is a state sub) closes over &s2 and expects
2929            to see it in its outer CV’s pad.  If the introcv op clones &s1,
2930            then &s2 is still marked stale.  Since &s1 is not active, and
2931            &foo closes over &s1’s implicit entry for &s2, we get a â€˜Varia-
2932            ble will not stay shared’ warning.  Because it is the same stub
2933            that will be used when the introcv op for &s2 is executed, clos-
2934            ing over it is safe.  Hence, we have to turn off the stale flag
2935            on all lexical subs in the block before we clone any of them.
2936            Hence, having introcv clone the sub cannot work.  So we create a
2937            list of ops like this:
2938
2939                lineseq
2940                   |
2941                   +-- introcv
2942                   |
2943                   +-- introcv
2944                   |
2945                   +-- introcv
2946                   |
2947                   .
2948                   .
2949                   .
2950                   |
2951                   +-- clonecv
2952                   |
2953                   +-- clonecv
2954                   |
2955                   +-- clonecv
2956                   |
2957                   .
2958                   .
2959                   .
2960          */
2961         OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
2962         OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
2963         for (;; kid = kid->op_sibling) {
2964             OP *newkid = newOP(OP_CLONECV, 0);
2965             newkid->op_targ = kid->op_targ;
2966             o = op_append_elem(OP_LINESEQ, o, newkid);
2967             if (kid == last) break;
2968         }
2969         retval = op_prepend_elem(OP_LINESEQ, o, retval);
2970     }
2971
2972     CALL_BLOCK_HOOKS(bhk_post_end, &retval);
2973
2974     return retval;
2975 }
2976
2977 /*
2978 =head1 Compile-time scope hooks
2979
2980 =for apidoc Aox||blockhook_register
2981
2982 Register a set of hooks to be called when the Perl lexical scope changes
2983 at compile time. See L<perlguts/"Compile-time scope hooks">.
2984
2985 =cut
2986 */
2987
2988 void
2989 Perl_blockhook_register(pTHX_ BHK *hk)
2990 {
2991     PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
2992
2993     Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
2994 }
2995
2996 STATIC OP *
2997 S_newDEFSVOP(pTHX)
2998 {
2999     dVAR;
3000     const PADOFFSET offset = pad_findmy_pvs("$_", 0);
3001     if (offset == NOT_IN_PAD || PAD_COMPNAME_FLAGS_isOUR(offset)) {
3002         return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
3003     }
3004     else {
3005         OP * const o = newOP(OP_PADSV, 0);
3006         o->op_targ = offset;
3007         return o;
3008     }
3009 }
3010
3011 void
3012 Perl_newPROG(pTHX_ OP *o)
3013 {
3014     dVAR;
3015
3016     PERL_ARGS_ASSERT_NEWPROG;
3017
3018     if (PL_in_eval) {
3019         PERL_CONTEXT *cx;
3020         I32 i;
3021         if (PL_eval_root)
3022                 return;
3023         PL_eval_root = newUNOP(OP_LEAVEEVAL,
3024                                ((PL_in_eval & EVAL_KEEPERR)
3025                                 ? OPf_SPECIAL : 0), o);
3026
3027         cx = &cxstack[cxstack_ix];
3028         assert(CxTYPE(cx) == CXt_EVAL);
3029
3030         if ((cx->blk_gimme & G_WANT) == G_VOID)
3031             scalarvoid(PL_eval_root);
3032         else if ((cx->blk_gimme & G_WANT) == G_ARRAY)
3033             list(PL_eval_root);
3034         else
3035             scalar(PL_eval_root);
3036
3037         PL_eval_start = op_linklist(PL_eval_root);
3038         PL_eval_root->op_private |= OPpREFCOUNTED;
3039         OpREFCNT_set(PL_eval_root, 1);
3040         PL_eval_root->op_next = 0;
3041         i = PL_savestack_ix;
3042         SAVEFREEOP(o);
3043         ENTER;
3044         CALL_PEEP(PL_eval_start);
3045         finalize_optree(PL_eval_root);
3046         LEAVE;
3047         PL_savestack_ix = i;
3048     }
3049     else {
3050         if (o->op_type == OP_STUB) {
3051             /* This block is entered if nothing is compiled for the main
3052                program. This will be the case for an genuinely empty main
3053                program, or one which only has BEGIN blocks etc, so already
3054                run and freed.
3055
3056                Historically (5.000) the guard above was !o. However, commit
3057                f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
3058                c71fccf11fde0068, changed perly.y so that newPROG() is now
3059                called with the output of block_end(), which returns a new
3060                OP_STUB for the case of an empty optree. ByteLoader (and
3061                maybe other things) also take this path, because they set up
3062                PL_main_start and PL_main_root directly, without generating an
3063                optree.
3064
3065                If the parsing the main program aborts (due to parse errors,
3066                or due to BEGIN or similar calling exit), then newPROG()
3067                isn't even called, and hence this code path and its cleanups
3068                are skipped. This shouldn't make a make a difference:
3069                * a non-zero return from perl_parse is a failure, and
3070                  perl_destruct() should be called immediately.
3071                * however, if exit(0) is called during the parse, then
3072                  perl_parse() returns 0, and perl_run() is called. As
3073                  PL_main_start will be NULL, perl_run() will return
3074                  promptly, and the exit code will remain 0.
3075             */
3076
3077             PL_comppad_name = 0;
3078             PL_compcv = 0;
3079             S_op_destroy(aTHX_ o);
3080             return;
3081         }
3082         PL_main_root = op_scope(sawparens(scalarvoid(o)));
3083         PL_curcop = &PL_compiling;
3084         PL_main_start = LINKLIST(PL_main_root);
3085         PL_main_root->op_private |= OPpREFCOUNTED;
3086         OpREFCNT_set(PL_main_root, 1);
3087         PL_main_root->op_next = 0;
3088         CALL_PEEP(PL_main_start);
3089         finalize_optree(PL_main_root);
3090         cv_forget_slab(PL_compcv);
3091         PL_compcv = 0;
3092
3093         /* Register with debugger */
3094         if (PERLDB_INTER) {
3095             CV * const cv = get_cvs("DB::postponed", 0);
3096             if (cv) {
3097                 dSP;
3098                 PUSHMARK(SP);
3099                 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
3100                 PUTBACK;
3101                 call_sv(MUTABLE_SV(cv), G_DISCARD);
3102             }
3103         }
3104     }
3105 }
3106
3107 OP *
3108 Perl_localize(pTHX_ OP *o, I32 lex)
3109 {
3110     dVAR;
3111
3112     PERL_ARGS_ASSERT_LOCALIZE;
3113
3114     if (o->op_flags & OPf_PARENS)
3115 /* [perl #17376]: this appears to be premature, and results in code such as
3116    C< our(%x); > executing in list mode rather than void mode */
3117 #if 0
3118         list(o);
3119 #else
3120         NOOP;
3121 #endif
3122     else {
3123         if ( PL_parser->bufptr > PL_parser->oldbufptr
3124             && PL_parser->bufptr[-1] == ','
3125             && ckWARN(WARN_PARENTHESIS))
3126         {
3127             char *s = PL_parser->bufptr;
3128             bool sigil = FALSE;
3129
3130             /* some heuristics to detect a potential error */
3131             while (*s && (strchr(", \t\n", *s)))
3132                 s++;
3133
3134             while (1) {
3135                 if (*s && strchr("@$%*", *s) && *++s
3136                        && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
3137                     s++;
3138                     sigil = TRUE;
3139                     while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
3140                         s++;
3141                     while (*s && (strchr(", \t\n", *s)))
3142                         s++;
3143                 }
3144                 else
3145                     break;
3146             }
3147             if (sigil && (*s == ';' || *s == '=')) {
3148                 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
3149                                 "Parentheses missing around \"%s\" list",
3150                                 lex
3151                                     ? (PL_parser->in_my == KEY_our
3152                                         ? "our"
3153                                         : PL_parser->in_my == KEY_state
3154                                             ? "state"
3155                                             : "my")
3156                                     : "local");
3157             }
3158         }
3159     }
3160     if (lex)
3161         o = my(o);
3162     else
3163         o = op_lvalue(o, OP_NULL);              /* a bit kludgey */
3164     PL_parser->in_my = FALSE;
3165     PL_parser->in_my_stash = NULL;
3166     return o;
3167 }
3168
3169 OP *
3170 Perl_jmaybe(pTHX_ OP *o)
3171 {
3172     PERL_ARGS_ASSERT_JMAYBE;
3173
3174     if (o->op_type == OP_LIST) {
3175         OP * const o2
3176             = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
3177         o = convert(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
3178     }
3179     return o;
3180 }
3181
3182 PERL_STATIC_INLINE OP *
3183 S_op_std_init(pTHX_ OP *o)
3184 {
3185     I32 type = o->op_type;
3186
3187     PERL_ARGS_ASSERT_OP_STD_INIT;
3188
3189     if (PL_opargs[type] & OA_RETSCALAR)
3190         scalar(o);
3191     if (PL_opargs[type] & OA_TARGET && !o->op_targ)
3192         o->op_targ = pad_alloc(type, SVs_PADTMP);
3193
3194     return o;
3195 }
3196
3197 PERL_STATIC_INLINE OP *
3198 S_op_integerize(pTHX_ OP *o)
3199 {
3200     I32 type = o->op_type;
3201
3202     PERL_ARGS_ASSERT_OP_INTEGERIZE;
3203
3204     /* integerize op. */
3205     if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
3206     {
3207         dVAR;
3208         o->op_ppaddr = PL_ppaddr[type = ++(o->op_type)];
3209     }
3210
3211     if (type == OP_NEGATE)
3212         /* XXX might want a ck_negate() for this */
3213         cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
3214
3215     return o;
3216 }
3217
3218 static OP *
3219 S_fold_constants(pTHX_ OP *o)
3220 {
3221     dVAR;
3222     OP * VOL curop;
3223     OP *newop;
3224     VOL I32 type = o->op_type;
3225     SV * VOL sv = NULL;
3226     int ret = 0;
3227     I32 oldscope;
3228     OP *old_next;
3229     SV * const oldwarnhook = PL_warnhook;
3230     SV * const olddiehook  = PL_diehook;
3231     COP not_compiling;
3232     dJMPENV;
3233
3234     PERL_ARGS_ASSERT_FOLD_CONSTANTS;
3235
3236     if (!(PL_opargs[type] & OA_FOLDCONST))
3237         goto nope;
3238
3239     switch (type) {
3240     case OP_UCFIRST:
3241     case OP_LCFIRST:
3242     case OP_UC:
3243     case OP_LC:
3244     case OP_FC:
3245     case OP_SLT:
3246     case OP_SGT:
3247     case OP_SLE:
3248     case OP_SGE:
3249     case OP_SCMP:
3250     case OP_SPRINTF:
3251         /* XXX what about the numeric ops? */
3252         if (IN_LOCALE_COMPILETIME)
3253             goto nope;
3254         break;
3255     case OP_PACK:
3256         if (!cLISTOPo->op_first->op_sibling
3257           || cLISTOPo->op_first->op_sibling->op_type != OP_CONST)
3258             goto nope;
3259         {
3260             SV * const sv = cSVOPx_sv(cLISTOPo->op_first->op_sibling);
3261             if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
3262             {
3263                 const char *s = SvPVX_const(sv);
3264                 while (s < SvEND(sv)) {
3265                     if (*s == 'p' || *s == 'P') goto nope;
3266                     s++;
3267                 }
3268             }
3269         }
3270         break;
3271     case OP_REPEAT:
3272         if (o->op_private & OPpREPEAT_DOLIST) goto nope;
3273     }
3274
3275     if (PL_parser && PL_parser->error_count)
3276         goto nope;              /* Don't try to run w/ errors */
3277
3278     for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
3279         const OPCODE type = curop->op_type;
3280         if ((type != OP_CONST || (curop->op_private & OPpCONST_BARE)) &&
3281             type != OP_LIST &&
3282             type != OP_SCALAR &&
3283             type != OP_NULL &&
3284             type != OP_PUSHMARK)
3285         {
3286             goto nope;
3287         }
3288     }
3289
3290     curop = LINKLIST(o);
3291     old_next = o->op_next;
3292     o->op_next = 0;
3293     PL_op = curop;
3294
3295     oldscope = PL_scopestack_ix;
3296     create_eval_scope(G_FAKINGEVAL);
3297
3298     /* Verify that we don't need to save it:  */
3299     assert(PL_curcop == &PL_compiling);
3300     StructCopy(&PL_compiling, &not_compiling, COP);
3301     PL_curcop = &not_compiling;
3302     /* The above ensures that we run with all the correct hints of the
3303        currently compiling COP, but that IN_PERL_RUNTIME is not true. */
3304     assert(IN_PERL_RUNTIME);
3305     PL_warnhook = PERL_WARNHOOK_FATAL;
3306     PL_diehook  = NULL;
3307     JMPENV_PUSH(ret);
3308
3309     switch (ret) {
3310     case 0:
3311         CALLRUNOPS(aTHX);
3312         sv = *(PL_stack_sp--);
3313         if (o->op_targ && sv == PAD_SV(o->op_targ)) {   /* grab pad temp? */
3314 #ifdef PERL_MAD
3315             /* Can't simply swipe the SV from the pad, because that relies on
3316                the op being freed "real soon now". Under MAD, this doesn't
3317                happen (see the #ifdef below).  */
3318             sv = newSVsv(sv);
3319 #else
3320             pad_swipe(o->op_targ,  FALSE);
3321 #endif
3322         }
3323         else if (SvTEMP(sv)) {                  /* grab mortal temp? */
3324             SvREFCNT_inc_simple_void(sv);
3325             SvTEMP_off(sv);
3326         }
3327         break;
3328     case 3:
3329         /* Something tried to die.  Abandon constant folding.  */
3330         /* Pretend the error never happened.  */
3331         CLEAR_ERRSV();
3332         o->op_next = old_next;
3333         break;
3334     default:
3335         JMPENV_POP;
3336         /* Don't expect 1 (setjmp failed) or 2 (something called my_exit)  */
3337         PL_warnhook = oldwarnhook;
3338         PL_diehook  = olddiehook;
3339         /* XXX note that this croak may fail as we've already blown away
3340          * the stack - eg any nested evals */
3341         Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
3342     }
3343     JMPENV_POP;
3344     PL_warnhook = oldwarnhook;
3345     PL_diehook  = olddiehook;
3346     PL_curcop = &PL_compiling;
3347
3348     if (PL_scopestack_ix > oldscope)
3349         delete_eval_scope();
3350
3351     if (ret)
3352         goto nope;
3353
3354 #ifndef PERL_MAD
3355     op_free(o);
3356 #endif
3357     assert(sv);
3358     if (type == OP_RV2GV)
3359         newop = newGVOP(OP_GV, 0, MUTABLE_GV(sv));
3360     else
3361         newop = newSVOP(OP_CONST, OPpCONST_FOLDED<<8, MUTABLE_SV(sv));
3362     op_getmad(o,newop,'f');
3363     return newop;
3364
3365  nope:
3366     return o;
3367 }
3368
3369 static OP *
3370 S_gen_constant_list(pTHX_ OP *o)
3371 {
3372     dVAR;
3373     OP *curop;
3374     const I32 oldtmps_floor = PL_tmps_floor;
3375
3376     list(o);
3377     if (PL_parser && PL_parser->error_count)
3378         return o;               /* Don't attempt to run with errors */
3379
3380     PL_op = curop = LINKLIST(o);
3381     o->op_next = 0;
3382     CALL_PEEP(curop);
3383     Perl_pp_pushmark(aTHX);
3384     CALLRUNOPS(aTHX);
3385     PL_op = curop;
3386     assert (!(curop->op_flags & OPf_SPECIAL));
3387     assert(curop->op_type == OP_RANGE);
3388     Perl_pp_anonlist(aTHX);
3389     PL_tmps_floor = oldtmps_floor;
3390
3391     o->op_type = OP_RV2AV;
3392     o->op_ppaddr = PL_ppaddr[OP_RV2AV];
3393     o->op_flags &= ~OPf_REF;    /* treat \(1..2) like an ordinary list */
3394     o->op_flags |= OPf_PARENS;  /* and flatten \(1..2,3) */
3395     o->op_opt = 0;              /* needs to be revisited in rpeep() */
3396     curop = ((UNOP*)o)->op_first;
3397     ((UNOP*)o)->op_first = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(*PL_stack_sp--));
3398 #ifdef PERL_MAD
3399     op_getmad(curop,o,'O');
3400 #else
3401     op_free(curop);
3402 #endif
3403     LINKLIST(o);
3404     return list(o);
3405 }
3406
3407 OP *
3408 Perl_convert(pTHX_ I32 type, I32 flags, OP *o)
3409 {
3410     dVAR;
3411     if (type < 0) type = -type, flags |= OPf_SPECIAL;
3412     if (!o || o->op_type != OP_LIST)
3413         o = newLISTOP(OP_LIST, 0, o, NULL);
3414     else
3415         o->op_flags &= ~OPf_WANT;
3416
3417     if (!(PL_opargs[type] & OA_MARK))
3418         op_null(cLISTOPo->op_first);
3419     else {
3420         OP * const kid2 = cLISTOPo->op_first->op_sibling;
3421         if (kid2 && kid2->op_type == OP_COREARGS) {
3422             op_null(cLISTOPo->op_first);
3423             kid2->op_private |= OPpCOREARGS_PUSHMARK;
3424         }
3425     }   
3426
3427     o->op_type = (OPCODE)type;
3428     o->op_ppaddr = PL_ppaddr[type];
3429     o->op_flags |= flags;
3430
3431     o = CHECKOP(type, o);
3432     if (o->op_type != (unsigned)type)
3433         return o;
3434
3435     return fold_constants(op_integerize(op_std_init(o)));
3436 }
3437
3438 /*
3439 =head1 Optree Manipulation Functions
3440 */
3441
3442 /* List constructors */
3443
3444 /*
3445 =for apidoc Am|OP *|op_append_elem|I32 optype|OP *first|OP *last
3446
3447 Append an item to the list of ops contained directly within a list-type
3448 op, returning the lengthened list.  I<first> is the list-type op,
3449 and I<last> is the op to append to the list.  I<optype> specifies the
3450 intended opcode for the list.  If I<first> is not already a list of the
3451 right type, it will be upgraded into one.  If either I<first> or I<last>
3452 is null, the other is returned unchanged.
3453
3454 =cut
3455 */
3456
3457 OP *
3458 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
3459 {
3460     if (!first)
3461         return last;
3462
3463     if (!last)
3464         return first;
3465
3466     if (first->op_type != (unsigned)type
3467         || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
3468     {
3469         return newLISTOP(type, 0, first, last);
3470     }
3471
3472     if (first->op_flags & OPf_KIDS)
3473         ((LISTOP*)first)->op_last->op_sibling = last;
3474     else {
3475         first->op_flags |= OPf_KIDS;
3476         ((LISTOP*)first)->op_first = last;
3477     }
3478     ((LISTOP*)first)->op_last = last;
3479     return first;
3480 }
3481
3482 /*
3483 =for apidoc Am|OP *|op_append_list|I32 optype|OP *first|OP *last
3484
3485 Concatenate the lists of ops contained directly within two list-type ops,
3486 returning the combined list.  I<first> and I<last> are the list-type ops
3487 to concatenate.  I<optype> specifies the intended opcode for the list.
3488 If either I<first> or I<last> is not already a list of the right type,
3489 it will be upgraded into one.  If either I<first> or I<last> is null,
3490 the other is returned unchanged.
3491
3492 =cut
3493 */
3494
3495 OP *
3496 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
3497 {
3498     if (!first)
3499         return last;
3500
3501     if (!last)
3502         return first;
3503
3504     if (first->op_type != (unsigned)type)
3505         return op_prepend_elem(type, first, last);
3506
3507     if (last->op_type != (unsigned)type)
3508         return op_append_elem(type, first, last);
3509
3510     ((LISTOP*)first)->op_last->op_sibling = ((LISTOP*)last)->op_first;
3511     ((LISTOP*)first)->op_last = ((LISTOP*)last)->op_last;
3512     first->op_flags |= (last->op_flags & OPf_KIDS);
3513
3514 #ifdef PERL_MAD
3515     if (((LISTOP*)last)->op_first && first->op_madprop) {
3516         MADPROP *mp = ((LISTOP*)last)->op_first->op_madprop;
3517         if (mp) {
3518             while (mp->mad_next)
3519                 mp = mp->mad_next;
3520             mp->mad_next = first->op_madprop;
3521         }
3522         else {
3523             ((LISTOP*)last)->op_first->op_madprop = first->op_madprop;
3524         }
3525     }
3526     first->op_madprop = last->op_madprop;
3527     last->op_madprop = 0;
3528 #endif
3529
3530     S_op_destroy(aTHX_ last);
3531
3532     return first;
3533 }
3534
3535 /*
3536 =for apidoc Am|OP *|op_prepend_elem|I32 optype|OP *first|OP *last
3537
3538 Prepend an item to the list of ops contained directly within a list-type
3539 op, returning the lengthened list.  I<first> is the op to prepend to the
3540 list, and I<last> is the list-type op.  I<optype> specifies the intended
3541 opcode for the list.  If I<last> is not already a list of the right type,
3542 it will be upgraded into one.  If either I<first> or I<last> is null,
3543 the other is returned unchanged.
3544
3545 =cut
3546 */
3547
3548 OP *
3549 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
3550 {
3551     if (!first)
3552         return last;
3553
3554     if (!last)
3555         return first;
3556
3557     if (last->op_type == (unsigned)type) {
3558         if (type == OP_LIST) {  /* already a PUSHMARK there */
3559             first->op_sibling = ((LISTOP*)last)->op_first->op_sibling;
3560             ((LISTOP*)last)->op_first->op_sibling = first;
3561             if (!(first->op_flags & OPf_PARENS))
3562                 last->op_flags &= ~OPf_PARENS;
3563         }
3564         else {
3565             if (!(last->op_flags & OPf_KIDS)) {
3566                 ((LISTOP*)last)->op_last = first;
3567                 last->op_flags |= OPf_KIDS;
3568             }
3569             first->op_sibling = ((LISTOP*)last)->op_first;
3570             ((LISTOP*)last)->op_first = first;
3571         }
3572         last->op_flags |= OPf_KIDS;
3573         return last;
3574     }
3575
3576     return newLISTOP(type, 0, first, last);
3577 }
3578
3579 /* Constructors */
3580
3581 #ifdef PERL_MAD
3582  
3583 TOKEN *
3584 Perl_newTOKEN(pTHX_ I32 optype, YYSTYPE lval, MADPROP* madprop)
3585 {
3586     TOKEN *tk;
3587     Newxz(tk, 1, TOKEN);
3588     tk->tk_type = (OPCODE)optype;
3589     tk->tk_type = 12345;
3590     tk->tk_lval = lval;
3591     tk->tk_mad = madprop;
3592     return tk;
3593 }
3594
3595 void
3596 Perl_token_free(pTHX_ TOKEN* tk)
3597 {
3598     PERL_ARGS_ASSERT_TOKEN_FREE;
3599
3600     if (tk->tk_type != 12345)
3601         return;
3602     mad_free(tk->tk_mad);
3603     Safefree(tk);
3604 }
3605
3606 void
3607 Perl_token_getmad(pTHX_ TOKEN* tk, OP* o, char slot)
3608 {
3609     MADPROP* mp;
3610     MADPROP* tm;
3611
3612     PERL_ARGS_ASSERT_TOKEN_GETMAD;
3613
3614     if (tk->tk_type != 12345) {
3615         Perl_warner(aTHX_ packWARN(WARN_MISC),
3616              "Invalid TOKEN object ignored");
3617         return;
3618     }
3619     tm = tk->tk_mad;
3620     if (!tm)
3621         return;
3622
3623     /* faked up qw list? */
3624     if (slot == '(' &&
3625         tm->mad_type == MAD_SV &&
3626         SvPVX((SV *)tm->mad_val)[0] == 'q')
3627             slot = 'x';
3628
3629     if (o) {
3630         mp = o->op_madprop;
3631         if (mp) {
3632             for (;;) {
3633                 /* pretend constant fold didn't happen? */
3634                 if (mp->mad_key == 'f' &&
3635                     (o->op_type == OP_CONST ||
3636                      o->op_type == OP_GV) )
3637                 {
3638                     token_getmad(tk,(OP*)mp->mad_val,slot);
3639                     return;
3640                 }
3641                 if (!mp->mad_next)
3642                     break;
3643                 mp = mp->mad_next;
3644             }
3645             mp->mad_next = tm;
3646             mp = mp->mad_next;
3647         }
3648         else {
3649             o->op_madprop = tm;
3650             mp = o->op_madprop;
3651         }
3652         if (mp->mad_key == 'X')
3653             mp->mad_key = slot; /* just change the first one */
3654
3655         tk->tk_mad = 0;
3656     }
3657     else
3658         mad_free(tm);
3659     Safefree(tk);
3660 }
3661
3662 void
3663 Perl_op_getmad_weak(pTHX_ OP* from, OP* o, char slot)
3664 {
3665     MADPROP* mp;
3666     if (!from)
3667         return;
3668     if (o) {
3669         mp = o->op_madprop;
3670         if (mp) {
3671             for (;;) {
3672                 /* pretend constant fold didn't happen? */
3673                 if (mp->mad_key == 'f' &&
3674                     (o->op_type == OP_CONST ||
3675                      o->op_type == OP_GV) )
3676                 {
3677                     op_getmad(from,(OP*)mp->mad_val,slot);
3678                     return;
3679                 }
3680                 if (!mp->mad_next)
3681                     break;
3682                 mp = mp->mad_next;
3683             }
3684             mp->mad_next = newMADPROP(slot,MAD_OP,from,0);
3685         }
3686         else {
3687             o->op_madprop = newMADPROP(slot,MAD_OP,from,0);
3688         }
3689     }
3690 }
3691
3692 void
3693 Perl_op_getmad(pTHX_ OP* from, OP* o, char slot)
3694 {
3695     MADPROP* mp;
3696     if (!from)
3697         return;
3698     if (o) {
3699         mp = o->op_madprop;
3700         if (mp) {
3701             for (;;) {
3702                 /* pretend constant fold didn't happen? */
3703                 if (mp->mad_key == 'f' &&
3704                     (o->op_type == OP_CONST ||
3705                      o->op_type == OP_GV) )
3706                 {
3707                     op_getmad(from,(OP*)mp->mad_val,slot);
3708                     return;
3709                 }
3710                 if (!mp->mad_next)
3711                     break;
3712                 mp = mp->mad_next;
3713             }
3714             mp->mad_next = newMADPROP(slot,MAD_OP,from,1);
3715         }
3716         else {
3717             o->op_madprop = newMADPROP(slot,MAD_OP,from,1);
3718         }
3719     }
3720     else {
3721         PerlIO_printf(PerlIO_stderr(),
3722                       "DESTROYING op = %0"UVxf"\n", PTR2UV(from));
3723         op_free(from);
3724     }
3725 }
3726
3727 void
3728 Perl_prepend_madprops(pTHX_ MADPROP* mp, OP* o, char slot)
3729 {
3730     MADPROP* tm;
3731     if (!mp || !o)
3732         return;
3733     if (slot)
3734         mp->mad_key = slot;
3735     tm = o->op_madprop;
3736     o->op_madprop = mp;
3737     for (;;) {
3738         if (!mp->mad_next)
3739             break;
3740         mp = mp->mad_next;
3741     }
3742     mp->mad_next = tm;
3743 }
3744
3745 void
3746 Perl_append_madprops(pTHX_ MADPROP* tm, OP* o, char slot)
3747 {
3748     if (!o)
3749         return;
3750     addmad(tm, &(o->op_madprop), slot);
3751 }
3752
3753 void
3754 Perl_addmad(pTHX_ MADPROP* tm, MADPROP** root, char slot)
3755 {
3756     MADPROP* mp;
3757     if (!tm || !root)
3758         return;
3759     if (slot)
3760         tm->mad_key = slot;
3761     mp = *root;
3762     if (!mp) {
3763         *root = tm;
3764         return;
3765     }
3766     for (;;) {
3767         if (!mp->mad_next)
3768             break;
3769         mp = mp->mad_next;
3770     }
3771     mp->mad_next = tm;
3772 }
3773
3774 MADPROP *
3775 Perl_newMADsv(pTHX_ char key, SV* sv)
3776 {
3777     PERL_ARGS_ASSERT_NEWMADSV;
3778
3779     return newMADPROP(key, MAD_SV, sv, 0);
3780 }
3781
3782 MADPROP *
3783 Perl_newMADPROP(pTHX_ char key, char type, void* val, I32 vlen)
3784 {
3785     MADPROP *const mp = (MADPROP *) PerlMemShared_malloc(sizeof(MADPROP));
3786     mp->mad_next = 0;
3787     mp->mad_key = key;
3788     mp->mad_vlen = vlen;
3789     mp->mad_type = type;
3790     mp->mad_val = val;
3791 /*    PerlIO_printf(PerlIO_stderr(), "NEW  mp = %0x\n", mp);  */
3792     return mp;
3793 }
3794
3795 void
3796 Perl_mad_free(pTHX_ MADPROP* mp)
3797 {
3798 /*    PerlIO_printf(PerlIO_stderr(), "FREE mp = %0x\n", mp); */
3799     if (!mp)
3800         return;
3801     if (mp->mad_next)
3802         mad_free(mp->mad_next);
3803 /*    if (PL_parser && PL_parser->lex_state != LEX_NOTPARSING && mp->mad_vlen)
3804         PerlIO_printf(PerlIO_stderr(), "DESTROYING '%c'=<%s>\n", mp->mad_key & 255, mp->mad_val); */
3805     switch (mp->mad_type) {
3806     case MAD_NULL:
3807         break;
3808     case MAD_PV:
3809         Safefree(mp->mad_val);
3810         break;
3811     case MAD_OP:
3812         if (mp->mad_vlen)       /* vlen holds "strong/weak" boolean */
3813             op_free((OP*)mp->mad_val);
3814         break;
3815     case MAD_SV:
3816         sv_free(MUTABLE_SV(mp->mad_val));
3817         break;
3818     default:
3819         PerlIO_printf(PerlIO_stderr(), "Unrecognized mad\n");
3820         break;
3821     }
3822     PerlMemShared_free(mp);
3823 }
3824
3825 #endif
3826
3827 /*
3828 =head1 Optree construction
3829
3830 =for apidoc Am|OP *|newNULLLIST
3831
3832 Constructs, checks, and returns a new C<stub> op, which represents an
3833 empty list expression.
3834
3835 =cut
3836 */
3837
3838 OP *
3839 Perl_newNULLLIST(pTHX)
3840 {
3841     return newOP(OP_STUB, 0);
3842 }
3843
3844 static OP *
3845 S_force_list(pTHX_ OP *o)
3846 {
3847     if (!o || o->op_type != OP_LIST)
3848         o = newLISTOP(OP_LIST, 0, o, NULL);
3849     op_null(o);
3850     return o;
3851 }
3852
3853 /*
3854 =for apidoc Am|OP *|newLISTOP|I32 type|I32 flags|OP *first|OP *last
3855
3856 Constructs, checks, and returns an op of any list type.  I<type> is
3857 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
3858 C<OPf_KIDS> will be set automatically if required.  I<first> and I<last>
3859 supply up to two ops to be direct children of the list op; they are
3860 consumed by this function and become part of the constructed op tree.
3861
3862 =cut
3863 */
3864
3865 OP *
3866 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
3867 {
3868     dVAR;
3869     LISTOP *listop;
3870
3871     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP);
3872
3873     NewOp(1101, listop, 1, LISTOP);
3874
3875     listop->op_type = (OPCODE)type;
3876     listop->op_ppaddr = PL_ppaddr[type];
3877     if (first || last)
3878         flags |= OPf_KIDS;
3879     listop->op_flags = (U8)flags;
3880
3881     if (!last && first)
3882         last = first;
3883     else if (!first && last)
3884         first = last;
3885     else if (first)
3886         first->op_sibling = last;
3887     listop->op_first = first;
3888     listop->op_last = last;
3889     if (type == OP_LIST) {
3890         OP* const pushop = newOP(OP_PUSHMARK, 0);
3891         pushop->op_sibling = first;
3892         listop->op_first = pushop;
3893         listop->op_flags |= OPf_KIDS;
3894         if (!last)
3895             listop->op_last = pushop;
3896     }
3897
3898     return CHECKOP(type, listop);
3899 }
3900
3901 /*
3902 =for apidoc Am|OP *|newOP|I32 type|I32 flags
3903
3904 Constructs, checks, and returns an op of any base type (any type that
3905 has no extra fields).  I<type> is the opcode.  I<flags> gives the
3906 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
3907 of C<op_private>.
3908
3909 =cut
3910 */
3911
3912 OP *
3913 Perl_newOP(pTHX_ I32 type, I32 flags)
3914 {
3915     dVAR;
3916     OP *o;
3917
3918     if (type == -OP_ENTEREVAL) {
3919         type = OP_ENTEREVAL;
3920         flags |= OPpEVAL_BYTES<<8;
3921     }
3922
3923     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
3924         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
3925         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
3926         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
3927
3928     NewOp(1101, o, 1, OP);
3929     o->op_type = (OPCODE)type;
3930     o->op_ppaddr = PL_ppaddr[type];
3931     o->op_flags = (U8)flags;
3932
3933     o->op_next = o;
3934     o->op_private = (U8)(0 | (flags >> 8));
3935     if (PL_opargs[type] & OA_RETSCALAR)
3936         scalar(o);
3937     if (PL_opargs[type] & OA_TARGET)
3938         o->op_targ = pad_alloc(type, SVs_PADTMP);
3939     return CHECKOP(type, o);
3940 }
3941
3942 /*
3943 =for apidoc Am|OP *|newUNOP|I32 type|I32 flags|OP *first
3944
3945 Constructs, checks, and returns an op of any unary type.  I<type> is
3946 the opcode.  I<flags> gives the eight bits of C<op_flags>, except that
3947 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
3948 bits, the eight bits of C<op_private>, except that the bit with value 1
3949 is automatically set.  I<first> supplies an optional op to be the direct
3950 child of the unary op; it is consumed by this function and become part
3951 of the constructed op tree.
3952
3953 =cut
3954 */
3955
3956 OP *
3957 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
3958 {
3959     dVAR;
3960     UNOP *unop;
3961
3962     if (type == -OP_ENTEREVAL) {
3963         type = OP_ENTEREVAL;
3964         flags |= OPpEVAL_BYTES<<8;
3965     }
3966
3967     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
3968         || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
3969         || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
3970         || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
3971         || type == OP_SASSIGN
3972         || type == OP_ENTERTRY
3973         || type == OP_NULL );
3974
3975     if (!first)
3976         first = newOP(OP_STUB, 0);
3977     if (PL_opargs[type] & OA_MARK)
3978         first = force_list(first);
3979
3980     NewOp(1101, unop, 1, UNOP);
3981     unop->op_type = (OPCODE)type;
3982     unop->op_ppaddr = PL_ppaddr[type];
3983     unop->op_first = first;
3984     unop->op_flags = (U8)(flags | OPf_KIDS);
3985     unop->op_private = (U8)(1 | (flags >> 8));
3986     unop = (UNOP*) CHECKOP(type, unop);
3987     if (unop->op_next)
3988         return (OP*)unop;
3989
3990     return fold_constants(op_integerize(op_std_init((OP *) unop)));
3991 }
3992
3993 /*
3994 =for apidoc Am|OP *|newBINOP|I32 type|I32 flags|OP *first|OP *last
3995
3996 Constructs, checks, and returns an op of any binary type.  I<type>
3997 is the opcode.  I<flags> gives the eight bits of C<op_flags>, except
3998 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
3999 the eight bits of C<op_private>, except that the bit with value 1 or
4000 2 is automatically set as required.  I<first> and I<last> supply up to
4001 two ops to be the direct children of the binary op; they are consumed
4002 by this function and become part of the constructed op tree.
4003
4004 =cut
4005 */
4006
4007 OP *
4008 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
4009 {
4010     dVAR;
4011     BINOP *binop;
4012
4013     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
4014         || type == OP_SASSIGN || type == OP_NULL );
4015
4016     NewOp(1101, binop, 1, BINOP);
4017
4018     if (!first)
4019         first = newOP(OP_NULL, 0);
4020
4021     binop->op_type = (OPCODE)type;
4022     binop->op_ppaddr = PL_ppaddr[type];
4023     binop->op_first = first;
4024     binop->op_flags = (U8)(flags | OPf_KIDS);
4025     if (!last) {
4026         last = first;
4027         binop->op_private = (U8)(1 | (flags >> 8));
4028     }
4029     else {
4030         binop->op_private = (U8)(2 | (flags >> 8));
4031         first->op_sibling = last;
4032     }
4033
4034     binop = (BINOP*)CHECKOP(type, binop);
4035     if (binop->op_next || binop->op_type != (OPCODE)type)
4036         return (OP*)binop;
4037
4038     binop->op_last = binop->op_first->op_sibling;
4039
4040     return fold_constants(op_integerize(op_std_init((OP *)binop)));
4041 }
4042
4043 static int uvcompare(const void *a, const void *b)
4044     __attribute__nonnull__(1)
4045     __attribute__nonnull__(2)
4046     __attribute__pure__;
4047 static int uvcompare(const void *a, const void *b)
4048 {
4049     if (*((const UV *)a) < (*(const UV *)b))
4050         return -1;
4051     if (*((const UV *)a) > (*(const UV *)b))
4052         return 1;
4053     if (*((const UV *)a+1) < (*(const UV *)b+1))
4054         return -1;
4055     if (*((const UV *)a+1) > (*(const UV *)b+1))
4056         return 1;
4057     return 0;
4058 }
4059
4060 static OP *
4061 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
4062 {
4063     dVAR;
4064     SV * const tstr = ((SVOP*)expr)->op_sv;
4065     SV * const rstr =
4066 #ifdef PERL_MAD
4067                         (repl->op_type == OP_NULL)
4068                             ? ((SVOP*)((LISTOP*)repl)->op_first)->op_sv :
4069 #endif
4070                               ((SVOP*)repl)->op_sv;
4071     STRLEN tlen;
4072     STRLEN rlen;
4073     const U8 *t = (U8*)SvPV_const(tstr, tlen);
4074     const U8 *r = (U8*)SvPV_const(rstr, rlen);
4075     I32 i;
4076     I32 j;
4077     I32 grows = 0;
4078     short *tbl;
4079
4080     const I32 complement = o->op_private & OPpTRANS_COMPLEMENT;
4081     const I32 squash     = o->op_private & OPpTRANS_SQUASH;
4082     I32 del              = o->op_private & OPpTRANS_DELETE;
4083     SV* swash;
4084
4085     PERL_ARGS_ASSERT_PMTRANS;
4086
4087     PL_hints |= HINT_BLOCK_SCOPE;
4088
4089     if (SvUTF8(tstr))
4090         o->op_private |= OPpTRANS_FROM_UTF;
4091
4092     if (SvUTF8(rstr))
4093         o->op_private |= OPpTRANS_TO_UTF;
4094
4095     if (o->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF)) {
4096         SV* const listsv = newSVpvs("# comment\n");
4097         SV* transv = NULL;
4098         const U8* tend = t + tlen;
4099         const U8* rend = r + rlen;
4100         STRLEN ulen;
4101         UV tfirst = 1;
4102         UV tlast = 0;
4103         IV tdiff;
4104         UV rfirst = 1;
4105         UV rlast = 0;
4106         IV rdiff;
4107         IV diff;
4108         I32 none = 0;
4109         U32 max = 0;
4110         I32 bits;
4111         I32 havefinal = 0;
4112         U32 final = 0;
4113         const I32 from_utf  = o->op_private & OPpTRANS_FROM_UTF;
4114         const I32 to_utf    = o->op_private & OPpTRANS_TO_UTF;
4115         U8* tsave = NULL;
4116         U8* rsave = NULL;
4117         const U32 flags = UTF8_ALLOW_DEFAULT;
4118
4119         if (!from_utf) {
4120             STRLEN len = tlen;
4121             t = tsave = bytes_to_utf8(t, &len);
4122             tend = t + len;
4123         }
4124         if (!to_utf && rlen) {
4125             STRLEN len = rlen;
4126             r = rsave = bytes_to_utf8(r, &len);
4127             rend = r + len;
4128         }
4129
4130 /* There are several snags with this code on EBCDIC:
4131    1. 0xFF is a legal UTF-EBCDIC byte (there are no illegal bytes).
4132    2. scan_const() in toke.c has encoded chars in native encoding which makes
4133       ranges at least in EBCDIC 0..255 range the bottom odd.
4134 */
4135
4136         if (complement) {
4137             U8 tmpbuf[UTF8_MAXBYTES+1];
4138             UV *cp;
4139             UV nextmin = 0;
4140             Newx(cp, 2*tlen, UV);
4141             i = 0;
4142             transv = newSVpvs("");
4143             while (t < tend) {
4144                 cp[2*i] = utf8n_to_uvuni(t, tend-t, &ulen, flags);
4145                 t += ulen;
4146                 if (t < tend && NATIVE_TO_UTF(*t) == 0xff) {
4147                     t++;
4148                     cp[2*i+1] = utf8n_to_uvuni(t, tend-t, &ulen, flags);
4149                     t += ulen;
4150                 }
4151                 else {
4152                  cp[2*i+1] = cp[2*i];
4153                 }
4154                 i++;
4155             }
4156             qsort(cp, i, 2*sizeof(UV), uvcompare);
4157             for (j = 0; j < i; j++) {
4158                 UV  val = cp[2*j];
4159                 diff = val - nextmin;
4160                 if (diff > 0) {
4161                     t = uvuni_to_utf8(tmpbuf,nextmin);
4162                     sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4163                     if (diff > 1) {
4164                         U8  range_mark = UTF_TO_NATIVE(0xff);
4165                         t = uvuni_to_utf8(tmpbuf, val - 1);
4166                         sv_catpvn(transv, (char *)&range_mark, 1);
4167                         sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4168                     }
4169                 }
4170                 val = cp[2*j+1];
4171                 if (val >= nextmin)
4172                     nextmin = val + 1;
4173             }
4174             t = uvuni_to_utf8(tmpbuf,nextmin);
4175             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4176             {
4177                 U8 range_mark = UTF_TO_NATIVE(0xff);
4178                 sv_catpvn(transv, (char *)&range_mark, 1);
4179             }
4180             t = uvuni_to_utf8(tmpbuf, 0x7fffffff);
4181             sv_catpvn(transv, (char*)tmpbuf, t - tmpbuf);
4182             t = (const U8*)SvPVX_const(transv);
4183             tlen = SvCUR(transv);
4184             tend = t + tlen;
4185             Safefree(cp);
4186         }
4187         else if (!rlen && !del) {
4188             r = t; rlen = tlen; rend = tend;
4189         }
4190         if (!squash) {
4191                 if ((!rlen && !del) || t == r ||
4192                     (tlen == rlen && memEQ((char *)t, (char *)r, tlen)))
4193                 {
4194                     o->op_private |= OPpTRANS_IDENTICAL;
4195                 }
4196         }
4197
4198         while (t < tend || tfirst <= tlast) {
4199             /* see if we need more "t" chars */
4200             if (tfirst > tlast) {
4201                 tfirst = (I32)utf8n_to_uvuni(t, tend - t, &ulen, flags);
4202                 t += ulen;
4203                 if (t < tend && NATIVE_TO_UTF(*t) == 0xff) {    /* illegal utf8 val indicates range */
4204                     t++;
4205                     tlast = (I32)utf8n_to_uvuni(t, tend - t, &ulen, flags);
4206                     t += ulen;
4207                 }
4208                 else
4209                     tlast = tfirst;
4210             }
4211
4212             /* now see if we need more "r" chars */
4213             if (rfirst > rlast) {
4214                 if (r < rend) {
4215                     rfirst = (I32)utf8n_to_uvuni(r, rend - r, &ulen, flags);
4216                     r += ulen;
4217                     if (r < rend && NATIVE_TO_UTF(*r) == 0xff) {        /* illegal utf8 val indicates range */
4218                         r++;
4219                         rlast = (I32)utf8n_to_uvuni(r, rend - r, &ulen, flags);
4220                         r += ulen;
4221                     }
4222                     else
4223                         rlast = rfirst;
4224                 }
4225                 else {
4226                     if (!havefinal++)
4227                         final = rlast;
4228                     rfirst = rlast = 0xffffffff;
4229                 }
4230             }
4231
4232             /* now see which range will peter our first, if either. */
4233             tdiff = tlast - tfirst;
4234             rdiff = rlast - rfirst;
4235
4236             if (tdiff <= rdiff)
4237                 diff = tdiff;
4238             else
4239                 diff = rdiff;
4240
4241             if (rfirst == 0xffffffff) {
4242                 diff = tdiff;   /* oops, pretend rdiff is infinite */
4243                 if (diff > 0)
4244                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\tXXXX\n",
4245                                    (long)tfirst, (long)tlast);
4246                 else
4247                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\tXXXX\n", (long)tfirst);
4248             }
4249             else {
4250                 if (diff > 0)
4251                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t%04lx\t%04lx\n",
4252                                    (long)tfirst, (long)(tfirst + diff),
4253                                    (long)rfirst);
4254                 else
4255                     Perl_sv_catpvf(aTHX_ listsv, "%04lx\t\t%04lx\n",
4256                                    (long)tfirst, (long)rfirst);
4257
4258                 if (rfirst + diff > max)
4259                     max = rfirst + diff;
4260                 if (!grows)
4261                     grows = (tfirst < rfirst &&
4262                              UNISKIP(tfirst) < UNISKIP(rfirst + diff));
4263                 rfirst += diff + 1;
4264             }
4265             tfirst += diff + 1;
4266         }
4267
4268         none = ++max;
4269         if (del)
4270             del = ++max;
4271
4272         if (max > 0xffff)
4273             bits = 32;
4274         else if (max > 0xff)
4275             bits = 16;
4276         else
4277             bits = 8;
4278
4279         swash = MUTABLE_SV(swash_init("utf8", "", listsv, bits, none));
4280 #ifdef USE_ITHREADS
4281         cPADOPo->op_padix = pad_alloc(OP_TRANS, SVs_PADTMP);
4282         SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
4283         PAD_SETSV(cPADOPo->op_padix, swash);
4284         SvPADTMP_on(swash);
4285         SvREADONLY_on(swash);
4286 #else
4287         cSVOPo->op_sv = swash;
4288 #endif
4289         SvREFCNT_dec(listsv);
4290         SvREFCNT_dec(transv);
4291
4292         if (!del && havefinal && rlen)
4293             (void)hv_store(MUTABLE_HV(SvRV(swash)), "FINAL", 5,
4294                            newSVuv((UV)final), 0);
4295
4296         if (grows)
4297             o->op_private |= OPpTRANS_GROWS;
4298
4299         Safefree(tsave);
4300         Safefree(rsave);
4301
4302 #ifdef PERL_MAD
4303         op_getmad(expr,o,'e');
4304         op_getmad(repl,o,'r');
4305 #else
4306         op_free(expr);
4307         op_free(repl);
4308 #endif
4309         return o;
4310     }
4311
4312     tbl = (short*)PerlMemShared_calloc(
4313         (o->op_private & OPpTRANS_COMPLEMENT) &&
4314             !(o->op_private & OPpTRANS_DELETE) ? 258 : 256,
4315         sizeof(short));
4316     cPVOPo->op_pv = (char*)tbl;
4317     if (complement) {
4318         for (i = 0; i < (I32)tlen; i++)
4319             tbl[t[i]] = -1;
4320         for (i = 0, j = 0; i < 256; i++) {
4321             if (!tbl[i]) {
4322                 if (j >= (I32)rlen) {
4323                     if (del)
4324                         tbl[i] = -2;
4325                     else if (rlen)
4326                         tbl[i] = r[j-1];
4327                     else
4328                         tbl[i] = (short)i;
4329                 }
4330                 else {
4331                     if (i < 128 && r[j] >= 128)
4332                         grows = 1;
4333                     tbl[i] = r[j++];
4334                 }
4335             }
4336         }
4337         if (!del) {
4338             if (!rlen) {
4339                 j = rlen;
4340                 if (!squash)
4341                     o->op_private |= OPpTRANS_IDENTICAL;
4342             }
4343             else if (j >= (I32)rlen)
4344                 j = rlen - 1;
4345             else {
4346                 tbl = 
4347                     (short *)
4348                     PerlMemShared_realloc(tbl,
4349                                           (0x101+rlen-j) * sizeof(short));
4350                 cPVOPo->op_pv = (char*)tbl;
4351             }
4352             tbl[0x100] = (short)(rlen - j);
4353             for (i=0; i < (I32)rlen - j; i++)
4354                 tbl[0x101+i] = r[j+i];
4355         }
4356     }
4357     else {
4358         if (!rlen && !del) {
4359             r = t; rlen = tlen;
4360             if (!squash)
4361                 o->op_private |= OPpTRANS_IDENTICAL;
4362         }
4363         else if (!squash && rlen == tlen && memEQ((char*)t, (char*)r, tlen)) {
4364             o->op_private |= OPpTRANS_IDENTICAL;
4365         }
4366         for (i = 0; i < 256; i++)
4367             tbl[i] = -1;
4368         for (i = 0, j = 0; i < (I32)tlen; i++,j++) {
4369             if (j >= (I32)rlen) {
4370                 if (del) {
4371                     if (tbl[t[i]] == -1)
4372                         tbl[t[i]] = -2;
4373                     continue;
4374                 }
4375                 --j;
4376             }
4377             if (tbl[t[i]] == -1) {
4378                 if (t[i] < 128 && r[j] >= 128)
4379                     grows = 1;
4380                 tbl[t[i]] = r[j];
4381             }
4382         }
4383     }
4384
4385     if(del && rlen == tlen) {
4386         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator"); 
4387     } else if(rlen > tlen && !complement) {
4388         Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
4389     }
4390
4391     if (grows)
4392         o->op_private |= OPpTRANS_GROWS;
4393 #ifdef PERL_MAD
4394     op_getmad(expr,o,'e');
4395     op_getmad(repl,o,'r');
4396 #else
4397     op_free(expr);
4398     op_free(repl);
4399 #endif
4400
4401     return o;
4402 }
4403
4404 /*
4405 =for apidoc Am|OP *|newPMOP|I32 type|I32 flags
4406
4407 Constructs, checks, and returns an op of any pattern matching type.
4408 I<type> is the opcode.  I<flags> gives the eight bits of C<op_flags>
4409 and, shifted up eight bits, the eight bits of C<op_private>.
4410
4411 =cut
4412 */
4413
4414 OP *
4415 Perl_newPMOP(pTHX_ I32 type, I32 flags)
4416 {
4417     dVAR;
4418     PMOP *pmop;
4419
4420     assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP);
4421
4422     NewOp(1101, pmop, 1, PMOP);
4423     pmop->op_type = (OPCODE)type;
4424     pmop->op_ppaddr = PL_ppaddr[type];
4425     pmop->op_flags = (U8)flags;
4426     pmop->op_private = (U8)(0 | (flags >> 8));
4427
4428     if (PL_hints & HINT_RE_TAINT)
4429         pmop->op_pmflags |= PMf_RETAINT;
4430     if (IN_LOCALE_COMPILETIME) {
4431         set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
4432     }
4433     else if ((! (PL_hints & HINT_BYTES))
4434                 /* Both UNI_8_BIT and locale :not_characters imply Unicode */
4435              && (PL_hints & (HINT_UNI_8_BIT|HINT_LOCALE_NOT_CHARS)))
4436     {
4437         set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
4438     }
4439     if (PL_hints & HINT_RE_FLAGS) {
4440         SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4441          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
4442         );
4443         if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
4444         reflags = Perl_refcounted_he_fetch_pvn(aTHX_
4445          PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
4446         );
4447         if (reflags && SvOK(reflags)) {
4448             set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
4449         }
4450     }
4451
4452
4453 #ifdef USE_ITHREADS
4454     assert(SvPOK(PL_regex_pad[0]));
4455     if (SvCUR(PL_regex_pad[0])) {
4456         /* Pop off the "packed" IV from the end.  */
4457         SV *const repointer_list = PL_regex_pad[0];
4458         const char *p = SvEND(repointer_list) - sizeof(IV);
4459         const IV offset = *((IV*)p);
4460
4461         assert(SvCUR(repointer_list) % sizeof(IV) == 0);
4462
4463         SvEND_set(repointer_list, p);
4464
4465         pmop->op_pmoffset = offset;
4466         /* This slot should be free, so assert this:  */
4467         assert(PL_regex_pad[offset] == &PL_sv_undef);
4468     } else {
4469         SV * const repointer = &PL_sv_undef;
4470         av_push(PL_regex_padav, repointer);
4471         pmop->op_pmoffset = av_len(PL_regex_padav);
4472         PL_regex_pad = AvARRAY(PL_regex_padav);
4473     }
4474 #endif
4475
4476     return CHECKOP(type, pmop);
4477 }
4478
4479 /* Given some sort of match op o, and an expression expr containing a
4480  * pattern, either compile expr into a regex and attach it to o (if it's
4481  * constant), or convert expr into a runtime regcomp op sequence (if it's
4482  * not)
4483  *
4484  * isreg indicates that the pattern is part of a regex construct, eg
4485  * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
4486  * split "pattern", which aren't. In the former case, expr will be a list
4487  * if the pattern contains more than one term (eg /a$b/) or if it contains
4488  * a replacement, ie s/// or tr///.
4489  *
4490  * When the pattern has been compiled within a new anon CV (for
4491  * qr/(?{...})/ ), then floor indicates the savestack level just before
4492  * the new sub was created
4493  */
4494
4495 OP *
4496 Perl_pmruntime(pTHX_ OP *o, OP *expr, bool isreg, I32 floor)
4497 {
4498     dVAR;
4499     PMOP *pm;
4500     LOGOP *rcop;
4501     I32 repl_has_vars = 0;
4502     OP* repl = NULL;
4503     bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
4504     bool is_compiletime;
4505     bool has_code;
4506
4507     PERL_ARGS_ASSERT_PMRUNTIME;
4508
4509     /* for s/// and tr///, last element in list is the replacement; pop it */
4510
4511     if (is_trans || o->op_type == OP_SUBST) {
4512         OP* kid;
4513         repl = cLISTOPx(expr)->op_last;
4514         kid = cLISTOPx(expr)->op_first;
4515         while (kid->op_sibling != repl)
4516             kid = kid->op_sibling;
4517         kid->op_sibling = NULL;
4518         cLISTOPx(expr)->op_last = kid;
4519     }
4520
4521     /* for TRANS, convert LIST/PUSH/CONST into CONST, and pass to pmtrans() */
4522
4523     if (is_trans) {
4524         OP* const oe = expr;
4525         assert(expr->op_type == OP_LIST);
4526         assert(cLISTOPx(expr)->op_first->op_type == OP_PUSHMARK);
4527         assert(cLISTOPx(expr)->op_first->op_sibling == cLISTOPx(expr)->op_last);
4528         expr = cLISTOPx(oe)->op_last;
4529         cLISTOPx(oe)->op_first->op_sibling = NULL;
4530         cLISTOPx(oe)->op_last = NULL;
4531         op_free(oe);
4532
4533         return pmtrans(o, expr, repl);
4534     }
4535
4536     /* find whether we have any runtime or code elements;
4537      * at the same time, temporarily set the op_next of each DO block;
4538      * then when we LINKLIST, this will cause the DO blocks to be excluded
4539      * from the op_next chain (and from having LINKLIST recursively
4540      * applied to them). We fix up the DOs specially later */
4541
4542     is_compiletime = 1;
4543     has_code = 0;
4544     if (expr->op_type == OP_LIST) {
4545         OP *o;
4546         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
4547             if (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)) {
4548                 has_code = 1;
4549                 assert(!o->op_next && o->op_sibling);
4550                 o->op_next = o->op_sibling;
4551             }
4552             else if (o->op_type != OP_CONST && o->op_type != OP_PUSHMARK)
4553                 is_compiletime = 0;
4554         }
4555     }
4556     else if (expr->op_type != OP_CONST)
4557         is_compiletime = 0;
4558
4559     LINKLIST(expr);
4560
4561     /* fix up DO blocks; treat each one as a separate little sub;
4562      * also, mark any arrays as LIST/REF */
4563
4564     if (expr->op_type == OP_LIST) {
4565         OP *o;
4566         for (o = cLISTOPx(expr)->op_first; o; o = o->op_sibling) {
4567
4568             if (o->op_type == OP_PADAV || o->op_type == OP_RV2AV) {
4569                 assert( !(o->op_flags  & OPf_WANT));
4570                 /* push the array rather than its contents. The regex
4571                  * engine will retrieve and join the elements later */
4572                 o->op_flags |= (OPf_WANT_LIST | OPf_REF);
4573                 continue;
4574             }
4575
4576             if (!(o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)))
4577                 continue;
4578             o->op_next = NULL; /* undo temporary hack from above */
4579             scalar(o);
4580             LINKLIST(o);
4581             if (cLISTOPo->op_first->op_type == OP_LEAVE) {
4582                 LISTOP *leaveop = cLISTOPx(cLISTOPo->op_first);
4583                 /* skip ENTER */
4584                 assert(leaveop->op_first->op_type == OP_ENTER);
4585                 assert(leaveop->op_first->op_sibling);
4586                 o->op_next = leaveop->op_first->op_sibling;
4587                 /* skip leave */
4588                 assert(leaveop->op_flags & OPf_KIDS);
4589                 assert(leaveop->op_last->op_next == (OP*)leaveop);
4590                 leaveop->op_next = NULL; /* stop on last op */
4591                 op_null((OP*)leaveop);
4592             }
4593             else {
4594                 /* skip SCOPE */
4595                 OP *scope = cLISTOPo->op_first;
4596                 assert(scope->op_type == OP_SCOPE);
4597                 assert(scope->op_flags & OPf_KIDS);
4598                 scope->op_next = NULL; /* stop on last op */
4599                 op_null(scope);
4600             }
4601             /* have to peep the DOs individually as we've removed it from
4602              * the op_next chain */
4603             CALL_PEEP(o);
4604             if (is_compiletime)
4605                 /* runtime finalizes as part of finalizing whole tree */
4606                 finalize_optree(o);
4607         }
4608     }
4609     else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
4610         assert( !(expr->op_flags  & OPf_WANT));
4611         /* push the array rather than its contents. The regex
4612          * engine will retrieve and join the elements later */
4613         expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
4614     }
4615
4616     PL_hints |= HINT_BLOCK_SCOPE;
4617     pm = (PMOP*)o;
4618     assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
4619
4620     if (is_compiletime) {
4621         U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
4622         regexp_engine const *eng = current_re_engine();
4623
4624         if (o->op_flags & OPf_SPECIAL)
4625             rx_flags |= RXf_SPLIT;
4626
4627         if (!has_code || !eng->op_comp) {
4628             /* compile-time simple constant pattern */
4629
4630             if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
4631                 /* whoops! we guessed that a qr// had a code block, but we
4632                  * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
4633                  * that isn't required now. Note that we have to be pretty
4634                  * confident that nothing used that CV's pad while the
4635                  * regex was parsed */
4636                 assert(AvFILLp(PL_comppad) == 0); /* just @_ */
4637                 /* But we know that one op is using this CV's slab. */
4638                 cv_forget_slab(PL_compcv);
4639                 LEAVE_SCOPE(floor);
4640                 pm->op_pmflags &= ~PMf_HAS_CV;
4641             }
4642
4643             PM_SETRE(pm,
4644                 eng->op_comp
4645                     ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4646                                         rx_flags, pm->op_pmflags)
4647                     : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4648                                         rx_flags, pm->op_pmflags)
4649             );
4650 #ifdef PERL_MAD
4651             op_getmad(expr,(OP*)pm,'e');
4652 #else
4653             op_free(expr);
4654 #endif
4655         }
4656         else {
4657             /* compile-time pattern that includes literal code blocks */
4658             REGEXP* re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
4659                         rx_flags,
4660                         (pm->op_pmflags |
4661                             ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
4662                     );
4663             PM_SETRE(pm, re);
4664             if (pm->op_pmflags & PMf_HAS_CV) {
4665                 CV *cv;
4666                 /* this QR op (and the anon sub we embed it in) is never
4667                  * actually executed. It's just a placeholder where we can
4668                  * squirrel away expr in op_code_list without the peephole
4669                  * optimiser etc processing it for a second time */
4670                 OP *qr = newPMOP(OP_QR, 0);
4671                 ((PMOP*)qr)->op_code_list = expr;
4672
4673                 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
4674                 SvREFCNT_inc_simple_void(PL_compcv);
4675                 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
4676                 ReANY(re)->qr_anoncv = cv;
4677
4678                 /* attach the anon CV to the pad so that
4679                  * pad_fixup_inner_anons() can find it */
4680                 (void)pad_add_anon(cv, o->op_type);
4681                 SvREFCNT_inc_simple_void(cv);
4682             }
4683             else {
4684                 pm->op_code_list = expr;
4685             }
4686         }
4687     }
4688     else {
4689         /* runtime pattern: build chain of regcomp etc ops */
4690         bool reglist;
4691         PADOFFSET cv_targ = 0;
4692
4693         reglist = isreg && expr->op_type == OP_LIST;
4694         if (reglist)
4695             op_null(expr);
4696
4697         if (has_code) {
4698             pm->op_code_list = expr;
4699             /* don't free op_code_list; its ops are embedded elsewhere too */
4700             pm->op_pmflags |= PMf_CODELIST_PRIVATE;
4701         }
4702
4703         if (o->op_flags & OPf_SPECIAL)
4704             pm->op_pmflags |= PMf_SPLIT;
4705
4706         /* the OP_REGCMAYBE is a placeholder in the non-threaded case
4707          * to allow its op_next to be pointed past the regcomp and
4708          * preceding stacking ops;
4709          * OP_REGCRESET is there to reset taint before executing the
4710          * stacking ops */
4711         if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
4712             expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
4713
4714         if (pm->op_pmflags & PMf_HAS_CV) {
4715             /* we have a runtime qr with literal code. This means
4716              * that the qr// has been wrapped in a new CV, which
4717              * means that runtime consts, vars etc will have been compiled
4718              * against a new pad. So... we need to execute those ops
4719              * within the environment of the new CV. So wrap them in a call
4720              * to a new anon sub. i.e. for
4721              *
4722              *     qr/a$b(?{...})/,
4723              *
4724              * we build an anon sub that looks like
4725              *
4726              *     sub { "a", $b, '(?{...})' }
4727              *
4728              * and call it, passing the returned list to regcomp.
4729              * Or to put it another way, the list of ops that get executed
4730              * are:
4731              *
4732              *     normal              PMf_HAS_CV
4733              *     ------              -------------------
4734              *                         pushmark (for regcomp)
4735              *                         pushmark (for entersub)
4736              *                         pushmark (for refgen)
4737              *                         anoncode
4738              *                         refgen
4739              *                         entersub
4740              *     regcreset                  regcreset
4741              *     pushmark                   pushmark
4742              *     const("a")                 const("a")
4743              *     gvsv(b)                    gvsv(b)
4744              *     const("(?{...})")          const("(?{...})")
4745              *                                leavesub
4746              *     regcomp             regcomp
4747              */
4748
4749             SvREFCNT_inc_simple_void(PL_compcv);
4750             /* these lines are just an unrolled newANONATTRSUB */
4751             expr = newSVOP(OP_ANONCODE, 0,
4752                     MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
4753             cv_targ = expr->op_targ;
4754             expr = newUNOP(OP_REFGEN, 0, expr);
4755
4756             expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr))));
4757         }
4758
4759         NewOp(1101, rcop, 1, LOGOP);
4760         rcop->op_type = OP_REGCOMP;
4761         rcop->op_ppaddr = PL_ppaddr[OP_REGCOMP];
4762         rcop->op_first = scalar(expr);
4763         rcop->op_flags |= OPf_KIDS
4764                             | ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
4765                             | (reglist ? OPf_STACKED : 0);
4766         rcop->op_private = 0;
4767         rcop->op_other = o;
4768         rcop->op_targ = cv_targ;
4769
4770         /* /$x/ may cause an eval, since $x might be qr/(?{..})/  */
4771         if (PL_hints & HINT_RE_EVAL) PL_cv_has_eval = 1;
4772
4773         /* establish postfix order */
4774         if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
4775             LINKLIST(expr);
4776             rcop->op_next = expr;
4777             ((UNOP*)expr)->op_first->op_next = (OP*)rcop;
4778         }
4779         else {
4780             rcop->op_next = LINKLIST(expr);
4781             expr->op_next = (OP*)rcop;
4782         }
4783
4784         op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
4785     }
4786
4787     if (repl) {
4788         OP *curop = repl;
4789         bool konst;
4790         if (pm->op_pmflags & PMf_EVAL) {
4791             if (CopLINE(PL_curcop) < (line_t)PL_parser->multi_end)
4792                 CopLINE_set(PL_curcop, (line_t)PL_parser->multi_end);
4793         }
4794         /* If we are looking at s//.../e with a single statement, get past
4795            the implicit do{}. */
4796         if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
4797          && cUNOPx(curop)->op_first->op_type == OP_SCOPE
4798          && cUNOPx(curop)->op_first->op_flags & OPf_KIDS) {
4799             OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
4800             if (kid->op_type == OP_NULL && kid->op_sibling
4801              && !kid->op_sibling->op_sibling)
4802                 curop = kid->op_sibling;
4803         }
4804         if (curop->op_type == OP_CONST)
4805             konst = TRUE;
4806         else if (( (curop->op_type == OP_RV2SV ||
4807                     curop->op_type == OP_RV2AV ||
4808                     curop->op_type == OP_RV2HV ||
4809                     curop->op_type == OP_RV2GV)
4810                    && cUNOPx(curop)->op_first
4811                    && cUNOPx(curop)->op_first->op_type == OP_GV )
4812                 || curop->op_type == OP_PADSV
4813                 || curop->op_type == OP_PADAV
4814                 || curop->op_type == OP_PADHV
4815                 || curop->op_type == OP_PADANY) {
4816             repl_has_vars = 1;
4817             konst = TRUE;
4818         }
4819         else konst = FALSE;
4820         if (konst
4821             && !(repl_has_vars