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