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
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.
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
19 * [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
22 /* This file contains the functions that create and manipulate the OP
23 * structures that hold a compiled perl program.
25 * Note that during the build of miniperl, a temporary copy of this file
26 * is made, called opmini.c.
28 * A Perl program is compiled into a tree of OP nodes. Each op contains:
29 * * structural OP pointers to its children and siblings (op_sibling,
30 * op_first etc) that define the tree structure;
31 * * execution order OP pointers (op_next, plus sometimes op_other,
32 * op_lastop etc) that define the execution sequence plus variants;
33 * * a pointer to the C "pp" function that would execute the op;
34 * * any data specific to that op.
35 * For example, an OP_CONST op points to the pp_const() function and to an
36 * SV containing the constant value. When pp_const() is executed, its job
37 * is to push that SV onto the stack.
39 * OPs are mainly created by the newFOO() functions, which are mainly
40 * called from the parser (in perly.y) as the code is parsed. For example
41 * the Perl code $a + $b * $c would cause the equivalent of the following
42 * to be called (oversimplifying a bit):
44 * newBINOP(OP_ADD, flags,
46 * newBINOP(OP_MULTIPLY, flags, newSVREF($b), newSVREF($c))
49 * As the parser reduces low-level rules, it creates little op subtrees;
50 * as higher-level rules are resolved, these subtrees get joined together
51 * as branches on a bigger subtree, until eventually a top-level rule like
52 * a subroutine definition is reduced, at which point there is one large
55 * The execution order pointers (op_next) are generated as the subtrees
56 * are joined together. Consider this sub-expression: A*B + C/D: at the
57 * point when it's just been parsed, the op tree looks like:
65 * with the intended execution order being:
67 * [PREV] => A => B => [*] => C => D => [/] => [+] => [NEXT]
69 * At this point all the nodes' op_next pointers will have been set,
71 * * we don't know what the [NEXT] node will be yet;
72 * * we don't know what the [PREV] node will be yet, but when it gets
73 * created and needs its op_next set, it needs to be set to point to
74 * A, which is non-obvious.
75 * To handle both those cases, we temporarily set the top node's
76 * op_next to point to the first node to be executed in this subtree (A in
77 * this case). This means that initially a subtree's op_next chain,
78 * starting from the top node, will visit each node in execution sequence
79 * then point back at the top node.
80 * When we embed this subtree in a larger tree, its top op_next is used
81 * to get the start node, then is set to point to its new neighbour.
82 * For example the two separate [*],A,B and [/],C,D subtrees would
84 * [*] => A; A => B; B => [*]
86 * [/] => C; C => D; D => [/]
87 * When these two subtrees were joined together to make the [+] subtree,
88 * [+]'s op_next was set to [*]'s op_next, i.e. A; then [*]'s op_next was
89 * set to point to [/]'s op_next, i.e. C.
91 * This op_next linking is done by the LINKLIST() macro and its underlying
92 * op_linklist() function. Given a top-level op, if its op_next is
93 * non-null, it's already been linked, so leave it. Otherwise link it with
94 * its children as described above, possibly recursively if any of the
95 * children have a null op_next.
97 * In summary: given a subtree, its top-level node's op_next will either
99 * NULL: the subtree hasn't been LINKLIST()ed yet;
100 * fake: points to the start op for this subtree;
101 * real: once the subtree has been embedded into a larger tree
106 Here's an older description from Larry.
108 Perl's compiler is essentially a 3-pass compiler with interleaved phases:
112 An execution-order pass
114 The bottom-up pass is represented by all the "newOP" routines and
115 the ck_ routines. The bottom-upness is actually driven by yacc.
116 So at the point that a ck_ routine fires, we have no idea what the
117 context is, either upward in the syntax tree, or either forward or
118 backward in the execution order. (The bottom-up parser builds that
119 part of the execution order it knows about, but if you follow the "next"
120 links around, you'll find it's actually a closed loop through the
123 Whenever the bottom-up parser gets to a node that supplies context to
124 its components, it invokes that portion of the top-down pass that applies
125 to that part of the subtree (and marks the top node as processed, so
126 if a node further up supplies context, it doesn't have to take the
127 plunge again). As a particular subcase of this, as the new node is
128 built, it takes all the closed execution loops of its subcomponents
129 and links them into a new closed loop for the higher level node. But
130 it's still not the real execution order.
132 The actual execution order is not known till we get a grammar reduction
133 to a top-level unit like a subroutine or file that will be called by
134 "name" rather than via a "next" pointer. At that point, we can call
135 into peep() to do that code's portion of the 3rd pass. It has to be
136 recursive, but it's recursive on basic blocks, not on tree nodes.
139 /* To implement user lexical pragmas, there needs to be a way at run time to
140 get the compile time state of %^H for that block. Storing %^H in every
141 block (or even COP) would be very expensive, so a different approach is
142 taken. The (running) state of %^H is serialised into a tree of HE-like
143 structs. Stores into %^H are chained onto the current leaf as a struct
144 refcounted_he * with the key and the value. Deletes from %^H are saved
145 with a value of PL_sv_placeholder. The state of %^H at any point can be
146 turned back into a regular HV by walking back up the tree from that point's
147 leaf, ignoring any key you've already seen (placeholder or not), storing
148 the rest into the HV structure, then removing the placeholders. Hence
149 memory is only used to store the %^H deltas from the enclosing COP, rather
150 than the entire %^H on each COP.
152 To cause actions on %^H to write out the serialisation records, it has
153 magic type 'H'. This magic (itself) does nothing, but its presence causes
154 the values to gain magic type 'h', which has entries for set and clear.
155 C<Perl_magic_sethint> updates C<PL_compiling.cop_hints_hash> with a store
156 record, with deletes written by C<Perl_magic_clearhint>. C<SAVEHINTS>
157 saves the current C<PL_compiling.cop_hints_hash> on the save stack, so that
158 it will be correctly restored when any inner compiling scope is exited.
164 #include "keywords.h"
167 #include "invlist_inline.h"
169 #define CALL_PEEP(o) PL_peepp(aTHX_ o)
170 #define CALL_OPFREEHOOK(o) if (PL_opfreehook) PL_opfreehook(aTHX_ o)
172 static const char array_passed_to_stat[] = "Array passed to stat will be coerced to a scalar";
174 /* remove any leading "empty" ops from the op_next chain whose first
175 * node's address is stored in op_p. Store the updated address of the
176 * first node in op_p.
180 Perl_op_prune_chain_head(OP** op_p)
182 PERL_ARGS_ASSERT_OP_PRUNE_CHAIN_HEAD;
185 && ( (*op_p)->op_type == OP_NULL
186 || (*op_p)->op_type == OP_SCOPE
187 || (*op_p)->op_type == OP_SCALAR
188 || (*op_p)->op_type == OP_LINESEQ)
190 *op_p = (*op_p)->op_next;
194 /* See the explanatory comments above struct opslab in op.h. */
196 #ifdef PERL_DEBUG_READONLY_OPS
197 # define PERL_SLAB_SIZE 128
198 # define PERL_MAX_SLAB_SIZE 4096
199 # include <sys/mman.h>
202 #ifndef PERL_SLAB_SIZE
203 # define PERL_SLAB_SIZE 64
205 #ifndef PERL_MAX_SLAB_SIZE
206 # define PERL_MAX_SLAB_SIZE 2048
209 /* rounds up to nearest pointer */
210 #define SIZE_TO_PSIZE(x) (((x) + sizeof(I32 *) - 1)/sizeof(I32 *))
213 (assert(((char *)(p) - (char *)(o)) % sizeof(I32**) == 0), \
214 ((size_t)((I32 **)(p) - (I32**)(o))))
216 /* requires double parens and aTHX_ */
217 #define DEBUG_S_warn(args) \
219 PerlIO_printf(Perl_debug_log, "%s", SvPVx_nolen(Perl_mess args)) \
222 /* opslot_size includes the size of the slot header, and an op can't be smaller than BASEOP */
223 #define OPSLOT_SIZE_BASE (SIZE_TO_PSIZE(sizeof(OPSLOT)))
225 /* the number of bytes to allocate for a slab with sz * sizeof(I32 **) space for op */
226 #define OpSLABSizeBytes(sz) \
227 ((sz) * sizeof(I32 *) + STRUCT_OFFSET(OPSLAB, opslab_slots))
229 /* malloc a new op slab (suitable for attaching to PL_compcv).
230 * sz is in units of pointers from the beginning of opslab_opslots */
233 S_new_slab(pTHX_ OPSLAB *head, size_t sz)
236 size_t sz_bytes = OpSLABSizeBytes(sz);
238 /* opslot_offset is only U16 */
239 assert(sz < U16_MAX);
240 /* room for at least one op */
241 assert(sz >= OPSLOT_SIZE_BASE);
243 #ifdef PERL_DEBUG_READONLY_OPS
244 slab = (OPSLAB *) mmap(0, sz_bytes,
245 PROT_READ|PROT_WRITE,
246 MAP_ANON|MAP_PRIVATE, -1, 0);
247 DEBUG_m(PerlIO_printf(Perl_debug_log, "mapped %lu at %p\n",
248 (unsigned long) sz, slab));
249 if (slab == MAP_FAILED) {
250 perror("mmap failed");
254 slab = (OPSLAB *)PerlMemShared_malloc(sz_bytes);
255 Zero(slab, sz_bytes, char);
257 slab->opslab_size = (U16)sz;
260 /* The context is unused in non-Windows */
263 slab->opslab_free_space = sz;
264 slab->opslab_head = head ? head : slab;
265 DEBUG_S_warn((aTHX_ "allocated new op slab sz 0x%x, %p, head slab %p",
266 (unsigned int)slab->opslab_size, (void*)slab,
267 (void*)(slab->opslab_head)));
271 #define OPSLOT_SIZE_TO_INDEX(sz) ((sz) - OPSLOT_SIZE_BASE)
273 #define link_freed_op(slab, o) S_link_freed_op(aTHX_ slab, o)
275 S_link_freed_op(pTHX_ OPSLAB *slab, OP *o) {
276 U16 sz = OpSLOT(o)->opslot_size;
277 U16 index = OPSLOT_SIZE_TO_INDEX(sz);
279 assert(sz >= OPSLOT_SIZE_BASE);
280 /* make sure the array is large enough to include ops this large */
281 if (!slab->opslab_freed) {
282 /* we don't have a free list array yet, make a new one */
283 slab->opslab_freed_size = index+1;
284 slab->opslab_freed = (OP**)PerlMemShared_calloc((slab->opslab_freed_size), sizeof(OP*));
286 if (!slab->opslab_freed)
289 else if (index >= slab->opslab_freed_size) {
290 /* It's probably not worth doing exponential expansion here, the number of op sizes
293 /* We already have a list that isn't large enough, expand it */
294 size_t newsize = index+1;
295 OP **p = (OP **)PerlMemShared_realloc(slab->opslab_freed, newsize * sizeof(OP*));
300 Zero(p+slab->opslab_freed_size, newsize - slab->opslab_freed_size, OP *);
302 slab->opslab_freed = p;
303 slab->opslab_freed_size = newsize;
306 o->op_next = slab->opslab_freed[index];
307 slab->opslab_freed[index] = o;
310 /* Returns a sz-sized block of memory (suitable for holding an op) from
311 * a free slot in the chain of op slabs attached to PL_compcv.
312 * Allocates a new slab if necessary.
313 * if PL_compcv isn't compiling, malloc() instead.
317 Perl_Slab_Alloc(pTHX_ size_t sz)
319 OPSLAB *head_slab; /* first slab in the chain */
323 size_t sz_in_p; /* size in pointer units, including the OPSLOT header */
325 /* We only allocate ops from the slab during subroutine compilation.
326 We find the slab via PL_compcv, hence that must be non-NULL. It could
327 also be pointing to a subroutine which is now fully set up (CvROOT()
328 pointing to the top of the optree for that sub), or a subroutine
329 which isn't using the slab allocator. If our sanity checks aren't met,
330 don't use a slab, but allocate the OP directly from the heap. */
331 if (!PL_compcv || CvROOT(PL_compcv)
332 || (CvSTART(PL_compcv) && !CvSLABBED(PL_compcv)))
334 o = (OP*)PerlMemShared_calloc(1, sz);
338 /* While the subroutine is under construction, the slabs are accessed via
339 CvSTART(), to avoid needing to expand PVCV by one pointer for something
340 unneeded at runtime. Once a subroutine is constructed, the slabs are
341 accessed via CvROOT(). So if CvSTART() is NULL, no slab has been
342 allocated yet. See the commit message for 8be227ab5eaa23f2 for more
344 if (!CvSTART(PL_compcv)) {
346 (OP *)(head_slab = S_new_slab(aTHX_ NULL, PERL_SLAB_SIZE));
347 CvSLABBED_on(PL_compcv);
348 head_slab->opslab_refcnt = 2; /* one for the CV; one for the new OP */
350 else ++(head_slab = (OPSLAB *)CvSTART(PL_compcv))->opslab_refcnt;
352 sz_in_p = SIZE_TO_PSIZE(sz + OPSLOT_HEADER);
354 /* The head slab for each CV maintains a free list of OPs. In particular, constant folding
355 will free up OPs, so it makes sense to re-use them where possible. A
356 freed up slot is used in preference to a new allocation. */
357 if (head_slab->opslab_freed &&
358 OPSLOT_SIZE_TO_INDEX(sz_in_p) < head_slab->opslab_freed_size) {
361 /* look for a large enough size with any freed ops */
362 for (base_index = OPSLOT_SIZE_TO_INDEX(sz_in_p);
363 base_index < head_slab->opslab_freed_size && !head_slab->opslab_freed[base_index];
367 if (base_index < head_slab->opslab_freed_size) {
368 /* found a freed op */
369 o = head_slab->opslab_freed[base_index];
371 DEBUG_S_warn((aTHX_ "realloced op at %p, slab %p, head slab %p",
372 (void *)o, (void *)OpMySLAB(o), (void *)head_slab));
373 head_slab->opslab_freed[base_index] = o->op_next;
380 #define INIT_OPSLOT(s) \
381 slot->opslot_offset = DIFF(&slab2->opslab_slots, slot) ; \
382 slot->opslot_size = s; \
383 slab2->opslab_free_space -= s; \
384 o = &slot->opslot_op; \
387 /* The partially-filled slab is next in the chain. */
388 slab2 = head_slab->opslab_next ? head_slab->opslab_next : head_slab;
389 if (slab2->opslab_free_space < sz_in_p) {
390 /* Remaining space is too small. */
391 /* If we can fit a BASEOP, add it to the free chain, so as not
393 if (slab2->opslab_free_space >= OPSLOT_SIZE_BASE) {
394 slot = &slab2->opslab_slots;
395 INIT_OPSLOT(slab2->opslab_free_space);
396 o->op_type = OP_FREED;
397 DEBUG_S_warn((aTHX_ "linked unused op space at %p, slab %p, head slab %p",
398 (void *)o, (void *)slab2, (void *)head_slab));
399 link_freed_op(head_slab, o);
402 /* Create a new slab. Make this one twice as big. */
403 slab2 = S_new_slab(aTHX_ head_slab,
404 slab2->opslab_size > PERL_MAX_SLAB_SIZE / 2
406 : slab2->opslab_size * 2);
407 slab2->opslab_next = head_slab->opslab_next;
408 head_slab->opslab_next = slab2;
410 assert(slab2->opslab_size >= sz_in_p);
412 /* Create a new op slot */
413 slot = OpSLOToff(slab2, slab2->opslab_free_space - sz_in_p);
414 assert(slot >= &slab2->opslab_slots);
415 INIT_OPSLOT(sz_in_p);
416 DEBUG_S_warn((aTHX_ "allocating op at %p, slab %p, head slab %p",
417 (void*)o, (void*)slab2, (void*)head_slab));
420 /* moresib == 0, op_sibling == 0 implies a solitary unattached op */
421 assert(!o->op_moresib);
422 assert(!o->op_sibparent);
429 #ifdef PERL_DEBUG_READONLY_OPS
431 Perl_Slab_to_ro(pTHX_ OPSLAB *slab)
433 PERL_ARGS_ASSERT_SLAB_TO_RO;
435 if (slab->opslab_readonly) return;
436 slab->opslab_readonly = 1;
437 for (; slab; slab = slab->opslab_next) {
438 /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->ro %lu at %p\n",
439 (unsigned long) slab->opslab_size, (void *)slab));*/
440 if (mprotect(slab, OpSLABSizeBytes(slab->opslab_size), PROT_READ))
441 Perl_warn(aTHX_ "mprotect for %p %lu failed with %d", (void *)slab,
442 (unsigned long)slab->opslab_size, errno);
447 Perl_Slab_to_rw(pTHX_ OPSLAB *const slab)
451 PERL_ARGS_ASSERT_SLAB_TO_RW;
453 if (!slab->opslab_readonly) return;
455 for (; slab2; slab2 = slab2->opslab_next) {
456 /*DEBUG_U(PerlIO_printf(Perl_debug_log,"mprotect ->rw %lu at %p\n",
457 (unsigned long) size, (void *)slab2));*/
458 if (mprotect((void *)slab2, OpSLABSizeBytes(slab2->opslab_size),
459 PROT_READ|PROT_WRITE)) {
460 Perl_warn(aTHX_ "mprotect RW for %p %lu failed with %d", (void *)slab,
461 (unsigned long)slab2->opslab_size, errno);
464 slab->opslab_readonly = 0;
468 # define Slab_to_rw(op) NOOP
471 /* make freed ops die if they're inadvertently executed */
476 DIE(aTHX_ "panic: freed op 0x%p called\n", PL_op);
481 /* Return the block of memory used by an op to the free list of
482 * the OP slab associated with that op.
486 Perl_Slab_Free(pTHX_ void *op)
488 OP * const o = (OP *)op;
491 PERL_ARGS_ASSERT_SLAB_FREE;
494 o->op_ppaddr = S_pp_freed;
497 if (!o->op_slabbed) {
499 PerlMemShared_free(op);
504 /* If this op is already freed, our refcount will get screwy. */
505 assert(o->op_type != OP_FREED);
506 o->op_type = OP_FREED;
507 link_freed_op(slab, o);
508 DEBUG_S_warn((aTHX_ "freeing op at %p, slab %p, head slab %p",
509 (void*)o, (void *)OpMySLAB(o), (void*)slab));
510 OpslabREFCNT_dec_padok(slab);
514 Perl_opslab_free_nopad(pTHX_ OPSLAB *slab)
516 const bool havepad = cBOOL(PL_comppad);
517 PERL_ARGS_ASSERT_OPSLAB_FREE_NOPAD;
520 PAD_SAVE_SETNULLPAD();
526 /* Free a chain of OP slabs. Should only be called after all ops contained
527 * in it have been freed. At this point, its reference count should be 1,
528 * because OpslabREFCNT_dec() skips doing rc-- when it detects that rc == 1,
529 * and just directly calls opslab_free().
530 * (Note that the reference count which PL_compcv held on the slab should
531 * have been removed once compilation of the sub was complete).
537 Perl_opslab_free(pTHX_ OPSLAB *slab)
540 PERL_ARGS_ASSERT_OPSLAB_FREE;
542 DEBUG_S_warn((aTHX_ "freeing slab %p", (void*)slab));
543 assert(slab->opslab_refcnt == 1);
544 PerlMemShared_free(slab->opslab_freed);
546 slab2 = slab->opslab_next;
548 slab->opslab_refcnt = ~(size_t)0;
550 #ifdef PERL_DEBUG_READONLY_OPS
551 DEBUG_m(PerlIO_printf(Perl_debug_log, "Deallocate slab at %p\n",
553 if (munmap(slab, OpSLABSizeBytes(slab->opslab_size))) {
554 perror("munmap failed");
558 PerlMemShared_free(slab);
564 /* like opslab_free(), but first calls op_free() on any ops in the slab
565 * not marked as OP_FREED
569 Perl_opslab_force_free(pTHX_ OPSLAB *slab)
573 size_t savestack_count = 0;
575 PERL_ARGS_ASSERT_OPSLAB_FORCE_FREE;
578 OPSLOT *slot = OpSLOToff(slab2, slab2->opslab_free_space);
579 OPSLOT *end = OpSLOToff(slab2, slab2->opslab_size);
581 slot = (OPSLOT*) ((I32**)slot + slot->opslot_size) )
583 if (slot->opslot_op.op_type != OP_FREED
584 && !(slot->opslot_op.op_savefree
590 assert(slot->opslot_op.op_slabbed);
591 op_free(&slot->opslot_op);
592 if (slab->opslab_refcnt == 1) goto free;
595 } while ((slab2 = slab2->opslab_next));
596 /* > 1 because the CV still holds a reference count. */
597 if (slab->opslab_refcnt > 1) { /* still referenced by the savestack */
599 assert(savestack_count == slab->opslab_refcnt-1);
601 /* Remove the CV’s reference count. */
602 slab->opslab_refcnt--;
609 #ifdef PERL_DEBUG_READONLY_OPS
611 Perl_op_refcnt_inc(pTHX_ OP *o)
614 OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
615 if (slab && slab->opslab_readonly) {
628 Perl_op_refcnt_dec(pTHX_ OP *o)
631 OPSLAB *const slab = o->op_slabbed ? OpSLAB(o) : NULL;
633 PERL_ARGS_ASSERT_OP_REFCNT_DEC;
635 if (slab && slab->opslab_readonly) {
637 result = --o->op_targ;
640 result = --o->op_targ;
646 * In the following definition, the ", (OP*)0" is just to make the compiler
647 * think the expression is of the right type: croak actually does a Siglongjmp.
649 #define CHECKOP(type,o) \
650 ((PL_op_mask && PL_op_mask[type]) \
651 ? ( op_free((OP*)o), \
652 Perl_croak(aTHX_ "'%s' trapped by operation mask", PL_op_desc[type]), \
654 : PL_check[type](aTHX_ (OP*)o))
656 #define RETURN_UNLIMITED_NUMBER (PERL_INT_MAX / 2)
659 S_no_fh_allowed(pTHX_ OP *o)
661 PERL_ARGS_ASSERT_NO_FH_ALLOWED;
663 yyerror(Perl_form(aTHX_ "Missing comma after first argument to %s function",
669 S_too_few_arguments_pv(pTHX_ OP *o, const char* name, U32 flags)
671 PERL_ARGS_ASSERT_TOO_FEW_ARGUMENTS_PV;
672 yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %s", name), flags);
677 S_too_many_arguments_pv(pTHX_ OP *o, const char *name, U32 flags)
679 PERL_ARGS_ASSERT_TOO_MANY_ARGUMENTS_PV;
681 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %s", name), flags);
686 S_bad_type_pv(pTHX_ I32 n, const char *t, const OP *o, const OP *kid)
688 PERL_ARGS_ASSERT_BAD_TYPE_PV;
690 yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %s must be %s (not %s)",
691 (int)n, PL_op_desc[(o)->op_type], t, OP_DESC(kid)), 0);
695 S_bad_type_gv(pTHX_ I32 n, GV *gv, const OP *kid, const char *t)
697 SV * const namesv = cv_name((CV *)gv, NULL, 0);
698 PERL_ARGS_ASSERT_BAD_TYPE_GV;
700 yyerror_pv(Perl_form(aTHX_ "Type of arg %d to %" SVf " must be %s (not %s)",
701 (int)n, SVfARG(namesv), t, OP_DESC(kid)), SvUTF8(namesv));
705 Perl_no_bareword_allowed(pTHX_ OP *o)
707 PERL_ARGS_ASSERT_NO_BAREWORD_ALLOWED;
709 qerror(Perl_mess(aTHX_
710 "Bareword \"%" SVf "\" not allowed while \"strict subs\" in use",
712 o->op_private &= ~OPpCONST_STRICT; /* prevent warning twice about the same OP */
716 Perl_no_bareword_filehandle(pTHX_ const char *fhname) {
717 PERL_ARGS_ASSERT_NO_BAREWORD_FILEHANDLE;
719 if (strNE(fhname, "STDERR")
720 && strNE(fhname, "STDOUT")
721 && strNE(fhname, "STDIN")
722 && strNE(fhname, "_")
723 && strNE(fhname, "ARGV")
724 && strNE(fhname, "ARGVOUT")
725 && strNE(fhname, "DATA")) {
726 qerror(Perl_mess(aTHX_ "Bareword filehandle \"%s\" not allowed under 'no feature \"bareword_filehandles\"'", fhname));
730 /* "register" allocation */
733 Perl_allocmy(pTHX_ const char *const name, const STRLEN len, const U32 flags)
736 bool is_idfirst, is_default;
737 const bool is_our = (PL_parser->in_my == KEY_our);
739 PERL_ARGS_ASSERT_ALLOCMY;
741 if (flags & ~SVf_UTF8)
742 Perl_croak(aTHX_ "panic: allocmy illegal flag bits 0x%" UVxf,
745 is_idfirst = flags & SVf_UTF8
746 ? isIDFIRST_utf8_safe((U8*)name + 1, name + len)
747 : isIDFIRST_A(name[1]);
750 is_default = len == 2 && name[1] == '_';
752 /* complain about "my $<special_var>" etc etc */
753 if (!is_our && (!is_idfirst || is_default)) {
754 const char * const type =
755 PL_parser->in_my == KEY_sigvar ? "subroutine signature" :
756 PL_parser->in_my == KEY_state ? "\"state\"" : "\"my\"";
758 if (!(flags & SVf_UTF8 && UTF8_IS_START(name[1]))
760 && (!isPRINT(name[1]) || memCHRs("\t\n\r\f", name[1]))) {
761 /* diag_listed_as: Can't use global %s in %s */
762 yyerror(Perl_form(aTHX_ "Can't use global %c^%c%.*s in %s",
763 name[0], toCTRL(name[1]),
764 (int)(len - 2), name + 2,
767 yyerror_pv(Perl_form(aTHX_ "Can't use global %.*s in %s",
769 type), flags & SVf_UTF8);
773 /* allocate a spare slot and store the name in that slot */
775 off = pad_add_name_pvn(name, len,
776 (is_our ? padadd_OUR :
777 PL_parser->in_my == KEY_state ? padadd_STATE : 0),
778 PL_parser->in_my_stash,
780 /* $_ is always in main::, even with our */
781 ? (PL_curstash && !memEQs(name,len,"$_")
787 /* anon sub prototypes contains state vars should always be cloned,
788 * otherwise the state var would be shared between anon subs */
790 if (PL_parser->in_my == KEY_state && CvANON(PL_compcv))
791 CvCLONE_on(PL_compcv);
797 =for apidoc_section $optree_manipulation
799 =for apidoc alloccopstash
801 Available only under threaded builds, this function allocates an entry in
802 C<PL_stashpad> for the stash passed to it.
809 Perl_alloccopstash(pTHX_ HV *hv)
811 PADOFFSET off = 0, o = 1;
812 bool found_slot = FALSE;
814 PERL_ARGS_ASSERT_ALLOCCOPSTASH;
816 if (PL_stashpad[PL_stashpadix] == hv) return PL_stashpadix;
818 for (; o < PL_stashpadmax; ++o) {
819 if (PL_stashpad[o] == hv) return PL_stashpadix = o;
820 if (!PL_stashpad[o] || SvTYPE(PL_stashpad[o]) != SVt_PVHV)
821 found_slot = TRUE, off = o;
824 Renew(PL_stashpad, PL_stashpadmax + 10, HV *);
825 Zero(PL_stashpad + PL_stashpadmax, 10, HV *);
826 off = PL_stashpadmax;
827 PL_stashpadmax += 10;
830 PL_stashpad[PL_stashpadix = off] = hv;
835 /* free the body of an op without examining its contents.
836 * Always use this rather than FreeOp directly */
839 S_op_destroy(pTHX_ OP *o)
849 Free an op and its children. Only use this when an op is no longer linked
856 Perl_op_free(pTHX_ OP *o)
861 bool went_up = FALSE; /* whether we reached the current node by
862 following the parent pointer from a child, and
863 so have already seen this node */
865 if (!o || o->op_type == OP_FREED)
868 if (o->op_private & OPpREFCOUNTED) {
869 /* if base of tree is refcounted, just decrement */
870 switch (o->op_type) {
880 refcnt = OpREFCNT_dec(o);
883 /* Need to find and remove any pattern match ops from
884 * the list we maintain for reset(). */
885 find_and_forget_pmops(o);
898 /* free child ops before ourself, (then free ourself "on the
901 if (!went_up && o->op_flags & OPf_KIDS) {
902 next_op = cUNOPo->op_first;
906 /* find the next node to visit, *then* free the current node
907 * (can't rely on o->op_* fields being valid after o has been
910 /* The next node to visit will be either the sibling, or the
911 * parent if no siblings left, or NULL if we've worked our way
912 * back up to the top node in the tree */
913 next_op = (o == top_op) ? NULL : o->op_sibparent;
914 went_up = cBOOL(!OpHAS_SIBLING(o)); /* parents are already visited */
916 /* Now process the current node */
918 /* Though ops may be freed twice, freeing the op after its slab is a
920 assert(!o->op_slabbed || OpSLAB(o)->opslab_refcnt != ~(size_t)0);
921 /* During the forced freeing of ops after compilation failure, kidops
922 may be freed before their parents. */
923 if (!o || o->op_type == OP_FREED)
928 /* an op should only ever acquire op_private flags that we know about.
929 * If this fails, you may need to fix something in regen/op_private.
930 * Don't bother testing if:
931 * * the op_ppaddr doesn't match the op; someone may have
932 * overridden the op and be doing strange things with it;
933 * * we've errored, as op flags are often left in an
934 * inconsistent state then. Note that an error when
935 * compiling the main program leaves PL_parser NULL, so
936 * we can't spot faults in the main code, only
937 * evaled/required code;
938 * * it's a banned op - we may be croaking before the op is
939 * fully formed. - see CHECKOP. */
941 if ( o->op_ppaddr == PL_ppaddr[type]
943 && !PL_parser->error_count
944 && !(PL_op_mask && PL_op_mask[type])
947 assert(!(o->op_private & ~PL_op_private_valid[type]));
952 /* Call the op_free hook if it has been set. Do it now so that it's called
953 * at the right time for refcounted ops, but still before all of the kids
958 type = (OPCODE)o->op_targ;
961 Slab_to_rw(OpSLAB(o));
963 /* COP* is not cleared by op_clear() so that we may track line
964 * numbers etc even after null() */
965 if (type == OP_NEXTSTATE || type == OP_DBSTATE) {
977 /* S_op_clear_gv(): free a GV attached to an OP */
981 void S_op_clear_gv(pTHX_ OP *o, PADOFFSET *ixp)
983 void S_op_clear_gv(pTHX_ OP *o, SV**svp)
987 GV *gv = (o->op_type == OP_GV || o->op_type == OP_GVSV
988 || o->op_type == OP_MULTIDEREF)
991 ? ((GV*)PAD_SVl(*ixp)) : NULL;
993 ? (GV*)(*svp) : NULL;
995 /* It's possible during global destruction that the GV is freed
996 before the optree. Whilst the SvREFCNT_inc is happy to bump from
997 0 to 1 on a freed SV, the corresponding SvREFCNT_dec from 1 to 0
998 will trigger an assertion failure, because the entry to sv_clear
999 checks that the scalar is not already freed. A check of for
1000 !SvIS_FREED(gv) turns out to be invalid, because during global
1001 destruction the reference count can be forced down to zero
1002 (with SVf_BREAK set). In which case raising to 1 and then
1003 dropping to 0 triggers cleanup before it should happen. I
1004 *think* that this might actually be a general, systematic,
1005 weakness of the whole idea of SVf_BREAK, in that code *is*
1006 allowed to raise and lower references during global destruction,
1007 so any *valid* code that happens to do this during global
1008 destruction might well trigger premature cleanup. */
1009 bool still_valid = gv && SvREFCNT(gv);
1012 SvREFCNT_inc_simple_void(gv);
1015 pad_swipe(*ixp, TRUE);
1023 int try_downgrade = SvREFCNT(gv) == 2;
1024 SvREFCNT_dec_NN(gv);
1026 gv_try_downgrade(gv);
1032 Perl_op_clear(pTHX_ OP *o)
1036 PERL_ARGS_ASSERT_OP_CLEAR;
1038 switch (o->op_type) {
1039 case OP_NULL: /* Was holding old type, if any. */
1042 case OP_ENTEREVAL: /* Was holding hints. */
1043 case OP_ARGDEFELEM: /* Was holding signature index. */
1047 if (!(o->op_flags & OPf_REF) || !OP_IS_STAT(o->op_type))
1054 S_op_clear_gv(aTHX_ o, &(cPADOPx(o)->op_padix));
1056 S_op_clear_gv(aTHX_ o, &(cSVOPx(o)->op_sv));
1059 case OP_METHOD_REDIR:
1060 case OP_METHOD_REDIR_SUPER:
1062 if (cMETHOPo->op_rclass_targ) {
1063 pad_swipe(cMETHOPo->op_rclass_targ, 1);
1064 cMETHOPo->op_rclass_targ = 0;
1067 SvREFCNT_dec(cMETHOPo->op_rclass_sv);
1068 cMETHOPo->op_rclass_sv = NULL;
1071 case OP_METHOD_NAMED:
1072 case OP_METHOD_SUPER:
1073 SvREFCNT_dec(cMETHOPo->op_u.op_meth_sv);
1074 cMETHOPo->op_u.op_meth_sv = NULL;
1077 pad_swipe(o->op_targ, 1);
1084 SvREFCNT_dec(cSVOPo->op_sv);
1085 cSVOPo->op_sv = NULL;
1088 Even if op_clear does a pad_free for the target of the op,
1089 pad_free doesn't actually remove the sv that exists in the pad;
1090 instead it lives on. This results in that it could be reused as
1091 a target later on when the pad was reallocated.
1094 pad_swipe(o->op_targ,1);
1104 if (o->op_flags & (OPf_SPECIAL|OPf_STACKED|OPf_KIDS))
1109 if ( (o->op_type == OP_TRANS || o->op_type == OP_TRANSR)
1110 && (o->op_private & OPpTRANS_USE_SVOP))
1113 if (cPADOPo->op_padix > 0) {
1114 pad_swipe(cPADOPo->op_padix, TRUE);
1115 cPADOPo->op_padix = 0;
1118 SvREFCNT_dec(cSVOPo->op_sv);
1119 cSVOPo->op_sv = NULL;
1123 PerlMemShared_free(cPVOPo->op_pv);
1124 cPVOPo->op_pv = NULL;
1128 op_free(cPMOPo->op_pmreplrootu.op_pmreplroot);
1132 if ( (o->op_private & OPpSPLIT_ASSIGN) /* @array = split */
1133 && !(o->op_flags & OPf_STACKED)) /* @{expr} = split */
1135 if (o->op_private & OPpSPLIT_LEX)
1136 pad_free(cPMOPo->op_pmreplrootu.op_pmtargetoff);
1139 pad_swipe(cPMOPo->op_pmreplrootu.op_pmtargetoff, TRUE);
1141 SvREFCNT_dec(MUTABLE_SV(cPMOPo->op_pmreplrootu.op_pmtargetgv));
1148 if (!(cPMOPo->op_pmflags & PMf_CODELIST_PRIVATE))
1149 op_free(cPMOPo->op_code_list);
1150 cPMOPo->op_code_list = NULL;
1151 forget_pmop(cPMOPo);
1152 cPMOPo->op_pmreplrootu.op_pmreplroot = NULL;
1153 /* we use the same protection as the "SAFE" version of the PM_ macros
1154 * here since sv_clean_all might release some PMOPs
1155 * after PL_regex_padav has been cleared
1156 * and the clearing of PL_regex_padav needs to
1157 * happen before sv_clean_all
1160 if(PL_regex_pad) { /* We could be in destruction */
1161 const IV offset = (cPMOPo)->op_pmoffset;
1162 ReREFCNT_dec(PM_GETRE(cPMOPo));
1163 PL_regex_pad[offset] = &PL_sv_undef;
1164 sv_catpvn_nomg(PL_regex_pad[0], (const char *)&offset,
1168 ReREFCNT_dec(PM_GETRE(cPMOPo));
1169 PM_SETRE(cPMOPo, NULL);
1175 PerlMemShared_free(cUNOP_AUXo->op_aux);
1178 case OP_MULTICONCAT:
1180 UNOP_AUX_item *aux = cUNOP_AUXo->op_aux;
1181 /* aux[PERL_MULTICONCAT_IX_PLAIN_PV] and/or
1182 * aux[PERL_MULTICONCAT_IX_UTF8_PV] point to plain and/or
1183 * utf8 shared strings */
1184 char *p1 = aux[PERL_MULTICONCAT_IX_PLAIN_PV].pv;
1185 char *p2 = aux[PERL_MULTICONCAT_IX_UTF8_PV].pv;
1187 PerlMemShared_free(p1);
1189 PerlMemShared_free(p2);
1190 PerlMemShared_free(aux);
1196 UNOP_AUX_item *items = cUNOP_AUXo->op_aux;
1197 UV actions = items->uv;
1199 bool is_hash = FALSE;
1202 switch (actions & MDEREF_ACTION_MASK) {
1205 actions = (++items)->uv;
1208 case MDEREF_HV_padhv_helem:
1211 case MDEREF_AV_padav_aelem:
1212 pad_free((++items)->pad_offset);
1215 case MDEREF_HV_gvhv_helem:
1218 case MDEREF_AV_gvav_aelem:
1220 S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1222 S_op_clear_gv(aTHX_ o, &((++items)->sv));
1226 case MDEREF_HV_gvsv_vivify_rv2hv_helem:
1229 case MDEREF_AV_gvsv_vivify_rv2av_aelem:
1231 S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1233 S_op_clear_gv(aTHX_ o, &((++items)->sv));
1235 goto do_vivify_rv2xv_elem;
1237 case MDEREF_HV_padsv_vivify_rv2hv_helem:
1240 case MDEREF_AV_padsv_vivify_rv2av_aelem:
1241 pad_free((++items)->pad_offset);
1242 goto do_vivify_rv2xv_elem;
1244 case MDEREF_HV_pop_rv2hv_helem:
1245 case MDEREF_HV_vivify_rv2hv_helem:
1248 do_vivify_rv2xv_elem:
1249 case MDEREF_AV_pop_rv2av_aelem:
1250 case MDEREF_AV_vivify_rv2av_aelem:
1252 switch (actions & MDEREF_INDEX_MASK) {
1253 case MDEREF_INDEX_none:
1256 case MDEREF_INDEX_const:
1260 pad_swipe((++items)->pad_offset, 1);
1262 SvREFCNT_dec((++items)->sv);
1268 case MDEREF_INDEX_padsv:
1269 pad_free((++items)->pad_offset);
1271 case MDEREF_INDEX_gvsv:
1273 S_op_clear_gv(aTHX_ o, &((++items)->pad_offset));
1275 S_op_clear_gv(aTHX_ o, &((++items)->sv));
1280 if (actions & MDEREF_FLAG_last)
1293 actions >>= MDEREF_SHIFT;
1296 /* start of malloc is at op_aux[-1], where the length is
1298 PerlMemShared_free(cUNOP_AUXo->op_aux - 1);
1303 if (o->op_targ > 0) {
1304 pad_free(o->op_targ);
1310 S_cop_free(pTHX_ COP* cop)
1312 PERL_ARGS_ASSERT_COP_FREE;
1314 /* If called during global destruction PL_defstash might be NULL and there
1315 shouldn't be any code running that will trip over the bad cop address.
1316 This also avoids uselessly creating the AV after it's been destroyed.
1318 if (cop->op_type == OP_DBSTATE && PL_phase != PERL_PHASE_DESTRUCT) {
1319 /* Remove the now invalid op from the line number information.
1320 This could cause a freed memory overwrite if the debugger tried to
1321 set a breakpoint on this line.
1323 AV *av = CopFILEAVn(cop);
1325 SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
1326 if (svp && *svp != &PL_sv_undef && SvIVX(*svp) == PTR2IV(cop) ) {
1327 (void)SvIOK_off(*svp);
1333 if (! specialWARN(cop->cop_warnings))
1334 PerlMemShared_free(cop->cop_warnings);
1335 cophh_free(CopHINTHASH_get(cop));
1336 if (PL_curcop == cop)
1341 S_forget_pmop(pTHX_ PMOP *const o)
1343 HV * const pmstash = PmopSTASH(o);
1345 PERL_ARGS_ASSERT_FORGET_PMOP;
1347 if (pmstash && !SvIS_FREED(pmstash) && SvMAGICAL(pmstash)) {
1348 MAGIC * const mg = mg_find((const SV *)pmstash, PERL_MAGIC_symtab);
1350 PMOP **const array = (PMOP**) mg->mg_ptr;
1351 U32 count = mg->mg_len / sizeof(PMOP**);
1355 if (array[i] == o) {
1356 /* Found it. Move the entry at the end to overwrite it. */
1357 array[i] = array[--count];
1358 mg->mg_len = count * sizeof(PMOP**);
1359 /* Could realloc smaller at this point always, but probably
1360 not worth it. Probably worth free()ing if we're the
1363 Safefree(mg->mg_ptr);
1377 S_find_and_forget_pmops(pTHX_ OP *o)
1381 PERL_ARGS_ASSERT_FIND_AND_FORGET_PMOPS;
1384 switch (o->op_type) {
1389 forget_pmop(cPMOPo);
1392 if (o->op_flags & OPf_KIDS) {
1393 o = cUNOPo->op_first;
1399 return; /* at top; no parents/siblings to try */
1400 if (OpHAS_SIBLING(o)) {
1401 o = o->op_sibparent; /* process next sibling */
1404 o = o->op_sibparent; /*try parent's next sibling */
1413 Neutralizes an op when it is no longer needed, but is still linked to from
1420 Perl_op_null(pTHX_ OP *o)
1423 PERL_ARGS_ASSERT_OP_NULL;
1425 if (o->op_type == OP_NULL)
1428 o->op_targ = o->op_type;
1429 OpTYPE_set(o, OP_NULL);
1433 =for apidoc op_refcnt_lock
1435 Implements the C<OP_REFCNT_LOCK> macro which you should use instead.
1441 Perl_op_refcnt_lock(pTHX)
1442 PERL_TSA_ACQUIRE(PL_op_mutex)
1444 PERL_UNUSED_CONTEXT;
1449 =for apidoc op_refcnt_unlock
1451 Implements the C<OP_REFCNT_UNLOCK> macro which you should use instead.
1457 Perl_op_refcnt_unlock(pTHX)
1458 PERL_TSA_RELEASE(PL_op_mutex)
1460 PERL_UNUSED_CONTEXT;
1466 =for apidoc op_sibling_splice
1468 A general function for editing the structure of an existing chain of
1469 op_sibling nodes. By analogy with the perl-level C<splice()> function, allows
1470 you to delete zero or more sequential nodes, replacing them with zero or
1471 more different nodes. Performs the necessary op_first/op_last
1472 housekeeping on the parent node and op_sibling manipulation on the
1473 children. The last deleted node will be marked as the last node by
1474 updating the op_sibling/op_sibparent or op_moresib field as appropriate.
1476 Note that op_next is not manipulated, and nodes are not freed; that is the
1477 responsibility of the caller. It also won't create a new list op for an
1478 empty list etc; use higher-level functions like op_append_elem() for that.
1480 C<parent> is the parent node of the sibling chain. It may passed as C<NULL> if
1481 the splicing doesn't affect the first or last op in the chain.
1483 C<start> is the node preceding the first node to be spliced. Node(s)
1484 following it will be deleted, and ops will be inserted after it. If it is
1485 C<NULL>, the first node onwards is deleted, and nodes are inserted at the
1488 C<del_count> is the number of nodes to delete. If zero, no nodes are deleted.
1489 If -1 or greater than or equal to the number of remaining kids, all
1490 remaining kids are deleted.
1492 C<insert> is the first of a chain of nodes to be inserted in place of the nodes.
1493 If C<NULL>, no nodes are inserted.
1495 The head of the chain of deleted ops is returned, or C<NULL> if no ops were
1500 action before after returns
1501 ------ ----- ----- -------
1504 splice(P, A, 2, X-Y-Z) | | B-C
1508 splice(P, NULL, 1, X-Y) | | A
1512 splice(P, NULL, 3, NULL) | | A-B-C
1516 splice(P, B, 0, X-Y) | | NULL
1520 For lower-level direct manipulation of C<op_sibparent> and C<op_moresib>,
1521 see C<L</OpMORESIB_set>>, C<L</OpLASTSIB_set>>, C<L</OpMAYBESIB_set>>.
1527 Perl_op_sibling_splice(OP *parent, OP *start, int del_count, OP* insert)
1531 OP *last_del = NULL;
1532 OP *last_ins = NULL;
1535 first = OpSIBLING(start);
1539 first = cLISTOPx(parent)->op_first;
1541 assert(del_count >= -1);
1543 if (del_count && first) {
1545 while (--del_count && OpHAS_SIBLING(last_del))
1546 last_del = OpSIBLING(last_del);
1547 rest = OpSIBLING(last_del);
1548 OpLASTSIB_set(last_del, NULL);
1555 while (OpHAS_SIBLING(last_ins))
1556 last_ins = OpSIBLING(last_ins);
1557 OpMAYBESIB_set(last_ins, rest, NULL);
1563 OpMAYBESIB_set(start, insert, NULL);
1567 cLISTOPx(parent)->op_first = insert;
1569 parent->op_flags |= OPf_KIDS;
1571 parent->op_flags &= ~OPf_KIDS;
1575 /* update op_last etc */
1582 /* ought to use OP_CLASS(parent) here, but that can't handle
1583 * ex-foo OP_NULL ops. Also note that XopENTRYCUSTOM() can't
1585 type = parent->op_type;
1586 if (type == OP_CUSTOM) {
1588 type = XopENTRYCUSTOM(parent, xop_class);
1591 if (type == OP_NULL)
1592 type = parent->op_targ;
1593 type = PL_opargs[type] & OA_CLASS_MASK;
1596 lastop = last_ins ? last_ins : start ? start : NULL;
1597 if ( type == OA_BINOP
1598 || type == OA_LISTOP
1602 cLISTOPx(parent)->op_last = lastop;
1605 OpLASTSIB_set(lastop, parent);
1607 return last_del ? first : NULL;
1610 Perl_croak_nocontext("panic: op_sibling_splice(): NULL parent");
1614 =for apidoc op_parent
1616 Returns the parent OP of C<o>, if it has a parent. Returns C<NULL> otherwise.
1622 Perl_op_parent(OP *o)
1624 PERL_ARGS_ASSERT_OP_PARENT;
1625 while (OpHAS_SIBLING(o))
1627 return o->op_sibparent;
1630 /* replace the sibling following start with a new UNOP, which becomes
1631 * the parent of the original sibling; e.g.
1633 * op_sibling_newUNOP(P, A, unop-args...)
1641 * where U is the new UNOP.
1643 * parent and start args are the same as for op_sibling_splice();
1644 * type and flags args are as newUNOP().
1646 * Returns the new UNOP.
1650 S_op_sibling_newUNOP(pTHX_ OP *parent, OP *start, I32 type, I32 flags)
1654 kid = op_sibling_splice(parent, start, 1, NULL);
1655 newop = newUNOP(type, flags, kid);
1656 op_sibling_splice(parent, start, 0, newop);
1661 /* lowest-level newLOGOP-style function - just allocates and populates
1662 * the struct. Higher-level stuff should be done by S_new_logop() /
1663 * newLOGOP(). This function exists mainly to avoid op_first assignment
1664 * being spread throughout this file.
1668 Perl_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other)
1672 NewOp(1101, logop, 1, LOGOP);
1673 OpTYPE_set(logop, type);
1674 logop->op_first = first;
1675 logop->op_other = other;
1677 logop->op_flags = OPf_KIDS;
1678 while (kid && OpHAS_SIBLING(kid))
1679 kid = OpSIBLING(kid);
1681 OpLASTSIB_set(kid, (OP*)logop);
1686 /* Contextualizers */
1689 =for apidoc op_contextualize
1691 Applies a syntactic context to an op tree representing an expression.
1692 C<o> is the op tree, and C<context> must be C<G_SCALAR>, C<G_LIST>,
1693 or C<G_VOID> to specify the context to apply. The modified op tree
1700 Perl_op_contextualize(pTHX_ OP *o, I32 context)
1702 PERL_ARGS_ASSERT_OP_CONTEXTUALIZE;
1704 case G_SCALAR: return scalar(o);
1705 case G_LIST: return list(o);
1706 case G_VOID: return scalarvoid(o);
1708 Perl_croak(aTHX_ "panic: op_contextualize bad context %ld",
1715 =for apidoc op_linklist
1716 This function is the implementation of the L</LINKLIST> macro. It should
1717 not be called directly.
1724 Perl_op_linklist(pTHX_ OP *o)
1731 PERL_ARGS_ASSERT_OP_LINKLIST;
1734 /* Descend down the tree looking for any unprocessed subtrees to
1737 if (o->op_flags & OPf_KIDS) {
1738 o = cUNOPo->op_first;
1741 o->op_next = o; /* leaf node; link to self initially */
1744 /* if we're at the top level, there either weren't any children
1745 * to process, or we've worked our way back to the top. */
1749 /* o is now processed. Next, process any sibling subtrees */
1751 if (OpHAS_SIBLING(o)) {
1756 /* Done all the subtrees at this level. Go back up a level and
1757 * link the parent in with all its (processed) children.
1760 o = o->op_sibparent;
1761 assert(!o->op_next);
1762 prevp = &(o->op_next);
1763 kid = (o->op_flags & OPf_KIDS) ? cUNOPo->op_first : NULL;
1765 *prevp = kid->op_next;
1766 prevp = &(kid->op_next);
1767 kid = OpSIBLING(kid);
1775 S_scalarkids(pTHX_ OP *o)
1777 if (o && o->op_flags & OPf_KIDS) {
1779 for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
1786 S_scalarboolean(pTHX_ OP *o)
1788 PERL_ARGS_ASSERT_SCALARBOOLEAN;
1790 if ((o->op_type == OP_SASSIGN && cBINOPo->op_first->op_type == OP_CONST &&
1791 !(cBINOPo->op_first->op_flags & OPf_SPECIAL)) ||
1792 (o->op_type == OP_NOT && cUNOPo->op_first->op_type == OP_SASSIGN &&
1793 cBINOPx(cUNOPo->op_first)->op_first->op_type == OP_CONST &&
1794 !(cBINOPx(cUNOPo->op_first)->op_first->op_flags & OPf_SPECIAL))) {
1795 if (ckWARN(WARN_SYNTAX)) {
1796 const line_t oldline = CopLINE(PL_curcop);
1798 if (PL_parser && PL_parser->copline != NOLINE) {
1799 /* This ensures that warnings are reported at the first line
1800 of the conditional, not the last. */
1801 CopLINE_set(PL_curcop, PL_parser->copline);
1803 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Found = in conditional, should be ==");
1804 CopLINE_set(PL_curcop, oldline);
1811 S_op_varname_subscript(pTHX_ const OP *o, int subscript_type)
1814 assert(o->op_type == OP_PADAV || o->op_type == OP_RV2AV ||
1815 o->op_type == OP_PADHV || o->op_type == OP_RV2HV);
1817 const char funny = o->op_type == OP_PADAV
1818 || o->op_type == OP_RV2AV ? '@' : '%';
1819 if (o->op_type == OP_RV2AV || o->op_type == OP_RV2HV) {
1821 if (cUNOPo->op_first->op_type != OP_GV
1822 || !(gv = cGVOPx_gv(cUNOPo->op_first)))
1824 return varname(gv, funny, 0, NULL, 0, subscript_type);
1827 varname(MUTABLE_GV(PL_compcv), funny, o->op_targ, NULL, 0, subscript_type);
1832 Perl_op_varname(pTHX_ const OP *o)
1834 PERL_ARGS_ASSERT_OP_VARNAME;
1836 return S_op_varname_subscript(aTHX_ o, 1);
1841 Warns that an access of a single element from a named container variable in
1842 scalar context might not be what the programmer wanted. The container
1843 variable's (sigiled, full) name is given by C<name>, and the key to access
1844 it is given by the C<SVOP_sv> of the C<OP_CONST> op given by C<o>.
1845 C<is_hash> selects whether it prints using {KEY} or [KEY] brackets.
1847 C<is_slice> selects between two different messages used in different places.
1850 Perl_warn_elem_scalar_context(pTHX_ const OP *o, SV *name, bool is_hash, bool is_slice)
1852 PERL_ARGS_ASSERT_WARN_ELEM_SCALAR_CONTEXT;
1855 const char *keypv = NULL;
1857 const char lbrack = is_hash ? '{' : '[';
1858 const char rbrack = is_hash ? '}' : ']';
1860 if (o->op_type == OP_CONST) {
1864 keysv = sv_newmortal();
1865 pv_pretty(keysv, SvPVX_const(sv), SvCUR(sv), 32, NULL, NULL,
1866 PERL_PV_PRETTY_DUMP |PERL_PV_ESCAPE_UNI_DETECT);
1868 else if (!SvOK(keysv))
1873 assert(SvPOK(name));
1874 sv_chop(name,SvPVX(name)+1);
1880 /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1881 PERL_DIAG_WARN_SYNTAX(
1882 "Scalar value @%" SVf "%c%s%c better written as $%" SVf "%c%s%c") :
1883 /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1884 PERL_DIAG_WARN_SYNTAX(
1885 "%%%" SVf "%c%s%c in scalar context better written as $%" SVf "%c%s%c");
1887 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), msg,
1888 SVfARG(name), lbrack, keypv, rbrack,
1889 SVfARG(name), lbrack, keypv, rbrack);
1893 /* diag_listed_as: Scalar value @%s[%s] better written as $%s[%s] */
1894 PERL_DIAG_WARN_SYNTAX(
1895 "Scalar value @%" SVf "%c%" SVf "%c better written as $%" SVf "%c%" SVf "%c") :
1896 /* diag_listed_as: %%s[%s] in scalar context better written as $%s[%s] */
1897 PERL_DIAG_WARN_SYNTAX(
1898 "%%%" SVf "%c%" SVf "%c in scalar context better written as $%" SVf "%c%" SVf "%c");
1900 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), msg,
1901 SVfARG(name), lbrack, SVfARG(keysv), rbrack,
1902 SVfARG(name), lbrack, SVfARG(keysv), rbrack);
1907 /* apply scalar context to the o subtree */
1910 Perl_scalar(pTHX_ OP *o)
1915 OP *next_kid = NULL; /* what op (if any) to process next */
1918 /* assumes no premature commitment */
1919 if (!o || (PL_parser && PL_parser->error_count)
1920 || (o->op_flags & OPf_WANT)
1921 || o->op_type == OP_RETURN)
1926 o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_SCALAR;
1928 switch (o->op_type) {
1930 scalar(cBINOPo->op_first);
1931 /* convert what initially looked like a list repeat into a
1932 * scalar repeat, e.g. $s = (1) x $n
1934 if (o->op_private & OPpREPEAT_DOLIST) {
1935 kid = cLISTOPx(cUNOPo->op_first)->op_first;
1936 assert(kid->op_type == OP_PUSHMARK);
1937 if (OpHAS_SIBLING(kid) && !OpHAS_SIBLING(OpSIBLING(kid))) {
1938 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
1939 o->op_private &=~ OPpREPEAT_DOLIST;
1947 /* impose scalar context on everything except the condition */
1948 next_kid = OpSIBLING(cUNOPo->op_first);
1952 if (o->op_flags & OPf_KIDS)
1953 next_kid = cUNOPo->op_first; /* do all kids */
1956 /* the children of these ops are usually a list of statements,
1957 * except the leaves, whose first child is a corresponding enter
1962 kid = cLISTOPo->op_first;
1966 kid = cLISTOPo->op_first;
1968 kid = OpSIBLING(kid);
1971 OP *sib = OpSIBLING(kid);
1972 /* Apply void context to all kids except the last, which
1973 * is scalar (ignoring a trailing ex-nextstate in determining
1974 * if it's the last kid). E.g.
1975 * $scalar = do { void; void; scalar }
1976 * Except that 'when's are always scalar, e.g.
1977 * $scalar = do { given(..) {
1978 * when (..) { scalar }
1979 * when (..) { scalar }
1984 || ( !OpHAS_SIBLING(sib)
1985 && sib->op_type == OP_NULL
1986 && ( sib->op_targ == OP_NEXTSTATE
1987 || sib->op_targ == OP_DBSTATE )
1991 /* tail call optimise calling scalar() on the last kid */
1995 else if (kid->op_type == OP_LEAVEWHEN)
2001 NOT_REACHED; /* NOTREACHED */
2005 Perl_ck_warner(aTHX_ packWARN(WARN_SCALAR), "Useless use of %s in scalar context", "sort");
2011 /* Warn about scalar context */
2014 /* This warning can be nonsensical when there is a syntax error. */
2015 if (PL_parser && PL_parser->error_count)
2018 if (!ckWARN(WARN_SYNTAX)) break;
2020 kid = cLISTOPo->op_first;
2021 kid = OpSIBLING(kid); /* get past pushmark */
2022 assert(OpSIBLING(kid));
2023 name = op_varname(OpSIBLING(kid));
2024 if (!name) /* XS module fiddling with the op tree */
2026 warn_elem_scalar_context(kid, name, o->op_type == OP_KVHSLICE, false);
2030 /* If next_kid is set, someone in the code above wanted us to process
2031 * that kid and all its remaining siblings. Otherwise, work our way
2032 * back up the tree */
2036 return top_op; /* at top; no parents/siblings to try */
2037 if (OpHAS_SIBLING(o))
2038 next_kid = o->op_sibparent;
2040 o = o->op_sibparent; /*try parent's next sibling */
2041 switch (o->op_type) {
2047 /* should really restore PL_curcop to its old value, but
2048 * setting it to PL_compiling is better than do nothing */
2049 PL_curcop = &PL_compiling;
2058 /* apply void context to the optree arg */
2061 Perl_scalarvoid(pTHX_ OP *arg)
2067 PERL_ARGS_ASSERT_SCALARVOID;
2071 SV *useless_sv = NULL;
2072 const char* useless = NULL;
2073 OP * next_kid = NULL;
2075 if (o->op_type == OP_NEXTSTATE
2076 || o->op_type == OP_DBSTATE
2077 || (o->op_type == OP_NULL && (o->op_targ == OP_NEXTSTATE
2078 || o->op_targ == OP_DBSTATE)))
2079 PL_curcop = (COP*)o; /* for warning below */
2081 /* assumes no premature commitment */
2082 want = o->op_flags & OPf_WANT;
2083 if ((want && want != OPf_WANT_SCALAR)
2084 || (PL_parser && PL_parser->error_count)
2085 || o->op_type == OP_RETURN || o->op_type == OP_REQUIRE || o->op_type == OP_LEAVEWHEN)
2090 if ((o->op_private & OPpTARGET_MY)
2091 && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2093 /* newASSIGNOP has already applied scalar context, which we
2094 leave, as if this op is inside SASSIGN. */
2098 o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_VOID;
2100 switch (o->op_type) {
2102 if (!(PL_opargs[o->op_type] & OA_FOLDCONST))
2106 if (o->op_flags & OPf_STACKED)
2108 if (o->op_type == OP_REPEAT)
2109 scalar(cBINOPo->op_first);
2112 if ((o->op_flags & OPf_STACKED) &&
2113 !(o->op_private & OPpCONCAT_NESTED))
2117 if (o->op_private == 4)
2152 case OP_GETSOCKNAME:
2153 case OP_GETPEERNAME:
2158 case OP_GETPRIORITY:
2183 useless = OP_DESC(o);
2193 case OP_AELEMFAST_LEX:
2197 if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))
2198 /* Otherwise it's "Useless use of grep iterator" */
2199 useless = OP_DESC(o);
2203 if (!(o->op_private & OPpSPLIT_ASSIGN))
2204 useless = OP_DESC(o);
2208 kid = cUNOPo->op_first;
2209 if (kid->op_type != OP_MATCH && kid->op_type != OP_SUBST &&
2210 kid->op_type != OP_TRANS && kid->op_type != OP_TRANSR) {
2213 useless = "negative pattern binding (!~)";
2217 if (cPMOPo->op_pmflags & PMf_NONDESTRUCT)
2218 useless = "non-destructive substitution (s///r)";
2222 useless = "non-destructive transliteration (tr///r)";
2229 if (!(o->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)) &&
2230 (!OpHAS_SIBLING(o) || OpSIBLING(o)->op_type != OP_READLINE))
2231 useless = "a variable";
2236 if (cSVOPo->op_private & OPpCONST_STRICT)
2237 no_bareword_allowed(o);
2239 if (ckWARN(WARN_VOID)) {
2241 /* don't warn on optimised away booleans, eg
2242 * use constant Foo, 5; Foo || print; */
2243 if (cSVOPo->op_private & OPpCONST_SHORTCIRCUIT)
2245 /* the constants 0 and 1 are permitted as they are
2246 conventionally used as dummies in constructs like
2247 1 while some_condition_with_side_effects; */
2248 else if (SvNIOK(sv) && ((nv = SvNV(sv)) == 0.0 || nv == 1.0))
2250 else if (SvPOK(sv)) {
2251 SV * const dsv = newSVpvs("");
2253 = Perl_newSVpvf(aTHX_
2255 pv_pretty(dsv, SvPVX_const(sv),
2256 SvCUR(sv), 32, NULL, NULL,
2258 | PERL_PV_ESCAPE_NOCLEAR
2259 | PERL_PV_ESCAPE_UNI_DETECT));
2260 SvREFCNT_dec_NN(dsv);
2262 else if (SvOK(sv)) {
2263 useless_sv = Perl_newSVpvf(aTHX_ "a constant (%" SVf ")", SVfARG(sv));
2266 useless = "a constant (undef)";
2269 op_null(o); /* don't execute or even remember it */
2273 OpTYPE_set(o, OP_PREINC); /* pre-increment is faster */
2277 OpTYPE_set(o, OP_PREDEC); /* pre-decrement is faster */
2281 OpTYPE_set(o, OP_I_PREINC); /* pre-increment is faster */
2285 OpTYPE_set(o, OP_I_PREDEC); /* pre-decrement is faster */
2290 UNOP *refgen, *rv2cv;
2293 if ((o->op_private & ~OPpASSIGN_BACKWARDS) != 2)
2296 rv2gv = cBINOPo->op_last;
2297 if (!rv2gv || rv2gv->op_type != OP_RV2GV)
2300 refgen = cUNOPx(cBINOPo->op_first);
2302 if (!refgen || (refgen->op_type != OP_REFGEN
2303 && refgen->op_type != OP_SREFGEN))
2306 exlist = cLISTOPx(refgen->op_first);
2307 if (!exlist || exlist->op_type != OP_NULL
2308 || exlist->op_targ != OP_LIST)
2311 if (exlist->op_first->op_type != OP_PUSHMARK
2312 && exlist->op_first != exlist->op_last)
2315 rv2cv = cUNOPx(exlist->op_last);
2317 if (rv2cv->op_type != OP_RV2CV)
2320 assert ((rv2gv->op_private & OPpDONT_INIT_GV) == 0);
2321 assert ((o->op_private & OPpASSIGN_CV_TO_GV) == 0);
2322 assert ((rv2cv->op_private & OPpMAY_RETURN_CONSTANT) == 0);
2324 o->op_private |= OPpASSIGN_CV_TO_GV;
2325 rv2gv->op_private |= OPpDONT_INIT_GV;
2326 rv2cv->op_private |= OPpMAY_RETURN_CONSTANT;
2338 kid = cLOGOPo->op_first;
2339 if (kid->op_type == OP_NOT
2340 && (kid->op_flags & OPf_KIDS)) {
2341 if (o->op_type == OP_AND) {
2342 OpTYPE_set(o, OP_OR);
2344 OpTYPE_set(o, OP_AND);
2354 next_kid = OpSIBLING(cUNOPo->op_first);
2358 if (o->op_flags & OPf_STACKED)
2365 if (!(o->op_flags & OPf_KIDS))
2376 next_kid = cLISTOPo->op_first;
2379 /* If the first kid after pushmark is something that the padrange
2380 optimisation would reject, then null the list and the pushmark.
2382 if ((kid = cLISTOPo->op_first)->op_type == OP_PUSHMARK
2383 && ( !(kid = OpSIBLING(kid))
2384 || ( kid->op_type != OP_PADSV
2385 && kid->op_type != OP_PADAV
2386 && kid->op_type != OP_PADHV)
2387 || kid->op_private & ~OPpLVAL_INTRO
2388 || !(kid = OpSIBLING(kid))
2389 || ( kid->op_type != OP_PADSV
2390 && kid->op_type != OP_PADAV
2391 && kid->op_type != OP_PADHV)
2392 || kid->op_private & ~OPpLVAL_INTRO)
2394 op_null(cUNOPo->op_first); /* NULL the pushmark */
2395 op_null(o); /* NULL the list */
2407 /* mortalise it, in case warnings are fatal. */
2408 Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2409 "Useless use of %" SVf " in void context",
2410 SVfARG(sv_2mortal(useless_sv)));
2413 Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
2414 "Useless use of %s in void context",
2419 /* if a kid hasn't been nominated to process, continue with the
2420 * next sibling, or if no siblings left, go back to the parent's
2421 * siblings and so on
2425 return arg; /* at top; no parents/siblings to try */
2426 if (OpHAS_SIBLING(o))
2427 next_kid = o->op_sibparent;
2429 o = o->op_sibparent; /*try parent's next sibling */
2439 S_listkids(pTHX_ OP *o)
2441 if (o && o->op_flags & OPf_KIDS) {
2443 for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2450 /* apply list context to the o subtree */
2453 Perl_list(pTHX_ OP *o)
2458 OP *next_kid = NULL; /* what op (if any) to process next */
2462 /* assumes no premature commitment */
2463 if (!o || (o->op_flags & OPf_WANT)
2464 || (PL_parser && PL_parser->error_count)
2465 || o->op_type == OP_RETURN)
2470 if ((o->op_private & OPpTARGET_MY)
2471 && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
2473 goto do_next; /* As if inside SASSIGN */
2476 o->op_flags = (o->op_flags & ~OPf_WANT) | OPf_WANT_LIST;
2478 switch (o->op_type) {
2480 if (o->op_private & OPpREPEAT_DOLIST
2481 && !(o->op_flags & OPf_STACKED))
2483 list(cBINOPo->op_first);
2484 kid = cBINOPo->op_last;
2485 /* optimise away (.....) x 1 */
2486 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)
2487 && SvIVX(kSVOP_sv) == 1)
2489 op_null(o); /* repeat */
2490 op_null(cUNOPx(cBINOPo->op_first)->op_first);/* pushmark */
2492 op_free(op_sibling_splice(o, cBINOPo->op_first, 1, NULL));
2500 /* impose list context on everything except the condition */
2501 next_kid = OpSIBLING(cUNOPo->op_first);
2505 if (!(o->op_flags & OPf_KIDS))
2507 /* possibly flatten 1..10 into a constant array */
2508 if (!o->op_next && cUNOPo->op_first->op_type == OP_FLOP) {
2509 list(cBINOPo->op_first);
2510 gen_constant_list(o);
2513 next_kid = cUNOPo->op_first; /* do all kids */
2517 if (cLISTOPo->op_first->op_type == OP_PUSHMARK) {
2518 op_null(cUNOPo->op_first); /* NULL the pushmark */
2519 op_null(o); /* NULL the list */
2521 if (o->op_flags & OPf_KIDS)
2522 next_kid = cUNOPo->op_first; /* do all kids */
2525 /* the children of these ops are usually a list of statements,
2526 * except the leaves, whose first child is a corresponding enter
2530 kid = cLISTOPo->op_first;
2534 kid = cLISTOPo->op_first;
2536 kid = OpSIBLING(kid);
2539 OP *sib = OpSIBLING(kid);
2540 /* Apply void context to all kids except the last, which
2542 * @a = do { void; void; list }
2543 * Except that 'when's are always list context, e.g.
2544 * @a = do { given(..) {
2545 * when (..) { list }
2546 * when (..) { list }
2551 /* tail call optimise calling list() on the last kid */
2555 else if (kid->op_type == OP_LEAVEWHEN)
2561 NOT_REACHED; /* NOTREACHED */
2566 /* If next_kid is set, someone in the code above wanted us to process
2567 * that kid and all its remaining siblings. Otherwise, work our way
2568 * back up the tree */
2572 return top_op; /* at top; no parents/siblings to try */
2573 if (OpHAS_SIBLING(o))
2574 next_kid = o->op_sibparent;
2576 o = o->op_sibparent; /*try parent's next sibling */
2577 switch (o->op_type) {
2583 /* should really restore PL_curcop to its old value, but
2584 * setting it to PL_compiling is better than do nothing */
2585 PL_curcop = &PL_compiling;
2595 /* apply void context to non-final ops of a sequence */
2598 S_voidnonfinal(pTHX_ OP *o)
2601 const OPCODE type = o->op_type;
2603 if (type == OP_LINESEQ || type == OP_SCOPE ||
2604 type == OP_LEAVE || type == OP_LEAVETRY)
2606 OP *kid = cLISTOPo->op_first, *sib;
2607 if(type == OP_LEAVE) {
2608 /* Don't put the OP_ENTER in void context */
2609 assert(kid->op_type == OP_ENTER);
2610 kid = OpSIBLING(kid);
2612 for (; kid; kid = sib) {
2613 if ((sib = OpSIBLING(kid))
2614 && ( OpHAS_SIBLING(sib) || sib->op_type != OP_NULL
2615 || ( sib->op_targ != OP_NEXTSTATE
2616 && sib->op_targ != OP_DBSTATE )))
2621 PL_curcop = &PL_compiling;
2623 o->op_flags &= ~OPf_PARENS;
2624 if (PL_hints & HINT_BLOCK_SCOPE)
2625 o->op_flags |= OPf_PARENS;
2628 o = newOP(OP_STUB, 0);
2633 S_modkids(pTHX_ OP *o, I32 type)
2635 if (o && o->op_flags & OPf_KIDS) {
2637 for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
2638 op_lvalue(kid, type);
2644 /* for a helem/hslice/kvslice, if its a fixed hash, croak on invalid
2645 * const fields. Also, convert CONST keys to HEK-in-SVs.
2646 * rop is the op that retrieves the hash;
2647 * key_op is the first key
2648 * real if false, only check (and possibly croak); don't update op
2652 Perl_check_hash_fields_and_hekify(pTHX_ UNOP *rop, SVOP *key_op, int real)
2658 /* find the padsv corresponding to $lex->{} or @{$lex}{} */
2660 if (rop->op_first->op_type == OP_PADSV)
2661 /* @$hash{qw(keys here)} */
2662 rop = cUNOPx(rop->op_first);
2664 /* @{$hash}{qw(keys here)} */
2665 if (rop->op_first->op_type == OP_SCOPE
2666 && cLISTOPx(rop->op_first)->op_last->op_type == OP_PADSV)
2668 rop = cUNOPx(cLISTOPx(rop->op_first)->op_last);
2675 lexname = NULL; /* just to silence compiler warnings */
2676 fields = NULL; /* just to silence compiler warnings */
2680 && (lexname = padnamelist_fetch(PL_comppad_name, rop->op_targ),
2681 PadnameHasTYPE(lexname))
2682 && (fields = (GV**)hv_fetchs(PadnameTYPE(lexname), "FIELDS", FALSE))
2683 && isGV(*fields) && GvHV(*fields);
2685 for (; key_op; key_op = cSVOPx(OpSIBLING(key_op))) {
2687 if (key_op->op_type != OP_CONST)
2689 svp = cSVOPx_svp(key_op);
2691 /* make sure it's not a bareword under strict subs */
2692 if (key_op->op_private & OPpCONST_BARE &&
2693 key_op->op_private & OPpCONST_STRICT)
2695 no_bareword_allowed((OP*)key_op);
2698 /* Make the CONST have a shared SV */
2699 if ( !SvIsCOW_shared_hash(sv = *svp)
2700 && SvTYPE(sv) < SVt_PVMG
2706 const char * const key = SvPV_const(sv, *(STRLEN*)&keylen);
2707 SV *nsv = newSVpvn_share(key, SvUTF8(sv) ? -keylen : keylen, 0);
2708 SvREFCNT_dec_NN(sv);
2713 && !hv_fetch_ent(GvHV(*fields), *svp, FALSE, 0))
2715 Perl_croak(aTHX_ "No such class field \"%" SVf "\" "
2716 "in variable %" PNf " of type %" HEKf,
2717 SVfARG(*svp), PNfARG(lexname),
2718 HEKfARG(HvNAME_HEK(PadnameTYPE(lexname))));
2724 /* do all the final processing on an optree (e.g. running the peephole
2725 * optimiser on it), then attach it to cv (if cv is non-null)
2729 S_process_optree(pTHX_ CV *cv, OP *optree, OP* start)
2733 /* XXX for some reason, evals, require and main optrees are
2734 * never attached to their CV; instead they just hang off
2735 * PL_main_root + PL_main_start or PL_eval_root + PL_eval_start
2736 * and get manually freed when appropriate */
2738 startp = &CvSTART(cv);
2740 startp = PL_in_eval? &PL_eval_start : &PL_main_start;
2743 optree->op_private |= OPpREFCOUNTED;
2744 OpREFCNT_set(optree, 1);
2745 optimize_optree(optree);
2747 finalize_optree(optree);
2748 op_prune_chain_head(startp);
2751 /* now that optimizer has done its work, adjust pad values */
2752 pad_tidy(optree->op_type == OP_LEAVEWRITE ? padtidy_FORMAT
2753 : CvCLONE(cv) ? padtidy_SUBCLONE : padtidy_SUB);
2758 /* Relocate sv to the pad for thread safety.
2759 * Despite being a "constant", the SV is written to,
2760 * for reference counts, sv_upgrade() etc. */
2762 Perl_op_relocate_sv(pTHX_ SV** svp, PADOFFSET* targp)
2765 PERL_ARGS_ASSERT_OP_RELOCATE_SV;
2767 ix = pad_alloc(OP_CONST, SVf_READONLY);
2768 SvREFCNT_dec(PAD_SVl(ix));
2769 PAD_SETSV(ix, *svp);
2770 /* XXX I don't know how this isn't readonly already. */
2771 if (!SvIsCOW(PAD_SVl(ix))) SvREADONLY_on(PAD_SVl(ix));
2778 S_mark_padname_lvalue(pTHX_ PADNAME *pn)
2781 PadnameLVALUE_on(pn);
2782 while (PadnameOUTER(pn) && PARENT_PAD_INDEX(pn)) {
2784 /* RT #127786: cv can be NULL due to an eval within the DB package
2785 * called from an anon sub - anon subs don't have CvOUTSIDE() set
2786 * unless they contain an eval, but calling eval within DB
2787 * pretends the eval was done in the caller's scope.
2791 assert(CvPADLIST(cv));
2793 PadlistNAMESARRAY(CvPADLIST(cv))[PARENT_PAD_INDEX(pn)];
2794 assert(PadnameLEN(pn));
2795 PadnameLVALUE_on(pn);
2800 S_vivifies(const OPCODE type)
2803 case OP_RV2AV: case OP_ASLICE:
2804 case OP_RV2HV: case OP_KVASLICE:
2805 case OP_RV2SV: case OP_HSLICE:
2806 case OP_AELEMFAST: case OP_KVHSLICE:
2815 /* apply lvalue reference (aliasing) context to the optree o.
2818 * o would be the list ($x,$y) and type would be OP_AASSIGN.
2819 * It may descend and apply this to children too, for example in
2820 * \( $cond ? $x, $y) = (...)
2824 S_lvref(pTHX_ OP *o, I32 type)
2830 switch (o->op_type) {
2832 o = OpSIBLING(cUNOPo->op_first);
2839 if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2840 o->op_flags |= OPf_STACKED;
2841 if (o->op_flags & OPf_PARENS) {
2842 if (o->op_private & OPpLVAL_INTRO) {
2843 yyerror(Perl_form(aTHX_ "Can't modify reference to "
2844 "localized parenthesized array in list assignment"));
2848 OpTYPE_set(o, OP_LVAVREF);
2849 o->op_private &= OPpLVAL_INTRO|OPpPAD_STATE;
2850 o->op_flags |= OPf_MOD|OPf_REF;
2853 o->op_private |= OPpLVREF_AV;
2857 kid = cUNOPo->op_first;
2858 if (kid->op_type == OP_NULL)
2859 kid = cUNOPx(OpSIBLING(kUNOP->op_first))
2861 o->op_private = OPpLVREF_CV;
2862 if (kid->op_type == OP_GV)
2863 o->op_flags |= OPf_STACKED;
2864 else if (kid->op_type == OP_PADCV) {
2865 o->op_targ = kid->op_targ;
2867 op_free(cUNOPo->op_first);
2868 cUNOPo->op_first = NULL;
2869 o->op_flags &=~ OPf_KIDS;
2875 if (o->op_flags & OPf_PARENS) {
2877 yyerror(Perl_form(aTHX_ "Can't modify reference to "
2878 "parenthesized hash in list assignment"));
2881 o->op_private |= OPpLVREF_HV;
2885 if (cUNOPo->op_first->op_type != OP_GV) goto badref;
2886 o->op_flags |= OPf_STACKED;
2890 if (o->op_flags & OPf_PARENS) goto parenhash;
2891 o->op_private |= OPpLVREF_HV;
2894 PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2898 PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
2899 if (o->op_flags & OPf_PARENS) goto slurpy;
2900 o->op_private |= OPpLVREF_AV;
2905 o->op_private |= OPpLVREF_ELEM;
2906 o->op_flags |= OPf_STACKED;
2911 OpTYPE_set(o, OP_LVREFSLICE);
2912 o->op_private &= OPpLVAL_INTRO;
2916 if (o->op_flags & OPf_SPECIAL) /* do BLOCK */
2918 else if (!(o->op_flags & OPf_KIDS))
2921 /* the code formerly only recursed into the first child of
2922 * a non ex-list OP_NULL. if we ever encounter such a null op with
2923 * more than one child, need to decide whether its ok to process
2924 * *all* its kids or not */
2925 assert(o->op_targ == OP_LIST
2926 || !(OpHAS_SIBLING(cBINOPo->op_first)));
2929 o = cLISTOPo->op_first;
2933 if (o->op_flags & OPf_PARENS)
2938 /* diag_listed_as: Can't modify reference to %s in %s assignment */
2939 yyerror(Perl_form(aTHX_ "Can't modify reference to %s in %s",
2940 o->op_type == OP_NULL && o->op_flags & OPf_SPECIAL
2947 OpTYPE_set(o, OP_LVREF);
2949 OPpLVAL_INTRO|OPpLVREF_ELEM|OPpLVREF_TYPE|OPpPAD_STATE;
2950 if (type == OP_ENTERLOOP)
2951 o->op_private |= OPpLVREF_ITER;
2956 return; /* at top; no parents/siblings to try */
2957 if (OpHAS_SIBLING(o)) {
2958 o = o->op_sibparent;
2961 o = o->op_sibparent; /*try parent's next sibling */
2967 PERL_STATIC_INLINE bool
2968 S_potential_mod_type(I32 type)
2970 /* Types that only potentially result in modification. */
2971 return type == OP_GREPSTART || type == OP_ENTERSUB
2972 || type == OP_REFGEN || type == OP_LEAVESUBLV;
2977 =for apidoc op_lvalue
2979 Propagate lvalue ("modifiable") context to an op and its children.
2980 C<type> represents the context type, roughly based on the type of op that
2981 would do the modifying, although C<local()> is represented by C<OP_NULL>,
2982 because it has no op type of its own (it is signalled by a flag on
2985 This function detects things that can't be modified, such as C<$x+1>, and
2986 generates errors for them. For example, C<$x+1 = 2> would cause it to be
2987 called with an op of type C<OP_ADD> and a C<type> argument of C<OP_SASSIGN>.
2989 It also flags things that need to behave specially in an lvalue context,
2990 such as C<$$x = 5> which might have to vivify a reference in C<$x>.
2994 Perl_op_lvalue_flags() is a non-API lower-level interface to
2995 op_lvalue(). The flags param has these bits:
2996 OP_LVALUE_NO_CROAK: return rather than croaking on error
3001 Perl_op_lvalue_flags(pTHX_ OP *o, I32 type, U32 flags)
3005 if (!o || (PL_parser && PL_parser->error_count))
3010 /* -1 = error on localize, 0 = ignore localize, 1 = ok to localize */
3012 OP *next_kid = NULL;
3014 if ((o->op_private & OPpTARGET_MY)
3015 && (PL_opargs[o->op_type] & OA_TARGLEX))/* OPp share the meaning */
3020 /* elements of a list might be in void context because the list is
3021 in scalar context or because they are attribute sub calls */
3022 if ((o->op_flags & OPf_WANT) == OPf_WANT_VOID)
3025 if (type == OP_PRTF || type == OP_SPRINTF) type = OP_ENTERSUB;
3027 switch (o->op_type) {
3029 if (type == OP_SASSIGN)
3035 if ((o->op_flags & OPf_PARENS))
3040 if ((type == OP_UNDEF || type == OP_REFGEN || type == OP_LOCK) &&
3041 !(o->op_flags & OPf_STACKED)) {
3042 OpTYPE_set(o, OP_RV2CV); /* entersub => rv2cv */
3043 assert(cUNOPo->op_first->op_type == OP_NULL);
3044 op_null(cLISTOPx(cUNOPo->op_first)->op_first);/* disable pushmark */
3047 else { /* lvalue subroutine call */
3048 o->op_private |= OPpLVAL_INTRO;
3049 PL_modcount = RETURN_UNLIMITED_NUMBER;
3050 if (S_potential_mod_type(type)) {
3051 o->op_private |= OPpENTERSUB_INARGS;
3054 else { /* Compile-time error message: */
3055 OP *kid = cUNOPo->op_first;
3060 if (kid->op_type != OP_PUSHMARK) {
3061 if (kid->op_type != OP_NULL || kid->op_targ != OP_LIST)
3063 "panic: unexpected lvalue entersub "
3064 "args: type/targ %ld:%" UVuf,
3065 (long)kid->op_type, (UV)kid->op_targ);
3066 kid = kLISTOP->op_first;
3068 while (OpHAS_SIBLING(kid))
3069 kid = OpSIBLING(kid);
3070 if (!(kid->op_type == OP_NULL && kid->op_targ == OP_RV2CV)) {
3071 break; /* Postpone until runtime */
3074 kid = kUNOP->op_first;
3075 if (kid->op_type == OP_NULL && kid->op_targ == OP_RV2SV)
3076 kid = kUNOP->op_first;
3077 if (kid->op_type == OP_NULL)
3079 "panic: unexpected constant lvalue entersub "
3080 "entry via type/targ %ld:%" UVuf,
3081 (long)kid->op_type, (UV)kid->op_targ);
3082 if (kid->op_type != OP_GV) {
3089 : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
3090 ? MUTABLE_CV(SvRV(gv))
3096 if (flags & OP_LVALUE_NO_CROAK)
3099 namesv = cv_name(cv, NULL, 0);
3100 yyerror_pv(Perl_form(aTHX_ "Can't modify non-lvalue "
3101 "subroutine call of &%" SVf " in %s",
3102 SVfARG(namesv), PL_op_desc[type]),
3110 if (flags & OP_LVALUE_NO_CROAK) return NULL;
3111 /* grep, foreach, subcalls, refgen */
3112 if (S_potential_mod_type(type))
3114 yyerror(Perl_form(aTHX_ "Can't modify %s in %s",
3115 (o->op_type == OP_NULL && (o->op_flags & OPf_SPECIAL)
3118 type ? PL_op_desc[type] : "local"));
3131 case OP_RIGHT_SHIFT:
3140 if (!(o->op_flags & OPf_STACKED))
3146 if (o->op_flags & OPf_STACKED) {
3150 if (!(o->op_private & OPpREPEAT_DOLIST))
3153 const I32 mods = PL_modcount;
3154 /* we recurse rather than iterate here because we need to
3155 * calculate and use the delta applied to PL_modcount by the
3156 * first child. So in something like
3157 * ($x, ($y) x 3) = split;
3158 * split knows that 4 elements are wanted
3160 modkids(cBINOPo->op_first, type);
3161 if (type != OP_AASSIGN)
3163 kid = cBINOPo->op_last;
3164 if (kid->op_type == OP_CONST && SvIOK(kSVOP_sv)) {
3165 const IV iv = SvIV(kSVOP_sv);
3166 if (PL_modcount != RETURN_UNLIMITED_NUMBER)
3168 mods + (PL_modcount - mods) * (iv < 0 ? 0 : iv);
3171 PL_modcount = RETURN_UNLIMITED_NUMBER;
3177 next_kid = OpSIBLING(cUNOPo->op_first);
3182 if (type == OP_REFGEN && o->op_flags & OPf_PARENS) {
3183 PL_modcount = RETURN_UNLIMITED_NUMBER;
3184 /* Treat \(@foo) like ordinary list, but still mark it as modi-
3185 fiable since some contexts need to know. */
3186 o->op_flags |= OPf_MOD;
3191 if (scalar_mod_type(o, type))
3193 ref(cUNOPo->op_first, o->op_type);
3200 /* Do not apply the lvsub flag for rv2[ah]v in scalar context. */
3201 if (type == OP_LEAVESUBLV && (
3202 (o->op_type != OP_RV2AV && o->op_type != OP_RV2HV)
3203 || (o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
3205 o->op_private |= OPpMAYBE_LVSUB;
3209 PL_modcount = RETURN_UNLIMITED_NUMBER;
3215 if (type == OP_LEAVESUBLV)
3216 o->op_private |= OPpMAYBE_LVSUB;
3220 if (type == OP_LEAVESUBLV
3221 && (o->op_private & OPpAVHVSWITCH_MASK) + OP_EACH == OP_KEYS)
3222 o->op_private |= OPpMAYBE_LVSUB;
3226 PL_hints |= HINT_BLOCK_SCOPE;
3227 if (type == OP_LEAVESUBLV)
3228 o->op_private |= OPpMAYBE_LVSUB;
3233 ref(cUNOPo->op_first, o->op_type);
3237 PL_hints |= HINT_BLOCK_SCOPE;
3247 case OP_AELEMFAST_LEX:
3254 PL_modcount = RETURN_UNLIMITED_NUMBER;
3255 if (type == OP_REFGEN && o->op_flags & OPf_PARENS)
3257 /* Treat \(@foo) like ordinary list, but still mark it as modi-
3258 fiable since some contexts need to know. */
3259 o->op_flags |= OPf_MOD;
3262 if (scalar_mod_type(o, type))
3264 if ((o->op_flags & OPf_WANT) != OPf_WANT_SCALAR
3265 && type == OP_LEAVESUBLV)
3266 o->op_private |= OPpMAYBE_LVSUB;
3270 if (!type) /* local() */
3271 Perl_croak(aTHX_ "Can't localize lexical variable %" PNf,
3272 PNfARG(PAD_COMPNAME(o->op_targ)));
3273 if (!(o->op_private & OPpLVAL_INTRO)
3274 || ( type != OP_SASSIGN && type != OP_AASSIGN
3275 && PadnameIsSTATE(PAD_COMPNAME_SV(o->op_targ)) ))
3276 S_mark_padname_lvalue(aTHX_ PAD_COMPNAME_SV(o->op_targ));
3284 if (type != OP_LEAVESUBLV && !scalar_mod_type(NULL, type))
3288 if (o->op_private == 4) /* don't allow 4 arg substr as lvalue */
3294 if (type == OP_LEAVESUBLV)
3295 o->op_private |= OPpMAYBE_LVSUB;
3296 if (o->op_flags & OPf_KIDS && OpHAS_SIBLING(cBINOPo->op_first)) {
3297 /* we recurse rather than iterate here because the child
3298 * needs to be processed with a different 'type' parameter */
3300 /* substr and vec */
3301 /* If this op is in merely potential (non-fatal) modifiable
3302 context, then apply OP_ENTERSUB context to
3303 the kid op (to avoid croaking). Other-
3304 wise pass this op’s own type so the correct op is mentioned
3305 in error messages. */
3306 op_lvalue(OpSIBLING(cBINOPo->op_first),
3307 S_potential_mod_type(type)
3315 ref(cBINOPo->op_first, o->op_type);
3316 if (type == OP_ENTERSUB &&
3317 !(o->op_private & (OPpLVAL_INTRO | OPpDEREF)))
3318 o->op_private |= OPpLVAL_DEFER;
3319 if (type == OP_LEAVESUBLV)
3320 o->op_private |= OPpMAYBE_LVSUB;
3327 o->op_private |= OPpLVALUE;
3333 if (o->op_flags & OPf_KIDS)
3334 next_kid = cLISTOPo->op_last;
3339 if (o->op_flags & OPf_SPECIAL) /* do BLOCK */
3341 else if (!(o->op_flags & OPf_KIDS))
3344 if (o->op_targ != OP_LIST) {
3345 OP *sib = OpSIBLING(cLISTOPo->op_first);
3346 /* OP_TRANS and OP_TRANSR with argument have a weird optree
3353 * compared with things like OP_MATCH which have the argument
3359 * so handle specially to correctly get "Can't modify" croaks etc
3362 if (sib && (sib->op_type == OP_TRANS || sib->op_type == OP_TRANSR))
3364 /* this should trigger a "Can't modify transliteration" err */
3365 op_lvalue(sib, type);
3367 next_kid = cBINOPo->op_first;
3368 /* we assume OP_NULLs which aren't ex-list have no more than 2
3369 * children. If this assumption is wrong, increase the scan
3371 assert( !OpHAS_SIBLING(next_kid)
3372 || !OpHAS_SIBLING(OpSIBLING(next_kid)));
3378 next_kid = cLISTOPo->op_first;
3386 if (type == OP_LEAVESUBLV
3387 || !S_vivifies(cLOGOPo->op_first->op_type))
3388 next_kid = cLOGOPo->op_first;
3389 else if (type == OP_LEAVESUBLV
3390 || !S_vivifies(OpSIBLING(cLOGOPo->op_first)->op_type))
3391 next_kid = OpSIBLING(cLOGOPo->op_first);
3395 if (type == OP_NULL) { /* local */
3397 if (!FEATURE_MYREF_IS_ENABLED)
3398 Perl_croak(aTHX_ "The experimental declared_refs "
3399 "feature is not enabled");
3400 Perl_ck_warner_d(aTHX_
3401 packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
3402 "Declaring references is experimental");
3403 next_kid = cUNOPo->op_first;
3406 if (type != OP_AASSIGN && type != OP_SASSIGN
3407 && type != OP_ENTERLOOP)
3409 /* Don’t bother applying lvalue context to the ex-list. */
3410 kid = cUNOPx(cUNOPo->op_first)->op_first;
3411 assert (!OpHAS_SIBLING(kid));
3414 if (type == OP_NULL) /* local */
3416 if (type != OP_AASSIGN) goto nomod;
3417 kid = cUNOPo->op_first;
3420 const U8 ec = PL_parser ? PL_parser->error_count : 0;
3421 S_lvref(aTHX_ kid, type);
3422 if (!PL_parser || PL_parser->error_count == ec) {
3423 if (!FEATURE_REFALIASING_IS_ENABLED)
3425 "Experimental aliasing via reference not enabled");
3426 Perl_ck_warner_d(aTHX_
3427 packWARN(WARN_EXPERIMENTAL__REFALIASING),
3428 "Aliasing via reference is experimental");
3431 if (o->op_type == OP_REFGEN)
3432 op_null(cUNOPx(cUNOPo->op_first)->op_first); /* pushmark */
3437 if ((o->op_private & OPpSPLIT_ASSIGN)) {
3438 /* This is actually @array = split. */
3439 PL_modcount = RETURN_UNLIMITED_NUMBER;
3445 op_lvalue(cUNOPo->op_first, OP_ENTERSUB);
3449 /* [20011101.069 (#7861)] File test operators interpret OPf_REF to mean that
3450 their argument is a filehandle; thus \stat(".") should not set
3452 if (type == OP_REFGEN && OP_IS_STAT(o->op_type))
3455 if (type != OP_LEAVESUBLV)
3456 o->op_flags |= OPf_MOD;
3458 if (type == OP_AASSIGN || type == OP_SASSIGN)
3459 o->op_flags |= o->op_type == OP_ENTERSUB ? 0 : OPf_SPECIAL|OPf_REF;
3460 else if (!type) { /* local() */
3463 o->op_private |= OPpLVAL_INTRO;
3464 o->op_flags &= ~OPf_SPECIAL;
3465 PL_hints |= HINT_BLOCK_SCOPE;
3470 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
3471 "Useless localization of %s", OP_DESC(o));
3474 else if (type != OP_GREPSTART && type != OP_ENTERSUB
3475 && type != OP_LEAVESUBLV && o->op_type != OP_ENTERSUB)
3476 o->op_flags |= OPf_REF;
3481 return top_op; /* at top; no parents/siblings to try */
3482 if (OpHAS_SIBLING(o)) {
3483 next_kid = o->op_sibparent;
3484 if (!OpHAS_SIBLING(next_kid)) {
3485 /* a few node types don't recurse into their second child */
3486 OP *parent = next_kid->op_sibparent;
3487 I32 ptype = parent->op_type;
3488 if ( (ptype == OP_NULL && parent->op_targ != OP_LIST)
3489 || ( (ptype == OP_AND || ptype == OP_OR)
3490 && (type != OP_LEAVESUBLV
3491 && S_vivifies(next_kid->op_type))
3494 /*try parent's next sibling */
3501 o = o->op_sibparent; /*try parent's next sibling */
3512 S_scalar_mod_type(const OP *o, I32 type)
3517 if (o && o->op_type == OP_RV2GV)
3541 case OP_RIGHT_SHIFT:
3570 S_is_handle_constructor(const OP *o, I32 numargs)
3572 PERL_ARGS_ASSERT_IS_HANDLE_CONSTRUCTOR;
3574 switch (o->op_type) {
3582 case OP_SELECT: /* XXX c.f. SelectSaver.pm */
3595 S_refkids(pTHX_ OP *o, I32 type)
3597 if (o && o->op_flags & OPf_KIDS) {
3599 for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
3606 /* Apply reference (autovivification) context to the subtree at o.
3608 * push @{expression}, ....;
3609 * o will be the head of 'expression' and type will be OP_RV2AV.
3610 * It marks the op o (or a suitable child) as autovivifying, e.g. by
3612 * For OP_RV2AV/OP_PADAV and OP_RV2HV/OP_PADHV sets OPf_REF too if
3613 * set_op_ref is true.
3615 * Also calls scalar(o).
3619 Perl_doref(pTHX_ OP *o, I32 type, bool set_op_ref)
3623 PERL_ARGS_ASSERT_DOREF;
3625 if (PL_parser && PL_parser->error_count)
3629 switch (o->op_type) {
3631 if ((type == OP_EXISTS || type == OP_DEFINED) &&
3632 !(o->op_flags & OPf_STACKED)) {
3633 OpTYPE_set(o, OP_RV2CV); /* entersub => rv2cv */
3634 assert(cUNOPo->op_first->op_type == OP_NULL);
3635 /* disable pushmark */
3636 op_null(cLISTOPx(cUNOPo->op_first)->op_first);
3637 o->op_flags |= OPf_SPECIAL;
3639 else if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV){
3640 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3641 : type == OP_RV2HV ? OPpDEREF_HV
3643 o->op_flags |= OPf_MOD;
3649 o = OpSIBLING(cUNOPo->op_first);
3653 if (type == OP_DEFINED)
3654 o->op_flags |= OPf_SPECIAL; /* don't create GV */
3657 if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3658 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3659 : type == OP_RV2HV ? OPpDEREF_HV
3661 o->op_flags |= OPf_MOD;
3663 if (o->op_flags & OPf_KIDS) {
3665 o = cUNOPo->op_first;
3673 o->op_flags |= OPf_REF;
3676 if (type == OP_DEFINED)
3677 o->op_flags |= OPf_SPECIAL; /* don't create GV */
3679 o = cUNOPo->op_first;
3685 o->op_flags |= OPf_REF;
3690 if (!(o->op_flags & OPf_KIDS) || type == OP_DEFINED)
3692 o = cBINOPo->op_first;
3697 if (type == OP_RV2SV || type == OP_RV2AV || type == OP_RV2HV) {
3698 o->op_private |= (type == OP_RV2AV ? OPpDEREF_AV
3699 : type == OP_RV2HV ? OPpDEREF_HV
3701 o->op_flags |= OPf_MOD;
3704 o = cBINOPo->op_first;
3713 if (!(o->op_flags & OPf_KIDS))
3715 o = cLISTOPo->op_last;
3724 return scalar(top_op); /* at top; no parents/siblings to try */
3725 if (OpHAS_SIBLING(o)) {
3726 o = o->op_sibparent;
3727 /* Normally skip all siblings and go straight to the parent;
3728 * the only op that requires two children to be processed
3729 * is OP_COND_EXPR */
3730 if (!OpHAS_SIBLING(o)
3731 && o->op_sibparent->op_type == OP_COND_EXPR)
3735 o = o->op_sibparent; /*try parent's next sibling */
3742 S_dup_attrlist(pTHX_ OP *o)
3746 PERL_ARGS_ASSERT_DUP_ATTRLIST;
3748 /* An attrlist is either a simple OP_CONST or an OP_LIST with kids,
3749 * where the first kid is OP_PUSHMARK and the remaining ones
3750 * are OP_CONST. We need to push the OP_CONST values.
3752 if (o->op_type == OP_CONST)
3753 rop = newSVOP(OP_CONST, o->op_flags, SvREFCNT_inc_NN(cSVOPo->op_sv));
3755 assert((o->op_type == OP_LIST) && (o->op_flags & OPf_KIDS));
3757 for (o = cLISTOPo->op_first; o; o = OpSIBLING(o)) {
3758 if (o->op_type == OP_CONST)
3759 rop = op_append_elem(OP_LIST, rop,
3760 newSVOP(OP_CONST, o->op_flags,
3761 SvREFCNT_inc_NN(cSVOPo->op_sv)));
3768 S_apply_attrs(pTHX_ HV *stash, SV *target, OP *attrs)
3770 PERL_ARGS_ASSERT_APPLY_ATTRS;
3772 SV * const stashsv = newSVhek(HvNAME_HEK(stash));
3774 /* fake up C<use attributes $pkg,$rv,@attrs> */
3776 #define ATTRSMODULE "attributes"
3777 #define ATTRSMODULE_PM "attributes.pm"
3780 aTHX_ PERL_LOADMOD_IMPORT_OPS,
3781 newSVpvs(ATTRSMODULE),
3783 op_prepend_elem(OP_LIST,
3784 newSVOP(OP_CONST, 0, stashsv),
3785 op_prepend_elem(OP_LIST,
3786 newSVOP(OP_CONST, 0,
3788 dup_attrlist(attrs))));
3793 S_apply_attrs_my(pTHX_ HV *stash, OP *target, OP *attrs, OP **imopsp)
3795 OP *pack, *imop, *arg;
3796 SV *meth, *stashsv, **svp;
3798 PERL_ARGS_ASSERT_APPLY_ATTRS_MY;
3803 assert(target->op_type == OP_PADSV ||
3804 target->op_type == OP_PADHV ||
3805 target->op_type == OP_PADAV);
3807 /* Ensure that attributes.pm is loaded. */
3808 /* Don't force the C<use> if we don't need it. */
3809 svp = hv_fetchs(GvHVn(PL_incgv), ATTRSMODULE_PM, FALSE);
3810 if (svp && *svp != &PL_sv_undef)
3811 NOOP; /* already in %INC */
3813 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
3814 newSVpvs(ATTRSMODULE), NULL);
3816 /* Need package name for method call. */
3817 pack = newSVOP(OP_CONST, 0, newSVpvs(ATTRSMODULE));
3819 /* Build up the real arg-list. */
3820 stashsv = newSVhek(HvNAME_HEK(stash));
3822 arg = newOP(OP_PADSV, 0);
3823 arg->op_targ = target->op_targ;
3824 arg = op_prepend_elem(OP_LIST,
3825 newSVOP(OP_CONST, 0, stashsv),
3826 op_prepend_elem(OP_LIST,
3827 newUNOP(OP_REFGEN, 0,
3829 dup_attrlist(attrs)));
3831 /* Fake up a method call to import */
3832 meth = newSVpvs_share("import");
3833 imop = op_convert_list(OP_ENTERSUB, OPf_STACKED|OPf_WANT_VOID,
3834 op_append_elem(OP_LIST,
3835 op_prepend_elem(OP_LIST, pack, arg),
3836 newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
3838 /* Combine the ops. */
3839 *imopsp = op_append_elem(OP_LIST, *imopsp, imop);
3843 =notfor apidoc apply_attrs_string
3845 Attempts to apply a list of attributes specified by the C<attrstr> and
3846 C<len> arguments to the subroutine identified by the C<cv> argument which
3847 is expected to be associated with the package identified by the C<stashpv>
3848 argument (see L<attributes>). It gets this wrong, though, in that it
3849 does not correctly identify the boundaries of the individual attribute
3850 specifications within C<attrstr>. This is not really intended for the
3851 public API, but has to be listed here for systems such as AIX which
3852 need an explicit export list for symbols. (It's called from XS code
3853 in support of the C<ATTRS:> keyword from F<xsubpp>.) Patches to fix it
3854 to respect attribute syntax properly would be welcome.
3860 Perl_apply_attrs_string(pTHX_ const char *stashpv, CV *cv,
3861 const char *attrstr, STRLEN len)
3865 PERL_ARGS_ASSERT_APPLY_ATTRS_STRING;
3868 len = strlen(attrstr);
3872 for (; isSPACE(*attrstr) && len; --len, ++attrstr) ;
3874 const char * const sstr = attrstr;
3875 for (; !isSPACE(*attrstr) && len; --len, ++attrstr) ;
3876 attrs = op_append_elem(OP_LIST, attrs,
3877 newSVOP(OP_CONST, 0,
3878 newSVpvn(sstr, attrstr-sstr)));
3882 Perl_load_module(aTHX_ PERL_LOADMOD_IMPORT_OPS,
3883 newSVpvs(ATTRSMODULE),
3884 NULL, op_prepend_elem(OP_LIST,
3885 newSVOP(OP_CONST, 0, newSVpv(stashpv,0)),
3886 op_prepend_elem(OP_LIST,
3887 newSVOP(OP_CONST, 0,
3888 newRV(MUTABLE_SV(cv))),
3893 S_move_proto_attr(pTHX_ OP **proto, OP **attrs, const GV * name,
3896 OP *new_proto = NULL;
3901 PERL_ARGS_ASSERT_MOVE_PROTO_ATTR;
3907 if (o->op_type == OP_CONST) {
3908 pv = SvPV(cSVOPo_sv, pvlen);
3909 if (memBEGINs(pv, pvlen, "prototype(")) {
3910 SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3911 SV ** const tmpo = cSVOPx_svp(o);
3912 SvREFCNT_dec(cSVOPo_sv);
3917 } else if (o->op_type == OP_LIST) {
3919 assert(o->op_flags & OPf_KIDS);
3920 lasto = cLISTOPo->op_first;
3921 assert(lasto->op_type == OP_PUSHMARK);
3922 for (o = OpSIBLING(lasto); o; o = OpSIBLING(o)) {
3923 if (o->op_type == OP_CONST) {
3924 pv = SvPV(cSVOPo_sv, pvlen);
3925 if (memBEGINs(pv, pvlen, "prototype(")) {
3926 SV * const tmpsv = newSVpvn_flags(pv + 10, pvlen - 11, SvUTF8(cSVOPo_sv));
3927 SV ** const tmpo = cSVOPx_svp(o);
3928 SvREFCNT_dec(cSVOPo_sv);
3930 if (new_proto && ckWARN(WARN_MISC)) {
3932 const char * newp = SvPV(cSVOPo_sv, new_len);
3933 Perl_warner(aTHX_ packWARN(WARN_MISC),
3934 "Attribute prototype(%" UTF8f ") discards earlier prototype attribute in same sub",
3935 UTF8fARG(SvUTF8(cSVOPo_sv), new_len, newp));
3941 /* excise new_proto from the list */
3942 op_sibling_splice(*attrs, lasto, 1, NULL);
3949 /* If the list is now just the PUSHMARK, scrap the whole thing; otherwise attributes.xs
3950 would get pulled in with no real need */
3951 if (!OpHAS_SIBLING(cLISTOPx(*attrs)->op_first)) {
3960 svname = sv_newmortal();
3961 gv_efullname3(svname, name, NULL);
3963 else if (SvPOK(name) && *SvPVX((SV *)name) == '&')
3964 svname = newSVpvn_flags(SvPVX((SV *)name)+1, SvCUR(name)-1, SvUTF8(name)|SVs_TEMP);
3966 svname = (SV *)name;
3967 if (ckWARN(WARN_ILLEGALPROTO))
3968 (void)validate_proto(svname, cSVOPx_sv(new_proto), TRUE,
3970 if (*proto && ckWARN(WARN_PROTOTYPE)) {
3971 STRLEN old_len, new_len;
3972 const char * oldp = SvPV(cSVOPx_sv(*proto), old_len);
3973 const char * newp = SvPV(cSVOPx_sv(new_proto), new_len);
3975 if (curstash && svname == (SV *)name
3976 && !memchr(SvPVX(svname), ':', SvCUR(svname))) {
3977 svname = sv_2mortal(newSVsv(PL_curstname));
3978 sv_catpvs(svname, "::");
3979 sv_catsv(svname, (SV *)name);
3982 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE),
3983 "Prototype '%" UTF8f "' overridden by attribute 'prototype(%" UTF8f ")'"
3985 UTF8fARG(SvUTF8(cSVOPx_sv(*proto)), old_len, oldp),
3986 UTF8fARG(SvUTF8(cSVOPx_sv(new_proto)), new_len, newp),
3996 S_cant_declare(pTHX_ OP *o)
3998 if (o->op_type == OP_NULL
3999 && (o->op_flags & (OPf_SPECIAL|OPf_KIDS)) == OPf_KIDS)
4000 o = cUNOPo->op_first;
4001 yyerror(Perl_form(aTHX_ "Can't declare %s in \"%s\"",
4002 o->op_type == OP_NULL
4003 && o->op_flags & OPf_SPECIAL
4006 PL_parser->in_my == KEY_our ? "our" :
4007 PL_parser->in_my == KEY_state ? "state" :
4012 S_my_kid(pTHX_ OP *o, OP *attrs, OP **imopsp)
4015 const bool stately = PL_parser && PL_parser->in_my == KEY_state;
4017 PERL_ARGS_ASSERT_MY_KID;
4019 if (!o || (PL_parser && PL_parser->error_count))
4024 if (OP_TYPE_IS_OR_WAS(o, OP_LIST)) {
4026 for (kid = cLISTOPo->op_first; kid; kid = OpSIBLING(kid))
4027 my_kid(kid, attrs, imopsp);
4029 } else if (type == OP_UNDEF || type == OP_STUB) {
4031 } else if (type == OP_RV2SV || /* "our" declaration */
4034 if (cUNOPo->op_first->op_type != OP_GV) { /* MJD 20011224 */
4035 S_cant_declare(aTHX_ o);
4037 GV * const gv = cGVOPx_gv(cUNOPo->op_first);
4039 PL_parser->in_my = FALSE;
4040 PL_parser->in_my_stash = NULL;
4041 apply_attrs(GvSTASH(gv),
4042 (type == OP_RV2SV ? GvSVn(gv) :
4043 type == OP_RV2AV ? MUTABLE_SV(GvAVn(gv)) :
4044 type == OP_RV2HV ? MUTABLE_SV(GvHVn(gv)) : MUTABLE_SV(gv)),
4047 o->op_private |= OPpOUR_INTRO;
4050 else if (type == OP_REFGEN || type == OP_SREFGEN) {
4051 if (!FEATURE_MYREF_IS_ENABLED)
4052 Perl_croak(aTHX_ "The experimental declared_refs "
4053 "feature is not enabled");
4054 Perl_ck_warner_d(aTHX_
4055 packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
4056 "Declaring references is experimental");
4057 /* Kid is a nulled OP_LIST, handled above. */
4058 my_kid(cUNOPo->op_first, attrs, imopsp);
4061 else if (type != OP_PADSV &&
4064 type != OP_PUSHMARK)
4066 S_cant_declare(aTHX_ o);
4069 else if (attrs && type != OP_PUSHMARK) {
4073 PL_parser->in_my = FALSE;
4074 PL_parser->in_my_stash = NULL;
4076 /* check for C<my Dog $spot> when deciding package */
4077 stash = PAD_COMPNAME_TYPE(o->op_targ);
4079 stash = PL_curstash;
4080 apply_attrs_my(stash, o, attrs, imopsp);
4082 o->op_flags |= OPf_MOD;
4083 o->op_private |= OPpLVAL_INTRO;
4085 o->op_private |= OPpPAD_STATE;
4090 Perl_my_attrs(pTHX_ OP *o, OP *attrs)
4093 int maybe_scalar = 0;
4095 PERL_ARGS_ASSERT_MY_ATTRS;
4097 /* [perl #17376]: this appears to be premature, and results in code such as
4098 C< our(%x); > executing in list mode rather than void mode */
4100 if (o->op_flags & OPf_PARENS)
4110 o = my_kid(o, attrs, &rops);
4112 if (maybe_scalar && o->op_type == OP_PADSV) {
4113 o = scalar(op_append_list(OP_LIST, rops, o));
4114 o->op_private |= OPpLVAL_INTRO;
4117 /* The listop in rops might have a pushmark at the beginning,
4118 which will mess up list assignment. */
4119 LISTOP * const lrops = cLISTOPx(rops); /* for brevity */
4120 if (rops->op_type == OP_LIST &&
4121 lrops->op_first && lrops->op_first->op_type == OP_PUSHMARK)
4123 OP * const pushmark = lrops->op_first;
4124 /* excise pushmark */
4125 op_sibling_splice(rops, NULL, 1, NULL);
4128 o = op_append_list(OP_LIST, o, rops);
4131 PL_parser->in_my = FALSE;
4132 PL_parser->in_my_stash = NULL;
4137 Perl_sawparens(pTHX_ OP *o)
4139 PERL_UNUSED_CONTEXT;
4141 o->op_flags |= OPf_PARENS;
4146 Perl_bind_match(pTHX_ I32 type, OP *left, OP *right)
4150 const OPCODE ltype = left->op_type;
4151 const OPCODE rtype = right->op_type;
4153 PERL_ARGS_ASSERT_BIND_MATCH;
4155 if ( (ltype == OP_RV2AV || ltype == OP_RV2HV || ltype == OP_PADAV
4156 || ltype == OP_PADHV) && ckWARN(WARN_MISC))
4158 const char * const desc
4160 rtype == OP_SUBST || rtype == OP_TRANS
4161 || rtype == OP_TRANSR
4163 ? (int)rtype : OP_MATCH];
4164 const bool isary = ltype == OP_RV2AV || ltype == OP_PADAV;
4165 SV * const name = op_varname(left);
4167 Perl_warner(aTHX_ packWARN(WARN_MISC),
4168 "Applying %s to %" SVf " will act on scalar(%" SVf ")",
4169 desc, SVfARG(name), SVfARG(name));
4171 const char * const sample = (isary
4172 ? "@array" : "%hash");
4173 Perl_warner(aTHX_ packWARN(WARN_MISC),
4174 "Applying %s to %s will act on scalar(%s)",
4175 desc, sample, sample);
4179 if (rtype == OP_CONST &&
4180 cSVOPx(right)->op_private & OPpCONST_BARE &&
4181 cSVOPx(right)->op_private & OPpCONST_STRICT)
4183 no_bareword_allowed(right);
4186 /* !~ doesn't make sense with /r, so error on it for now */
4187 if (rtype == OP_SUBST && (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT) &&
4189 /* diag_listed_as: Using !~ with %s doesn't make sense */
4190 yyerror("Using !~ with s///r doesn't make sense");
4191 if (rtype == OP_TRANSR && type == OP_NOT)
4192 /* diag_listed_as: Using !~ with %s doesn't make sense */
4193 yyerror("Using !~ with tr///r doesn't make sense");
4195 ismatchop = (rtype == OP_MATCH ||
4196 rtype == OP_SUBST ||
4197 rtype == OP_TRANS || rtype == OP_TRANSR)
4198 && !(right->op_flags & OPf_SPECIAL);
4199 if (ismatchop && right->op_private & OPpTARGET_MY) {
4201 right->op_private &= ~OPpTARGET_MY;
4203 if (!(right->op_flags & OPf_STACKED) && !right->op_targ && ismatchop) {
4204 if (left->op_type == OP_PADSV
4205 && !(left->op_private & OPpLVAL_INTRO))
4207 right->op_targ = left->op_targ;
4212 right->op_flags |= OPf_STACKED;
4213 if (rtype != OP_MATCH && rtype != OP_TRANSR &&
4214 ! (rtype == OP_TRANS &&
4215 right->op_private & OPpTRANS_IDENTICAL) &&
4216 ! (rtype == OP_SUBST &&
4217 (cPMOPx(right)->op_pmflags & PMf_NONDESTRUCT)))
4218 left = op_lvalue(left, rtype);
4219 if (right->op_type == OP_TRANS || right->op_type == OP_TRANSR)
4220 o = newBINOP(OP_NULL, OPf_STACKED, scalar(left), right);
4222 o = op_prepend_elem(rtype, scalar(left), right);
4225 return newUNOP(OP_NOT, 0, scalar(o));
4229 return bind_match(type, left,
4230 pmruntime(newPMOP(OP_MATCH, 0), right, NULL, 0, 0));
4234 Perl_invert(pTHX_ OP *o)
4238 return newUNOP(OP_NOT, OPf_SPECIAL, scalar(o));
4242 Perl_cmpchain_start(pTHX_ I32 type, OP *left, OP *right)
4248 left = newOP(OP_NULL, 0);
4250 right = newOP(OP_NULL, 0);
4253 NewOp(0, bop, 1, BINOP);
4255 ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
4256 OpTYPE_set(op, type);
4257 cBINOPx(op)->op_flags = OPf_KIDS;
4258 cBINOPx(op)->op_private = 2;
4259 cBINOPx(op)->op_first = left;
4260 cBINOPx(op)->op_last = right;
4261 OpMORESIB_set(left, right);
4262 OpLASTSIB_set(right, op);
4267 Perl_cmpchain_extend(pTHX_ I32 type, OP *ch, OP *right)
4272 PERL_ARGS_ASSERT_CMPCHAIN_EXTEND;
4274 right = newOP(OP_NULL, 0);
4276 NewOp(0, bop, 1, BINOP);
4278 ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP);
4279 OpTYPE_set(op, type);
4280 if (ch->op_type != OP_NULL) {
4282 OP *nch, *cleft, *cright;
4283 NewOp(0, lch, 1, UNOP);
4285 OpTYPE_set(nch, OP_NULL);
4286 nch->op_flags = OPf_KIDS;
4287 cleft = cBINOPx(ch)->op_first;
4288 cright = cBINOPx(ch)->op_last;
4289 cBINOPx(ch)->op_first = NULL;
4290 cBINOPx(ch)->op_last = NULL;
4291 cBINOPx(ch)->op_private = 0;
4292 cBINOPx(ch)->op_flags = 0;
4293 cUNOPx(nch)->op_first = cright;
4294 OpMORESIB_set(cright, ch);
4295 OpMORESIB_set(ch, cleft);
4296 OpLASTSIB_set(cleft, nch);
4299 OpMORESIB_set(right, op);
4300 OpMORESIB_set(op, cUNOPx(ch)->op_first);
4301 cUNOPx(ch)->op_first = right;
4306 Perl_cmpchain_finish(pTHX_ OP *ch)
4309 PERL_ARGS_ASSERT_CMPCHAIN_FINISH;
4310 if (ch->op_type != OP_NULL) {
4311 OPCODE cmpoptype = ch->op_type;
4312 ch = CHECKOP(cmpoptype, ch);
4313 if(!ch->op_next && ch->op_type == cmpoptype)
4314 ch = fold_constants(op_integerize(op_std_init(ch)));
4318 OP *rightarg = cUNOPx(ch)->op_first;
4319 cUNOPx(ch)->op_first = OpSIBLING(rightarg);
4320 OpLASTSIB_set(rightarg, NULL);
4322 OP *cmpop = cUNOPx(ch)->op_first;
4323 OP *leftarg = OpSIBLING(cmpop);
4324 OPCODE cmpoptype = cmpop->op_type;
4327 is_last = !(cUNOPx(ch)->op_first = OpSIBLING(leftarg));
4328 OpLASTSIB_set(cmpop, NULL);
4329 OpLASTSIB_set(leftarg, NULL);
4333 nextrightarg = NULL;
4335 nextrightarg = newUNOP(OP_CMPCHAIN_DUP, 0, leftarg);
4336 leftarg = newOP(OP_NULL, 0);
4338 cBINOPx(cmpop)->op_first = leftarg;
4339 cBINOPx(cmpop)->op_last = rightarg;
4340 OpMORESIB_set(leftarg, rightarg);
4341 OpLASTSIB_set(rightarg, cmpop);
4342 cmpop->op_flags = OPf_KIDS;
4343 cmpop->op_private = 2;
4344 cmpop = CHECKOP(cmpoptype, cmpop);
4345 if(!cmpop->op_next && cmpop->op_type == cmpoptype)
4346 cmpop = op_integerize(op_std_init(cmpop));
4347 condop = condop ? newLOGOP(OP_CMPCHAIN_AND, 0, cmpop, condop) :
4351 rightarg = nextrightarg;
4357 =for apidoc op_scope
4359 Wraps up an op tree with some additional ops so that at runtime a dynamic
4360 scope will be created. The original ops run in the new dynamic scope,
4361 and then, provided that they exit normally, the scope will be unwound.
4362 The additional ops used to create and unwind the dynamic scope will
4363 normally be an C<enter>/C<leave> pair, but a C<scope> op may be used
4364 instead if the ops are simple enough to not need the full dynamic scope
4371 Perl_op_scope(pTHX_ OP *o)
4374 if (o->op_flags & OPf_PARENS || PERLDB_NOOPT || TAINTING_get) {
4375 o = op_prepend_elem(OP_LINESEQ,
4376 newOP(OP_ENTER, (o->op_flags & OPf_WANT)), o);
4377 OpTYPE_set(o, OP_LEAVE);
4379 else if (o->op_type == OP_LINESEQ) {
4381 OpTYPE_set(o, OP_SCOPE);
4382 kid = cLISTOPo->op_first;
4383 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) {
4386 /* The following deals with things like 'do {1 for 1}' */
4387 kid = OpSIBLING(kid);
4389 (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE))
4394 o = newLISTOP(OP_SCOPE, 0, o, NULL);
4400 Perl_op_unscope(pTHX_ OP *o)
4402 if (o && o->op_type == OP_LINESEQ) {
4403 OP *kid = cLISTOPo->op_first;
4404 for(; kid; kid = OpSIBLING(kid))
4405 if (kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE)
4412 =for apidoc block_start
4414 Handles compile-time scope entry.
4415 Arranges for hints to be restored on block
4416 exit and also handles pad sequence numbers to make lexical variables scope
4417 right. Returns a savestack index for use with C<block_end>.
4423 Perl_block_start(pTHX_ int full)
4425 const int retval = PL_savestack_ix;
4427 PL_compiling.cop_seq = PL_cop_seqmax;
4429 pad_block_start(full);
4431 PL_hints &= ~HINT_BLOCK_SCOPE;
4432 SAVECOMPILEWARNINGS();
4433 PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings);
4434 SAVEI32(PL_compiling.cop_seq);
4435 PL_compiling.cop_seq = 0;
4437 CALL_BLOCK_HOOKS(bhk_start, full);
4443 =for apidoc block_end
4445 Handles compile-time scope exit. C<floor>
4446 is the savestack index returned by
4447 C<block_start>, and C<seq> is the body of the block. Returns the block,
4454 Perl_block_end(pTHX_ I32 floor, OP *seq)
4456 const int needblockscope = PL_hints & HINT_BLOCK_SCOPE;
4457 OP* retval = voidnonfinal(seq);
4460 /* XXX Is the null PL_parser check necessary here? */
4461 assert(PL_parser); /* Let’s find out under debugging builds. */
4462 if (PL_parser && PL_parser->parsed_sub) {
4463 o = newSTATEOP(0, NULL, NULL);
4465 retval = op_append_elem(OP_LINESEQ, retval, o);
4468 CALL_BLOCK_HOOKS(bhk_pre_end, &retval);
4472 PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */
4476 /* pad_leavemy has created a sequence of introcv ops for all my
4477 subs declared in the block. We have to replicate that list with
4478 clonecv ops, to deal with this situation:
4483 sub s1 { state sub foo { \&s2 } }
4486 Originally, I was going to have introcv clone the CV and turn
4487 off the stale flag. Since &s1 is declared before &s2, the
4488 introcv op for &s1 is executed (on sub entry) before the one for
4489 &s2. But the &foo sub inside &s1 (which is cloned when &s1 is
4490 cloned, since it is a state sub) closes over &s2 and expects
4491 to see it in its outer CV’s pad. If the introcv op clones &s1,
4492 then &s2 is still marked stale. Since &s1 is not active, and
4493 &foo closes over &s1’s implicit entry for &s2, we get a ‘Varia-
4494 ble will not stay shared’ warning. Because it is the same stub
4495 that will be used when the introcv op for &s2 is executed, clos-
4496 ing over it is safe. Hence, we have to turn off the stale flag
4497 on all lexical subs in the block before we clone any of them.
4498 Hence, having introcv clone the sub cannot work. So we create a
4499 list of ops like this:
4523 OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o;
4524 OP * const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o;
4525 for (;; kid = OpSIBLING(kid)) {
4526 OP *newkid = newOP(OP_CLONECV, 0);
4527 newkid->op_targ = kid->op_targ;
4528 o = op_append_elem(OP_LINESEQ, o, newkid);
4529 if (kid == last) break;
4531 retval = op_prepend_elem(OP_LINESEQ, o, retval);
4534 CALL_BLOCK_HOOKS(bhk_post_end, &retval);
4540 =for apidoc_section $scope
4542 =for apidoc blockhook_register
4544 Register a set of hooks to be called when the Perl lexical scope changes
4545 at compile time. See L<perlguts/"Compile-time scope hooks">.
4551 Perl_blockhook_register(pTHX_ BHK *hk)
4553 PERL_ARGS_ASSERT_BLOCKHOOK_REGISTER;
4555 Perl_av_create_and_push(aTHX_ &PL_blockhooks, newSViv(PTR2IV(hk)));
4559 Perl_newPROG(pTHX_ OP *o)
4563 PERL_ARGS_ASSERT_NEWPROG;
4570 PL_eval_root = newUNOP(OP_LEAVEEVAL,
4571 ((PL_in_eval & EVAL_KEEPERR)
4572 ? OPf_SPECIAL : 0), o);
4575 assert(CxTYPE(cx) == CXt_EVAL);
4577 if ((cx->blk_gimme & G_WANT) == G_VOID)
4578 scalarvoid(PL_eval_root);
4579 else if ((cx->blk_gimme & G_WANT) == G_LIST)
4582 scalar(PL_eval_root);
4584 start = op_linklist(PL_eval_root);
4585 PL_eval_root->op_next = 0;
4586 i = PL_savestack_ix;
4589 S_process_optree(aTHX_ NULL, PL_eval_root, start);
4591 PL_savestack_ix = i;
4594 if (o->op_type == OP_STUB) {
4595 /* This block is entered if nothing is compiled for the main
4596 program. This will be the case for an genuinely empty main
4597 program, or one which only has BEGIN blocks etc, so already
4600 Historically (5.000) the guard above was !o. However, commit
4601 f8a08f7b8bd67b28 (Jun 2001), integrated to blead as
4602 c71fccf11fde0068, changed perly.y so that newPROG() is now
4603 called with the output of block_end(), which returns a new
4604 OP_STUB for the case of an empty optree. ByteLoader (and
4605 maybe other things) also take this path, because they set up
4606 PL_main_start and PL_main_root directly, without generating an
4609 If the parsing the main program aborts (due to parse errors,
4610 or due to BEGIN or similar calling exit), then newPROG()
4611 isn't even called, and hence this code path and its cleanups
4612 are skipped. This shouldn't make a make a difference:
4613 * a non-zero return from perl_parse is a failure, and
4614 perl_destruct() should be called immediately.
4615 * however, if exit(0) is called during the parse, then
4616 perl_parse() returns 0, and perl_run() is called. As
4617 PL_main_start will be NULL, perl_run() will return
4618 promptly, and the exit code will remain 0.
4621 PL_comppad_name = 0;
4623 S_op_destroy(aTHX_ o);
4626 PL_main_root = op_scope(sawparens(scalarvoid(o)));
4627 PL_curcop = &PL_compiling;
4628 start = LINKLIST(PL_main_root);
4629 PL_main_root->op_next = 0;
4630 S_process_optree(aTHX_ NULL, PL_main_root, start);
4631 if (!PL_parser->error_count)
4632 /* on error, leave CV slabbed so that ops left lying around
4633 * will eb cleaned up. Else unslab */
4634 cv_forget_slab(PL_compcv);
4637 /* Register with debugger */
4639 CV * const cv = get_cvs("DB::postponed", 0);
4643 XPUSHs(MUTABLE_SV(CopFILEGV(&PL_compiling)));
4645 call_sv(MUTABLE_SV(cv), G_DISCARD);
4652 Perl_localize(pTHX_ OP *o, I32 lex)
4654 PERL_ARGS_ASSERT_LOCALIZE;
4656 if (o->op_flags & OPf_PARENS)
4657 /* [perl #17376]: this appears to be premature, and results in code such as
4658 C< our(%x); > executing in list mode rather than void mode */
4665 if ( PL_parser->bufptr > PL_parser->oldbufptr
4666 && PL_parser->bufptr[-1] == ','
4667 && ckWARN(WARN_PARENTHESIS))
4669 char *s = PL_parser->bufptr;
4672 /* some heuristics to detect a potential error */
4673 while (*s && (memCHRs(", \t\n", *s)))
4677 if (*s && (memCHRs("@$%", *s) || (!lex && *s == '*'))
4679 && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s))) {
4682 while (*s && (isWORDCHAR(*s) || UTF8_IS_CONTINUED(*s)))
4684 while (*s && (memCHRs(", \t\n", *s)))
4690 if (sigil && (*s == ';' || *s == '=')) {
4691 Perl_warner(aTHX_ packWARN(WARN_PARENTHESIS),
4692 "Parentheses missing around \"%s\" list",
4694 ? (PL_parser->in_my == KEY_our
4696 : PL_parser->in_my == KEY_state
4706 o = op_lvalue(o, OP_NULL); /* a bit kludgey */
4707 PL_parser->in_my = FALSE;
4708 PL_parser->in_my_stash = NULL;
4713 Perl_jmaybe(pTHX_ OP *o)
4715 PERL_ARGS_ASSERT_JMAYBE;
4717 if (o->op_type == OP_LIST) {
4718 if (FEATURE_MULTIDIMENSIONAL_IS_ENABLED) {
4720 = newSVREF(newGVOP(OP_GV, 0, gv_fetchpvs(";", GV_ADD|GV_NOTQUAL, SVt_PV)));
4721 o = op_convert_list(OP_JOIN, 0, op_prepend_elem(OP_LIST, o2, o));
4724 /* If the user disables this, then a warning might not be enough to alert
4725 them to a possible change of behaviour here, so throw an exception.
4727 yyerror("Multidimensional hash lookup is disabled");
4733 PERL_STATIC_INLINE OP *
4734 S_op_std_init(pTHX_ OP *o)
4736 I32 type = o->op_type;
4738 PERL_ARGS_ASSERT_OP_STD_INIT;
4740 if (PL_opargs[type] & OA_RETSCALAR)
4742 if (PL_opargs[type] & OA_TARGET && !o->op_targ)
4743 o->op_targ = pad_alloc(type, SVs_PADTMP);
4748 PERL_STATIC_INLINE OP *
4749 S_op_integerize(pTHX_ OP *o)
4751 I32 type = o->op_type;
4753 PERL_ARGS_ASSERT_OP_INTEGERIZE;
4755 /* integerize op. */
4756 if ((PL_opargs[type] & OA_OTHERINT) && (PL_hints & HINT_INTEGER))
4758 o->op_ppaddr = PL_ppaddr[++(o->op_type)];
4761 if (type == OP_NEGATE)
4762 /* XXX might want a ck_negate() for this */
4763 cUNOPo->op_first->op_private &= ~OPpCONST_STRICT;
4768 /* This function exists solely to provide a scope to limit
4769 setjmp/longjmp() messing with auto variables. It cannot be inlined because
4773 S_fold_constants_eval(pTHX) {
4789 S_fold_constants(pTHX_ OP *const o)
4793 I32 type = o->op_type;
4798 SV * const oldwarnhook = PL_warnhook;
4799 SV * const olddiehook = PL_diehook;
4801 U8 oldwarn = PL_dowarn;
4804 PERL_ARGS_ASSERT_FOLD_CONSTANTS;
4806 if (!(PL_opargs[type] & OA_FOLDCONST))
4815 #ifdef USE_LOCALE_CTYPE
4816 if (IN_LC_COMPILETIME(LC_CTYPE))
4825 #ifdef USE_LOCALE_COLLATE
4826 if (IN_LC_COMPILETIME(LC_COLLATE))
4831 /* XXX what about the numeric ops? */
4832 #ifdef USE_LOCALE_NUMERIC
4833 if (IN_LC_COMPILETIME(LC_NUMERIC))
4838 if (!OpHAS_SIBLING(cLISTOPo->op_first)
4839 || OpSIBLING(cLISTOPo->op_first)->op_type != OP_CONST)
4842 SV * const sv = cSVOPx_sv(OpSIBLING(cLISTOPo->op_first));
4843 if (!SvPOK(sv) || SvGMAGICAL(sv)) goto nope;
4845 const char *s = SvPVX_const(sv);
4846 while (s < SvEND(sv)) {
4847 if (isALPHA_FOLD_EQ(*s, 'p')) goto nope;
4854 if (o->op_private & OPpREPEAT_DOLIST) goto nope;
4857 if (cUNOPx(cUNOPo->op_first)->op_first->op_type != OP_CONST
4858 || SvPADTMP(cSVOPx_sv(cUNOPx(cUNOPo->op_first)->op_first)))
4862 if (PL_parser && PL_parser->error_count)
4863 goto nope; /* Don't try to run w/ errors */
4865 for (curop = LINKLIST(o); curop != o; curop = LINKLIST(curop)) {
4866 switch (curop->op_type) {
4868 if ( (curop->op_private & OPpCONST_BARE)
4869 && (curop->op_private & OPpCONST_STRICT)) {
4870 no_bareword_allowed(curop);
4878 /* Foldable; move to next op in list */
4882 /* No other op types are considered foldable */
4887 curop = LINKLIST(o);
4888 old_next = o->op_next;
4892 old_cxix = cxstack_ix;
4893 create_eval_scope(NULL, G_FAKINGEVAL);
4895 /* Verify that we don't need to save it: */
4896 assert(PL_curcop == &PL_compiling);
4897 StructCopy(&PL_compiling, ¬_compiling, COP);
4898 PL_curcop = ¬_compiling;
4899 /* The above ensures that we run with all the correct hints of the
4900 currently compiling COP, but that IN_PERL_RUNTIME is true. */
4901 assert(IN_PERL_RUNTIME);
4902 PL_warnhook = PERL_WARNHOOK_FATAL;
4905 /* Effective $^W=1. */
4906 if ( ! (PL_dowarn & G_WARN_ALL_MASK))
4907 PL_dowarn |= G_WARN_ON;
4909 ret = S_fold_constants_eval(aTHX);
4913 sv = *(PL_stack_sp--);
4914 if (o->op_targ && sv == PAD_SV(o->op_targ)) { /* grab pad temp? */
4915 pad_swipe(o->op_targ, FALSE);
4917 else if (SvTEMP(sv)) { /* grab mortal temp? */
4918 SvREFCNT_inc_simple_void(sv);
4921 else { assert(SvIMMORTAL(sv)); }
4924 /* Something tried to die. Abandon constant folding. */
4925 /* Pretend the error never happened. */
4927 o->op_next = old_next;
4930 /* Don't expect 1 (setjmp failed) or 2 (something called my_exit) */
4931 PL_warnhook = oldwarnhook;
4932 PL_diehook = olddiehook;
4933 /* XXX note that this croak may fail as we've already blown away
4934 * the stack - eg any nested evals */
4935 Perl_croak(aTHX_ "panic: fold_constants JMPENV_PUSH returned %d", ret);
4937 PL_dowarn = oldwarn;
4938 PL_warnhook = oldwarnhook;
4939 PL_diehook = olddiehook;
4940 PL_curcop = &PL_compiling;
4942 /* if we croaked, depending on how we croaked the eval scope
4943 * may or may not have already been popped */
4944 if (cxstack_ix > old_cxix) {
4945 assert(cxstack_ix == old_cxix + 1);
4946 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
4947 delete_eval_scope();
4952 /* OP_STRINGIFY and constant folding are used to implement qq.
4953 Here the constant folding is an implementation detail that we
4954 want to hide. If the stringify op is itself already marked
4955 folded, however, then it is actually a folded join. */
4956 is_stringify = type == OP_STRINGIFY && !o->op_folded;
4961 else if (!SvIMMORTAL(sv)) {
4965 newop = newSVOP(OP_CONST, 0, MUTABLE_SV(sv));
4966 if (!is_stringify) newop->op_folded = 1;
4973 /* convert a constant range in list context into an OP_RV2AV, OP_CONST pair;
4974 * the constant value being an AV holding the flattened range.
4978 S_gen_constant_list(pTHX_ OP *o)
4980 OP *curop, *old_next;
4981 SV * const oldwarnhook = PL_warnhook;
4982 SV * const olddiehook = PL_diehook;
4984 U8 oldwarn = PL_dowarn;
4994 if (PL_parser && PL_parser->error_count)
4995 return; /* Don't attempt to run with errors */
4997 curop = LINKLIST(o);
4998 old_next = o->op_next;
5000 op_was_null = o->op_type == OP_NULL;
5001 if (op_was_null) /* b3698342565fb462291fba4b432cfcd05b6eb4e1 */
5002 o->op_type = OP_CUSTOM;
5005 o->op_type = OP_NULL;
5006 op_prune_chain_head(&curop);
5009 old_cxix = cxstack_ix;
5010 create_eval_scope(NULL, G_FAKINGEVAL);
5012 old_curcop = PL_curcop;
5013 StructCopy(old_curcop, ¬_compiling, COP);
5014 PL_curcop = ¬_compiling;
5015 /* The above ensures that we run with all the correct hints of the
5016 current COP, but that IN_PERL_RUNTIME is true. */
5017 assert(IN_PERL_RUNTIME);
5018 PL_warnhook = PERL_WARNHOOK_FATAL;
5022 /* Effective $^W=1. */
5023 if ( ! (PL_dowarn & G_WARN_ALL_MASK))
5024 PL_dowarn |= G_WARN_ON;
5028 #if defined DEBUGGING && !defined DEBUGGING_RE_ONLY
5029 PL_curstackinfo->si_stack_hwm = 0; /* stop valgrind complaining */
5031 Perl_pp_pushmark(aTHX);
5034 assert (!(curop->op_flags & OPf_SPECIAL));
5035 assert(curop->op_type == OP_RANGE);
5036 Perl_pp_anonlist(aTHX);
5040 o->op_next = old_next;
5044 PL_warnhook = oldwarnhook;
5045 PL_diehook = olddiehook;
5046 Perl_croak(aTHX_ "panic: gen_constant_list JMPENV_PUSH returned %d",
5051 PL_dowarn = oldwarn;
5052 PL_warnhook = oldwarnhook;
5053 PL_diehook = olddiehook;
5054 PL_curcop = old_curcop;
5056 if (cxstack_ix > old_cxix) {
5057 assert(cxstack_ix == old_cxix + 1);
5058 assert(CxTYPE(CX_CUR()) == CXt_EVAL);
5059 delete_eval_scope();
5064 OpTYPE_set(o, OP_RV2AV);
5065 o->op_flags &= ~OPf_REF; /* treat \(1..2) like an ordinary list */
5066 o->op_flags |= OPf_PARENS; /* and flatten \(1..2,3) */
5067 o->op_opt = 0; /* needs to be revisited in rpeep() */
5068 av = (AV *)SvREFCNT_inc_NN(*PL_stack_sp--);
5070 /* replace subtree with an OP_CONST */
5071 curop = cUNOPo->op_first;
5072 op_sibling_splice(o, NULL, -1, newSVOP(OP_CONST, 0, (SV *)av));
5075 if (AvFILLp(av) != -1)
5076 for (svp = AvARRAY(av) + AvFILLp(av); svp >= AvARRAY(av); --svp)
5079 SvREADONLY_on(*svp);
5087 =for apidoc_section $optree_manipulation
5090 /* List constructors */
5093 =for apidoc op_append_elem
5095 Append an item to the list of ops contained directly within a list-type
5096 op, returning the lengthened list. C<first> is the list-type op,
5097 and C<last> is the op to append to the list. C<optype> specifies the
5098 intended opcode for the list. If C<first> is not already a list of the
5099 right type, it will be upgraded into one. If either C<first> or C<last>
5100 is null, the other is returned unchanged.
5106 Perl_op_append_elem(pTHX_ I32 type, OP *first, OP *last)
5114 if (first->op_type != (unsigned)type
5115 || (type == OP_LIST && (first->op_flags & OPf_PARENS)))
5117 return newLISTOP(type, 0, first, last);
5120 op_sibling_splice(first, cLISTOPx(first)->op_last, 0, last);
5121 first->op_flags |= OPf_KIDS;
5126 =for apidoc op_append_list
5128 Concatenate the lists of ops contained directly within two list-type ops,
5129 returning the combined list. C<first> and C<last> are the list-type ops
5130 to concatenate. C<optype> specifies the intended opcode for the list.
5131 If either C<first> or C<last> is not already a list of the right type,
5132 it will be upgraded into one. If either C<first> or C<last> is null,
5133 the other is returned unchanged.
5139 Perl_op_append_list(pTHX_ I32 type, OP *first, OP *last)
5147 if (first->op_type != (unsigned)type)
5148 return op_prepend_elem(type, first, last);
5150 if (last->op_type != (unsigned)type)
5151 return op_append_elem(type, first, last);
5153 OpMORESIB_set(cLISTOPx(first)->op_last, cLISTOPx(last)->op_first);
5154 cLISTOPx(first)->op_last = cLISTOPx(last)->op_last;
5155 OpLASTSIB_set(cLISTOPx(first)->op_last, first);
5156 first->op_flags |= (last->op_flags & OPf_KIDS);
5158 S_op_destroy(aTHX_ last);
5164 =for apidoc op_prepend_elem
5166 Prepend an item to the list of ops contained directly within a list-type
5167 op, returning the lengthened list. C<first> is the op to prepend to the
5168 list, and C<last> is the list-type op. C<optype> specifies the intended
5169 opcode for the list. If C<last> is not already a list of the right type,
5170 it will be upgraded into one. If either C<first> or C<last> is null,
5171 the other is returned unchanged.
5177 Perl_op_prepend_elem(pTHX_ I32 type, OP *first, OP *last)
5185 if (last->op_type == (unsigned)type) {
5186 if (type == OP_LIST) { /* already a PUSHMARK there */
5187 /* insert 'first' after pushmark */
5188 op_sibling_splice(last, cLISTOPx(last)->op_first, 0, first);
5189 if (!(first->op_flags & OPf_PARENS))
5190 last->op_flags &= ~OPf_PARENS;
5193 op_sibling_splice(last, NULL, 0, first);
5194 last->op_flags |= OPf_KIDS;
5198 return newLISTOP(type, 0, first, last);
5202 =for apidoc op_convert_list
5204 Converts C<o> into a list op if it is not one already, and then converts it
5205 into the specified C<type>, calling its check function, allocating a target if
5206 it needs one, and folding constants.
5208 A list-type op is usually constructed one kid at a time via C<newLISTOP>,
5209 C<op_prepend_elem> and C<op_append_elem>. Then finally it is passed to
5210 C<op_convert_list> to make it the right type.
5216 Perl_op_convert_list(pTHX_ I32 type, I32 flags, OP *o)
5218 if (type < 0) type = -type, flags |= OPf_SPECIAL;
5219 if (!o || o->op_type != OP_LIST)
5220 o = force_list(o, FALSE);
5223 o->op_flags &= ~OPf_WANT;
5224 o->op_private &= ~OPpLVAL_INTRO;
5227 if (!(PL_opargs[type] & OA_MARK))
5228 op_null(cLISTOPo->op_first);
5230 OP * const kid2 = OpSIBLING(cLISTOPo->op_first);
5231 if (kid2 && kid2->op_type == OP_COREARGS) {
5232 op_null(cLISTOPo->op_first);
5233 kid2->op_private |= OPpCOREARGS_PUSHMARK;
5237 if (type != OP_SPLIT)
5238 /* At this point o is a LISTOP, but OP_SPLIT is a PMOP; let
5239 * ck_split() create a real PMOP and leave the op's type as listop
5240 * for now. Otherwise op_free() etc will crash.
5242 OpTYPE_set(o, type);
5244 o->op_flags |= flags;
5245 if (flags & OPf_FOLDED)
5248 o = CHECKOP(type, o);
5249 if (o->op_type != (unsigned)type)
5252 return fold_constants(op_integerize(op_std_init(o)));
5259 =for apidoc_section $optree_construction
5261 =for apidoc newNULLLIST
5263 Constructs, checks, and returns a new C<stub> op, which represents an
5264 empty list expression.
5270 Perl_newNULLLIST(pTHX)
5272 return newOP(OP_STUB, 0);
5275 /* promote o and any siblings to be a list if its not already; i.e.
5283 * pushmark - o - A - B
5285 * If nullit it true, the list op is nulled.
5289 S_force_list(pTHX_ OP *o, bool nullit)
5291 if (!o || o->op_type != OP_LIST) {
5294 /* manually detach any siblings then add them back later */
5295 rest = OpSIBLING(o);
5296 OpLASTSIB_set(o, NULL);
5298 o = newLISTOP(OP_LIST, 0, o, NULL);
5300 op_sibling_splice(o, cLISTOPo->op_last, 0, rest);
5308 =for apidoc newLISTOP
5310 Constructs, checks, and returns an op of any list type. C<type> is
5311 the opcode. C<flags> gives the eight bits of C<op_flags>, except that
5312 C<OPf_KIDS> will be set automatically if required. C<first> and C<last>
5313 supply up to two ops to be direct children of the list op; they are
5314 consumed by this function and become part of the constructed op tree.
5316 For most list operators, the check function expects all the kid ops to be
5317 present already, so calling C<newLISTOP(OP_JOIN, ...)> (e.g.) is not
5318 appropriate. What you want to do in that case is create an op of type
5319 C<OP_LIST>, append more children to it, and then call L</op_convert_list>.
5320 See L</op_convert_list> for more information.
5327 Perl_newLISTOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
5330 /* Note that allocating an OP_PUSHMARK can die under Safe.pm if
5331 * pushmark is banned. So do it now while existing ops are in a
5332 * consistent state, in case they suddenly get freed */
5333 OP* const pushop = type == OP_LIST ? newOP(OP_PUSHMARK, 0) : NULL;
5335 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LISTOP
5336 || type == OP_CUSTOM);
5338 NewOp(1101, listop, 1, LISTOP);
5339 OpTYPE_set(listop, type);
5342 listop->op_flags = (U8)flags;
5346 else if (!first && last)
5349 OpMORESIB_set(first, last);
5350 listop->op_first = first;
5351 listop->op_last = last;
5354 OpMORESIB_set(pushop, first);
5355 listop->op_first = pushop;
5356 listop->op_flags |= OPf_KIDS;
5358 listop->op_last = pushop;
5360 if (listop->op_last)
5361 OpLASTSIB_set(listop->op_last, (OP*)listop);
5363 return CHECKOP(type, listop);
5369 Constructs, checks, and returns an op of any base type (any type that
5370 has no extra fields). C<type> is the opcode. C<flags> gives the
5371 eight bits of C<op_flags>, and, shifted up eight bits, the eight bits
5378 Perl_newOP(pTHX_ I32 type, I32 flags)
5382 if (type == -OP_ENTEREVAL) {
5383 type = OP_ENTEREVAL;
5384 flags |= OPpEVAL_BYTES<<8;
5387 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP
5388 || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
5389 || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5390 || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
5392 NewOp(1101, o, 1, OP);
5393 OpTYPE_set(o, type);
5394 o->op_flags = (U8)flags;
5397 o->op_private = (U8)(0 | (flags >> 8));
5398 if (PL_opargs[type] & OA_RETSCALAR)
5400 if (PL_opargs[type] & OA_TARGET)
5401 o->op_targ = pad_alloc(type, SVs_PADTMP);
5402 return CHECKOP(type, o);
5408 Constructs, checks, and returns an op of any unary type. C<type> is
5409 the opcode. C<flags> gives the eight bits of C<op_flags>, except that
5410 C<OPf_KIDS> will be set automatically if required, and, shifted up eight
5411 bits, the eight bits of C<op_private>, except that the bit with value 1
5412 is automatically set. C<first> supplies an optional op to be the direct
5413 child of the unary op; it is consumed by this function and become part
5414 of the constructed op tree.
5416 =for apidoc Amnh||OPf_KIDS
5422 Perl_newUNOP(pTHX_ I32 type, I32 flags, OP *first)
5426 if (type == -OP_ENTEREVAL) {
5427 type = OP_ENTEREVAL;
5428 flags |= OPpEVAL_BYTES<<8;
5431 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP
5432 || (PL_opargs[type] & OA_CLASS_MASK) == OA_BASEOP_OR_UNOP
5433 || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
5434 || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
5435 || type == OP_SASSIGN
5436 || type == OP_ENTERTRY
5437 || type == OP_ENTERTRYCATCH
5438 || type == OP_CUSTOM
5439 || type == OP_NULL );
5442 first = newOP(OP_STUB, 0);
5443 if (PL_opargs[type] & OA_MARK)
5444 first = force_list(first, TRUE);
5446 NewOp(1101, unop, 1, UNOP);
5447 OpTYPE_set(unop, type);
5448 unop->op_first = first;
5449 unop->op_flags = (U8)(flags | OPf_KIDS);
5450 unop->op_private = (U8)(1 | (flags >> 8));
5452 if (!OpHAS_SIBLING(first)) /* true unless weird syntax error */
5453 OpLASTSIB_set(first, (OP*)unop);
5455 unop = (UNOP*) CHECKOP(type, unop);
5459 return fold_constants(op_integerize(op_std_init((OP *) unop)));
5463 =for apidoc newUNOP_AUX
5465 Similar to C<newUNOP>, but creates an C<UNOP_AUX> struct instead, with C<op_aux>
5466 initialised to C<aux>
5472 Perl_newUNOP_AUX(pTHX_ I32 type, I32 flags, OP *first, UNOP_AUX_item *aux)
5476 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_UNOP_AUX
5477 || type == OP_CUSTOM);
5479 NewOp(1101, unop, 1, UNOP_AUX);
5480 unop->op_type = (OPCODE)type;
5481 unop->op_ppaddr = PL_ppaddr[type];
5482 unop->op_first = first;
5483 unop->op_flags = (U8)(flags | (first ? OPf_KIDS : 0));
5484 unop->op_private = (U8)((first ? 1 : 0) | (flags >> 8));
5487 if (first && !OpHAS_SIBLING(first)) /* true unless weird syntax error */
5488 OpLASTSIB_set(first, (OP*)unop);
5490 unop = (UNOP_AUX*) CHECKOP(type, unop);
5492 return op_std_init((OP *) unop);
5496 =for apidoc newMETHOP
5498 Constructs, checks, and returns an op of method type with a method name
5499 evaluated at runtime. C<type> is the opcode. C<flags> gives the eight
5500 bits of C<op_flags>, except that C<OPf_KIDS> will be set automatically,
5501 and, shifted up eight bits, the eight bits of C<op_private>, except that
5502 the bit with value 1 is automatically set. C<dynamic_meth> supplies an
5503 op which evaluates method name; it is consumed by this function and
5504 become part of the constructed op tree.
5505 Supported optypes: C<OP_METHOD>.
5511 S_newMETHOP_internal(pTHX_ I32 type, I32 flags, OP* dynamic_meth, SV* const_meth) {
5514 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_METHOP
5515 || type == OP_CUSTOM);
5517 NewOp(1101, methop, 1, METHOP);
5519 if (PL_opargs[type] & OA_MARK) dynamic_meth = force_list(dynamic_meth, TRUE);
5520 methop->op_flags = (U8)(flags | OPf_KIDS);
5521 methop->op_u.op_first = dynamic_meth;
5522 methop->op_private = (U8)(1 | (flags >> 8));
5524 if (!OpHAS_SIBLING(dynamic_meth))
5525 OpLASTSIB_set(dynamic_meth, (OP*)methop);
5529 methop->op_flags = (U8)(flags & ~OPf_KIDS);
5530 methop->op_u.op_meth_sv = const_meth;
5531 methop->op_private = (U8)(0 | (flags >> 8));
5532 methop->op_next = (OP*)methop;
5536 methop->op_rclass_targ = 0;
5538 methop->op_rclass_sv = NULL;
5541 OpTYPE_set(methop, type);
5542 return CHECKOP(type, methop);
5546 Perl_newMETHOP (pTHX_ I32 type, I32 flags, OP* dynamic_meth) {
5547 PERL_ARGS_ASSERT_NEWMETHOP;
5548 return newMETHOP_internal(type, flags, dynamic_meth, NULL);
5552 =for apidoc newMETHOP_named
5554 Constructs, checks, and returns an op of method type with a constant
5555 method name. C<type> is the opcode. C<flags> gives the eight bits of
5556 C<op_flags>, and, shifted up eight bits, the eight bits of
5557 C<op_private>. C<const_meth> supplies a constant method name;
5558 it must be a shared COW string.
5559 Supported optypes: C<OP_METHOD_NAMED>.
5565 Perl_newMETHOP_named (pTHX_ I32 type, I32 flags, SV* const_meth) {
5566 PERL_ARGS_ASSERT_NEWMETHOP_NAMED;
5567 return newMETHOP_internal(type, flags, NULL, const_meth);
5571 =for apidoc newBINOP
5573 Constructs, checks, and returns an op of any binary type. C<type>
5574 is the opcode. C<flags> gives the eight bits of C<op_flags>, except
5575 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
5576 the eight bits of C<op_private>, except that the bit with value 1 or
5577 2 is automatically set as required. C<first> and C<last> supply up to
5578 two ops to be the direct children of the binary op; they are consumed
5579 by this function and become part of the constructed op tree.
5585 Perl_newBINOP(pTHX_ I32 type, I32 flags, OP *first, OP *last)
5589 ASSUME((PL_opargs[type] & OA_CLASS_MASK) == OA_BINOP
5590 || type == OP_NULL || type == OP_CUSTOM);
5592 NewOp(1101, binop, 1, BINOP);
5595 first = newOP(OP_NULL, 0);
5597 OpTYPE_set(binop, type);
5598 binop->op_first = first;
5599 binop->op_flags = (U8)(flags | OPf_KIDS);
5602 binop->op_private = (U8)(1 | (flags >> 8));
5605 binop->op_private = (U8)(2 | (flags >> 8));
5606 OpMORESIB_set(first, last);
5609 if (!OpHAS_SIBLING(last)) /* true unless weird syntax error */
5610 OpLASTSIB_set(last, (OP*)binop);
5612 binop->op_last = OpSIBLING(binop->op_first);
5614 OpLASTSIB_set(binop->op_last, (OP*)binop);
5616 binop = (BINOP*) CHECKOP(type, binop);
5617 if (binop->op_next || binop->op_type != (OPCODE)type)
5620 return fold_constants(op_integerize(op_std_init((OP *)binop)));
5624 Perl_invmap_dump(pTHX_ SV* invlist, UV *map)
5626 const char indent[] = " ";
5628 UV len = _invlist_len(invlist);
5629 UV * array = invlist_array(invlist);
5632 PERL_ARGS_ASSERT_INVMAP_DUMP;
5634 for (i = 0; i < len; i++) {
5635 UV start = array[i];
5636 UV end = (i + 1 < len) ? array[i+1] - 1 : IV_MAX;
5638 PerlIO_printf(Perl_debug_log, "%s[%" UVuf "] 0x%04" UVXf, indent, i, start);
5639 if (end == IV_MAX) {
5640 PerlIO_printf(Perl_debug_log, " .. INFTY");
5642 else if (end != start) {
5643 PerlIO_printf(Perl_debug_log, " .. 0x%04" UVXf, end);
5646 PerlIO_printf(Perl_debug_log, " ");
5649 PerlIO_printf(Perl_debug_log, "\t");
5651 if (map[i] == TR_UNLISTED) {
5652 PerlIO_printf(Perl_debug_log, "TR_UNLISTED\n");
5654 else if (map[i] == TR_SPECIAL_HANDLING) {
5655 PerlIO_printf(Perl_debug_log, "TR_SPECIAL_HANDLING\n");
5658 PerlIO_printf(Perl_debug_log, "0x%04" UVXf "\n", map[i]);
5663 /* Given an OP_TRANS / OP_TRANSR op o, plus OP_CONST ops expr and repl
5664 * containing the search and replacement strings, assemble into
5665 * a translation table attached as o->op_pv.
5666 * Free expr and repl.
5667 * It expects the toker to have already set the
5668 * OPpTRANS_COMPLEMENT
5671 * flags as appropriate; this function may add
5673 * OPpTRANS_CAN_FORCE_UTF8
5674 * OPpTRANS_IDENTICAL
5680 S_pmtrans(pTHX_ OP *o, OP *expr, OP *repl)
5682 /* This function compiles a tr///, from data gathered from toke.c, into a
5683 * form suitable for use by do_trans() in doop.c at runtime.
5685 * It first normalizes the data, while discarding extraneous inputs; then
5686 * writes out the compiled data. The normalization allows for complete
5687 * analysis, and avoids some false negatives and positives earlier versions
5690 * The normalization form is an inversion map (described below in detail).
5691 * This is essentially the compiled form for tr///'s that require UTF-8,
5692 * and its easy to use it to write the 257-byte table for tr///'s that
5693 * don't need UTF-8. That table is identical to what's been in use for
5694 * many perl versions, except that it doesn't handle some edge cases that
5695 * it used to, involving code points above 255. The UTF-8 form now handles
5696 * these. (This could be changed with extra coding should it shown to be
5699 * If the complement (/c) option is specified, the lhs string (tstr) is
5700 * parsed into an inversion list. Complementing these is trivial. Then a
5701 * complemented tstr is built from that, and used thenceforth. This hides
5702 * the fact that it was complemented from almost all successive code.
5704 * One of the important characteristics to know about the input is whether
5705 * the transliteration may be done in place, or does a temporary need to be
5706 * allocated, then copied. If the replacement for every character in every
5707 * possible string takes up no more bytes than the character it
5708 * replaces, then it can be edited in place. Otherwise the replacement
5709 * could overwrite a byte we are about to read, depending on the strings
5710 * being processed. The comments and variable names here refer to this as
5711 * "growing". Some inputs won't grow, and might even shrink under /d, but
5712 * some inputs could grow, so we have to assume any given one might grow.
5713 * On very long inputs, the temporary could eat up a lot of memory, so we
5714 * want to avoid it if possible. For non-UTF-8 inputs, everything is
5715 * single-byte, so can be edited in place, unless there is something in the
5716 * pattern that could force it into UTF-8. The inversion map makes it
5717 * feasible to determine this. Previous versions of this code pretty much
5718 * punted on determining if UTF-8 could be edited in place. Now, this code
5719 * is rigorous in making that determination.
5721 * Another characteristic we need to know is whether the lhs and rhs are
5722 * identical. If so, and no other flags are present, the only effect of
5723 * the tr/// is to count the characters present in the input that are
5724 * mentioned in the lhs string. The implementation of that is easier and
5725 * runs faster than the more general case. Normalizing here allows for
5726 * accurate determination of this. Previously there were false negatives
5729 * Instead of 'transliterated', the comments here use 'unmapped' for the
5730 * characters that are left unchanged by the operation; otherwise they are
5733 * The lhs of the tr/// is here referred to as the t side.
5734 * The rhs of the tr/// is here referred to as the r side.
5737 SV * const tstr = cSVOPx(expr)->op_sv;
5738 SV * const rstr = cSVOPx(repl)->op_sv;
5741 const U8 * t0 = (U8*)SvPV_const(tstr, tlen);
5742 const U8 * r0 = (U8*)SvPV_const(rstr, rlen);
5745 UV t_count = 0, r_count = 0; /* Number of characters in search and
5746 replacement lists */
5748 /* khw thinks some of the private flags for this op are quaintly named.
5749 * OPpTRANS_GROWS for example is TRUE if the replacement for some lhs
5750 * character when represented in UTF-8 is longer than the original
5751 * character's UTF-8 representation */
5752 const bool complement = cBOOL(o->op_private & OPpTRANS_COMPLEMENT);
5753 const bool squash = cBOOL(o->op_private & OPpTRANS_SQUASH);
5754 const bool del = cBOOL(o->op_private & OPpTRANS_DELETE);
5756 /* Set to true if there is some character < 256 in the lhs that maps to
5757 * above 255. If so, a non-UTF-8 match string can be forced into being in
5758 * UTF-8 by a tr/// operation. */
5759 bool can_force_utf8 = FALSE;
5761 /* What is the maximum expansion factor in UTF-8 transliterations. If a
5762 * 2-byte UTF-8 encoded character is to be replaced by a 3-byte one, its
5763 * expansion factor is 1.5. This number is used at runtime to calculate
5764 * how much space to allocate for non-inplace transliterations. Without
5765 * this number, the worst case is 14, which is extremely unlikely to happen
5766 * in real life, and could require significant memory overhead. */
5767 NV max_expansion = 1.;
5769 UV t_range_count, r_range_count, min_range_count;
5773 UV r_cp = 0, t_cp = 0;
5774 UV t_cp_end = (UV) -1;
5778 UV final_map = TR_UNLISTED; /* The final character in the replacement
5779 list, updated as we go along. Initialize
5780 to something illegal */
5782 bool rstr_utf8 = cBOOL(SvUTF8(rstr));
5783 bool tstr_utf8 = cBOOL(SvUTF8(tstr));
5785 const U8* tend = t + tlen;
5786 const U8* rend = r + rlen;
5788 SV * inverted_tstr = NULL;
5793 /* This routine implements detection of a transliteration having a longer
5794 * UTF-8 representation than its source, by partitioning all the possible
5795 * code points of the platform into equivalence classes of the same UTF-8
5796 * byte length in the first pass. As it constructs the mappings, it carves
5797 * these up into smaller chunks, but doesn't merge any together. This
5798 * makes it easy to find the instances it's looking for. A second pass is
5799 * done after this has been determined which merges things together to
5800 * shrink the table for runtime. The table below is used for both ASCII
5801 * and EBCDIC platforms. On EBCDIC, the byte length is not monotonically
5802 * increasing for code points below 256. To correct for that, the macro
5803 * CP_ADJUST defined below converts those code points to ASCII in the first
5804 * pass, and we use the ASCII partition values. That works because the
5805 * growth factor will be unaffected, which is all that is calculated during
5806 * the first pass. */
5807 UV PL_partition_by_byte_length[] = {
5809 0x80, /* Below this is 1 byte representations */
5810 (32 * (1UL << ( UTF_ACCUMULATION_SHIFT))), /* 2 bytes below this */
5811 (16 * (1UL << (2 * UTF_ACCUMULATION_SHIFT))), /* 3 bytes below this */
5812 ( 8 * (1UL << (3 * UTF_ACCUMULATION_SHIFT))), /* 4 bytes below this */
5813 ( 4 * (1UL << (4 * UTF_ACCUMULATION_SHIFT))), /* 5 bytes below this */
5814 ( 2 * (1UL << (5 * UTF_ACCUMULATION_SHIFT))) /* 6 bytes below this */
5818 ( ((UV) 1U << (6 * UTF_ACCUMULATION_SHIFT))) /* 7 bytes below this */
5823 PERL_ARGS_ASSERT_PMTRANS;
5825 PL_hints |= HINT_BLOCK_SCOPE;
5827 /* If /c, the search list is sorted and complemented. This is now done by
5828 * creating an inversion list from it, and then trivially inverting that.
5829 * The previous implementation used qsort, but creating the list
5830 * automatically keeps it sorted as we go along */
5833 SV * inverted_tlist = _new_invlist(tlen);
5836 DEBUG_y(PerlIO_printf(Perl_debug_log,
5837 "%s: %d: tstr before inversion=\n%s\n",
5838 __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
5842 /* Non-utf8 strings don't have ranges, so each character is listed
5845 inverted_tlist = add_cp_to_invlist(inverted_tlist, *t);
5848 else { /* But UTF-8 strings have been parsed in toke.c to have
5849 * ranges if appropriate. */
5853 /* Get the first character */
5854 t_cp = valid_utf8_to_uvchr(t, &t_char_len);
5857 /* If the next byte indicates that this wasn't the first
5858 * element of a range, the range is just this one */
5859 if (t >= tend || *t != RANGE_INDICATOR) {
5860 inverted_tlist = add_cp_to_invlist(inverted_tlist, t_cp);
5862 else { /* Otherwise, ignore the indicator byte, and get the
5863 final element, and add the whole range */
5865 t_cp_end = valid_utf8_to_uvchr(t, &t_char_len);
5868 inverted_tlist = _add_range_to_invlist(inverted_tlist,
5872 } /* End of parse through tstr */
5874 /* The inversion list is done; now invert it */
5875 _invlist_invert(inverted_tlist);
5877 /* Now go through the inverted list and create a new tstr for the rest
5878 * of the routine to use. Since the UTF-8 version can have ranges, and
5879 * can be much more compact than the non-UTF-8 version, we create the
5880 * string in UTF-8 even if not necessary. (This is just an intermediate
5881 * value that gets thrown away anyway.) */
5882 invlist_iterinit(inverted_tlist);
5883 inverted_tstr = newSVpvs("");
5884 while (invlist_iternext(inverted_tlist, &start, &end)) {
5885 U8 temp[UTF8_MAXBYTES];
5888 /* IV_MAX keeps things from going out of bounds */
5889 start = MIN(IV_MAX, start);
5890 end = MIN(IV_MAX, end);
5892 temp_end_pos = uvchr_to_utf8(temp, start);
5893 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
5896 Perl_sv_catpvf(aTHX_ inverted_tstr, "%c", RANGE_INDICATOR);
5897 temp_end_pos = uvchr_to_utf8(temp, end);
5898 sv_catpvn(inverted_tstr, (char *) temp, temp_end_pos - temp);
5902 /* Set up so the remainder of the routine uses this complement, instead
5903 * of the actual input */
5904 t0 = t = (U8*)SvPV_const(inverted_tstr, temp_len);
5905 tend = t0 + temp_len;
5908 SvREFCNT_dec_NN(inverted_tlist);
5911 /* For non-/d, an empty rhs means to use the lhs */
5912 if (rlen == 0 && ! del) {
5915 rstr_utf8 = tstr_utf8;
5918 t_invlist = _new_invlist(1);
5920 /* Initialize to a single range */
5921 t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
5923 /* Below, we parse the (potentially adjusted) input, creating the inversion
5924 * map. This is done in two passes. The first pass is just to determine
5925 * if the transliteration can be done in-place. It can be done in place if
5926 * no possible inputs result in the replacement taking up more bytes than
5927 * the input. To figure that out, in the first pass we start with all the
5928 * possible code points partitioned into ranges so that every code point in
5929 * a range occupies the same number of UTF-8 bytes as every other code
5930 * point in the range. Constructing the inversion map doesn't merge ranges
5931 * together, but can split them into multiple ones. Given the starting
5932 * partition, the ending state will also have the same characteristic,
5933 * namely that each code point in each partition requires the same number
5934 * of UTF-8 bytes to represent as every other code point in the same
5937 * This partioning has been pre-compiled. Copy it to initialize */
5938 len = C_ARRAY_LENGTH(PL_partition_by_byte_length);
5939 invlist_extend(t_invlist, len);
5940 t_array = invlist_array(t_invlist);
5941 Copy(PL_partition_by_byte_length, t_array, len, UV);
5942 invlist_set_len(t_invlist, len, *(get_invlist_offset_addr(t_invlist)));
5943 Newx(r_map, len + 1, UV);
5945 /* The inversion map the first pass creates could be used as-is, but
5946 * generally would be larger and slower to run than the output of the
5949 for (pass2 = 0; pass2 < 2; pass2++) {
5951 /* In the second pass, we start with a single range */
5952 t_invlist = _add_range_to_invlist(t_invlist, 0, UV_MAX);
5954 t_array = invlist_array(t_invlist);
5957 /* As noted earlier, we convert EBCDIC code points to Unicode in the first pass
5958 * so as to get the well-behaved length 1 vs length 2 boundary. Only code
5959 * points below 256 differ between the two character sets in this regard. For
5960 * these, we also can't have any ranges, as they have to be individually
5963 # define CP_ADJUST(x) ((pass2) ? (x) : NATIVE_TO_UNI(x))
5964 # define FORCE_RANGE_LEN_1(x) ((pass2) ? 0 : ((x) < 256))
5965 # define CP_SKIP(x) ((pass2) ? UVCHR_SKIP(x) : OFFUNISKIP(x))
5967 # define CP_ADJUST(x) (x)
5968 # define FORCE_RANGE_LEN_1(x) 0
5969 # define CP_SKIP(x) UVCHR_SKIP(x)
5972 /* And the mapping of each of the ranges is initialized. Initially,
5973 * everything is TR_UNLISTED. */
5974 for (i = 0; i < len; i++) {
5975 r_map[i] = TR_UNLISTED;
5982 t_range_count = r_range_count = 0;
5984 DEBUG_y(PerlIO_printf(Perl_debug_log, "%s: %d:\ntstr=%s\n",
5985 __FILE__, __LINE__, _byte_dump_string(t, tend - t, 0)));
5986 DEBUG_y(PerlIO_printf(Perl_debug_log, "rstr=%s\n",
5987 _byte_dump_string(r, rend - r, 0)));
5988 DEBUG_y(PerlIO_printf(Perl_debug_log, "/c=%d; /s=%d; /d=%d\n",
5989 complement, squash, del));
5990 DEBUG_y(invmap_dump(t_invlist, r_map));
5992 /* Now go through the search list constructing an inversion map. The
5993 * input is not necessarily in any particular order. Making it an
5994 * inversion map orders it, potentially simplifying, and makes it easy
5995 * to deal with at run time. This is the only place in core that
5996 * generates an inversion map; if others were introduced, it might be
5997 * better to create general purpose routines to handle them.
5998 * (Inversion maps are created in perl in other places.)
6000 * An inversion map consists of two parallel arrays. One is
6001 * essentially an inversion list: an ordered list of code points such
6002 * that each element gives the first code point of a range of
6003 * consecutive code points that map to the element in the other array
6004 * that has the same index as this one (in other words, the
6005 * corresponding element). Thus the range extends up to (but not
6006 * including) the code point given by the next higher element. In a
6007 * true inversion map, the corresponding element in the other array
6008 * gives the mapping of the first code point in the range, with the
6009 * understanding that the next higher code point in the inversion
6010 * list's range will map to the next higher code point in the map.
6012 * So if at element [i], let's say we have:
6017 * This means that A => a, B => b, C => c.... Let's say that the
6018 * situation is such that:
6022 * This means the sequence that started at [i] stops at K => k. This
6023 * illustrates that you need to look at the next element to find where
6024 * a sequence stops. Except, the highest element in the inversion list
6025 * begins a range that is understood to extend to the platform's
6028 * This routine modifies traditional inversion maps to reserve two
6031 * TR_UNLISTED (or -1) indicates that no code point in the range
6032 * is listed in the tr/// searchlist. At runtime, these are
6033 * always passed through unchanged. In the inversion map, all
6034 * points in the range are mapped to -1, instead of increasing,
6035 * like the 'L' in the example above.
6037 * We start the parse with every code point mapped to this, and as
6038 * we parse and find ones that are listed in the search list, we
6039 * carve out ranges as we go along that override that.
6041 * TR_SPECIAL_HANDLING (or -2) indicates that every code point in the
6042 * range needs special handling. Again, all code points in the
6043 * range are mapped to -2, instead of increasing.
6045 * Under /d this value means the code point should be deleted from
6046 * the transliteration when encountered.
6048 * Otherwise, it marks that every code point in the range is to
6049 * map to the final character in the replacement list. This
6050 * happens only when the replacement list is shorter than the
6051 * search one, so there are things in the search list that have no
6052 * correspondence in the replacement list. For example, in
6053 * tr/a-z/A/, 'A' is the final value, and the inversion map
6054 * generated for this would be like this:
6059 * 'A' appears once, then the remainder of the range maps to -2.
6060 * The use of -2 isn't strictly necessary, as an inversion map is
6061 * capable of representing this situation, but not nearly so
6062 * compactly, and this is actually quite commonly encountered.
6063 * Indeed, the original design of this code used a full inversion
6064 * map for this. But things like
6066 * generated huge data structures, slowly, and the execution was
6067 * also slow. So the current scheme was implemented.
6069 * So, if the next element in our example is:
6073 * Then all of L, M, N, O, and P map to TR_UNLISTED. If the next
6077 * [i+4] S TR_UNLISTED
6079 * Then Q => q; R => z; and S => TR_UNLISTED. If [i+4] (the 'S') is
6080 * the final element in the arrays, every code point from S to infinity
6081 * maps to TR_UNLISTED.
6084 /* Finish up range started in what otherwise would
6085 * have been the final iteration */
6086 while (t < tend || t_range_count > 0) {
6087 bool adjacent_to_range_above = FALSE;
6088 bool adjacent_to_range_below = FALSE;
6090 bool merge_with_range_above = FALSE;
6091 bool merge_with_range_below = FALSE;
6093 UV span, invmap_range_length_remaining;
6097 /* If we are in the middle of processing a range in the 'target'
6098 * side, the previous iteration has set us up. Otherwise, look at
6099 * the next character in the search list */
6100 if (t_range_count <= 0) {
6103 /* Here, not in the middle of a range, and not UTF-8. The
6104 * next code point is the single byte where we're at */
6105 t_cp = CP_ADJUST(*t);
6112 /* Here, not in the middle of a range, and is UTF-8. The
6113 * next code point is the next UTF-8 char in the input. We
6114 * know the input is valid, because the toker constructed
6116 t_cp = CP_ADJUST(valid_utf8_to_uvchr(t, &t_char_len));
6119 /* UTF-8 strings (only) have been parsed in toke.c to have
6120 * ranges. See if the next byte indicates that this was
6121 * the first element of a range. If so, get the final
6122 * element and calculate the range size. If not, the range
6124 if ( t < tend && *t == RANGE_INDICATOR
6125 && ! FORCE_RANGE_LEN_1(t_cp))
6128 t_range_count = valid_utf8_to_uvchr(t, &t_char_len)
6137 /* Count the total number of listed code points * */
6138 t_count += t_range_count;
6141 /* Similarly, get the next character in the replacement list */
6142 if (r_range_count <= 0) {
6145 /* But if we've exhausted the rhs, there is nothing to map
6146 * to, except the special handling one, and we make the
6147 * range the same size as the lhs one. */
6148 r_cp = TR_SPECIAL_HANDLING;
6149 r_range_count = t_range_count;
6152 DEBUG_yv(PerlIO_printf(Perl_debug_log,
6153 "final_map =%" UVXf "\n", final_map));
6158 r_cp = CP_ADJUST(*r);
6165 r_cp = CP_ADJUST(valid_utf8_to_uvchr(r, &r_char_len));
6167 if ( r < rend && *r == RANGE_INDICATOR
6168 && ! FORCE_RANGE_LEN_1(r_cp))
6171 r_range_count = valid_utf8_to_uvchr(r,
6172 &r_char_len) - r_cp + 1;
6180 if (r_cp == TR_SPECIAL_HANDLING) {
6181 r_range_count = t_range_count;
6184 /* This is the final character so far */
6185 final_map = r_cp + r_range_count - 1;
6187 r_count += r_range_count;
6191 /* Here, we have the next things ready in both sides. They are
6192 * potentially ranges. We try to process as big a chunk as
6193 * possible at once, but the lhs and rhs must be synchronized, so
6194 * things like tr/A-Z/a-ij-z/ will need to be processed in 2 chunks
6196 min_range_count = MIN(t_range_count, r_range_count);
6198 /* Search the inversion list for the entry that contains the input
6199 * code point <cp>. The inversion map was initialized to cover the
6200 * entire range of possible inputs, so this should not fail. So
6201 * the return value is the index into the list's array of the range
6202 * that contains <cp>, that is, 'i' such that array[i] <= cp <
6204 j = _invlist_search(t_invlist, t_cp);
6208 /* Here, the data structure might look like:
6211 * [i-1] J j # J-L => j-l
6212 * [i] M -1 # M => default; as do N, O, P, Q
6213 * [i+1] R x # R => x, S => x+1, T => x+2
6214 * [i+2] U y # U => y, V => y+1, ...
6216 * [-1] Z -1 # Z => default; as do Z+1, ... infinity
6218 * where 'x' and 'y' above are not to be taken literally.
6220 * The maximum chunk we can handle in this loop iteration, is the
6221 * smallest of the three components: the lhs 't_', the rhs 'r_',
6222 * and the remainder of the range in element [i]. (In pass 1, that
6223 * range will have everything in it be of the same class; we can't
6224 * cross into another class.) 'min_range_count' already contains
6225 * the smallest of the first two values. The final one is
6226 * irrelevant if the map is to the special indicator */
6228 invmap_range_length_remaining = (i + 1 < len)
6229 ? t_array[i+1] - t_cp
6231 span = MAX(1, MIN(min_range_count, invmap_range_length_remaining));
6233 /* The end point of this chunk is where we are, plus the span, but
6234 * never larger than the platform's infinity */
6235 t_cp_end = MIN(IV_MAX, t_cp + span - 1);
6237 if (r_cp == TR_SPECIAL_HANDLING) {
6239 /* If unmatched lhs code points map to the final map, use that
6240 * value. This being set to TR_SPECIAL_HANDLING indicates that
6241 * we don't have a final map: unmatched lhs code points are
6243 r_cp_end = (del) ? TR_SPECIAL_HANDLING : final_map;
6246 r_cp_end = MIN(IV_MAX, r_cp + span - 1);
6248 /* If something on the lhs is below 256, and something on the
6249 * rhs is above, there is a potential mapping here across that
6250 * boundary. Indeed the only way there isn't is if both sides
6251 * start at the same point. That means they both cross at the
6252 * same time. But otherwise one crosses before the other */
6253 if (t_cp < 256 && r_cp_end > 255 && r_cp != t_cp) {
6254 can_force_utf8 = TRUE;
6258 /* If a character appears in the search list more than once, the
6259 * 2nd and succeeding occurrences are ignored, so only do this
6260 * range if haven't already processed this character. (The range
6261 * has been set up so that all members in it will be of the same
6263 if (r_map[i] == TR_UNLISTED) {
6264 DEBUG_yv(PerlIO_printf(Perl_debug_log,
6265 "Processing %" UVxf "-%" UVxf " => %" UVxf "-%" UVxf "\n",
6266 t_cp, t_cp_end, r_cp, r_cp_end));
6268 /* This is the first definition for this chunk, hence is valid
6269 * and needs to be processed. Here and in the comments below,
6270 * we use the above sample data. The t_cp chunk must be any
6271 * contiguous subset of M, N, O, P, and/or Q.
6273 * In the first pass, calculate if there is any possible input
6274 * string that has a character whose transliteration will be
6275 * longer than it. If none, the transliteration may be done
6276 * in-place, as it can't write over a so-far unread byte.
6277 * Otherwise, a copy must first be made. This could be
6278 * expensive for long inputs.
6280 * In the first pass, the t_invlist has been partitioned so
6281 * that all elements in any single range have the same number
6282 * of bytes in their UTF-8 representations. And the r space is
6283 * either a single byte, or a range of strictly monotonically
6284 * increasing code points. So the final element in the range
6285 * will be represented by no fewer bytes than the initial one.
6286 * That means that if the final code point in the t range has
6287 * at least as many bytes as the final code point in the r,
6288 * then all code points in the t range have at least as many
6289 * bytes as their corresponding r range element. But if that's
6290 * not true, the transliteration of at least the final code
6291 * point grows in length. As an example, suppose we had
6292 * tr/\x{fff0}-\x{fff1}/\x{ffff}-\x{10000}/
6293 * The UTF-8 for all but 10000 occupies 3 bytes on ASCII
6294 * platforms. We have deliberately set up the data structure
6295 * so that any range in the lhs gets split into chunks for
6296 * processing, such that every code point in a chunk has the
6297 * same number of UTF-8 bytes. We only have to check the final
6298 * code point in the rhs against any code point in the lhs. */
6300 && r_cp_end != TR_SPECIAL_HANDLING
6301 && CP_SKIP(t_cp_end) < CP_SKIP(r_cp_end))
6303 /* Here, we will need to make a copy of the input string
6304 * before doing the transliteration. The worst possible
6305 * case is an expansion ratio of 14:1. This is rare, and
6306 * we'd rather allocate only the necessary amount of extra
6307 * memory for that copy. We can calculate the worst case
6308 * for this particular transliteration is by keeping track
6309 * of the expansion factor for each range.
6311 * Consider tr/\xCB/\X{E000}/. The maximum expansion
6312 * factor is 1 byte going to 3 if the target string is not
6313 * UTF-8, but 2 bytes going to 3 if it is in UTF-8. We
6314 * could pass two different values so doop could choose
6315 * based on the UTF-8ness of the target. But khw thinks
6316 * (perhaps wrongly) that is overkill. It is used only to
6317 * make sure we malloc enough space.
6319 * If no target string can force the result to be UTF-8,
6320 * then we don't have to worry about the case of the target
6321 * string not being UTF-8 */
6322 NV t_size = (can_force_utf8 && t_cp < 256)
6324 : CP_SKIP(t_cp_end);
6325 NV ratio = CP_SKIP(r_cp_end) / t_size;
6327 o->op_private |= OPpTRANS_GROWS;
6329 /* Now that we know it grows, we can keep track of the
6331 if (ratio > max_expansion) {
6332 max_expansion = ratio;
6333 DEBUG_y(PerlIO_printf(Perl_debug_log,
6334 "New expansion factor: %" NVgf "\n",
6339 /* The very first range is marked as adjacent to the
6340 * non-existent range below it, as it causes things to "just
6343 * If the lowest code point in this chunk is M, it adjoins the
6345 if (t_cp == t_array[i]) {
6346 adjacent_to_range_below = TRUE;
6348 /* And if the map has the same offset from the beginning of
6349 * the range as does this new code point (or both are for
6350 * TR_SPECIAL_HANDLING), this chunk can be completely
6351 * merged with the range below. EXCEPT, in the first pass,
6352 * we don't merge ranges whose UTF-8 byte representations
6353 * have different lengths, so that we can more easily
6354 * detect if a replacement is longer than the source, that
6355 * is if it 'grows'. But in the 2nd pass, there's no
6356 * reason to not merge */
6357 if ( (i > 0 && ( pass2
6358 || CP_SKIP(t_array[i-1])
6360 && ( ( r_cp == TR_SPECIAL_HANDLING
6361 && r_map[i-1] == TR_SPECIAL_HANDLING)
6362 || ( r_cp != TR_SPECIAL_HANDLING
6363 && r_cp - r_map[i-1] == t_cp - t_array[i-1])))
6365 merge_with_range_below = TRUE;
6369 /* Similarly, if the highest code point in this chunk is 'Q',
6370 * it adjoins the range above, and if the map is suitable, can
6371 * be merged with it */
6372 if ( t_cp_end >= IV_MAX - 1
6374 && t_cp_end + 1 == t_array[i+1]))
6376 adjacent_to_range_above = TRUE;
6379 || CP_SKIP(t_cp) == CP_SKIP(t_array[i+1]))
6380 && ( ( r_cp == TR_SPECIAL_HANDLING
6381 && r_map[i+1] == (UV) TR_SPECIAL_HANDLING)
6382 || ( r_cp != TR_SPECIAL_HANDLING
6383 && r_cp_end == r_map[i+1] - 1)))
6385 merge_with_range_above = TRUE;
6389 if (merge_with_range_below && merge_with_range_above) {
6391 /* Here the new chunk looks like M => m, ... Q => q; and
6392 * the range above is like R => r, .... Thus, the [i-1]
6393 * and [i+1] ranges should be seamlessly melded so the
6396 * [i-1] J j # J-T => j-t
6397 * [i] U y # U => y, V => y+1, ...
6399 * [-1] Z -1 # Z => default; as do Z+1, ... infinity
6401 Move(t_array + i + 2, t_array + i, len - i - 2, UV);
6402 Move(r_map + i + 2, r_map + i, len - i - 2, UV);
6404 invlist_set_len(t_invlist,
6406 *(get_invlist_offset_addr(t_invlist)));
6408 else if (merge_with_range_below) {
6410 /* Here the new chunk looks like M => m, .... But either
6411 * (or both) it doesn't extend all the way up through Q; or
6412 * the range above doesn't start with R => r. */
6413 if (! adjacent_to_range_above) {
6415 /* In the first case, let's say the new chunk extends
6416 * through O. We then want:
6418 * [i-1] J j # J-O => j-o
6419 * [i] P -1 # P => -1, Q => -1
6420 * [i+1] R x # R => x, S => x+1, T => x+2
6421 * [i+2] U y # U => y, V => y+1, ...
6423 * [-1] Z -1 # Z => default; as do Z+1, ...
6426 t_array[i] = t_cp_end + 1;
6427 r_map[i] = TR_UNLISTED;
6429 else { /* Adjoins the range above, but can't merge with it
6430 (because 'x' is not the next map after q) */
6432 * [i-1] J j # J-Q => j-q
6433 * [i] R x # R => x, S => x+1, T => x+2
6434 * [i+1] U y # U => y, V => y+1, ...
6436 * [-1] Z -1 # Z => default; as do Z+1, ...
6440 Move(t_array + i + 1, t_array + i, len - i - 1, UV);
6441 Move(r_map + i + 1, r_map + i, len - i - 1, UV);
6443 invlist_set_len(t_invlist, len,
6444 *(get_invlist_offset_addr(t_invlist)));
6447 else if (merge_with_range_above) {
6449 /* Here the new chunk ends with Q => q, and the range above
6450 * must start with R => r, so the two can be merged. But
6451 * either (or both) the new chunk doesn't extend all the
6452 * way down to M; or the mapping of the final code point
6453 * range below isn't m */
6454 if (! adjacent_to_range_below) {
6456 /* In the first case, let's assume the new chunk starts
6457 * with P => p. Then, because it's merge-able with the
6458 * range above, that range must be R => r. We want:
6460 * [i-1] J j # J-L => j-l
6461 * [i] M -1 # M => -1, N => -1
6462 * [i+1] P p # P-T => p-t
6463 * [i+2] U y # U => y, V => y+1, ...
6465 * [-1] Z -1 # Z => default; as do Z+1, ...
6468 t_array[i+1] = t_cp;
6471 else { /* Adjoins the range below, but can't merge with it
6474 * [i-1] J j # J-L => j-l
6475 * [i] M x # M-T => x-5 .. x+2
6476 * [i+1] U y # U => y, V => y+1, ...
6478 * [-1] Z -1 # Z => default; as do Z+1, ...
6481 Move(t_array + i + 1, t_array + i, len - i - 1, UV);
6482 Move(r_map + i + 1, r_map + i, len - i - 1, UV);
6486 invlist_set_len(t_invlist, len,
6487 *(get_invlist_offset_addr(t_invlist)));
6490 else if (adjacent_to_range_below && adjacent_to_range_above) {
6491 /* The new chunk completely fills the gap between the
6492 * ranges on either side, but can't merge with either of
6495 * [i-1] J j # J-L => j-l
6496 * [i] M z # M => z, N => z+1 ... Q => z+4
6497 * [i+1] R x # R => x, S => x+1, T => x+2
6498 * [i+2] U y # U => y, V => y+1, ...
6500 * [-1] Z -1 # Z => default; as do Z+1, ... infinity
6504 else if (adjacent_to_range_below) {
6505 /* The new chunk adjoins the range below, but not the range
6506 * above, and can't merge. Let's assume the chunk ends at
6509 * [i-1] J j # J-L => j-l
6510 * [i] M z # M => z, N => z+1, O => z+2
6511 * [i+1] P -1 # P => -1, Q => -1
6512 * [i+2] R x # R => x, S => x+1, T => x+2
6513 * [i+3] U y # U => y, V => y+1, ...
6515 * [-w] Z -1 # Z => default; as do Z+1, ... infinity
6517 invlist_extend(t_invlist, len + 1);
6518 t_array = invlist_array(t_invlist);
6519 Renew(r_map, len + 1, UV);
6521 Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
6522 Move(r_map + i + 1, r_map + i + 2, len - i - 1, UV);
6524 t_array[i+1] = t_cp_end + 1;
6525 r_map[i+1] = TR_UNLISTED;
6527 invlist_set_len(t_invlist, len,
6528 *(get_invlist_offset_addr(t_invlist)));
6530 else if (adjacent_to_range_above) {
6531 /* The new chunk adjoins the range above, but not the range
6532 * below, and can't merge. Let's assume the new chunk
6535 * [i-1] J j # J-L => j-l
6536 * [i] M -1 # M => default, N => default
6537 * [i+1] O z # O => z, P => z+1, Q => z+2
6538 * [i+2] R x # R => x, S => x+1, T => x+2
6539 * [i+3] U y # U => y, V => y+1, ...
6541 * [-1] Z -1 # Z => default; as do Z+1, ... infinity
6543 invlist_extend(t_invlist, len + 1);
6544 t_array = invlist_array(t_invlist);
6545 Renew(r_map, len + 1, UV);
6547 Move(t_array + i + 1, t_array + i + 2, len - i - 1, UV);
6548 Move(r_map + i + 1, r_map + i + 2, len - i - 1, UV);
6549 t_array[i+1] = t_cp;
6552 invlist_set_len(t_invlist, len,
6553 *(get_invlist_offset_addr(t_invlist)));
6556 /* The new chunk adjoins neither the range above, nor the
6557 * range below. Lets assume it is N..P => n..p
6559 * [i-1] J j # J-L => j-l
6560 * [i] M -1 # M => default
6561 * [i+1] N n # N..P => n..p
6562 * [i+2] Q -1 # Q => default
6563 * [i+3] R x # R => x, S => x+1, T => x+2
6564 * [i+4] U y # U => y, V => y+1, ...
6566 * [-1] Z -1 # Z => default; as do Z+1, ... infinity
6569 DEBUG_yv(PerlIO_printf(Perl_debug_log,
6570 "Before fixing up: len=%d, i=%d\n",
6571 (int) len, (int) i));
6572 DEBUG_yv(invmap_dump(t_invlist, r_map));
6574 invlist_extend(t_invlist, len + 2);
6575 t_array = invlist_array(t_invlist);
6576 Renew(r_map, len + 2, UV);
6578 Move(t_array + i + 1,
6579 t_array + i + 2 + 1, len - i - (2 - 1), UV);
6581 r_map + i + 2 + 1, len - i - (2 - 1), UV);
6584 invlist_set_len(t_invlist, len,
6585 *(get_invlist_offset_addr(t_invlist)));
6587 t_array[i+1] = t_cp;
6590 t_array[i+2] = t_cp_end + 1;
6591 r_map[i+2] = TR_UNLISTED;
6593 DEBUG_yv(PerlIO_printf(Perl_debug_log,
6594 "After iteration: span=%" UVuf ", t_range_count=%"
6595 UVuf " r_range_count=%" UVuf "\n",
6596 span, t_range_count, r_range_count));
6597 DEBUG_yv(invmap_dump(t_invlist, r_map));
6598 } /* End of this chunk needs to be processed */
6600 /* Done with this chunk. */
6602 if (t_cp >= IV_MAX) {
6605 t_range_count -= span;
6606 if (r_cp != TR_SPECIAL_HANDLING) {
6608 r_range_count -= span;
6614 } /* End of loop through the search list */
6616 /* We don't need an exact count, but we do need to know if there is
6617 * anything left over in the replacement list. So, just assume it's
6618 * one byte per character */
6622 } /* End of passes */
6624 SvREFCNT_dec(inverted_tstr);
6626 DEBUG_y(PerlIO_printf(Perl_debug_log, "After everything: \n"));
6627 DEBUG_y(invmap_dump(t_invlist, r_map));
6629 /* We now have normalized the input into an inversion map.
6631 * See if the lhs and rhs are equivalent. If so, this tr/// is a no-op
6632 * except for the count, and streamlined runtime code can be used */
6633 if (!del && !squash) {
6635 /* They are identical if they point to the same address, or if
6636 * everything maps to UNLISTED or to itself. This catches things that
6637 * not looking at the normalized inversion map doesn't catch, like
6638 * tr/aa/ab/ or tr/\x{100}-\x{104}/\x{100}-\x{102}\x{103}-\x{104} */
6640 for (i = 0; i < len; i++) {
6641 if (r_map[i] != TR_UNLISTED && r_map[i] != t_array[i]) {
6642 goto done_identical_check;
6647 /* Here have gone through entire list, and didn't find any
6648 * non-identical mappings */
6649 o->op_private |= OPpTRANS_IDENTICAL;
6651 done_identical_check: ;
6654 t_array = invlist_array(t_invlist);
6656 /* If has components above 255, we generally need to use the inversion map
6660 && t_array[len-1] > 255
6661 /* If the final range is 0x100-INFINITY and is a special
6662 * mapping, the table implementation can handle it */
6663 && ! ( t_array[len-1] == 256
6664 && ( r_map[len-1] == TR_UNLISTED
6665 || r_map[len-1] == TR_SPECIAL_HANDLING))))
6670 /* A UTF-8 op is generated, indicated by this flag. This op is an
6672 o->op_private |= OPpTRANS_USE_SVOP;
6674 if (can_force_utf8) {
6675 o->op_private |= OPpTRANS_CAN_FORCE_UTF8;
6678 /* The inversion map is pushed; first the list. */
6679 invmap = MUTABLE_AV(newAV());
6681 SvREADONLY_on(t_invlist);
6682 av_push(invmap, t_invlist);
6684 /* 2nd is the mapping */
6685 r_map_sv = newSVpvn((char *) r_map, len * sizeof(UV));
6686 SvREADONLY_on(r_map_sv);
6687 av_push(invmap, r_map_sv);
6689 /* 3rd is the max possible expansion factor */
6690 temp_sv = newSVnv(max_expansion);
6691 SvREADONLY_on(temp_sv);
6692 av_push(invmap, temp_sv);
6694 /* Characters that are in the search list, but not in the replacement
6695 * list are mapped to the final character in the replacement list */
6696 if (! del && r_count < t_count) {
6697 temp_sv = newSVuv(final_map);
6698 SvREADONLY_on(temp_sv);
6699 av_push(invmap, temp_sv);
6703 cPADOPo->op_padix = pad_alloc(OP_TRANS, SVf_READONLY);
6704 SvREFCNT_dec(PAD_SVl(cPADOPo->op_padix));
6705 PAD_SETSV(cPADOPo->op_padix, (SV *) invmap);
6706 SvPADTMP_on(invmap);
6707 SvREADONLY_on(invmap);
6709 cSVOPo->op_sv = (SV *) invmap;
6717 /* The OPtrans_map struct already contains one slot; hence the -1. */
6718 SSize_t struct_size = sizeof(OPtrans_map)
6719 + (256 - 1 + 1)*sizeof(short);
6721 /* Non-utf8 case: set o->op_pv to point to a simple 256+ entry lookup
6722 * table. Entries with the value TR_UNMAPPED indicate chars not to be
6723 * translated, while TR_DELETE indicates a search char without a
6724 * corresponding replacement char under /d.
6726 * In addition, an extra slot at the end is used to store the final
6727 * repeating char, or TR_R_EMPTY under an empty replacement list, or
6728 * TR_DELETE under /d; which makes the runtime code easier. */
6730 /* Indicate this is an op_pv */
6731 o->op_private &= ~OPpTRANS_USE_SVOP;
6733 tbl = (OPtrans_map*)PerlMemShared_calloc(struct_size, 1);
6735 cPVOPo->op_pv = (char*)tbl;
6737 for (i = 0; i < len; i++) {
6738 STATIC_ASSERT_DECL(TR_SPECIAL_HANDLING == TR_DELETE);
6739 short upper = i >= len - 1 ? 256 : (short) t_array[i+1];
6740 short to = (short) r_map[i];
6742 bool do_increment = TRUE;
6744 /* Any code points above our limit should be irrelevant */
6745 if (t_array[i] >= tbl->size) break;
6747 /* Set up the map */
6748 if (to == (short) TR_SPECIAL_HANDLING && ! del) {
6749 to = (short) final_map;
6750 do_increment = FALSE;
6753 do_increment = FALSE;
6756 /* Create a map for everything in this range. The value increases
6757 * except for the special cases */
6758 for (j = (short) t_array[i]; j < upper; j++) {
6760 if (do_increment) to++;
6764 tbl->map[tbl->size] = del
6768 : (short) TR_R_EMPTY;
6769 DEBUG_y(PerlIO_printf(Perl_debug_log,"%s: %d\n", __FILE__, __LINE__));
6770 for (i = 0; i < tbl->size; i++) {
6771 if (tbl->map[i] < 0) {
6772 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%d",
6773 (unsigned) i, tbl->map[i]));
6776 DEBUG_y(PerlIO_printf(Perl_debug_log," %02x=>%02x",
6777 (unsigned) i, tbl->map[i]));
6779 if ((i+1) % 8 == 0 || i + 1 == (short) tbl->size) {
6780 DEBUG_y(PerlIO_printf(Perl_debug_log,"\n"));
6783 DEBUG_y(PerlIO_printf(Perl_debug_log,"Final map 0x%x=>%02x\n",
6784 (unsigned) tbl->size, tbl->map[tbl->size]));
6786 SvREFCNT_dec(t_invlist);
6788 #if 0 /* code that added excess above-255 chars at the end of the table, in
6789 case we ever want to not use the inversion map implementation for
6796 /* More replacement chars than search chars:
6797 * store excess replacement chars at end of main table.
6800 struct_size += excess;
6801 tbl = (OPtrans_map*)PerlMemShared_realloc(tbl,
6802 struct_size + excess * sizeof(short));
6803 tbl->size += excess;
6804 cPVOPo->op_pv = (char*)tbl;
6806 for (i = 0; i < excess; i++)
6807 tbl->map[i + 256] = r[j+i];
6810 /* no more replacement chars than search chars */
6816 DEBUG_y(PerlIO_printf(Perl_debug_log,
6817 "/d=%d, /s=%d, /c=%d, identical=%d, grows=%d,"
6818 " use_svop=%d, can_force_utf8=%d,\nexpansion=%" NVgf "\n",
6819 del, squash, complement,
6820 cBOOL(o->op_private & OPpTRANS_IDENTICAL),
6821 cBOOL(o->op_private & OPpTRANS_USE_SVOP),
6822 cBOOL(o->op_private & OPpTRANS_GROWS),
6823 cBOOL(o->op_private & OPpTRANS_CAN_FORCE_UTF8),
6828 if(del && rlen != 0 && r_count == t_count) {
6829 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Useless use of /d modifier in transliteration operator");
6830 } else if(r_count > t_count) {
6831 Perl_ck_warner(aTHX_ packWARN(WARN_MISC), "Replacement list is longer than search list");
6844 Constructs, checks, and returns an op of any pattern matching type.
6845 C<type> is the opcode. C<flags> gives the eight bits of C<op_flags>
6846 and, shifted up eight bits, the eight bits of C<op_private>.
6852 Perl_newPMOP(pTHX_ I32 type, I32 flags)
6856 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PMOP
6857 || type == OP_CUSTOM);
6859 NewOp(1101, pmop, 1, PMOP);
6860 OpTYPE_set(pmop, type);
6861 pmop->op_flags = (U8)flags;
6862 pmop->op_private = (U8)(0 | (flags >> 8));
6863 if (PL_opargs[type] & OA_RETSCALAR)
6866 if (PL_hints & HINT_RE_TAINT)
6867 pmop->op_pmflags |= PMf_RETAINT;
6868 #ifdef USE_LOCALE_CTYPE
6869 if (IN_LC_COMPILETIME(LC_CTYPE)) {
6870 set_regex_charset(&(pmop->op_pmflags), REGEX_LOCALE_CHARSET);
6875 set_regex_charset(&(pmop->op_pmflags), REGEX_UNICODE_CHARSET);
6877 if (PL_hints & HINT_RE_FLAGS) {
6878 SV *reflags = Perl_refcounted_he_fetch_pvn(aTHX_
6879 PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags"), 0, 0
6881 if (reflags && SvOK(reflags)) pmop->op_pmflags |= SvIV(reflags);
6882 reflags = Perl_refcounted_he_fetch_pvn(aTHX_
6883 PL_compiling.cop_hints_hash, STR_WITH_LEN("reflags_charset"), 0, 0
6885 if (reflags && SvOK(reflags)) {
6886 set_regex_charset(&(pmop->op_pmflags), (regex_charset)SvIV(reflags));
6892 assert(SvPOK(PL_regex_pad[0]));
6893 if (SvCUR(PL_regex_pad[0])) {
6894 /* Pop off the "packed" IV from the end. */
6895 SV *const repointer_list = PL_regex_pad[0];
6896 const char *p = SvEND(repointer_list) - sizeof(IV);
6897 const IV offset = *((IV*)p);
6899 assert(SvCUR(repointer_list) % sizeof(IV) == 0);
6901 SvEND_set(repointer_list, p);
6903 pmop->op_pmoffset = offset;
6904 /* This slot should be free, so assert this: */
6905 assert(PL_regex_pad[offset] == &PL_sv_undef);
6907 SV * const repointer = &PL_sv_undef;
6908 av_push(PL_regex_padav, repointer);
6909 pmop->op_pmoffset = av_top_index(PL_regex_padav);
6910 PL_regex_pad = AvARRAY(PL_regex_padav);
6914 return CHECKOP(type, pmop);
6922 /* Any pad names in scope are potentially lvalues. */
6923 for (; i < PadnamelistMAXNAMED(PL_comppad_name); i++) {
6924 PADNAME *pn = PAD_COMPNAME_SV(i);
6925 if (!pn || !PadnameLEN(pn))
6927 if (PadnameOUTER(pn) || PadnameIN_SCOPE(pn, PL_cop_seqmax))
6928 S_mark_padname_lvalue(aTHX_ pn);
6932 /* Given some sort of match op o, and an expression expr containing a
6933 * pattern, either compile expr into a regex and attach it to o (if it's
6934 * constant), or convert expr into a runtime regcomp op sequence (if it's
6937 * Flags currently has 2 bits of meaning:
6938 * 1: isreg indicates that the pattern is part of a regex construct, eg
6939 * $x =~ /pattern/ or split /pattern/, as opposed to $x =~ $pattern or
6940 * split "pattern", which aren't. In the former case, expr will be a list
6941 * if the pattern contains more than one term (eg /a$b/).
6942 * 2: The pattern is for a split.
6944 * When the pattern has been compiled within a new anon CV (for
6945 * qr/(?{...})/ ), then floor indicates the savestack level just before
6946 * the new sub was created
6948 * tr/// is also handled.
6952 Perl_pmruntime(pTHX_ OP *o, OP *expr, OP *repl, UV flags, I32 floor)
6956 I32 repl_has_vars = 0;
6957 bool is_trans = (o->op_type == OP_TRANS || o->op_type == OP_TRANSR);
6958 bool is_compiletime;
6960 bool isreg = cBOOL(flags & 1);
6961 bool is_split = cBOOL(flags & 2);
6963 PERL_ARGS_ASSERT_PMRUNTIME;
6966 return pmtrans(o, expr, repl);
6969 /* find whether we have any runtime or code elements;
6970 * at the same time, temporarily set the op_next of each DO block;
6971 * then when we LINKLIST, this will cause the DO blocks to be excluded
6972 * from the op_next chain (and from having LINKLIST recursively
6973 * applied to them). We fix up the DOs specially later */
6977 if (expr->op_type == OP_LIST) {
6979 for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
6980 if (child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)) {
6982 assert(!child->op_next);
6983 if (UNLIKELY(!OpHAS_SIBLING(child))) {
6984 assert(PL_parser && PL_parser->error_count);
6985 /* This can happen with qr/ (?{(^{})/. Just fake up
6986 the op we were expecting to see, to avoid crashing
6988 op_sibling_splice(expr, child, 0,
6989 newSVOP(OP_CONST, 0, &PL_sv_no));
6991 child->op_next = OpSIBLING(child);
6993 else if (child->op_type != OP_CONST && child->op_type != OP_PUSHMARK)
6997 else if (expr->op_type != OP_CONST)
7002 /* fix up DO blocks; treat each one as a separate little sub;
7003 * also, mark any arrays as LIST/REF */
7005 if (expr->op_type == OP_LIST) {
7007 for (child = cLISTOPx(expr)->op_first; child; child = OpSIBLING(child)) {
7009 if (child->op_type == OP_PADAV || child->op_type == OP_RV2AV) {
7010 assert( !(child->op_flags & OPf_WANT));
7011 /* push the array rather than its contents. The regex
7012 * engine will retrieve and join the elements later */
7013 child->op_flags |= (OPf_WANT_LIST | OPf_REF);
7017 if (!(child->op_type == OP_NULL && (child->op_flags & OPf_SPECIAL)))
7019 child->op_next = NULL; /* undo temporary hack from above */
7022 if (cLISTOPx(child)->op_first->op_type == OP_LEAVE) {
7023 LISTOP *leaveop = cLISTOPx(cLISTOPx(child)->op_first);
7025 assert(leaveop->op_first->op_type == OP_ENTER);
7026 assert(OpHAS_SIBLING(leaveop->op_first));
7027 child->op_next = OpSIBLING(leaveop->op_first);
7029 assert(leaveop->op_flags & OPf_KIDS);
7030 assert(leaveop->op_last->op_next == (OP*)leaveop);
7031 leaveop->op_next = NULL; /* stop on last op */
7032 op_null((OP*)leaveop);
7036 OP *scope = cLISTOPx(child)->op_first;
7037 assert(scope->op_type == OP_SCOPE);
7038 assert(scope->op_flags & OPf_KIDS);
7039 scope->op_next = NULL; /* stop on last op */
7043 /* XXX optimize_optree() must be called on o before
7044 * CALL_PEEP(), as currently S_maybe_multiconcat() can't
7045 * currently cope with a peephole-optimised optree.
7046 * Calling optimize_optree() here ensures that condition
7047 * is met, but may mean optimize_optree() is applied
7048 * to the same optree later (where hopefully it won't do any
7049 * harm as it can't convert an op to multiconcat if it's
7050 * already been converted */
7051 optimize_optree(child);
7053 /* have to peep the DOs individually as we've removed it from
7054 * the op_next chain */
7056 op_prune_chain_head(&(child->op_next));
7058 /* runtime finalizes as part of finalizing whole tree */
7059 finalize_optree(child);
7062 else if (expr->op_type == OP_PADAV || expr->op_type == OP_RV2AV) {
7063 assert( !(expr->op_flags & OPf_WANT));
7064 /* push the array rather than its contents. The regex
7065 * engine will retrieve and join the elements later */
7066 expr->op_flags |= (OPf_WANT_LIST | OPf_REF);
7069 PL_hints |= HINT_BLOCK_SCOPE;
7071 assert(floor==0 || (pm->op_pmflags & PMf_HAS_CV));
7073 if (is_compiletime) {
7074 U32 rx_flags = pm->op_pmflags & RXf_PMf_COMPILETIME;
7075 regexp_engine const *eng = current_re_engine();
7078 /* make engine handle split ' ' specially */
7079 pm->op_pmflags |= PMf_SPLIT;
7080 rx_flags |= RXf_SPLIT;
7083 if (!has_code || !eng->op_comp) {
7084 /* compile-time simple constant pattern */
7086 if ((pm->op_pmflags & PMf_HAS_CV) && !has_code) {
7087 /* whoops! we guessed that a qr// had a code block, but we
7088 * were wrong (e.g. /[(?{}]/ ). Throw away the PL_compcv
7089 * that isn't required now. Note that we have to be pretty
7090 * confident that nothing used that CV's pad while the
7091 * regex was parsed, except maybe op targets for \Q etc.
7092 * If there were any op targets, though, they should have
7093 * been stolen by constant folding.
7097 assert(PadnamelistMAXNAMED(PL_comppad_name) == 0);
7098 while (++i <= AvFILLp(PL_comppad)) {
7099 # ifdef USE_PAD_RESET
7100 /* under USE_PAD_RESET, pad swipe replaces a swiped
7101 * folded constant with a fresh padtmp */
7102 assert(!PL_curpad[i] || SvPADTMP(PL_curpad[i]));
7104 assert(!PL_curpad[i]);
7108 /* This LEAVE_SCOPE will restore PL_compcv to point to the
7109 * outer CV (the one whose slab holds the pm op). The
7110 * inner CV (which holds expr) will be freed later, once
7111 * all the entries on the parse stack have been popped on
7112 * return from this function. Which is why its safe to
7113 * call op_free(expr) below.
7116 pm->op_pmflags &= ~PMf_HAS_CV;
7119 /* Skip compiling if parser found an error for this pattern */
7120 if (pm->op_pmflags & PMf_HAS_ERROR) {
7126 ? eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7127 rx_flags, pm->op_pmflags)
7128 : Perl_re_op_compile(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7129 rx_flags, pm->op_pmflags)
7134 /* compile-time pattern that includes literal code blocks */
7138 /* Skip compiling if parser found an error for this pattern */
7139 if (pm->op_pmflags & PMf_HAS_ERROR) {
7143 re = eng->op_comp(aTHX_ NULL, 0, expr, eng, NULL, NULL,
7146 ((PL_hints & HINT_RE_EVAL) ? PMf_USE_RE_EVAL : 0))
7149 if (pm->op_pmflags & PMf_HAS_CV) {
7151 /* this QR op (and the anon sub we embed it in) is never
7152 * actually executed. It's just a placeholder where we can
7153 * squirrel away expr in op_code_list without the peephole
7154 * optimiser etc processing it for a second time */
7155 OP *qr = newPMOP(OP_QR, 0);
7156 cPMOPx(qr)->op_code_list = expr;
7158 /* handle the implicit sub{} wrapped round the qr/(?{..})/ */
7159 SvREFCNT_inc_simple_void(PL_compcv);
7160 cv = newATTRSUB(floor, 0, NULL, NULL, qr);
7161 ReANY(re)->qr_anoncv = cv;
7163 /* attach the anon CV to the pad so that
7164 * pad_fixup_inner_anons() can find it */
7165 (void)pad_add_anon(cv, o->op_type);
7166 SvREFCNT_inc_simple_void(cv);
7169 pm->op_code_list = expr;
7174 /* runtime pattern: build chain of regcomp etc ops */
7176 PADOFFSET cv_targ = 0;
7178 reglist = isreg && expr->op_type == OP_LIST;
7183 pm->op_code_list = expr;
7184 /* don't free op_code_list; its ops are embedded elsewhere too */
7185 pm->op_pmflags |= PMf_CODELIST_PRIVATE;
7189 /* make engine handle split ' ' specially */
7190 pm->op_pmflags |= PMf_SPLIT;
7192 /* the OP_REGCMAYBE is a placeholder in the non-threaded case
7193 * to allow its op_next to be pointed past the regcomp and
7194 * preceding stacking ops;
7195 * OP_REGCRESET is there to reset taint before executing the
7197 if (pm->op_pmflags & PMf_KEEP || TAINTING_get)
7198 expr = newUNOP((TAINTING_get ? OP_REGCRESET : OP_REGCMAYBE),0,expr);
7200 if (pm->op_pmflags & PMf_HAS_CV) {
7201 /* we have a runtime qr with literal code. This means
7202 * that the qr// has been wrapped in a new CV, which
7203 * means that runtime consts, vars etc will have been compiled
7204 * against a new pad. So... we need to execute those ops
7205 * within the environment of the new CV. So wrap them in a call
7206 * to a new anon sub. i.e. for
7210 * we build an anon sub that looks like
7212 * sub { "a", $b, '(?{...})' }
7214 * and call it, passing the returned list to regcomp.
7215 * Or to put it another way, the list of ops that get executed
7219 * ------ -------------------
7220 * pushmark (for regcomp)
7221 * pushmark (for entersub)
7225 * regcreset regcreset
7227 * const("a") const("a")
7229 * const("(?{...})") const("(?{...})")
7234 SvREFCNT_inc_simple_void(PL_compcv);
7235 CvLVALUE_on(PL_compcv);
7236 /* these lines are just an unrolled newANONATTRSUB */
7237 expr = newSVOP(OP_ANONCODE, 0,
7238 MUTABLE_SV(newATTRSUB(floor, 0, NULL, NULL, expr)));
7239 cv_targ = expr->op_targ;
7240 expr = newUNOP(OP_REFGEN, 0, expr);
7242 expr = list(force_list(newUNOP(OP_ENTERSUB, 0, scalar(expr)), TRUE));
7245 rcop = alloc_LOGOP(OP_REGCOMP, scalar(expr), o);
7246 rcop->op_flags |= ((PL_hints & HINT_RE_EVAL) ? OPf_SPECIAL : 0)
7247 | (reglist ? OPf_STACKED : 0);
7248 rcop->op_targ = cv_targ;
7250 /* /$x/ may cause an eval, since $x might be qr/(?{..})/ */
7251 if (PL_hints & HINT_RE_EVAL)
7252 S_set_haseval(aTHX);
7254 /* establish postfix order */
7255 if (expr->op_type == OP_REGCRESET || expr->op_type == OP_REGCMAYBE) {
7257 rcop->op_next = expr;
7258 cUNOPx(expr)->op_first->op_next = (OP*)rcop;
7261 rcop->op_next = LINKLIST(expr);
7262 expr->op_next = (OP*)rcop;
7265 op_prepend_elem(o->op_type, scalar((OP*)rcop), o);
7271 /* If we are looking at s//.../e with a single statement, get past
7272 the implicit do{}. */
7273 if (curop->op_type == OP_NULL && curop->op_flags & OPf_KIDS
7274 && cUNOPx(curop)->op_first->op_type == OP_SCOPE
7275 && cUNOPx(curop)->op_first->op_flags & OPf_KIDS)
7278 OP *kid = cUNOPx(cUNOPx(curop)->op_first)->op_first;
7279 if (kid->op_type == OP_NULL && (sib = OpSIBLING(kid))
7280 && !OpHAS_SIBLING(sib))
7283 if (curop->op_type == OP_CONST)
7285 else if (( (curop->op_type == OP_RV2SV ||
7286 curop->op_type == OP_RV2AV ||
7287 curop->op_type == OP_RV2HV ||
7288 curop->op_type == OP_RV2GV)
7289 && cUNOPx(curop)->op_first
7290 && cUNOPx(curop)->op_first->op_type == OP_GV )
7291 || curop->op_type == OP_PADSV
7292 || curop->op_type == OP_PADAV
7293 || curop->op_type == OP_PADHV
7294 || curop->op_type == OP_PADANY) {
7302 || !RX_PRELEN(PM_GETRE(pm))
7303 || RX_EXTFLAGS(PM_GETRE(pm)) & RXf_EVAL_SEEN)))
7305 pm->op_pmflags |= PMf_CONST; /* const for long enough */
7306 op_prepend_elem(o->op_type, scalar(repl), o);
7309 rcop = alloc_LOGOP(OP_SUBSTCONT, scalar(repl), o);
7310 rcop->op_private = 1;
7312 /* establish postfix order */
7313 rcop->op_next = LINKLIST(repl);
7314 repl->op_next = (OP*)rcop;
7316 pm->op_pmreplrootu.op_pmreplroot = scalar((OP*)rcop);
7317 assert(!(pm->op_pmflags & PMf_ONCE));
7318 pm->op_pmstashstartu.op_pmreplstart = LINKLIST(rcop);
7329 Constructs, checks, and returns an op of any type that involves an
7330 embedded SV. C<type> is the opcode. C<flags> gives the eight bits
7331 of C<op_flags>. C<sv> gives the SV to embed in the op; this function
7332 takes ownership of one reference to it.
7338 Perl_newSVOP(pTHX_ I32 type, I32 flags, SV *sv)
7342 PERL_ARGS_ASSERT_NEWSVOP;
7344 /* OP_RUNCV is allowed specially so rpeep has room to convert it into an
7346 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7347 || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7348 || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7350 || type == OP_CUSTOM);
7352 NewOp(1101, svop, 1, SVOP);
7353 OpTYPE_set(svop, type);
7355 svop->op_next = (OP*)svop;
7356 svop->op_flags = (U8)flags;
7357 svop->op_private = (U8)(0 | (flags >> 8));
7358 if (PL_opargs[type] & OA_RETSCALAR)
7360 if (PL_opargs[type] & OA_TARGET)
7361 svop->op_targ = pad_alloc(type, SVs_PADTMP);
7362 return CHECKOP(type, svop);
7366 =for apidoc newDEFSVOP
7368 Constructs and returns an op to access C<$_>.
7374 Perl_newDEFSVOP(pTHX)
7376 return newSVREF(newGVOP(OP_GV, 0, PL_defgv));
7382 =for apidoc newPADOP
7384 Constructs, checks, and returns an op of any type that involves a
7385 reference to a pad element. C<type> is the opcode. C<flags> gives the
7386 eight bits of C<op_flags>. A pad slot is automatically allocated, and
7387 is populated with C<sv>; this function takes ownership of one reference
7390 This function only exists if Perl has been compiled to use ithreads.
7396 Perl_newPADOP(pTHX_ I32 type, I32 flags, SV *sv)
7400 PERL_ARGS_ASSERT_NEWPADOP;
7402 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_SVOP
7403 || (PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7404 || (PL_opargs[type] & OA_CLASS_MASK) == OA_FILESTATOP
7405 || type == OP_CUSTOM);
7407 NewOp(1101, padop, 1, PADOP);
7408 OpTYPE_set(padop, type);
7410 pad_alloc(type, isGV(sv) ? SVf_READONLY : SVs_PADTMP);
7411 SvREFCNT_dec(PAD_SVl(padop->op_padix));
7412 PAD_SETSV(padop->op_padix, sv);
7414 padop->op_next = (OP*)padop;
7415 padop->op_flags = (U8)flags;
7416 if (PL_opargs[type] & OA_RETSCALAR)
7418 if (PL_opargs[type] & OA_TARGET)
7419 padop->op_targ = pad_alloc(type, SVs_PADTMP);
7420 return CHECKOP(type, padop);
7423 #endif /* USE_ITHREADS */
7428 Constructs, checks, and returns an op of any type that involves an
7429 embedded reference to a GV. C<type> is the opcode. C<flags> gives the
7430 eight bits of C<op_flags>. C<gv> identifies the GV that the op should
7431 reference; calling this function does not transfer ownership of any
7438 Perl_newGVOP(pTHX_ I32 type, I32 flags, GV *gv)
7440 PERL_ARGS_ASSERT_NEWGVOP;
7443 return newPADOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7445 return newSVOP(type, flags, SvREFCNT_inc_simple_NN(gv));
7452 Constructs, checks, and returns an op of any type that involves an
7453 embedded C-level pointer (PV). C<type> is the opcode. C<flags> gives
7454 the eight bits of C<op_flags>. C<pv> supplies the C-level pointer.
7455 Depending on the op type, the memory referenced by C<pv> may be freed
7456 when the op is destroyed. If the op is of a freeing type, C<pv> must
7457 have been allocated using C<PerlMemShared_malloc>.
7463 Perl_newPVOP(pTHX_ I32 type, I32 flags, char *pv)
7465 const bool utf8 = cBOOL(flags & SVf_UTF8);
7470 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_PVOP_OR_SVOP
7471 || type == OP_CUSTOM
7472 || (PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP);
7474 NewOp(1101, pvop, 1, PVOP);
7475 OpTYPE_set(pvop, type);
7477 pvop->op_next = (OP*)pvop;
7478 pvop->op_flags = (U8)flags;
7479 pvop->op_private = utf8 ? OPpPV_IS_UTF8 : 0;
7480 if (PL_opargs[type] & OA_RETSCALAR)
7482 if (PL_opargs[type] & OA_TARGET)
7483 pvop->op_targ = pad_alloc(type, SVs_PADTMP);
7484 return CHECKOP(type, pvop);
7488 Perl_package(pTHX_ OP *o)
7490 SV *const sv = cSVOPo->op_sv;
7492 PERL_ARGS_ASSERT_PACKAGE;
7494 SAVEGENERICSV(PL_curstash);
7495 save_item(PL_curstname);
7497 PL_curstash = (HV *)SvREFCNT_inc(gv_stashsv(sv, GV_ADD));
7499 sv_setsv(PL_curstname, sv);
7501 PL_hints |= HINT_BLOCK_SCOPE;
7502 PL_parser->copline = NOLINE;
7508 Perl_package_version( pTHX_ OP *v )
7510 U32 savehints = PL_hints;
7511 PERL_ARGS_ASSERT_PACKAGE_VERSION;
7512 PL_hints &= ~HINT_STRICT_VARS;
7513 sv_setsv( GvSV(gv_fetchpvs("VERSION", GV_ADDMULTI, SVt_PV)), cSVOPx(v)->op_sv );
7514 PL_hints = savehints;
7518 /* Extract the first two components of a "version" object as two 8bit integers
7519 * and return them packed into a single U16 in the format of PL_prevailing_version.
7520 * This function only ever has to cope with version objects already known
7521 * bounded by the current perl version, so we know its components will fit
7522 * (Up until we reach perl version 5.256 anyway) */
7523 static U16 S_extract_shortver(pTHX_ SV *sv)
7526 if(!SvRV(sv) || !SvOBJECT(rv = SvRV(sv)) || !sv_derived_from(sv, "version"))
7529 AV *av = MUTABLE_AV(SvRV(*hv_fetchs(MUTABLE_HV(rv), "version", 0)));
7533 IV major = av_count(av) > 0 ? SvIV(*av_fetch(av, 0, false)) : 0;
7535 shortver |= 255 << 8;
7537 shortver |= major << 8;
7539 IV minor = av_count(av) > 1 ? SvIV(*av_fetch(av, 1, false)) : 0;
7547 #define SHORTVER(maj,min) ((maj << 8) | min)
7550 Perl_utilize(pTHX_ int aver, I32 floor, OP *version, OP *idop, OP *arg)
7555 SV *use_version = NULL;
7557 PERL_ARGS_ASSERT_UTILIZE;
7559 if (idop->op_type != OP_CONST)
7560 Perl_croak(aTHX_ "Module name must be constant");
7565 SV * const vesv = cSVOPx(version)->op_sv;
7567 if (!arg && !SvNIOKp(vesv)) {
7574 if (version->op_type != OP_CONST || !SvNIOKp(vesv))
7575 Perl_croak(aTHX_ "Version number must be a constant number");
7577 /* Make copy of idop so we don't free it twice */
7578 pack = newSVOP(OP_CONST, 0, newSVsv(cSVOPx(idop)->op_sv));
7580 /* Fake up a method call to VERSION */
7581 meth = newSVpvs_share("VERSION");
7582 veop = op_convert_list(OP_ENTERSUB, OPf_STACKED,
7583 op_append_elem(OP_LIST,
7584 op_prepend_elem(OP_LIST, pack, version),
7585 newMETHOP_named(OP_METHOD_NAMED, 0, meth)));
7589 /* Fake up an import/unimport */
7590 if (arg && arg->op_type == OP_STUB) {
7591 imop = arg; /* no import on explicit () */
7593 else if (SvNIOKp(cSVOPx(idop)->op_sv)) {
7594 imop = NULL; /* use 5.0; */
7596 use_version = cSVOPx(idop)->op_sv;
7598 idop->op_private |= OPpCONST_NOVER;
7603 /* Make copy of idop so we don't free it twice */
7604 pack = newSVOP(OP_CONST, 0, newSVsv(cSVOPx(idop)->op_sv));
7606 /* Fake up a method call to import/unimport */
7608 ? newSVpvs_share("import") : newSVpvs_share("unimport");
7609 imop = op_convert_list(OP_ENTERSUB, OPf_STACKED,
7610 op_append_elem(OP_LIST,
7611 op_prepend_elem(OP_LIST, pack, arg),
7612 newMETHOP_named(OP_METHOD_NAMED, 0, meth)
7616 /* Fake up the BEGIN {}, which does its thing immediately. */
7618 newSVOP(OP_CONST, 0, newSVpvs_share("BEGIN")),
7621 op_append_elem(OP_LINESEQ,
7622 op_append_elem(OP_LINESEQ,
7623 newSTATEOP(0, NULL, newUNOP(OP_REQUIRE, 0, idop)),
7624 newSTATEOP(0, NULL, veop)),
7625 newSTATEOP(0, NULL, imop) ));
7629 * feature bundle that corresponds to the required version. */
7630 use_version = sv_2mortal(new_version(use_version));
7631 S_enable_feature_bundle(aTHX_ use_version);
7633 U16 shortver = S_extract_shortver(aTHX_ use_version);
7635 /* If a version >= 5.11.0 is requested, strictures are on by default! */
7636 if (shortver >= SHORTVER(5, 11)) {
7637 if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7638 PL_hints |= HINT_STRICT_REFS;
7639 if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7640 PL_hints |= HINT_STRICT_SUBS;
7641 if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7642 PL_hints |= HINT_STRICT_VARS;
7644 if (shortver >= SHORTVER(5, 35))
7645 free_and_set_cop_warnings(&PL_compiling, pWARN_ALL);
7647 /* otherwise they are off */
7649 if(PL_prevailing_version >= SHORTVER(5, 11))
7650 deprecate_fatal_in("5.40",
7651 "Downgrading a use VERSION declaration to below v5.11");
7653 if (!(PL_hints & HINT_EXPLICIT_STRICT_REFS))
7654 PL_hints &= ~HINT_STRICT_REFS;
7655 if (!(PL_hints & HINT_EXPLICIT_STRICT_SUBS))
7656 PL_hints &= ~HINT_STRICT_SUBS;
7657 if (!(PL_hints & HINT_EXPLICIT_STRICT_VARS))
7658 PL_hints &= ~HINT_STRICT_VARS;
7661 PL_prevailing_version = shortver;
7664 /* The "did you use incorrect case?" warning used to be here.
7665 * The problem is that on case-insensitive filesystems one
7666 * might get false positives for "use" (and "require"):
7667 * "use Strict" or "require CARP" will work. This causes
7668 * portability problems for the script: in case-strict
7669 * filesystems the script will stop working.
7671 * The "incorrect case" warning checked whether "use Foo"
7672 * imported "Foo" to your namespace, but that is wrong, too:
7673 * there is no requirement nor promise in the language that
7674 * a Foo.pm should or would contain anything in package "Foo".
7676 * There is very little Configure-wise that can be done, either:
7677 * the case-sensitivity of the build filesystem of Perl does not
7678 * help in guessing the case-sensitivity of the runtime environment.
7681 PL_hints |= HINT_BLOCK_SCOPE;
7682 PL_parser->copline = NOLINE;
7683 COP_SEQMAX_INC; /* Purely for B::*'s benefit */
7687 =for apidoc_section $embedding
7689 =for apidoc load_module
7690 =for apidoc_item load_module_nocontext
7692 These load the module whose name is pointed to by the string part of C<name>.
7693 Note that the actual module name, not its filename, should be given.
7694 Eg, "Foo::Bar" instead of "Foo/Bar.pm". ver, if specified and not NULL,
7695 provides version semantics similar to C<use Foo::Bar VERSION>. The optional
7696 trailing arguments can be used to specify arguments to the module's C<import()>
7697 method, similar to C<use Foo::Bar VERSION LIST>; their precise handling depends
7698 on the flags. The flags argument is a bitwise-ORed collection of any of
7699 C<PERL_LOADMOD_DENY>, C<PERL_LOADMOD_NOIMPORT>, or C<PERL_LOADMOD_IMPORT_OPS>
7700 (or 0 for no flags).
7702 If C<PERL_LOADMOD_NOIMPORT> is set, the module is loaded as if with an empty
7703 import list, as in C<use Foo::Bar ()>; this is the only circumstance in which
7704 the trailing optional arguments may be omitted entirely. Otherwise, if
7705 C<PERL_LOADMOD_IMPORT_OPS> is set, the trailing arguments must consist of
7706 exactly one C<OP*>, containing the op tree that produces the relevant import
7707 arguments. Otherwise, the trailing arguments must all be C<SV*> values that
7708 will be used as import arguments; and the list must be terminated with C<(SV*)
7709 NULL>. If neither C<PERL_LOADMOD_NOIMPORT> nor C<PERL_LOADMOD_IMPORT_OPS> is
7710 set, the trailing C<NULL> pointer is needed even if no import arguments are
7711 desired. The reference count for each specified C<SV*> argument is
7712 decremented. In addition, the C<name> argument is modified.
7714 If C<PERL_LOADMOD_DENY> is set, the module is loaded as if with C<no> rather
7717 C<load_module> and C<load_module_nocontext> have the same apparent signature,
7718 but the former hides the fact that it is accessing a thread context parameter.
7719 So use the latter when you get a compilation error about C<pTHX>.
7721 =for apidoc Amnh||PERL_LOADMOD_DENY
7722 =for apidoc Amnh||PERL_LOADMOD_NOIMPORT
7723 =for apidoc Amnh||PERL_LOADMOD_IMPORT_OPS
7725 =for apidoc vload_module
7726 Like C<L</load_module>> but the arguments are an encapsulated argument list.
7731 Perl_load_module(pTHX_ U32 flags, SV *name, SV *ver, ...)
7735 PERL_ARGS_ASSERT_LOAD_MODULE;
7737 va_start(args, ver);
7738 vload_module(flags, name, ver, &args);
7744 Perl_load_module_nocontext(U32 flags, SV *name, SV *ver, ...)
7748 PERL_ARGS_ASSERT_LOAD_MODULE_NOCONTEXT;
7749 va_start(args, ver);
7750 vload_module(flags, name, ver, &args);
7756 Perl_vload_module(pTHX_ U32 flags, SV *name, SV *ver, va_list *args)
7762 PERL_ARGS_ASSERT_VLOAD_MODULE;
7764 /* utilize() fakes up a BEGIN { require ..; import ... }, so make sure
7765 * that it has a PL_parser to play with while doing that, and also
7766 * that it doesn't mess with any existing parser, by creating a tmp
7767 * new parser with lex_start(). This won't actually be used for much,
7768 * since pp_require() will create another parser for the real work.
7769 * The ENTER/LEAVE pair protect callers from any side effects of use.
7771 * start_subparse() creates a new PL_compcv. This means that any ops
7772 * allocated below will be allocated from that CV's op slab, and so
7773 * will be automatically freed if the utilise() fails
7777 SAVEVPTR(PL_curcop);
7778 lex_start(NULL, NULL, LEX_START_SAME_FILTER);
7779 floor = start_subparse(FALSE, 0);
7781 modname = newSVOP(OP_CONST, 0, name);
7782 modname->op_private |= OPpCONST_BARE;
7784 veop = newSVOP(OP_CONST, 0, ver);
7788 if (flags & PERL_LOADMOD_NOIMPORT) {
7789 imop = sawparens(newNULLLIST());
7791 else if (flags & PERL_LOADMOD_IMPORT_OPS) {
7792 imop = va_arg(*args, OP*);
7797 sv = va_arg(*args, SV*);
7799 imop = op_append_elem(OP_LIST, imop, newSVOP(OP_CONST, 0, sv));
7800 sv = va_arg(*args, SV*);
7804 utilize(!(flags & PERL_LOADMOD_DENY), floor, veop, modname, imop);
7808 PERL_STATIC_INLINE OP *
7809 S_new_entersubop(pTHX_ GV *gv, OP *arg)
7811 return newUNOP(OP_ENTERSUB, OPf_STACKED,
7812 newLISTOP(OP_LIST, 0, arg,
7813 newUNOP(OP_RV2CV, 0,
7814 newGVOP(OP_GV, 0, gv))));
7818 Perl_dofile(pTHX_ OP *term, I32 force_builtin)
7823 PERL_ARGS_ASSERT_DOFILE;
7825 if (!force_builtin && (gv = gv_override("do", 2))) {
7826 doop = S_new_entersubop(aTHX_ gv, term);
7829 doop = newUNOP(OP_DOFILE, 0, scalar(term));
7835 =for apidoc_section $optree_construction
7837 =for apidoc newSLICEOP
7839 Constructs, checks, and returns an C<lslice> (list slice) op. C<flags>
7840 gives the eight bits of C<op_flags>, except that C<OPf_KIDS> will
7841 be set automatically, and, shifted up eight bits, the eight bits of
7842 C<op_private>, except that the bit with value 1 or 2 is automatically
7843 set as required. C<listval> and C<subscript> supply the parameters of
7844 the slice; they are consumed by this function and become part of the
7845 constructed op tree.
7851 Perl_newSLICEOP(pTHX_ I32 flags, OP *subscript, OP *listval)
7853 return newBINOP(OP_LSLICE, flags,
7854 list(force_list(subscript, TRUE)),
7855 list(force_list(listval, TRUE)));
7858 #define ASSIGN_SCALAR 0
7859 #define ASSIGN_LIST 1
7860 #define ASSIGN_REF 2
7862 /* given the optree o on the LHS of an assignment, determine whether its:
7863 * ASSIGN_SCALAR $x = ...
7864 * ASSIGN_LIST ($x) = ...
7865 * ASSIGN_REF \$x = ...
7869 S_assignment_type(pTHX_ const OP *o)
7878 if (o->op_type == OP_SREFGEN)
7880 OP * const kid = cUNOPx(cUNOPo->op_first)->op_first;
7881 type = kid->op_type;
7882 flags = o->op_flags | kid->op_flags;
7883 if (!(flags & OPf_PARENS)
7884 && (kid->op_type == OP_RV2AV || kid->op_type == OP_PADAV ||
7885 kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV ))
7889 if ((o->op_type == OP_NULL) && (o->op_flags & OPf_KIDS))
7890 o = cUNOPo->op_first;
7891 flags = o->op_flags;
7893 ret = ASSIGN_SCALAR;
7896 if (type == OP_COND_EXPR) {
7897 OP * const sib = OpSIBLING(cLOGOPo->op_first);
7898 const I32 t = assignment_type(sib);
7899 const I32 f = assignment_type(OpSIBLING(sib));
7901 if (t == ASSIGN_LIST && f == ASSIGN_LIST)
7903 if ((t == ASSIGN_LIST) ^ (f == ASSIGN_LIST))
7904 yyerror("Assignment to both a list and a scalar");
7905 return ASSIGN_SCALAR;
7908 if (type == OP_LIST &&
7909 (flags & OPf_WANT) == OPf_WANT_SCALAR &&
7910 o->op_private & OPpLVAL_INTRO)
7913 if (type == OP_LIST || flags & OPf_PARENS ||
7914 type == OP_RV2AV || type == OP_RV2HV ||
7915 type == OP_ASLICE || type == OP_HSLICE ||
7916 type == OP_KVASLICE || type == OP_KVHSLICE || type == OP_REFGEN)
7919 if (type == OP_PADAV || type == OP_PADHV)
7922 if (type == OP_RV2SV)
7929 S_newONCEOP(pTHX_ OP *initop, OP *padop)
7931 const PADOFFSET target = padop->op_targ;
7932 OP *const other = newOP(OP_PADSV,
7934 | ((padop->op_private & ~OPpLVAL_INTRO) << 8));
7935 OP *const first = newOP(OP_NULL, 0);
7936 OP *const nullop = newCONDOP(0, first, initop, other);
7937 /* XXX targlex disabled for now; see ticket #124160
7938 newCONDOP(0, first, S_maybe_targlex(aTHX_ initop), other);
7940 OP *const condop = first->op_next;
7942 OpTYPE_set(condop, OP_ONCE);
7943 other->op_targ = target;
7944 nullop->op_flags |= OPf_WANT_SCALAR;
7946 /* Store the initializedness of state vars in a separate
7949 pad_add_name_pvn("$",1,padadd_NO_DUP_CHECK|padadd_STATE,0,0);
7950 /* hijacking PADSTALE for uninitialized state variables */
7951 SvPADSTALE_on(PAD_SVl(condop->op_targ));
7957 =for apidoc newASSIGNOP
7959 Constructs, checks, and returns an assignment op. C<left> and C<right>
7960 supply the parameters of the assignment; they are consumed by this
7961 function and become part of the constructed op tree.
7963 If C<optype> is C<OP_ANDASSIGN>, C<OP_ORASSIGN>, or C<OP_DORASSIGN>, then
7964 a suitable conditional optree is constructed. If C<optype> is the opcode
7965 of a binary operator, such as C<OP_BIT_OR>, then an op is constructed that
7966 performs the binary operation and assigns the result to the left argument.
7967 Either way, if C<optype> is non-zero then C<flags> has no effect.
7969 If C<optype> is zero, then a plain scalar or list assignment is
7970 constructed. Which type of assignment it is is automatically determined.
7971 C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
7972 will be set automatically, and, shifted up eight bits, the eight bits
7973 of C<op_private>, except that the bit with value 1 or 2 is automatically
7980 Perl_newASSIGNOP(pTHX_ I32 flags, OP *left, I32 optype, OP *right)
7990 right = scalar(right);
7991 return newLOGOP(optype, 0,
7992 op_lvalue(scalar(left), optype),
7993 newBINOP(OP_SASSIGN, OPpASSIGN_BACKWARDS<<8, right, right));
7995 return newBINOP(optype, OPf_STACKED,
7996 op_lvalue(scalar(left), optype), scalar(right));
7999 if ((assign_type = assignment_type(left)) == ASSIGN_LIST) {
8000 OP *state_var_op = NULL;
8001 static const char no_list_state[] = "Initialization of state variables"
8002 " in list currently forbidden";
8005 if (left->op_type == OP_ASLICE || left->op_type == OP_HSLICE)
8006 left->op_private &= ~ OPpSLICEWARNING;
8009 left = op_lvalue(left, OP_AASSIGN);
8010 curop = list(force_list(left, TRUE));
8011 o = newBINOP(OP_AASSIGN, flags, list(force_list(right, TRUE)), curop);
8012 o->op_private = (U8)(0 | (flags >> 8));
8014 if (OP_TYPE_IS_OR_WAS(left, OP_LIST))
8016 OP *lop = cLISTOPx(left)->op_first, *vop, *eop;
8017 if (!(left->op_flags & OPf_PARENS) &&
8018 lop->op_type == OP_PUSHMARK &&
8019 (vop = OpSIBLING(lop)) &&
8020 (vop->op_type == OP_PADAV || vop->op_type == OP_PADHV) &&
8021 !(vop->op_flags & OPf_PARENS) &&
8022 (vop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE)) ==
8023 (OPpLVAL_INTRO|OPpPAD_STATE) &&
8024 (eop = OpSIBLING(vop)) &&
8025 eop->op_type == OP_ENTERSUB &&
8026 !OpHAS_SIBLING(eop)) {
8030 if ((lop->op_type == OP_PADSV ||
8031 lop->op_type == OP_PADAV ||
8032 lop->op_type == OP_PADHV ||
8033 lop->op_type == OP_PADANY)
8034 && (lop->op_private & OPpPAD_STATE)
8036 yyerror(no_list_state);
8037 lop = OpSIBLING(lop);
8041 else if ( (left->op_private & OPpLVAL_INTRO)
8042 && (left->op_private & OPpPAD_STATE)
8043 && ( left->op_type == OP_PADSV
8044 || left->op_type == OP_PADAV
8045 || left->op_type == OP_PADHV
8046 || left->op_type == OP_PADANY)
8048 /* All single variable list context state assignments, hence
8058 if (left->op_flags & OPf_PARENS)
8059 yyerror(no_list_state);
8061 state_var_op = left;
8064 /* optimise @a = split(...) into:
8065 * @{expr}: split(..., @{expr}) (where @a is not flattened)
8066 * @a, my @a, local @a: split(...) (where @a is attached to
8067 * the split op itself)
8071 && right->op_type == OP_SPLIT
8072 /* don't do twice, e.g. @b = (@a = split) */
8073 && !(right->op_private & OPpSPLIT_ASSIGN))
8077 if ( ( left->op_type == OP_RV2AV
8078 && (gvop=cUNOPx(left)->op_first)->op_type==OP_GV)
8079 || left->op_type == OP_PADAV)
8081 /* @pkg or @lex or local @pkg' or 'my @lex' */
8085 cPMOPx(right)->op_pmreplrootu.op_pmtargetoff
8086 = cPADOPx(gvop)->op_padix;
8087 cPADOPx(gvop)->op_padix = 0; /* steal it */
8089 cPMOPx(right)->op_pmreplrootu.op_pmtargetgv
8090 = MUTABLE_GV(cSVOPx(gvop)->op_sv);
8091 cSVOPx(gvop)->op_sv = NULL; /* steal it */
8093 right->op_private |=
8094 left->op_private & OPpOUR_INTRO;
8097 cPMOPx(right)->op_pmreplrootu.op_pmtargetoff = left->op_targ;
8098 left->op_targ = 0; /* steal it */
8099 right->op_private |= OPpSPLIT_LEX;
8101 right->op_private |= left->op_private & OPpLVAL_INTRO;
8104 tmpop = cUNOPo->op_first; /* to list (nulled) */
8105 tmpop = cUNOPx(tmpop)->op_first; /* to pushmark */
8106 assert(OpSIBLING(tmpop) == right);
8107 assert(!OpHAS_SIBLING(right));
8108 /* detach the split subtreee from the o tree,
8109 * then free the residual o tree */
8110 op_sibling_splice(cUNOPo->op_first, tmpop, 1, NULL);
8111 op_free(o); /* blow off assign */
8112 right->op_private |= OPpSPLIT_ASSIGN;
8113 right->op_flags &= ~OPf_WANT;
8114 /* "I don't know and I don't care." */
8117 else if (left->op_type == OP_RV2AV) {
8120 OP *pushop = cUNOPx(cBINOPo->op_last)->op_first;
8121 assert(OpSIBLING(pushop) == left);
8122 /* Detach the array ... */
8123 op_sibling_splice(cBINOPo->op_last, pushop, 1, NULL);
8124 /* ... and attach it to the split. */
8125 op_sibling_splice(right, cLISTOPx(right)->op_last,
8127 right->op_flags |= OPf_STACKED;
8128 /* Detach split and expunge aassign as above. */
8131 else if (PL_modcount < RETURN_UNLIMITED_NUMBER &&
8132 cLISTOPx(right)->op_last->op_type == OP_CONST)
8134 /* convert split(...,0) to split(..., PL_modcount+1) */
8136 &cSVOPx(cLISTOPx(right)->op_last)->op_sv;
8137 SV * const sv = *svp;
8138 if (SvIOK(sv) && SvIVX(sv) == 0)
8140 if (right->op_private & OPpSPLIT_IMPLIM) {
8141 /* our own SV, created in ck_split */
8143 sv_setiv(sv, PL_modcount+1);
8146 /* SV may belong to someone else */
8148 *svp = newSViv(PL_modcount+1);
8155 o = S_newONCEOP(aTHX_ o, state_var_op);
8158 if (assign_type == ASSIGN_REF)
8159 return newBINOP(OP_REFASSIGN, flags, scalar(right), left);
8161 right = newOP(OP_UNDEF, 0);
8162 if (right->op_type == OP_READLINE) {
8163 right->op_flags |= OPf_STACKED;
8164 return newBINOP(OP_NULL, flags, op_lvalue(scalar(left), OP_SASSIGN),
8168 o = newBINOP(OP_SASSIGN, flags,
8169 scalar(right), op_lvalue(scalar(left), OP_SASSIGN) );
8175 =for apidoc newSTATEOP
8177 Constructs a state op (COP). The state op is normally a C<nextstate> op,
8178 but will be a C<dbstate> op if debugging is enabled for currently-compiled
8179 code. The state op is populated from C<PL_curcop> (or C<PL_compiling>).
8180 If C<label> is non-null, it supplies the name of a label to attach to
8181 the state op; this function takes ownership of the memory pointed at by
8182 C<label>, and will free it. C<flags> gives the eight bits of C<op_flags>
8185 If C<o> is null, the state op is returned. Otherwise the state op is
8186 combined with C<o> into a C<lineseq> list op, which is returned. C<o>
8187 is consumed by this function and becomes part of the returned op tree.
8193 Perl_newSTATEOP(pTHX_ I32 flags, char *label, OP *o)
8195 const U32 seq = intro_my();
8196 const U32 utf8 = flags & SVf_UTF8;
8200 PL_parser->parsed_sub = 0;
8204 NewOp(1101, cop, 1, COP);
8205 if (PERLDB_LINE && CopLINE(PL_curcop) && PL_curstash != PL_debstash) {
8206 OpTYPE_set(cop, OP_DBSTATE);
8209 OpTYPE_set(cop, OP_NEXTSTATE);
8211 cop->op_flags = (U8)flags;
8212 CopHINTS_set(cop, PL_hints);
8214 if (VMSISH_HUSHED) cop->op_private |= OPpHUSH_VMSISH;
8216 cop->op_next = (OP*)cop;
8219 cop->cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
8220 CopHINTHASH_set(cop, cophh_copy(CopHINTHASH_get(PL_curcop)));
8222 Perl_cop_store_label(aTHX_ cop, label, strlen(label), utf8);
8224 PL_hints |= HINT_BLOCK_SCOPE;
8225 /* It seems that we need to defer freeing this pointer, as other parts
8226 of the grammar end up wanting to copy it after this op has been
8231 if (PL_parser->preambling != NOLINE) {
8232 CopLINE_set(cop, PL_parser->preambling);
8233 PL_parser->copline = NOLINE;
8235 else if (PL_parser->copline == NOLINE)
8236 CopLINE_set(cop, CopLINE(PL_curcop));
8238 CopLINE_set(cop, PL_parser->copline);
8239 PL_parser->copline = NOLINE;
8242 CopFILE_set(cop, CopFILE(PL_curcop)); /* XXX share in a pvtable? */
8244 CopFILEGV_set(cop, CopFILEGV(PL_curcop));
8246 CopSTASH_set(cop, PL_curstash);
8248 if (cop->op_type == OP_DBSTATE) {
8249 /* this line can have a breakpoint - store the cop in IV */
8250 AV *av = CopFILEAVx(PL_curcop);
8252 SV * const * const svp = av_fetch(av, CopLINE(cop), FALSE);
8253 if (svp && *svp != &PL_sv_undef ) {
8254 (void)SvIOK_on(*svp);
8255 SvIV_set(*svp, PTR2IV(cop));
8260 if (flags & OPf_SPECIAL)
8262 return op_prepend_elem(OP_LINESEQ, (OP*)cop, o);
8266 =for apidoc newLOGOP
8268 Constructs, checks, and returns a logical (flow control) op. C<type>
8269 is the opcode. C<flags> gives the eight bits of C<op_flags>, except
8270 that C<OPf_KIDS> will be set automatically, and, shifted up eight bits,
8271 the eight bits of C<op_private>, except that the bit with value 1 is
8272 automatically set. C<first> supplies the expression controlling the
8273 flow, and C<other> supplies the side (alternate) chain of ops; they are
8274 consumed by this function and become part of the constructed op tree.
8280 Perl_newLOGOP(pTHX_ I32 type, I32 flags, OP *first, OP *other)
8282 PERL_ARGS_ASSERT_NEWLOGOP;
8284 return new_logop(type, flags, &first, &other);
8288 /* See if the optree o contains a single OP_CONST (plus possibly
8289 * surrounding enter/nextstate/null etc). If so, return it, else return
8294 S_search_const(pTHX_ OP *o)
8296 PERL_ARGS_ASSERT_SEARCH_CONST;
8299 switch (o->op_type) {
8303 if (o->op_flags & OPf_KIDS) {
8304 o = cUNOPo->op_first;
8313 if (!(o->op_flags & OPf_KIDS))
8315 kid = cLISTOPo->op_first;
8318 switch (kid->op_type) {
8322 kid = OpSIBLING(kid);
8325 if (kid != cLISTOPo->op_last)
8332 kid = cLISTOPo->op_last;
8344 S_new_logop(pTHX_ I32 type, I32 flags, OP** firstp, OP** otherp)
8351 int prepend_not = 0;
8353 PERL_ARGS_ASSERT_NEW_LOGOP;
8358 /* [perl #59802]: Warn about things like "return $a or $b", which
8359 is parsed as "(return $a) or $b" rather than "return ($a or
8360 $b)". NB: This also applies to xor, which is why we do it
8363 switch (first->op_type) {
8367 /* XXX: Perhaps we should emit a stronger warning for these.
8368 Even with the high-precedence operator they don't seem to do
8371 But until we do, fall through here.
8377 /* XXX: Currently we allow people to "shoot themselves in the
8378 foot" by explicitly writing "(return $a) or $b".
8380 Warn unless we are looking at the result from folding or if
8381 the programmer explicitly grouped the operators like this.
8382 The former can occur with e.g.
8384 use constant FEATURE => ( $] >= ... );
8385 sub { not FEATURE and return or do_stuff(); }
8387 if (!first->op_folded && !(first->op_flags & OPf_PARENS))
8388 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
8389 "Possible precedence issue with control flow operator");
8390 /* XXX: Should we optimze this to "return $a;" (i.e. remove
8396 if (type == OP_XOR) /* Not short circuit, but here by precedence. */
8397 return newBINOP(type, flags, scalar(first), scalar(other));
8399 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOGOP
8400 || type == OP_CUSTOM);
8402 scalarboolean(first);
8404 /* search for a constant op that could let us fold the test */
8405 if ((cstop = search_const(first))) {
8406 if (cstop->op_private & OPpCONST_STRICT)
8407 no_bareword_allowed(cstop);
8408 else if ((cstop->op_private & OPpCONST_BARE))
8409 Perl_ck_warner(aTHX_ packWARN(WARN_BAREWORD), "Bareword found in conditional");
8410 if ((type == OP_AND && SvTRUE(cSVOPx(cstop)->op_sv)) ||
8411 (type == OP_OR && !SvTRUE(cSVOPx(cstop)->op_sv)) ||
8412 (type == OP_DOR && !SvOK(cSVOPx(cstop)->op_sv))) {
8413 /* Elide the (constant) lhs, since it can't affect the outcome */
8415 if (other->op_type == OP_CONST)
8416 other->op_private |= OPpCONST_SHORTCIRCUIT;
8418 if (other->op_type == OP_LEAVE)
8419 other = newUNOP(OP_NULL, OPf_SPECIAL, other);
8420 else if (other->op_type == OP_MATCH
8421 || other->op_type == OP_SUBST
8422 || other->op_type == OP_TRANSR
8423 || other->op_type == OP_TRANS)
8424 /* Mark the op as being unbindable with =~ */
8425 other->op_flags |= OPf_SPECIAL;
8427 other->op_folded = 1;
8431 /* Elide the rhs, since the outcome is entirely determined by
8432 * the (constant) lhs */
8434 /* check for C<my $x if 0>, or C<my($x,$y) if 0> */
8435 const OP *o2 = other;
8436 if ( ! (o2->op_type == OP_LIST
8437 && (( o2 = cUNOPx(o2)->op_first))
8438 && o2->op_type == OP_PUSHMARK
8439 && (( o2 = OpSIBLING(o2))) )
8442 if ((o2->op_type == OP_PADSV || o2->op_type == OP_PADAV
8443 || o2->op_type == OP_PADHV)
8444 && o2->op_private & OPpLVAL_INTRO
8445 && !(o2->op_private & OPpPAD_STATE))
8447 Perl_croak(aTHX_ "This use of my() in false conditional is "
8448 "no longer allowed");
8452 if (cstop->op_type == OP_CONST)
8453 cstop->op_private |= OPpCONST_SHORTCIRCUIT;
8458 else if ((first->op_flags & OPf_KIDS) && type != OP_DOR
8459 && ckWARN(WARN_MISC)) /* [#24076] Don't warn for <FH> err FOO. */
8461 const OP * const k1 = cUNOPx(first)->op_first;
8462 const OP * const k2 = OpSIBLING(k1);
8464 switch (first->op_type)
8467 if (k2 && k2->op_type == OP_READLINE
8468 && (k2->op_flags & OPf_STACKED)
8469 && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8471 warnop = k2->op_type;
8476 if (k1->op_type == OP_READDIR
8477 || k1->op_type == OP_GLOB
8478 || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8479 || k1->op_type == OP_EACH
8480 || k1->op_type == OP_AEACH)
8482 warnop = ((k1->op_type == OP_NULL)
8483 ? (OPCODE)k1->op_targ : k1->op_type);
8488 const line_t oldline = CopLINE(PL_curcop);
8489 /* This ensures that warnings are reported at the first line
8490 of the construction, not the last. */
8491 CopLINE_set(PL_curcop, PL_parser->copline);
8492 Perl_warner(aTHX_ packWARN(WARN_MISC),
8493 "Value of %s%s can be \"0\"; test with defined()",
8495 ((warnop == OP_READLINE || warnop == OP_GLOB)
8496 ? " construct" : "() operator"));
8497 CopLINE_set(PL_curcop, oldline);
8501 /* optimize AND and OR ops that have NOTs as children */
8502 if (first->op_type == OP_NOT
8503 && (first->op_flags & OPf_KIDS)
8504 && ((first->op_flags & OPf_SPECIAL) /* unless ($x) { } */
8505 || (other->op_type == OP_NOT)) /* if (!$x && !$y) { } */
8507 if (type == OP_AND || type == OP_OR) {
8513 if (other->op_type == OP_NOT) { /* !a AND|OR !b => !(a OR|AND b) */
8515 prepend_not = 1; /* prepend a NOT op later */
8520 logop = alloc_LOGOP(type, first, LINKLIST(other));
8521 logop->op_flags |= (U8)flags;
8522 logop->op_private = (U8)(1 | (flags >> 8));
8524 /* establish postfix order */
8525 logop->op_next = LINKLIST(first);
8526 first->op_next = (OP*)logop;
8527 assert(!OpHAS_SIBLING(first));
8528 op_sibling_splice((OP*)logop, first, 0, other);
8530 CHECKOP(type,logop);
8532 o = newUNOP(prepend_not ? OP_NOT : OP_NULL,
8533 PL_opargs[type] & OA_RETSCALAR ? OPf_WANT_SCALAR : 0,
8541 =for apidoc newCONDOP
8543 Constructs, checks, and returns a conditional-expression (C<cond_expr>)
8544 op. C<flags> gives the eight bits of C<op_flags>, except that C<OPf_KIDS>
8545 will be set automatically, and, shifted up eight bits, the eight bits of
8546 C<op_private>, except that the bit with value 1 is automatically set.
8547 C<first> supplies the expression selecting between the two branches,
8548 and C<trueop> and C<falseop> supply the branches; they are consumed by
8549 this function and become part of the constructed op tree.
8555 Perl_newCONDOP(pTHX_ I32 flags, OP *first, OP *trueop, OP *falseop)
8562 PERL_ARGS_ASSERT_NEWCONDOP;
8565 return newLOGOP(OP_AND, 0, first, trueop);
8567 return newLOGOP(OP_OR, 0, first, falseop);
8569 scalarboolean(first);
8570 if ((cstop = search_const(first))) {
8571 /* Left or right arm of the conditional? */
8572 const bool left = SvTRUE(cSVOPx(cstop)->op_sv);
8573 OP *live = left ? trueop : falseop;
8574 OP *const dead = left ? falseop : trueop;
8575 if (cstop->op_private & OPpCONST_BARE &&
8576 cstop->op_private & OPpCONST_STRICT) {
8577 no_bareword_allowed(cstop);
8581 if (live->op_type == OP_LEAVE)
8582 live = newUNOP(OP_NULL, OPf_SPECIAL, live);
8583 else if (live->op_type == OP_MATCH || live->op_type == OP_SUBST
8584 || live->op_type == OP_TRANS || live->op_type == OP_TRANSR)
8585 /* Mark the op as being unbindable with =~ */
8586 live->op_flags |= OPf_SPECIAL;
8587 live->op_folded = 1;
8590 logop = alloc_LOGOP(OP_COND_EXPR, first, LINKLIST(trueop));
8591 logop->op_flags |= (U8)flags;
8592 logop->op_private = (U8)(1 | (flags >> 8));
8593 logop->op_next = LINKLIST(falseop);
8595 CHECKOP(OP_COND_EXPR, /* that's logop->op_type */
8598 /* establish postfix order */
8599 start = LINKLIST(first);
8600 first->op_next = (OP*)logop;
8602 /* make first, trueop, falseop siblings */
8603 op_sibling_splice((OP*)logop, first, 0, trueop);
8604 op_sibling_splice((OP*)logop, trueop, 0, falseop);
8606 o = newUNOP(OP_NULL, 0, (OP*)logop);
8608 trueop->op_next = falseop->op_next = o;
8615 =for apidoc newTRYCATCHOP
8617 Constructs and returns a conditional execution statement that implements
8618 the C<try>/C<catch> semantics. First the op tree in C<tryblock> is executed,
8619 inside a context that traps exceptions. If an exception occurs then the
8620 optree in C<catchblock> is executed, with the trapped exception set into the
8621 lexical variable given by C<catchvar> (which must be an op of type
8622 C<OP_PADSV>). All the optrees are consumed by this function and become part
8623 of the returned op tree.
8625 The C<flags> argument is currently ignored.
8631 Perl_newTRYCATCHOP(pTHX_ I32 flags, OP *tryblock, OP *catchvar, OP *catchblock)
8635 PERL_ARGS_ASSERT_NEWTRYCATCHOP;
8636 assert(catchvar->op_type == OP_PADSV);
8638 PERL_UNUSED_ARG(flags);
8640 /* The returned optree is shaped as:
8641 * LISTOP leavetrycatch
8642 * LOGOP entertrycatch
8649 if(tryblock->op_type != OP_LINESEQ)
8650 tryblock = op_convert_list(OP_LINESEQ, 0, tryblock);
8651 OpTYPE_set(tryblock, OP_POPTRY);
8653 /* Manually construct a naked LOGOP.
8654 * Normally if we call newLOGOP the returned value is a UNOP(OP_NULL)
8655 * containing the LOGOP we wanted as its op_first */
8656 catchop = (OP *)alloc_LOGOP(OP_CATCH, newOP(OP_NULL, 0), catchblock);
8657 OpMORESIB_set(cUNOPx(catchop)->op_first, catchblock);
8658 OpLASTSIB_set(catchblock, catchop);
8660 /* Inject the catchvar's pad offset into the OP_CATCH targ */
8661 cLOGOPx(catchop)->op_targ = catchvar->op_targ;
8664 /* Build the optree structure */
8665 o = newLISTOP(OP_LIST, 0, tryblock, catchop);
8666 o = op_convert_list(OP_ENTERTRYCATCH, 0, o);
8672 =for apidoc newRANGE
8674 Constructs and returns a C<range> op, with subordinate C<flip> and
8675 C<flop> ops. C<flags> gives the eight bits of C<op_flags> for the
8676 C<flip> op and, shifted up eight bits, the eight bits of C<op_private>
8677 for both the C<flip> and C<range> ops, except that the bit with value
8678 1 is automatically set. C<left> and C<right> supply the expressions
8679 controlling the endpoints of the range; they are consumed by this function
8680 and become part of the constructed op tree.
8686 Perl_newRANGE(pTHX_ I32 flags, OP *left, OP *right)
8694 PERL_ARGS_ASSERT_NEWRANGE;
8696 range = alloc_LOGOP(OP_RANGE, left, LINKLIST(right));
8697 range->op_flags = OPf_KIDS;
8698 leftstart = LINKLIST(left);
8699 range->op_private = (U8)(1 | (flags >> 8));
8701 /* make left and right siblings */
8702 op_sibling_splice((OP*)range, left, 0, right);
8704 range->op_next = (OP*)range;
8705 flip = newUNOP(OP_FLIP, flags, (OP*)range);
8706 flop = newUNOP(OP_FLOP, 0, flip);
8707 o = newUNOP(OP_NULL, 0, flop);
8709 range->op_next = leftstart;
8711 left->op_next = flip;
8712 right->op_next = flop;
8715 pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);
8716 sv_upgrade(PAD_SV(range->op_targ), SVt_PVNV);
8718 pad_add_name_pvn("$", 1, padadd_NO_DUP_CHECK|padadd_STATE, 0, 0);;
8719 sv_upgrade(PAD_SV(flip->op_targ), SVt_PVNV);
8720 SvPADTMP_on(PAD_SV(flip->op_targ));
8722 flip->op_private = left->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8723 flop->op_private = right->op_type == OP_CONST ? OPpFLIP_LINENUM : 0;
8725 /* check barewords before they might be optimized aways */
8726 if (flip->op_private && cSVOPx(left)->op_private & OPpCONST_STRICT)
8727 no_bareword_allowed(left);
8728 if (flop->op_private && cSVOPx(right)->op_private & OPpCONST_STRICT)
8729 no_bareword_allowed(right);
8732 if (!flip->op_private || !flop->op_private)
8733 LINKLIST(o); /* blow off optimizer unless constant */
8739 =for apidoc newLOOPOP
8741 Constructs, checks, and returns an op tree expressing a loop. This is
8742 only a loop in the control flow through the op tree; it does not have
8743 the heavyweight loop structure that allows exiting the loop by C<last>
8744 and suchlike. C<flags> gives the eight bits of C<op_flags> for the
8745 top-level op, except that some bits will be set automatically as required.
8746 C<expr> supplies the expression controlling loop iteration, and C<block>
8747 supplies the body of the loop; they are consumed by this function and
8748 become part of the constructed op tree. C<debuggable> is currently
8749 unused and should always be 1.
8755 Perl_newLOOPOP(pTHX_ I32 flags, I32 debuggable, OP *expr, OP *block)
8757 PERL_ARGS_ASSERT_NEWLOOPOP;
8761 const bool once = block && block->op_flags & OPf_SPECIAL &&
8762 block->op_type == OP_NULL;
8764 PERL_UNUSED_ARG(debuggable);
8767 (expr->op_type == OP_CONST && !SvTRUE(cSVOPx(expr)->op_sv))
8768 || ( expr->op_type == OP_NOT
8769 && cUNOPx(expr)->op_first->op_type == OP_CONST
8770 && SvTRUE(cSVOPx_sv(cUNOPx(expr)->op_first))
8773 /* Return the block now, so that S_new_logop does not try to
8777 return block; /* do {} while 0 does once */
8780 if (expr->op_type == OP_READLINE
8781 || expr->op_type == OP_READDIR
8782 || expr->op_type == OP_GLOB
8783 || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
8784 || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
8785 expr = newUNOP(OP_DEFINED, 0,
8786 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
8787 } else if (expr->op_flags & OPf_KIDS) {
8788 const OP * const k1 = cUNOPx(expr)->op_first;
8789 const OP * const k2 = k1 ? OpSIBLING(k1) : NULL;
8790 switch (expr->op_type) {
8792 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
8793 && (k2->op_flags & OPf_STACKED)
8794 && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8795 expr = newUNOP(OP_DEFINED, 0, expr);
8799 if (k1 && (k1->op_type == OP_READDIR
8800 || k1->op_type == OP_GLOB
8801 || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8802 || k1->op_type == OP_EACH
8803 || k1->op_type == OP_AEACH))
8804 expr = newUNOP(OP_DEFINED, 0, expr);
8809 /* if block is null, the next op_append_elem() would put UNSTACK, a scalar
8810 * op, in listop. This is wrong. [perl #27024] */
8812 block = newOP(OP_NULL, 0);
8813 listop = op_append_elem(OP_LINESEQ, block, newOP(OP_UNSTACK, 0));
8814 o = new_logop(OP_AND, 0, &expr, &listop);
8821 cLISTOPx(listop)->op_last->op_next = LINKLIST(o);
8823 if (once && o != listop)
8825 assert(cUNOPo->op_first->op_type == OP_AND
8826 || cUNOPo->op_first->op_type == OP_OR);
8827 o->op_next = cLOGOPx(cUNOPo->op_first)->op_other;
8831 o = newUNOP(OP_NULL, 0, o); /* or do {} while 1 loses outer block */
8833 o->op_flags |= flags;
8835 o->op_flags |= OPf_SPECIAL; /* suppress cx_popblock() curpm restoration*/
8840 =for apidoc newWHILEOP
8842 Constructs, checks, and returns an op tree expressing a C<while> loop.
8843 This is a heavyweight loop, with structure that allows exiting the loop
8844 by C<last> and suchlike.
8846 C<loop> is an optional preconstructed C<enterloop> op to use in the
8847 loop; if it is null then a suitable op will be constructed automatically.
8848 C<expr> supplies the loop's controlling expression. C<block> supplies the
8849 main body of the loop, and C<cont> optionally supplies a C<continue> block
8850 that operates as a second half of the body. All of these optree inputs
8851 are consumed by this function and become part of the constructed op tree.
8853 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
8854 op and, shifted up eight bits, the eight bits of C<op_private> for
8855 the C<leaveloop> op, except that (in both cases) some bits will be set
8856 automatically. C<debuggable> is currently unused and should always be 1.
8857 C<has_my> can be supplied as true to force the
8858 loop body to be enclosed in its own scope.
8864 Perl_newWHILEOP(pTHX_ I32 flags, I32 debuggable, LOOP *loop,
8865 OP *expr, OP *block, OP *cont, I32 has_my)
8873 PERL_UNUSED_ARG(debuggable);
8876 if (expr->op_type == OP_READLINE
8877 || expr->op_type == OP_READDIR
8878 || expr->op_type == OP_GLOB
8879 || expr->op_type == OP_EACH || expr->op_type == OP_AEACH
8880 || (expr->op_type == OP_NULL && expr->op_targ == OP_GLOB)) {
8881 expr = newUNOP(OP_DEFINED, 0,
8882 newASSIGNOP(0, newDEFSVOP(), 0, expr) );
8883 } else if (expr->op_flags & OPf_KIDS) {
8884 const OP * const k1 = cUNOPx(expr)->op_first;
8885 const OP * const k2 = (k1) ? OpSIBLING(k1) : NULL;
8886 switch (expr->op_type) {
8888 if (k2 && (k2->op_type == OP_READLINE || k2->op_type == OP_READDIR)
8889 && (k2->op_flags & OPf_STACKED)
8890 && ((k1->op_flags & OPf_WANT) == OPf_WANT_SCALAR))
8891 expr = newUNOP(OP_DEFINED, 0, expr);
8895 if (k1 && (k1->op_type == OP_READDIR
8896 || k1->op_type == OP_GLOB
8897 || (k1->op_type == OP_NULL && k1->op_targ == OP_GLOB)
8898 || k1->op_type == OP_EACH
8899 || k1->op_type == OP_AEACH))
8900 expr = newUNOP(OP_DEFINED, 0, expr);
8907 block = newOP(OP_NULL, 0);
8908 else if (cont || has_my) {
8909 block = op_scope(block);
8913 next = LINKLIST(cont);
8916 OP * const unstack = newOP(OP_UNSTACK, 0);
8919 cont = op_append_elem(OP_LINESEQ, cont, unstack);
8923 listop = op_append_list(OP_LINESEQ, block, cont);
8925 redo = LINKLIST(listop);
8929 o = new_logop(OP_AND, 0, &expr, &listop);
8930 if (o == expr && o->op_type == OP_CONST && !SvTRUE(cSVOPo->op_sv)) {
8932 return expr; /* listop already freed by new_logop */
8935 cLISTOPx(listop)->op_last->op_next =
8936 (o == listop ? redo : LINKLIST(o));
8942 NewOp(1101,loop,1,LOOP);
8943 OpTYPE_set(loop, OP_ENTERLOOP);
8944 loop->op_private = 0;
8945 loop->op_next = (OP*)loop;
8948 o = newBINOP(OP_LEAVELOOP, 0, (OP*)loop, o);
8950 loop->op_redoop = redo;
8951 loop->op_lastop = o;
8952 o->op_private |= loopflags;
8955 loop->op_nextop = next;
8957 loop->op_nextop = o;
8959 o->op_flags |= flags;
8960 o->op_private |= (flags >> 8);
8965 =for apidoc newFOROP
8967 Constructs, checks, and returns an op tree expressing a C<foreach>
8968 loop (iteration through a list of values). This is a heavyweight loop,
8969 with structure that allows exiting the loop by C<last> and suchlike.
8971 C<sv> optionally supplies the variable(s) that will be aliased to each
8972 item in turn; if null, it defaults to C<$_>.
8973 C<expr> supplies the list of values to iterate over. C<block> supplies
8974 the main body of the loop, and C<cont> optionally supplies a C<continue>
8975 block that operates as a second half of the body. All of these optree
8976 inputs are consumed by this function and become part of the constructed
8979 C<flags> gives the eight bits of C<op_flags> for the C<leaveloop>
8980 op and, shifted up eight bits, the eight bits of C<op_private> for
8981 the C<leaveloop> op, except that (in both cases) some bits will be set
8988 Perl_newFOROP(pTHX_ I32 flags, OP *sv, OP *expr, OP *block, OP *cont)
8992 PADOFFSET padoff = 0;
8993 PADOFFSET how_many_more = 0;
8998 PERL_ARGS_ASSERT_NEWFOROP;
9001 if (sv->op_type == OP_RV2SV) { /* symbol table variable */
9002 iterpflags = sv->op_private & OPpOUR_INTRO; /* for our $x () */
9003 OpTYPE_set(sv, OP_RV2GV);
9005 /* The op_type check is needed to prevent a possible segfault
9006 * if the loop variable is undeclared and 'strict vars' is in
9007 * effect. This is illegal but is nonetheless parsed, so we
9008 * may reach this point with an OP_CONST where we're expecting
9011 if (cUNOPx(sv)->op_first->op_type == OP_GV
9012 && cGVOPx_gv(cUNOPx(sv)->op_first) == PL_defgv)
9013 iterpflags |= OPpITER_DEF;
9015 else if (sv->op_type == OP_PADSV) { /* private variable */
9016 if (sv->op_flags & OPf_PARENS) {
9017 /* handle degenerate 1-var form of "for my ($x, ...)" */
9018 sv->op_private |= OPpLVAL_INTRO;
9021 iterpflags = sv->op_private & OPpLVAL_INTRO; /* for my $x () */
9022 padoff = sv->op_targ;
9026 PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
9028 else if (sv->op_type == OP_NULL && sv->op_targ == OP_SREFGEN)
9030 else if (sv->op_type == OP_LIST) {
9031 LISTOP *list = cLISTOPx(sv);
9032 OP *pushmark = list->op_first;
9037 iterpflags = OPpLVAL_INTRO; /* for my ($k, $v) () */
9040 if (!pushmark || pushmark->op_type != OP_PUSHMARK) {
9041 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting pushmark",
9042 pushmark ? PL_op_desc[pushmark->op_type] : "NULL");
9044 first_padsv = OpSIBLING(pushmark);
9045 if (!first_padsv || first_padsv->op_type != OP_PADSV) {
9046 Perl_croak(aTHX_ "panic: newFORLOOP, found %s, expecting padsv",
9047 first_padsv ? PL_op_desc[first_padsv->op_type] : "NULL");
9049 padoff = first_padsv->op_targ;
9051 /* There should be at least one more PADSV to find, and the ops
9052 should have consecutive values in targ: */
9053 padsv = cUNOPx(OpSIBLING(first_padsv));
9055 if (!padsv || padsv->op_type != OP_PADSV) {
9056 Perl_croak(aTHX_ "panic: newFORLOOP, found %s at %zd, expecting padsv",
9057 padsv ? PL_op_desc[padsv->op_type] : "NULL",
9061 if (padsv->op_targ != padoff + how_many_more) {
9062 Perl_croak(aTHX_ "panic: newFORLOOP, padsv at %zd targ is %zd, not %zd",
9063 how_many_more, padsv->op_targ, padoff + how_many_more);
9066 padsv = cUNOPx(OpSIBLING(padsv));
9069 /* OK, this optree has the shape that we expected. So now *we*
9070 "claim" the Pad slots: */
9071 first_padsv->op_targ = 0;
9072 PAD_COMPNAME_GEN_set(padoff, PERL_INT_MAX);
9076 padsv = cUNOPx(OpSIBLING(first_padsv));
9080 PAD_COMPNAME_GEN_set(i, PERL_INT_MAX);
9082 padsv = cUNOPx(OpSIBLING(padsv));
9089 Perl_croak(aTHX_ "Can't use %s for loop variable", PL_op_desc[sv->op_type]);
9091 PADNAME * const pn = PAD_COMPNAME(padoff);
9092 const char * const name = PadnamePV(pn);
9094 if (PadnameLEN(pn) == 2 && name[0] == '$' && name[1] == '_')
9095 iterpflags |= OPpITER_DEF;
9099 sv = newGVOP(OP_GV, 0, PL_defgv);
9100 iterpflags |= OPpITER_DEF;
9103 if (expr->op_type == OP_RV2AV || expr->op_type == OP_PADAV) {
9104 expr = op_lvalue(force_list(scalar(ref(expr, OP_ITER)), TRUE), OP_GREPSTART);
9105 iterflags |= OPf_STACKED;
9107 else if (expr->op_type == OP_NULL &&
9108 (expr->op_flags & OPf_KIDS) &&
9109 cBINOPx(expr)->op_first->op_type == OP_FLOP)
9111 /* Basically turn for($x..$y) into the same as for($x,$y), but we
9112 * set the STACKED flag to indicate that these values are to be
9113 * treated as min/max values by 'pp_enteriter'.
9115 const UNOP* const flip = cUNOPx(cUNOPx(cBINOPx(expr)->op_first)->op_first);
9116 LOGOP* const range = cLOGOPx(flip->op_first);
9117 OP* const left = range->op_first;
9118 OP* const right = OpSIBLING(left);
9121 range->op_flags &= ~OPf_KIDS;
9122 /* detach range's children */
9123 op_sibling_splice((OP*)range, NULL, -1, NULL);
9125 listop = cLISTOPx(newLISTOP(OP_LIST, 0, left, right));
9126 listop->op_first->op_next = range->op_next;
9127 left->op_next = range->op_other;
9128 right->op_next = (OP*)listop;
9129 listop->op_next = listop->op_first;
9132 expr = (OP*)(listop);
9134 iterflags |= OPf_STACKED;
9137 expr = op_lvalue(force_list(expr, TRUE), OP_GREPSTART);
9140 loop = (LOOP*)op_convert_list(OP_ENTERITER, iterflags,
9141 op_append_elem(OP_LIST, list(expr),
9143 assert(!loop->op_next);
9144 /* for my $x () sets OPpLVAL_INTRO;
9145 * for our $x () sets OPpOUR_INTRO */
9146 loop->op_private = (U8)iterpflags;
9148 /* upgrade loop from a LISTOP to a LOOPOP;
9149 * keep it in-place if there's space */
9150 if (loop->op_slabbed
9151 && OpSLOT(loop)->opslot_size
9152 < SIZE_TO_PSIZE(sizeof(LOOP) + OPSLOT_HEADER))
9154 /* no space; allocate new op */
9156 NewOp(1234,tmp,1,LOOP);
9157 Copy(loop,tmp,1,LISTOP);
9158 assert(loop->op_last->op_sibparent == (OP*)loop);
9159 OpLASTSIB_set(loop->op_last, (OP*)tmp); /*point back to new parent */
9160 S_op_destroy(aTHX_ (OP*)loop);
9163 else if (!loop->op_slabbed)
9165 /* loop was malloc()ed */
9166 loop = (LOOP*)PerlMemShared_realloc(loop, sizeof(LOOP));
9167 OpLASTSIB_set(loop->op_last, (OP*)loop);
9169 loop->op_targ = padoff;
9171 /* hint to deparser that this: for my (...) ... */
9172 loop->op_flags |= OPf_PARENS;
9173 iter = newOP(OP_ITER, 0);
9174 iter->op_targ = how_many_more;
9175 return newWHILEOP(flags, 1, loop, iter, block, cont, 0);
9179 =for apidoc newLOOPEX
9181 Constructs, checks, and returns a loop-exiting op (such as C<goto>
9182 or C<last>). C<type> is the opcode. C<label> supplies the parameter
9183 determining the target of the op; it is consumed by this function and
9184 becomes part of the constructed op tree.
9190 Perl_newLOOPEX(pTHX_ I32 type, OP *label)
9194 PERL_ARGS_ASSERT_NEWLOOPEX;
9196 assert((PL_opargs[type] & OA_CLASS_MASK) == OA_LOOPEXOP
9197 || type == OP_CUSTOM);
9199 if (type != OP_GOTO) {
9200 /* "last()" means "last" */
9201 if (label->op_type == OP_STUB && (label->op_flags & OPf_PARENS)) {
9202 o = newOP(type, OPf_SPECIAL);
9206 /* Check whether it's going to be a goto &function */
9207 if (label->op_type == OP_ENTERSUB
9208 && !(label->op_flags & OPf_STACKED))
9209 label = newUNOP(OP_REFGEN, 0, op_lvalue(label, OP_REFGEN));
9212 /* Check for a constant argument */
9213 if (label->op_type == OP_CONST) {
9214 SV * const sv = cSVOPx(label)->op_sv;
9216 const char *s = SvPV_const(sv,l);
9217 if (l == strlen(s)) {
9219 SvUTF8(cSVOPx(label)->op_sv),
9221 SvPV_nolen_const(cSVOPx(label)->op_sv)));
9225 /* If we have already created an op, we do not need the label. */
9228 else o = newUNOP(type, OPf_STACKED, label);
9230 PL_hints |= HINT_BLOCK_SCOPE;
9234 /* if the condition is a literal array or hash
9235 (or @{ ... } etc), make a reference to it.
9238 S_ref_array_or_hash(pTHX_ OP *cond)
9241 && (cond->op_type == OP_RV2AV
9242 || cond->op_type == OP_PADAV
9243 || cond->op_type == OP_RV2HV
9244 || cond->op_type == OP_PADHV))
9246 return newUNOP(OP_REFGEN, 0, op_lvalue(cond, OP_REFGEN));
9249 && (cond->op_type == OP_ASLICE
9250 || cond->op_type == OP_KVASLICE
9251 || cond->op_type == OP_HSLICE
9252 || cond->op_type == OP_KVHSLICE)) {
9254 /* anonlist now needs a list from this op, was previously used in
9256 cond->op_flags &= ~(OPf_WANT_SCALAR | OPf_REF);
9257 cond->op_flags |= OPf_WANT_LIST;
9259 return newANONLIST(op_lvalue(cond, OP_ANONLIST));
9266 /* These construct the optree fragments representing given()
9269 entergiven and enterwhen are LOGOPs; the op_other pointer
9270 points up to the associated leave op. We need this so we
9271 can put it in the context and make break/continue work.
9272 (Also, of course, pp_enterwhen will jump straight to
9273 op_other if the match fails.)
9277 S_newGIVWHENOP(pTHX_ OP *cond, OP *block,
9278 I32 enter_opcode, I32 leave_opcode,
9279 PADOFFSET entertarg)
9284 PERL_ARGS_ASSERT_NEWGIVWHENOP;
9285 PERL_UNUSED_ARG(entertarg); /* used to indicate targ of lexical $_ */
9287 enterop = alloc_LOGOP(enter_opcode, block, NULL);
9288 enterop->op_targ = 0;
9289 enterop->op_private = 0;
9291 o = newUNOP(leave_opcode, 0, (OP *) enterop);
9294 /* prepend cond if we have one */
9295 op_sibling_splice((OP*)enterop, NULL, 0, scalar(cond));
9297 o->op_next = LINKLIST(cond);
9298 cond->op_next = (OP *) enterop;
9301 /* This is a default {} block */
9302 enterop->op_flags |= OPf_SPECIAL;
9303 o ->op_flags |= OPf_SPECIAL;
9305 o->op_next = (OP *) enterop;
9308 CHECKOP(enter_opcode, enterop); /* Currently does nothing, since
9309 entergiven and enterwhen both
9312 enterop->op_next = LINKLIST(block);
9313 block->op_next = enterop->op_other = o;
9319 /* For the purposes of 'when(implied_smartmatch)'
9320 * versus 'when(boolean_expression)',
9321 * does this look like a boolean operation? For these purposes
9322 a boolean operation is:
9323 - a subroutine call [*]
9324 - a logical connective
9325 - a comparison operator
9326 - a filetest operator, with the exception of -s -M -A -C
9327 - defined(), exists() or eof()
9328 - /$re/ or $foo =~ /$re/
9330 [*] possibly surprising
9333 S_looks_like_bool(pTHX_ const OP *o)
9335 PERL_ARGS_ASSERT_LOOKS_LIKE_BOOL;
9337 switch(o->op_type) {
9340 return looks_like_bool(cLOGOPo->op_first);
9344 OP* sibl = OpSIBLING(cLOGOPo->op_first);
9347 looks_like_bool(cLOGOPo->op_first)
9348 && looks_like_bool(sibl));
9354 o->op_flags & OPf_KIDS
9355 && looks_like_bool(cUNOPo->op_first));
9359 case OP_NOT: case OP_XOR:
9361 case OP_EQ: case OP_NE: case OP_LT:
9362 case OP_GT: case OP_LE: case OP_GE:
9364 case OP_I_EQ: case OP_I_NE: case OP_I_LT:
9365 case OP_I_GT: case OP_I_LE: case OP_I_GE:
9367 case OP_SEQ: case OP_SNE: case OP_SLT:
9368 case OP_SGT: case OP_SLE: case OP_SGE:
9372 case OP_FTRREAD: case OP_FTRWRITE: case OP_FTREXEC:
9373 case OP_FTEREAD: case OP_FTEWRITE: case OP_FTEEXEC:
9374 case OP_FTIS: case OP_FTEOWNED: case OP_FTROWNED:
9375 case OP_FTZERO: case OP_FTSOCK: case OP_FTCHR:
9376 case OP_FTBLK: case OP_FTFILE: case OP_FTDIR:
9377 case OP_FTPIPE: case OP_FTLINK: case OP_FTSUID:
9378 case OP_FTSGID: case OP_FTSVTX: case OP_FTTTY:
9379 case OP_FTTEXT: case OP_FTBINARY:
9381 case OP_DEFINED: case OP_EXISTS:
9382 case OP_MATCH: case OP_EOF:
9390 /* optimised-away (index() != -1) or similar comparison */
9391 if (o->op_private & OPpTRUEBOOL)
9396 /* Detect comparisons that have been optimized away */
9397 if (cSVOPo->op_sv == &PL_sv_yes
9398 || cSVOPo->op_sv == &PL_sv_no)
9411 =for apidoc newGIVENOP
9413 Constructs, checks, and returns an op tree expressing a C<given> block.
9414 C<cond> supplies the expression to whose value C<$_> will be locally
9415 aliased, and C<block> supplies the body of the C<given> construct; they
9416 are consumed by this function and become part of the constructed op tree.
9417 C<defsv_off> must be zero (it used to identity the pad slot of lexical $_).
9423 Perl_newGIVENOP(pTHX_ OP *cond, OP *block, PADOFFSET defsv_off)
9425 PERL_ARGS_ASSERT_NEWGIVENOP;
9426 PERL_UNUSED_ARG(defsv_off);
9429 return newGIVWHENOP(
9430 ref_array_or_hash(cond),
9432 OP_ENTERGIVEN, OP_LEAVEGIVEN,
9437 =for apidoc newWHENOP
9439 Constructs, checks, and returns an op tree expressing a C<when> block.
9440 C<cond> supplies the test expression, and C<block> supplies the block
9441 that will be executed if the test evaluates to true; they are consumed
9442 by this function and become part of the constructed op tree. C<cond>
9443 will be interpreted DWIMically, often as a comparison against C<$_>,
9444 and may be null to generate a C<default> block.
9450 Perl_newWHENOP(pTHX_ OP *cond, OP *block)
9452 const bool cond_llb = (!cond || looks_like_bool(cond));
9455 PERL_ARGS_ASSERT_NEWWHENOP;
9460 cond_op = newBINOP(OP_SMARTMATCH, OPf_SPECIAL,
9462 scalar(ref_array_or_hash(cond)));
9465 return newGIVWHENOP(cond_op, block, OP_ENTERWHEN, OP_LEAVEWHEN, 0);
9469 =for apidoc newDEFEROP
9471 Constructs and returns a deferred-block statement that implements the
9472 C<defer> semantics. The C<block> optree is consumed by this function and
9473 becomes part of the returned optree.
9475 The C<flags> argument carries additional flags to set on the returned op,
9476 including the C<op_private> field.
9482 Perl_newDEFEROP(pTHX_ I32 flags, OP *block)
9484 OP *o, *start, *blockfirst;
9486 PERL_ARGS_ASSERT_NEWDEFEROP;
9488 start = LINKLIST(block);
9490 /* Hide the block inside an OP_NULL with no exection */
9491 block = newUNOP(OP_NULL, 0, block);
9492 block->op_next = block;
9494 o = (OP *)alloc_LOGOP(OP_PUSHDEFER, block, start);
9495 o->op_flags |= OPf_WANT_VOID | (U8)(flags);
9496 o->op_private = (U8)(flags >> 8);
9498 /* Terminate the block */
9499 blockfirst = cUNOPx(block)->op_first;
9500 assert(blockfirst->op_type == OP_SCOPE || blockfirst->op_type == OP_LEAVE);
9501 blockfirst->op_next = NULL;
9507 =for apidoc op_wrap_finally
9509 Wraps the given C<block> optree fragment in its own scoped block, arranging
9510 for the C<finally> optree fragment to be invoked when leaving that block for
9511 any reason. Both optree fragments are consumed and the combined result is
9518 Perl_op_wrap_finally(pTHX_ OP *block, OP *finally)
9520 PERL_ARGS_ASSERT_OP_WRAP_FINALLY;
9522 /* TODO: If block is already an ENTER/LEAVE-wrapped line sequence we can
9523 * just splice the DEFEROP in at the top, for efficiency.
9526 OP *o = newLISTOP(OP_LINESEQ, 0, newDEFEROP((OPpDEFER_FINALLY << 8), finally), block);
9527 o = op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), o);
9528 OpTYPE_set(o, OP_LEAVE);
9533 /* must not conflict with SVf_UTF8 */
9534 #define CV_CKPROTO_CURSTASH 0x1
9537 Perl_cv_ckproto_len_flags(pTHX_ const CV *cv, const GV *gv, const char *p,
9538 const STRLEN len, const U32 flags)
9540 SV *name = NULL, *msg;
9541 const char * cvp = SvROK(cv)
9542 ? SvTYPE(SvRV_const(cv)) == SVt_PVCV
9543 ? (cv = (const CV *)SvRV_const(cv), CvPROTO(cv))
9546 STRLEN clen = CvPROTOLEN(cv), plen = len;
9548 PERL_ARGS_ASSERT_CV_CKPROTO_LEN_FLAGS;
9550 if (p == NULL && cvp == NULL)
9553 if (!ckWARN_d(WARN_PROTOTYPE))
9557 p = S_strip_spaces(aTHX_ p, &plen);
9558 cvp = S_strip_spaces(aTHX_ cvp, &clen);
9559 if ((flags & SVf_UTF8) == SvUTF8(cv)) {
9560 if (plen == clen && memEQ(cvp, p, plen))
9563 if (flags & SVf_UTF8) {
9564 if (bytes_cmp_utf8((const U8 *)cvp, clen, (const U8 *)p, plen) == 0)
9568 if (bytes_cmp_utf8((const U8 *)p, plen, (const U8 *)cvp, clen) == 0)
9574 msg = sv_newmortal();
9579 gv_efullname3(name = sv_newmortal(), gv, NULL);
9580 else if (SvPOK(gv) && *SvPVX((SV *)gv) == '&')
9581 name = newSVpvn_flags(SvPVX((SV *)gv)+1, SvCUR(gv)-1, SvUTF8(gv)|SVs_TEMP);
9582 else if (flags & CV_CKPROTO_CURSTASH || SvROK(gv)) {
9583 name = newSVhek_mortal(HvNAME_HEK(PL_curstash));
9584 sv_catpvs(name, "::");
9586 assert (SvTYPE(SvRV_const(gv)) == SVt_PVCV);
9587 assert (CvNAMED(SvRV_const(gv)));
9588 sv_cathek(name, CvNAME_HEK(MUTABLE_CV(SvRV_const(gv))));
9590 else sv_catsv(name, (SV *)gv);
9592 else name = (SV *)gv;
9594 sv_setpvs(msg, "Prototype mismatch:");
9596 Perl_sv_catpvf(aTHX_ msg, " sub %" SVf, SVfARG(name));
9598 Perl_sv_catpvf(aTHX_ msg, " (%" UTF8f ")",
9599 UTF8fARG(SvUTF8(cv),clen,cvp)
9602 sv_catpvs(msg, ": none");
9603 sv_catpvs(msg, " vs ");
9605 Perl_sv_catpvf(aTHX_ msg, "(%" UTF8f ")", UTF8fARG(flags & SVf_UTF8,len,p));
9607 sv_catpvs(msg, "none");
9608 Perl_warner(aTHX_ packWARN(WARN_PROTOTYPE), "%" SVf, SVfARG(msg));
9611 static void const_sv_xsub(pTHX_ CV* cv);
9612 static void const_av_xsub(pTHX_ CV* cv);
9616 =for apidoc_section $optree_manipulation
9618 =for apidoc cv_const_sv
9620 If C<cv> is a constant sub eligible for inlining, returns the constant
9621 value returned by the sub. Otherwise, returns C<NULL>.
9623 Constant subs can be created with C<newCONSTSUB> or as described in
9624 L<perlsub/"Constant Functions">.
9629 Perl_cv_const_sv(const CV *const cv)
9634 if (!(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM))
9636 sv = CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9637 if (sv && SvTYPE(sv) == SVt_PVAV) return NULL;
9642 Perl_cv_const_sv_or_av(const CV * const cv)
9646 if (SvROK(cv)) return SvRV((SV *)cv);
9647 assert (SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM);
9648 return CvCONST(cv) ? MUTABLE_SV(CvXSUBANY(cv).any_ptr) : NULL;
9651 /* op_const_sv: examine an optree to determine whether it's in-lineable.
9652 * Can be called in 2 ways:
9655 * look for a single OP_CONST with attached value: return the value
9657 * allow_lex && !CvCONST(cv);
9659 * examine the clone prototype, and if contains only a single
9660 * OP_CONST, return the value; or if it contains a single PADSV ref-
9661 * erencing an outer lexical, turn on CvCONST to indicate the CV is
9662 * a candidate for "constizing" at clone time, and return NULL.
9666 S_op_const_sv(pTHX_ const OP *o, CV *cv, bool allow_lex)
9674 for (; o; o = o->op_next) {
9675 const OPCODE type = o->op_type;
9677 if (type == OP_NEXTSTATE || type == OP_LINESEQ
9679 || type == OP_PUSHMARK)
9681 if (type == OP_DBSTATE)
9683 if (type == OP_LEAVESUB)
9687 if (type == OP_CONST && cSVOPo->op_sv)
9689 else if (type == OP_UNDEF && !o->op_private) {
9690 sv = newSV_type(SVt_NULL);
9693 else if (allow_lex && type == OP_PADSV) {
9694 if (PAD_COMPNAME_FLAGS(o->op_targ) & PADNAMEf_OUTER)
9696 sv = &PL_sv_undef; /* an arbitrary non-null value */
9714 S_already_defined(pTHX_ CV *const cv, OP * const block, OP * const o,
9715 PADNAME * const name, SV ** const const_svp)
9721 if (CvFLAGS(PL_compcv)) {
9722 /* might have had built-in attrs applied */
9723 const bool pureperl = !CvISXSUB(cv) && CvROOT(cv);
9724 if (CvLVALUE(PL_compcv) && ! CvLVALUE(cv) && pureperl
9725 && ckWARN(WARN_MISC))
9727 /* protect against fatal warnings leaking compcv */
9728 SAVEFREESV(PL_compcv);
9729 Perl_warner(aTHX_ packWARN(WARN_MISC), "lvalue attribute ignored after the subroutine has been defined");
9730 SvREFCNT_inc_simple_void_NN(PL_compcv);
9733 (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS
9734 & ~(CVf_LVALUE * pureperl));
9739 /* redundant check for speed: */
9740 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
9741 const line_t oldline = CopLINE(PL_curcop);
9744 : newSVpvn_flags( PadnamePV(name)+1,PadnameLEN(name)-1,
9745 (PadnameUTF8(name)) ? SVf_UTF8|SVs_TEMP : SVs_TEMP
9747 if (PL_parser && PL_parser->copline != NOLINE)
9748 /* This ensures that warnings are reported at the first
9749 line of a redefinition, not the last. */
9750 CopLINE_set(PL_curcop, PL_parser->copline);
9751 /* protect against fatal warnings leaking compcv */
9752 SAVEFREESV(PL_compcv);
9753 report_redefined_cv(namesv, cv, const_svp);
9754 SvREFCNT_inc_simple_void_NN(PL_compcv);
9755 CopLINE_set(PL_curcop, oldline);
9762 Perl_newMYSUB(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs, OP *block)
9767 STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
9770 CV *compcv = PL_compcv;
9773 PADOFFSET pax = o->op_targ;
9774 CV *outcv = CvOUTSIDE(PL_compcv);
9777 bool reusable = FALSE;
9779 #ifdef PERL_DEBUG_READONLY_OPS
9780 OPSLAB *slab = NULL;
9783 PERL_ARGS_ASSERT_NEWMYSUB;
9785 PL_hints |= HINT_BLOCK_SCOPE;
9787 /* Find the pad slot for storing the new sub.
9788 We cannot use PL_comppad, as it is the pad owned by the new sub. We
9789 need to look in CvOUTSIDE and find the pad belonging to the enclos-
9790 ing sub. And then we need to dig deeper if this is a lexical from
9792 my sub foo; sub { sub foo { } }
9795 name = PadlistNAMESARRAY(CvPADLIST(outcv))[pax];
9796 if (PadnameOUTER(name) && PARENT_PAD_INDEX(name)) {
9797 pax = PARENT_PAD_INDEX(name);
9798 outcv = CvOUTSIDE(outcv);
9803 &PadARRAY(PadlistARRAY(CvPADLIST(outcv))
9804 [CvDEPTH(outcv) ? CvDEPTH(outcv) : 1])[pax];
9805 spot = (CV **)svspot;
9807 if (!(PL_parser && PL_parser->error_count))
9808 move_proto_attr(&proto, &attrs, (GV *)PadnameSV(name), 0);
9811 assert(proto->op_type == OP_CONST);
9812 ps = SvPV_const(cSVOPx(proto)->op_sv, ps_len);
9813 ps_utf8 = SvUTF8(cSVOPx(proto)->op_sv);
9823 if (PL_parser && PL_parser->error_count) {
9825 SvREFCNT_dec(PL_compcv);
9830 if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9832 svspot = (SV **)(spot = &clonee);
9834 else if (PadnameIsSTATE(name) || CvDEPTH(outcv))
9837 assert (SvTYPE(*spot) == SVt_PVCV);
9839 hek = CvNAME_HEK(*spot);
9842 PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
9843 CvNAME_HEK_set(*spot, hek =
9846 (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
9850 CvLEXICAL_on(*spot);
9852 cv = PadnamePROTOCV(name);
9853 svspot = (SV **)(spot = &PadnamePROTOCV(name));
9857 /* This makes sub {}; work as expected. */
9858 if (block->op_type == OP_STUB) {
9859 const line_t l = PL_parser->copline;
9861 block = newSTATEOP(0, NULL, 0);
9862 PL_parser->copline = l;
9864 block = CvLVALUE(compcv)
9865 || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv))
9866 ? newUNOP(OP_LEAVESUBLV, 0,
9867 op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
9868 : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
9869 start = LINKLIST(block);
9871 if (ps && !*ps && !attrs && !CvLVALUE(compcv))
9872 const_sv = S_op_const_sv(aTHX_ start, compcv, FALSE);
9880 const bool exists = CvROOT(cv) || CvXSUB(cv);
9882 /* if the subroutine doesn't exist and wasn't pre-declared
9883 * with a prototype, assume it will be AUTOLOADed,
9884 * skipping the prototype check
9886 if (exists || SvPOK(cv))
9887 cv_ckproto_len_flags(cv, (GV *)PadnameSV(name), ps, ps_len,
9889 /* already defined? */
9891 S_already_defined(aTHX_ cv, block, NULL, name, &const_sv);
9897 /* just a "sub foo;" when &foo is already defined */
9902 else if (CvDEPTH(outcv) && CvCLONE(compcv)) {
9909 SvREFCNT_inc_simple_void_NN(const_sv);
9910 SvFLAGS(const_sv) |= SVs_PADTMP;
9912 assert(!CvROOT(cv) && !CvCONST(cv));
9916 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
9917 CvFILE_set_from_cop(cv, PL_curcop);
9918 CvSTASH_set(cv, PL_curstash);
9921 SvPVCLEAR(MUTABLE_SV(cv)); /* prototype is "" */
9922 CvXSUBANY(cv).any_ptr = const_sv;
9923 CvXSUB(cv) = const_sv_xsub;
9927 CvFLAGS(cv) |= CvNOWARN_AMBIGUOUS(compcv);
9929 SvREFCNT_dec(compcv);
9934 /* Checking whether outcv is CvOUTSIDE(compcv) is not sufficient to
9935 determine whether this sub definition is in the same scope as its
9936 declaration. If this sub definition is inside an inner named pack-
9937 age sub (my sub foo; sub bar { sub foo { ... } }), outcv points to
9938 the package sub. So check PadnameOUTER(name) too.
9940 if (outcv == CvOUTSIDE(compcv) && !PadnameOUTER(name)) {
9941 assert(!CvWEAKOUTSIDE(compcv));
9942 SvREFCNT_dec(CvOUTSIDE(compcv));
9943 CvWEAKOUTSIDE_on(compcv);
9945 /* XXX else do we have a circular reference? */
9947 if (cv) { /* must reuse cv in case stub is referenced elsewhere */
9948 /* transfer PL_compcv to cv */
9950 bool free_file = CvFILE(cv) && CvDYNFILE(cv);
9951 cv_flags_t preserved_flags =
9952 CvFLAGS(cv) & (CVf_BUILTIN_ATTRS|CVf_NAMED);
9953 PADLIST *const temp_padl = CvPADLIST(cv);
9954 CV *const temp_cv = CvOUTSIDE(cv);
9955 const cv_flags_t other_flags =
9956 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
9957 OP * const cvstart = CvSTART(cv);
9961 CvFLAGS(compcv) | preserved_flags;
9962 CvOUTSIDE(cv) = CvOUTSIDE(compcv);
9963 CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(compcv);
9964 CvPADLIST_set(cv, CvPADLIST(compcv));
9965 CvOUTSIDE(compcv) = temp_cv;
9966 CvPADLIST_set(compcv, temp_padl);
9967 CvSTART(cv) = CvSTART(compcv);
9968 CvSTART(compcv) = cvstart;
9969 CvFLAGS(compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
9970 CvFLAGS(compcv) |= other_flags;
9973 Safefree(CvFILE(cv));
9977 /* inner references to compcv must be fixed up ... */
9978 pad_fixup_inner_anons(CvPADLIST(cv), compcv, cv);
9979 if (PERLDB_INTER)/* Advice debugger on the new sub. */
9980 ++PL_sub_generation;
9983 /* Might have had built-in attributes applied -- propagate them. */
9984 CvFLAGS(cv) |= (CvFLAGS(compcv) & CVf_BUILTIN_ATTRS);
9986 /* ... before we throw it away */
9987 SvREFCNT_dec(compcv);
9988 PL_compcv = compcv = cv;
9997 if (!CvNAME_HEK(cv)) {
9998 if (hek) (void)share_hek_hek(hek);
10001 PERL_HASH(hash, PadnamePV(name)+1, PadnameLEN(name)-1);
10002 hek = share_hek(PadnamePV(name)+1,
10003 (PadnameLEN(name)-1) * (PadnameUTF8(name) ? -1 : 1),
10006 CvNAME_HEK_set(cv, hek);
10012 if (CvFILE(cv) && CvDYNFILE(cv))
10013 Safefree(CvFILE(cv));
10014 CvFILE_set_from_cop(cv, PL_curcop);
10015 CvSTASH_set(cv, PL_curstash);
10018 sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10020 SvUTF8_on(MUTABLE_SV(cv));
10024 /* If we assign an optree to a PVCV, then we've defined a
10025 * subroutine that the debugger could be able to set a breakpoint
10026 * in, so signal to pp_entereval that it should not throw away any
10027 * saved lines at scope exit. */
10029 PL_breakable_sub_gen++;
10030 CvROOT(cv) = block;
10031 /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10032 itself has a refcount. */
10034 OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10035 #ifdef PERL_DEBUG_READONLY_OPS
10036 slab = (OPSLAB *)CvSTART(cv);
10038 S_process_optree(aTHX_ cv, block, start);
10043 /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10044 apply_attrs(PL_curstash, MUTABLE_SV(cv), attrs);
10048 if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10049 SV * const tmpstr = sv_newmortal();
10050 GV * const db_postponed = gv_fetchpvs("DB::postponed",
10051 GV_ADDMULTI, SVt_PVHV);
10053 SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10054 CopFILE(PL_curcop),
10056 (long)CopLINE(PL_curcop));
10057 if (HvNAME_HEK(PL_curstash)) {
10058 sv_sethek(tmpstr, HvNAME_HEK(PL_curstash));
10059 sv_catpvs(tmpstr, "::");
10062 sv_setpvs(tmpstr, "__ANON__::");
10064 sv_catpvn_flags(tmpstr, PadnamePV(name)+1, PadnameLEN(name)-1,
10065 PadnameUTF8(name) ? SV_CATUTF8 : SV_CATBYTES);
10066 (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
10067 hv = GvHVn(db_postponed);
10068 if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
10069 CV * const pcv = GvCV(db_postponed);
10075 call_sv(MUTABLE_SV(pcv), G_DISCARD);
10083 assert(CvDEPTH(outcv));
10085 &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[CvDEPTH(outcv)])[pax];
10087 cv_clone_into(clonee, *spot);
10088 else *spot = cv_clone(clonee);
10089 SvREFCNT_dec_NN(clonee);
10093 if (CvDEPTH(outcv) && !reusable && PadnameIsSTATE(name)) {
10094 PADOFFSET depth = CvDEPTH(outcv);
10097 svspot = &PadARRAY(PadlistARRAY(CvPADLIST(outcv))[depth])[pax];
10099 *svspot = SvREFCNT_inc_simple_NN(cv);
10100 SvREFCNT_dec(oldcv);
10106 PL_parser->copline = NOLINE;
10107 LEAVE_SCOPE(floor);
10108 #ifdef PERL_DEBUG_READONLY_OPS
10117 =for apidoc newATTRSUB_x
10119 Construct a Perl subroutine, also performing some surrounding jobs.
10121 This function is expected to be called in a Perl compilation context,
10122 and some aspects of the subroutine are taken from global variables
10123 associated with compilation. In particular, C<PL_compcv> represents
10124 the subroutine that is currently being compiled. It must be non-null
10125 when this function is called, and some aspects of the subroutine being
10126 constructed are taken from it. The constructed subroutine may actually
10127 be a reuse of the C<PL_compcv> object, but will not necessarily be so.
10129 If C<block> is null then the subroutine will have no body, and for the
10130 time being it will be an error to call it. This represents a forward
10131 subroutine declaration such as S<C<sub foo ($$);>>. If C<block> is
10132 non-null then it provides the Perl code of the subroutine body, which
10133 will be executed when the subroutine is called. This body includes
10134 any argument unwrapping code resulting from a subroutine signature or
10135 similar. The pad use of the code must correspond to the pad attached
10136 to C<PL_compcv>. The code is not expected to include a C<leavesub> or
10137 C<leavesublv> op; this function will add such an op. C<block> is consumed
10138 by this function and will become part of the constructed subroutine.
10140 C<proto> specifies the subroutine's prototype, unless one is supplied
10141 as an attribute (see below). If C<proto> is null, then the subroutine
10142 will not have a prototype. If C<proto> is non-null, it must point to a
10143 C<const> op whose value is a string, and the subroutine will have that
10144 string as its prototype. If a prototype is supplied as an attribute, the
10145 attribute takes precedence over C<proto>, but in that case C<proto> should
10146 preferably be null. In any case, C<proto> is consumed by this function.
10148 C<attrs> supplies attributes to be applied the subroutine. A handful of
10149 attributes take effect by built-in means, being applied to C<PL_compcv>
10150 immediately when seen. Other attributes are collected up and attached
10151 to the subroutine by this route. C<attrs> may be null to supply no
10152 attributes, or point to a C<const> op for a single attribute, or point
10153 to a C<list> op whose children apart from the C<pushmark> are C<const>
10154 ops for one or more attributes. Each C<const> op must be a string,
10155 giving the attribute name optionally followed by parenthesised arguments,
10156 in the manner in which attributes appear in Perl source. The attributes
10157 will be applied to the sub by this function. C<attrs> is consumed by
10160 If C<o_is_gv> is false and C<o> is null, then the subroutine will
10161 be anonymous. If C<o_is_gv> is false and C<o> is non-null, then C<o>
10162 must point to a C<const> OP, which will be consumed by this function,
10163 and its string value supplies a name for the subroutine. The name may
10164 be qualified or unqualified, and if it is unqualified then a default
10165 stash will be selected in some manner. If C<o_is_gv> is true, then C<o>
10166 doesn't point to an C<OP> at all, but is instead a cast pointer to a C<GV>
10167 by which the subroutine will be named.
10169 If there is already a subroutine of the specified name, then the new
10170 sub will either replace the existing one in the glob or be merged with
10171 the existing one. A warning may be generated about redefinition.
10173 If the subroutine has one of a few special names, such as C<BEGIN> or
10174 C<END>, then it will be claimed by the appropriate queue for automatic
10175 running of phase-related subroutines. In this case the relevant glob will
10176 be left not containing any subroutine, even if it did contain one before.
10177 In the case of C<BEGIN>, the subroutine will be executed and the reference
10178 to it disposed of before this function returns.
10180 The function returns a pointer to the constructed subroutine. If the sub
10181 is anonymous then ownership of one counted reference to the subroutine
10182 is transferred to the caller. If the sub is named then the caller does
10183 not get ownership of a reference. In most such cases, where the sub
10184 has a non-phase name, the sub will be alive at the point it is returned
10185 by virtue of being contained in the glob that names it. A phase-named
10186 subroutine will usually be alive by virtue of the reference owned by the
10187 phase's automatic run queue. But a C<BEGIN> subroutine, having already
10188 been executed, will quite likely have been destroyed already by the
10189 time this function returns, making it erroneous for the caller to make
10190 any use of the returned pointer. It is the caller's responsibility to
10191 ensure that it knows which of these situations applies.
10193 =for apidoc newATTRSUB
10194 Construct a Perl subroutine, also performing some surrounding jobs.
10196 This is the same as L<perlintern/C<newATTRSUB_x>> with its C<o_is_gv> parameter set to
10197 FALSE. This means that if C<o> is null, the new sub will be anonymous; otherwise
10198 the name will be derived from C<o> in the way described (as with all other
10199 details) in L<perlintern/C<newATTRSUB_x>>.
10202 Like C<L</newATTRSUB>>, but without attributes.
10207 /* _x = extended */
10209 Perl_newATTRSUB_x(pTHX_ I32 floor, OP *o, OP *proto, OP *attrs,
10210 OP *block, bool o_is_gv)
10214 STRLEN ps_len = 0; /* init it to avoid false uninit warning from icc */
10216 CV *cv = NULL; /* the previous CV with this name, if any */
10218 const bool ec = PL_parser && PL_parser->error_count;
10219 /* If the subroutine has no body, no attributes, and no builtin attributes
10220 then it's just a sub declaration, and we may be able to get away with
10221 storing with a placeholder scalar in the symbol table, rather than a
10222 full CV. If anything is present then it will take a full CV to
10224 const I32 gv_fetch_flags
10225 = ec ? GV_NOADD_NOINIT :
10226 (block || attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS))
10227 ? GV_ADDMULTI : GV_ADDMULTI | GV_NOINIT;
10229 const char * const name =
10230 o ? SvPV_const(o_is_gv ? (SV *)o : cSVOPo->op_sv, namlen) : NULL;
10232 bool name_is_utf8 = o && !o_is_gv && SvUTF8(cSVOPo->op_sv);
10233 bool evanescent = FALSE;
10234 bool isBEGIN = FALSE;
10236 #ifdef PERL_DEBUG_READONLY_OPS
10237 OPSLAB *slab = NULL;
10245 /* Try to optimise and avoid creating a GV. Instead, the CV’s name
10246 hek and CvSTASH pointer together can imply the GV. If the name
10247 contains a package name, then GvSTASH(CvGV(cv)) may differ from
10248 CvSTASH, so forego the optimisation if we find any.
10249 Also, we may be called from load_module at run time, so
10250 PL_curstash (which sets CvSTASH) may not point to the stash the
10251 sub is stored in. */
10252 /* XXX This optimization is currently disabled for packages other
10253 than main, since there was too much CPAN breakage. */
10255 ec ? GV_NOADD_NOINIT
10256 : (IN_PERL_RUNTIME && PL_curstash != CopSTASH(PL_curcop))
10257 || PL_curstash != PL_defstash
10258 || memchr(name, ':', namlen) || memchr(name, '\'', namlen)
10260 : GV_ADDMULTI | GV_NOINIT | GV_NOTQUAL;
10261 gv = gv_fetchsv(cSVOPo->op_sv, flags, SVt_PVCV);
10263 } else if (PERLDB_NAMEANON && CopLINE(PL_curcop)) {
10264 SV * const sv = sv_newmortal();
10265 Perl_sv_setpvf(aTHX_ sv, "%s[%s:%" IVdf "]",
10266 PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
10267 CopFILE(PL_curcop), (IV)CopLINE(PL_curcop));
10268 gv = gv_fetchsv(sv, gv_fetch_flags, SVt_PVCV);
10270 } else if (PL_curstash) {
10271 gv = gv_fetchpvs("__ANON__", gv_fetch_flags, SVt_PVCV);
10274 gv = gv_fetchpvs("__ANON__::__ANON__", gv_fetch_flags, SVt_PVCV);
10280 move_proto_attr(&proto, &attrs, gv, 0);
10283 move_proto_attr(&proto, &attrs, (GV *)cSVOPo->op_sv, 1);
10294 /* we need this in two places later on, so set it up here */
10295 if (name && block) {
10296 const char *s = (char *) my_memrchr(name, ':', namlen);
10297 s = s ? s+1 : name;
10298 isBEGIN = strEQ(s,"BEGIN");
10302 /* Make sure that we do not have any prototypes or
10303 * attributes associated with this BEGIN block, as the block
10304 * is already done and dusted, and we will assert or worse
10305 * if we try to attach the prototype to the now essentially
10306 * nonexistent sub. */
10308 /* diag_listed_as: %s on BEGIN block ignored */
10309 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Prototype on BEGIN block ignored");
10311 /* diag_listed_as: %s on BEGIN block ignored */
10312 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "Attribute on BEGIN block ignored");
10318 assert(proto->op_type == OP_CONST);
10319 ps = SvPV_const(cSVOPx(proto)->op_sv, ps_len);
10320 ps_utf8 = SvUTF8(cSVOPx(proto)->op_sv);
10329 SvREFCNT_dec(PL_compcv);
10335 if (PL_in_eval & EVAL_KEEPERR)
10336 Perl_croak_nocontext("BEGIN not safe after errors--compilation aborted");
10338 SV * const errsv = ERRSV;
10339 /* force display of errors found but not reported */
10340 sv_catpvs(errsv, "BEGIN not safe after errors--compilation aborted");
10341 Perl_croak_nocontext("%" SVf, SVfARG(errsv));
10347 if (!block && SvTYPE(gv) != SVt_PVGV) {
10348 /* If we are not defining a new sub and the existing one is not a
10350 if (attrs || (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS)) {
10351 /* We are applying attributes to an existing sub, so we need it
10352 upgraded if it is a constant. */
10353 if (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)
10354 gv_init_pvn(gv, PL_curstash, name, namlen,
10355 SVf_UTF8 * name_is_utf8);
10357 else { /* Maybe prototype now, and had at maximum
10358 a prototype or const/sub ref before. */
10359 if (SvTYPE(gv) > SVt_NULL) {
10360 cv_ckproto_len_flags((const CV *)gv,
10361 o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10367 sv_setpvn(MUTABLE_SV(gv), ps, ps_len);
10369 SvUTF8_on(MUTABLE_SV(gv));
10372 sv_setiv(MUTABLE_SV(gv), -1);
10375 SvREFCNT_dec(PL_compcv);
10376 cv = PL_compcv = NULL;
10381 cv = (!name || (isGV(gv) && GvCVGEN(gv)))
10385 : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
10391 /* This makes sub {}; work as expected. */
10392 if (block->op_type == OP_STUB) {
10393 const line_t l = PL_parser->copline;
10395 block = newSTATEOP(0, NULL, 0);
10396 PL_parser->copline = l;
10398 block = CvLVALUE(PL_compcv)
10399 || (cv && CvLVALUE(cv) && !CvROOT(cv) && !CvXSUB(cv)
10400 && (!isGV(gv) || !GvASSUMECV(gv)))
10401 ? newUNOP(OP_LEAVESUBLV, 0,
10402 op_lvalue(voidnonfinal(block), OP_LEAVESUBLV))
10403 : newUNOP(OP_LEAVESUB, 0, voidnonfinal(block));
10404 start = LINKLIST(block);
10405 block->op_next = 0;
10406 if (ps && !*ps && !attrs && !CvLVALUE(PL_compcv))
10408 S_op_const_sv(aTHX_ start, PL_compcv,
10409 cBOOL(CvCLONE(PL_compcv)));
10416 if (SvPOK(gv) || (SvROK(gv) && SvTYPE(SvRV(gv)) != SVt_PVCV)) {
10417 cv_ckproto_len_flags((const CV *)gv,
10418 o ? (const GV *)cSVOPo->op_sv : NULL, ps,
10419 ps_len, ps_utf8|CV_CKPROTO_CURSTASH);
10421 /* All the other code for sub redefinition warnings expects the
10422 clobbered sub to be a CV. Instead of making all those code
10423 paths more complex, just inline the RV version here. */
10424 const line_t oldline = CopLINE(PL_curcop);
10425 assert(IN_PERL_COMPILETIME);
10426 if (PL_parser && PL_parser->copline != NOLINE)
10427 /* This ensures that warnings are reported at the first
10428 line of a redefinition, not the last. */
10429 CopLINE_set(PL_curcop, PL_parser->copline);
10430 /* protect against fatal warnings leaking compcv */
10431 SAVEFREESV(PL_compcv);
10433 if (ckWARN(WARN_REDEFINE)
10434 || ( ckWARN_d(WARN_REDEFINE)
10435 && ( !const_sv || SvRV(gv) == const_sv
10436 || sv_cmp(SvRV(gv), const_sv) ))) {
10438 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
10439 "Constant subroutine %" SVf " redefined",
10440 SVfARG(cSVOPo->op_sv));
10443 SvREFCNT_inc_simple_void_NN(PL_compcv);
10444 CopLINE_set(PL_curcop, oldline);
10445 SvREFCNT_dec(SvRV(gv));
10450 const bool exists = CvROOT(cv) || CvXSUB(cv);
10452 /* if the subroutine doesn't exist and wasn't pre-declared
10453 * with a prototype, assume it will be AUTOLOADed,
10454 * skipping the prototype check
10456 if (exists || SvPOK(cv))
10457 cv_ckproto_len_flags(cv, gv, ps, ps_len, ps_utf8);
10458 /* already defined (or promised)? */
10459 if (exists || (isGV(gv) && GvASSUMECV(gv))) {
10460 S_already_defined(aTHX_ cv, block, o, NULL, &const_sv);
10466 /* just a "sub foo;" when &foo is already defined */
10467 SAVEFREESV(PL_compcv);
10474 SvREFCNT_inc_simple_void_NN(const_sv);
10475 SvFLAGS(const_sv) |= SVs_PADTMP;
10477 assert(!CvROOT(cv) && !CvCONST(cv));
10478 cv_forget_slab(cv);
10479 SvPVCLEAR(MUTABLE_SV(cv)); /* prototype is "" */
10480 CvXSUBANY(cv).any_ptr = const_sv;
10481 CvXSUB(cv) = const_sv_xsub;
10485 CvFLAGS(cv) |= CvNOWARN_AMBIGUOUS(PL_compcv);
10488 if (isGV(gv) || CvNOWARN_AMBIGUOUS(PL_compcv)) {
10489 if (name && isGV(gv))
10490 GvCV_set(gv, NULL);
10491 cv = newCONSTSUB_flags(
10492 NULL, name, namlen, name_is_utf8 ? SVf_UTF8 : 0,
10496 assert(SvREFCNT((SV*)cv) != 0);
10497 CvFLAGS(cv) |= CvNOWARN_AMBIGUOUS(PL_compcv);
10501 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10502 prepare_SV_for_RV((SV *)gv);
10503 SvOK_off((SV *)gv);
10506 SvRV_set(gv, const_sv);
10510 SvREFCNT_dec(PL_compcv);
10515 /* don't copy new BEGIN CV to old BEGIN CV - RT #129099 */
10516 if (name && cv && *name == 'B' && strEQ(name, "BEGIN"))
10519 if (cv) { /* must reuse cv if autoloaded */
10520 /* transfer PL_compcv to cv */
10522 bool free_file = CvFILE(cv) && CvDYNFILE(cv);
10523 cv_flags_t existing_builtin_attrs = CvFLAGS(cv) & CVf_BUILTIN_ATTRS;
10524 PADLIST *const temp_av = CvPADLIST(cv);
10525 CV *const temp_cv = CvOUTSIDE(cv);
10526 const cv_flags_t other_flags =
10527 CvFLAGS(cv) & (CVf_SLABBED|CVf_WEAKOUTSIDE);
10528 OP * const cvstart = CvSTART(cv);
10532 assert(!CvCVGV_RC(cv));
10533 assert(CvGV(cv) == gv);
10537 PERL_HASH(hash, name, namlen);
10547 CvFLAGS(cv) = CvFLAGS(PL_compcv) | existing_builtin_attrs
10549 CvOUTSIDE(cv) = CvOUTSIDE(PL_compcv);
10550 CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(PL_compcv);
10551 CvPADLIST_set(cv,CvPADLIST(PL_compcv));
10552 CvOUTSIDE(PL_compcv) = temp_cv;
10553 CvPADLIST_set(PL_compcv, temp_av);
10554 CvSTART(cv) = CvSTART(PL_compcv);
10555 CvSTART(PL_compcv) = cvstart;
10556 CvFLAGS(PL_compcv) &= ~(CVf_SLABBED|CVf_WEAKOUTSIDE);
10557 CvFLAGS(PL_compcv) |= other_flags;
10560 Safefree(CvFILE(cv));
10562 CvFILE_set_from_cop(cv, PL_curcop);
10563 CvSTASH_set(cv, PL_curstash);
10565 /* inner references to PL_compcv must be fixed up ... */
10566 pad_fixup_inner_anons(CvPADLIST(cv), PL_compcv, cv);
10567 if (PERLDB_INTER)/* Advice debugger on the new sub. */
10568 ++PL_sub_generation;
10571 /* Might have had built-in attributes applied -- propagate them. */
10572 CvFLAGS(cv) |= (CvFLAGS(PL_compcv) & CVf_BUILTIN_ATTRS);
10574 /* ... before we throw it away */
10575 SvREFCNT_dec(PL_compcv);
10580 if (name && isGV(gv)) {
10583 if (HvENAME_HEK(GvSTASH(gv)))
10584 /* sub Foo::bar { (shift)+1 } */
10585 gv_method_changed(gv);
10589 SV_CHECK_THINKFIRST_COW_DROP((SV *)gv);
10590 prepare_SV_for_RV((SV *)gv);
10591 SvOK_off((SV *)gv);
10594 SvRV_set(gv, (SV *)cv);
10595 if (HvENAME_HEK(PL_curstash))
10596 mro_method_changed_in(PL_curstash);
10600 assert(SvREFCNT((SV*)cv) != 0);
10602 if (!CvHASGV(cv)) {
10607 PERL_HASH(hash, name, namlen);
10608 CvNAME_HEK_set(cv, share_hek(name,
10614 CvFILE_set_from_cop(cv, PL_curcop);
10615 CvSTASH_set(cv, PL_curstash);
10619 sv_setpvn(MUTABLE_SV(cv), ps, ps_len);
10621 SvUTF8_on(MUTABLE_SV(cv));
10625 /* If we assign an optree to a PVCV, then we've defined a
10626 * subroutine that the debugger could be able to set a breakpoint
10627 * in, so signal to pp_entereval that it should not throw away any
10628 * saved lines at scope exit. */
10630 PL_breakable_sub_gen++;
10631 CvROOT(cv) = block;
10632 /* The cv no longer needs to hold a refcount on the slab, as CvROOT
10633 itself has a refcount. */
10635 OpslabREFCNT_dec_padok((OPSLAB *)CvSTART(cv));
10636 #ifdef PERL_DEBUG_READONLY_OPS
10637 slab = (OPSLAB *)CvSTART(cv);
10639 S_process_optree(aTHX_ cv, block, start);
10644 /* Need to do a C<use attributes $stash_of_cv,\&cv,@attrs>. */
10645 HV *stash = name && !CvNAMED(cv) && GvSTASH(CvGV(cv))
10646 ? GvSTASH(CvGV(cv))
10650 apply_attrs(stash, MUTABLE_SV(cv), attrs);
10652 SvREFCNT_inc_simple_void_NN(cv);
10655 if (block && has_name) {
10656 if (PERLDB_SUBLINE && PL_curstash != PL_debstash) {
10657 SV * const tmpstr = cv_name(cv,NULL,0);
10658 GV * const db_postponed = gv_fetchpvs("DB::postponed",
10659 GV_ADDMULTI, SVt_PVHV);
10661 SV * const sv = Perl_newSVpvf(aTHX_ "%s:%ld-%ld",
10662 CopFILE(PL_curcop),
10664 (long)CopLINE(PL_curcop));
10665 (void)hv_store_ent(GvHV(PL_DBsub), tmpstr, sv, 0);
10666 hv = GvHVn(db_postponed);
10667 if (HvTOTALKEYS(hv) > 0 && hv_exists_ent(hv, tmpstr, 0)) {
10668 CV * const pcv = GvCV(db_postponed);
10674 call_sv(MUTABLE_SV(pcv), G_DISCARD);
10680 if (PL_parser && PL_parser->error_count)
10681 clear_special_blocks(name, gv, cv);
10684 process_special_blocks(floor, name, gv, cv);
10690 assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10692 PL_parser->copline = NOLINE;
10693 LEAVE_SCOPE(floor);
10695 assert(!cv || evanescent || SvREFCNT((SV*)cv) != 0);
10697 #ifdef PERL_DEBUG_READONLY_OPS
10701 if (cv && name && block && CvOUTSIDE(cv) && !CvEVAL(CvOUTSIDE(cv)))
10702 pad_add_weakref(cv);
10708 S_clear_special_blocks(pTHX_ const char *const fullname,
10709 GV *const gv, CV *const cv) {
10713 PERL_ARGS_ASSERT_CLEAR_SPECIAL_BLOCKS;
10715 colon = strrchr(fullname,':');
10716 name = colon ? colon + 1 : fullname;
10718 if ((*name == 'B' && strEQ(name, "BEGIN"))
10719 || (*name == 'E' && strEQ(name, "END"))
10720 || (*name == 'U' && strEQ(name, "UNITCHECK"))
10721 || (*name == 'C' && strEQ(name, "CHECK"))
10722 || (*name == 'I' && strEQ(name, "INIT"))) {
10727 GvCV_set(gv, NULL);
10728 SvREFCNT_dec_NN(MUTABLE_SV(cv));
10732 /* Returns true if the sub has been freed. */
10734 S_process_special_blocks(pTHX_ I32 floor, const char *const fullname,
10738 const char *const colon = strrchr(fullname,':');
10739 const char *const name = colon ? colon + 1 : fullname;
10740 int is_module_install_hack = 0;
10742 PERL_ARGS_ASSERT_PROCESS_SPECIAL_BLOCKS;
10744 if (*name == 'B') {
10745 module_install_hack:
10746 if (strEQ(name, "BEGIN") || is_module_install_hack) {
10747 const I32 oldscope = PL_scopestack_ix;
10748 SV *max_nest_sv = NULL;
10752 is_module_install_hack = 0;
10753 if (floor) LEAVE_SCOPE(floor);
10756 /* make sure we don't recurse too deeply into BEGIN blocks
10757 * but let the user control it via the new control variable
10759 * ${^MAX_NESTED_EVAL_BEGIN_BLOCKS}
10761 * Note this *looks* code like when max_nest_iv is 1 that it
10762 * would block the following code:
10764 * BEGIN { $n |= 1; BEGIN { $n |= 2; BEGIN { $n |= 4 } } }
10766 * but it does *not*, this code will happily execute when
10767 * the nest limit is 1. The reason is revealed in the
10768 * execution order. If we could watch $n in this code we
10769 * would see the follow order of modifications:
10775 * This is because nested BEGIN blocks execute in FILO
10776 * order, this is because BEGIN blocks are defined to
10777 * execute immediately they are closed. So the innermost
10778 * block is closed first, and it executes, which would the
10779 * eval_begin_nest_depth by 1, it would finish, which would
10780 * drop it back to its previous value. This would happen in
10781 * turn as each BEGIN was terminated.
10783 * The *only* place these counts matter is when BEGIN in
10784 * inside of some kind of eval, either a require or a true
10785 * eval. Only in that case would there be any nesting and
10786 * would perl try to execute a BEGIN before another had
10789 * Thus this logic puts an upper limit on module nesting.
10790 * Hence the reason we let the user control it, although its
10791 * hard to imagine a 1000 level deep module use dependency
10792 * even in a very large codebase. The real objective is to
10793 * prevent code like this:
10795 * perl -e'sub f { eval "BEGIN { f() }" } f()'
10797 * from segfaulting due to stack exhaustion.
10800 max_nest_sv = get_sv(PERL_VAR_MAX_NESTED_EVAL_BEGIN_BLOCKS, GV_ADD);
10801 if (!SvOK(max_nest_sv))
10802 sv_setiv(max_nest_sv, PERL_MAX_NESTED_EVAL_BEGIN_BLOCKS_DEFAULT);
10803 max_nest_iv = SvIV(max_nest_sv);
10804 if (max_nest_iv < 0) {
10805 max_nest_iv = PERL_MAX_NESTED_EVAL_BEGIN_BLOCKS_DEFAULT;
10806 sv_setiv(max_nest_sv, max_nest_iv);
10809 if (PL_eval_begin_nest_depth >= max_nest_iv) {
10810 Perl_croak(aTHX_ "Too many nested BEGIN blocks, maximum of %" IVdf " allowed",
10813 SAVEINT(PL_eval_begin_nest_depth);
10814 PL_eval_begin_nest_depth++;
10816 SAVEVPTR(PL_curcop);
10817 if (PL_curcop == &PL_compiling) {
10818 /* Avoid pushing the "global" &PL_compiling onto the
10819 * context stack. For example, a stack trace inside
10820 * nested use's would show all calls coming from whoever
10821 * most recently updated PL_compiling.cop_file and
10822 * cop_line. So instead, temporarily set PL_curcop to a
10823 * private copy of &PL_compiling. PL_curcop will soon be
10824 * set to point back to &PL_compiling anyway but only
10825 * after the temp value has been pushed onto the context
10826 * stack as blk_oldcop.
10827 * This is slightly hacky, but necessary. Note also
10828 * that in the brief window before PL_curcop is set back
10829 * to PL_compiling, IN_PERL_COMPILETIME/IN_PERL_RUNTIME
10830 * will give the wrong answer.
10832 PL_curcop = (COP*)newSTATEOP(PL_compiling.op_flags, NULL, NULL);
10833 CopLINE_set(PL_curcop, CopLINE(&PL_compiling));
10834 SAVEFREEOP(PL_curcop);
10837 PUSHSTACKi(PERLSI_REQUIRE);
10838 SAVECOPFILE(&PL_compiling);
10839 SAVECOPLINE(&PL_compiling);
10841 DEBUG_x( dump_sub(gv) );
10842 Perl_av_create_and_push(aTHX_ &PL_beginav, MUTABLE_SV(cv));
10843 GvCV_set(gv,0); /* cv has been hijacked */
10844 call_list(oldscope, PL_beginav);
10848 return !PL_savebegin;
10853 if (*name == 'E') {
10854 if (strEQ(name, "END")) {
10855 DEBUG_x( dump_sub(gv) );
10856 Perl_av_create_and_unshift_one(aTHX_ &PL_endav, MUTABLE_SV(cv));
10859 } else if (*name == 'U') {
10860 if (strEQ(name, "UNITCHECK")) {
10861 /* It's never too late to run a unitcheck block */
10862 Perl_av_create_and_unshift_one(aTHX_ &PL_unitcheckav, MUTABLE_SV(cv));
10866 } else if (*name == 'C') {
10867 if (strEQ(name, "CHECK")) {
10869 /* diag_listed_as: Too late to run %s block */
10870 Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10871 "Too late to run CHECK block");
10872 Perl_av_create_and_unshift_one(aTHX_ &PL_checkav, MUTABLE_SV(cv));
10876 } else if (*name == 'I') {
10877 if (strEQ(name, "INIT")) {
10878 #ifdef MI_INIT_WORKAROUND_PACK
10880 HV *hv= CvSTASH(cv);
10881 STRLEN len = hv ? HvNAMELEN(hv) : 0;
10882 char *pv= (len == sizeof(MI_INIT_WORKAROUND_PACK)-1)
10883 ? HvNAME_get(hv) : NULL;
10884 if ( pv && strEQ(pv,MI_INIT_WORKAROUND_PACK) )
10886 /* old versions of Module::Install::DSL contain code
10887 * that creates an INIT in eval, which expect to run
10888 * after an exit(0) in BEGIN. This unfortunately
10889 * breaks a lot of code in the CPAN river. So we magically
10890 * convert INIT blocks from Module::Install::DSL to
10891 * be BEGIN blocks. Which works out, since the INIT
10892 * blocks it creates are eval'ed so are late.
10894 Perl_warn(aTHX_ "Treating %s::INIT block as BEGIN block as workaround",
10895 MI_INIT_WORKAROUND_PACK);
10896 is_module_install_hack = 1;
10897 goto module_install_hack;
10903 /* diag_listed_as: Too late to run %s block */
10904 Perl_ck_warner(aTHX_ packWARN(WARN_VOID),
10905 "Too late to run INIT block");
10906 Perl_av_create_and_push(aTHX_ &PL_initav, MUTABLE_SV(cv));
10912 DEBUG_x( dump_sub(gv) );
10914 GvCV_set(gv,0); /* cv has been hijacked */
10920 =for apidoc newCONSTSUB
10922 Behaves like L</newCONSTSUB_flags>, except that C<name> is nul-terminated
10923 rather than of counted length, and no flags are set. (This means that
10924 C<name> is always interpreted as Latin-1.)
10930 Perl_newCONSTSUB(pTHX_ HV *stash, const char *name, SV *sv)
10932 return newCONSTSUB_flags(stash, name, name ? strlen(name) : 0, 0, sv);
10936 =for apidoc newCONSTSUB_flags
10938 Construct a constant subroutine, also performing some surrounding
10939 jobs. A scalar constant-valued subroutine is eligible for inlining
10940 at compile-time, and in Perl code can be created by S<C<sub FOO () {
10941 123 }>>. Other kinds of constant subroutine have other treatment.
10943 The subroutine will have an empty prototype and will ignore any arguments
10944 when called. Its constant behaviour is determined by C<sv>. If C<sv>
10945 is null, the subroutine will yield an empty list. If C<sv> points to a
10946 scalar, the subroutine will always yield that scalar. If C<sv> points
10947 to an array, the subroutine will always yield a list of the elements of
10948 that array in list context, or the number of elements in the array in
10949 scalar context. This function takes ownership of one counted reference
10950 to the scalar or array, and will arrange for the object to live as long
10951 as the subroutine does. If C<sv> points to a scalar then the inlining
10952 assumes that the value of the scalar will never change, so the caller
10953 must ensure that the scalar is not subsequently written to. If C<sv>
10954 points to an array then no such assumption is made, so it is ostensibly
10955 safe to mutate the array or its elements, but whether this is really
10956 supported has not been determined.
10958 The subroutine will have C<CvFILE> set according to C<PL_curcop>.
10959 Other aspects of the subroutine will be left in their default state.
10960 The caller is free to mutate the subroutine beyond its initial state
10961 after this function has returned.
10963 If C<name> is null then the subroutine will be anonymous, with its
10964 C<CvGV> referring to an C<__ANON__> glob. If C<name> is non-null then the
10965 subroutine will be named accordingly, referenced by the appropriate glob.
10966 C<name> is a string of length C<len> bytes giving a sigilless symbol
10967 name, in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1
10968 otherwise. The name may be either qualified or unqualified. If the
10969 name is unqualified then it defaults to being in the stash specified by
10970 C<stash> if that is non-null, or to C<PL_curstash> if C<stash> is null.
10971 The symbol is always added to the stash if necessary, with C<GV_ADDMULTI>
10974 C<flags> should not have bits set other than C<SVf_UTF8>.
10976 If there is already a subroutine of the specified name, then the new sub
10977 will replace the existing one in the glob. A warning may be generated
10978 about the redefinition.
10980 If the subroutine has one of a few special names, such as C<BEGIN> or
10981 C<END>, then it will be claimed by the appropriate queue for automatic
10982 running of phase-related subroutines. In this case the relevant glob will
10983 be left not containing any subroutine, even if it did contain one before.
10984 Execution of the subroutine will likely be a no-op, unless C<sv> was
10985 a tied array or the caller modified the subroutine in some interesting
10986 way before it was executed. In the case of C<BEGIN>, the treatment is
10987 buggy: the sub will be executed when only half built, and may be deleted
10988 prematurely, possibly causing a crash.
10990 The function returns a pointer to the constructed subroutine. If the sub
10991 is anonymous then ownership of one counted reference to the subroutine
10992 is transferred to the caller. If the sub is named then the caller does
10993 not get ownership of a reference. In most such cases, where the sub
10994 has a non-phase name, the sub will be alive at the point it is returned
10995 by virtue of being contained in the glob that names it. A phase-named
10996 subroutine will usually be alive by virtue of the reference owned by
10997 the phase's automatic run queue. A C<BEGIN> subroutine may have been
10998 destroyed already by the time this function returns, but currently bugs
10999 occur in that case before the caller gets control. It is the caller's
11000 responsibility to ensure that it knows which of these situations applies.
11006 Perl_newCONSTSUB_flags(pTHX_ HV *stash, const char *name, STRLEN len,
11010 const char *const file = CopFILE(PL_curcop);
11014 if (IN_PERL_RUNTIME) {
11015 /* at runtime, it's not safe to manipulate PL_curcop: it may be
11016 * an op shared between threads. Use a non-shared COP for our
11018 SAVEVPTR(PL_curcop);
11019 SAVECOMPILEWARNINGS();
11020 PL_compiling.cop_warnings = DUP_WARNINGS(PL_curcop->cop_warnings);
11021 PL_curcop = &PL_compiling;
11023 SAVECOPLINE(PL_curcop);
11024 CopLINE_set(PL_curcop, PL_parser ? PL_parser->copline : NOLINE);
11027 PL_hints &= ~HINT_BLOCK_SCOPE;
11030 SAVEGENERICSV(PL_curstash);
11031 PL_curstash = (HV *)SvREFCNT_inc_simple_NN(stash);
11034 /* Protect sv against leakage caused by fatal warnings. */
11035 if (sv) SAVEFREESV(sv);
11037 /* file becomes the CvFILE. For an XS, it's usually static storage,
11038 and so doesn't get free()d. (It's expected to be from the C pre-
11039 processor __FILE__ directive). But we need a dynamically allocated one,
11040 and we need it to get freed. */
11041 cv = newXS_len_flags(name, len,
11042 sv && SvTYPE(sv) == SVt_PVAV
11045 file ? file : "", "",
11046 &sv, XS_DYNAMIC_FILENAME | flags);
11048 assert(SvREFCNT((SV*)cv) != 0);
11049 CvXSUBANY(cv).any_ptr = SvREFCNT_inc_simple(sv);
11060 Used by C<xsubpp> to hook up XSUBs as Perl subs. C<filename> needs to be
11061 static storage, as it is used directly as CvFILE(), without a copy being made.
11067 Perl_newXS(pTHX_ const char *name, XSUBADDR_t subaddr, const char *filename)
11069 PERL_ARGS_ASSERT_NEWXS;
11070 return newXS_len_flags(
11071 name, name ? strlen(name) : 0, subaddr, filename, NULL, NULL, 0
11076 Perl_newXS_flags(pTHX_ const char *name, XSUBADDR_t subaddr,
11077 const char *const filename, const char *const proto,
11080 PERL_ARGS_ASSERT_NEWXS_FLAGS;
11081 return newXS_len_flags(
11082 name, name ? strlen(name) : 0, subaddr, filename, proto, NULL, flags
11087 Perl_newXS_deffile(pTHX_ const char *name, XSUBADDR_t subaddr)
11089 PERL_ARGS_ASSERT_NEWXS_DEFFILE;
11090 return newXS_len_flags(
11091 name, strlen(name), subaddr, NULL, NULL, NULL, 0
11096 =for apidoc newXS_len_flags
11098 Construct an XS subroutine, also performing some surrounding jobs.
11100 The subroutine will have the entry point C<subaddr>. It will have
11101 the prototype specified by the nul-terminated string C<proto>, or
11102 no prototype if C<proto> is null. The prototype string is copied;
11103 the caller can mutate the supplied string afterwards. If C<filename>
11104 is non-null, it must be a nul-terminated filename, and the subroutine
11105 will have its C<CvFILE> set accordingly. By default C<CvFILE> is set to
11106 point directly to the supplied string, which must be static. If C<flags>
11107 has the C<XS_DYNAMIC_FILENAME> bit set, then a copy of the string will
11110 Other aspects of the subroutine will be left in their default state.
11111 If anything else needs to be done to the subroutine for it to function
11112 correctly, it is the caller's responsibility to do that after this
11113 function has constructed it. However, beware of the subroutine
11114 potentially being destroyed before this function returns, as described
11117 If C<name> is null then the subroutine will be anonymous, with its
11118 C<CvGV> referring to an C<__ANON__> glob. If C<name> is non-null then the
11119 subroutine will be named accordingly, referenced by the appropriate glob.
11120 C<name> is a string of length C<len> bytes giving a sigilless symbol name,
11121 in UTF-8 if C<flags> has the C<SVf_UTF8> bit set and in Latin-1 otherwise.
11122 The name may be either qualified or unqualified, with the stash defaulting
11123 in the same manner as for C<gv_fetchpvn_flags>. C<flags> may contain
11124 flag bits understood by C<gv_fetchpvn_flags> with the same meaning as
11125 they have there, such as C<GV_ADDWARN>. The symbol is always added to
11126 the stash if necessary, with C<GV_ADDMULTI> semantics.
11128 If there is already a subroutine of the specified name, then the new sub
11129 will replace the existing one in the glob. A warning may be generated
11130 about the redefinition. If the old subroutine was C<CvCONST> then the
11131 decision about whether to warn is influenced by an expectation about
11132 whether the new subroutine will become a constant of similar value.
11133 That expectation is determined by C<const_svp>. (Note that the call to
11134 this function doesn't make the new subroutine C<CvCONST> in any case;
11135 that is left to the caller.) If C<const_svp> is null then it indicates
11136 that the new subroutine will not become a constant. If C<const_svp>
11137 is non-null then it indicates that the new subroutine will become a
11138 constant, and it points to an C<SV*> that provides the constant value
11139 that the subroutine will have.
11141 If the subroutine has one of a few special names, such as C<BEGIN> or
11142 C<END>, then it will be claimed by the appropriate queue for automatic
11143 running of phase-related subroutines. In this case the relevant glob will
11144 be left not containing any subroutine, even if it did contain one before.
11145 In the case of C<BEGIN>, the subroutine will be executed and the reference
11146 to it disposed of before this function returns, and also before its
11147 prototype is set. If a C<BEGIN> subroutine would not be sufficiently
11148 constructed by this function to be ready for execution then the caller
11149 must prevent this happening by giving the subroutine a different name.
11151 The function returns a pointer to the constructed subroutine. If the sub
11152 is anonymous then ownership of one counted reference to the subroutine
11153 is transferred to the caller. If the sub is named then the caller does
11154 not get ownership of a reference. In most such cases, where the sub
11155 has a non-phase name, the sub will be alive at the point it is returned
11156 by virtue of being contained in the glob that names it. A phase-named
11157 subroutine will usually be alive by virtue of the reference owned by the
11158 phase's automatic run queue. But a C<BEGIN> subroutine, having already
11159 been executed, will quite likely have been destroyed already by the
11160 time this function returns, making it erroneous for the caller to make
11161 any use of the returned pointer. It is the caller's responsibility to
11162 ensure that it knows which of these situations applies.
11168 Perl_newXS_len_flags(pTHX_ const char *name, STRLEN len,
11169 XSUBADDR_t subaddr, const char *const filename,
11170 const char *const proto, SV **const_svp,
11174 bool interleave = FALSE;
11175 bool evanescent = FALSE;
11177 PERL_ARGS_ASSERT_NEWXS_LEN_FLAGS;
11180 GV * const gv = gv_fetchpvn(
11181 name ? name : PL_curstash ? "__ANON__" : "__ANON__::__ANON__",
11182 name ? len : PL_curstash ? sizeof("__ANON__") - 1:
11183 sizeof("__ANON__::__ANON__") - 1,
11184 GV_ADDMULTI | flags, SVt_PVCV);
11186 if ((cv = (name ? GvCV(gv) : NULL))) {
11188 /* just a cached method */
11192 else if (CvROOT(cv) || CvXSUB(cv) || GvASSUMECV(gv)) {
11193 /* already defined (or promised) */
11194 /* Redundant check that allows us to avoid creating an SV
11195 most of the time: */
11196 if (CvCONST(cv) || ckWARN(WARN_REDEFINE)) {
11197 report_redefined_cv(newSVpvn_flags(
11198 name,len,(flags&SVf_UTF8)|SVs_TEMP
11209 if (cv) /* must reuse cv if autoloaded */
11212 cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11216 if (HvENAME_HEK(GvSTASH(gv)))
11217 gv_method_changed(gv); /* newXS */
11221 assert(SvREFCNT((SV*)cv) != 0);
11225 /* XSUBs can't be perl lang/perl5db.pl debugged
11226 if (PERLDB_LINE_OR_SAVESRC)
11227 (void)gv_fetchfile(filename); */
11228 assert(!CvDYNFILE(cv)); /* cv_undef should have turned it off */
11229 if (flags & XS_DYNAMIC_FILENAME) {
11231 CvFILE(cv) = savepv(filename);
11233 /* NOTE: not copied, as it is expected to be an external constant string */
11234 CvFILE(cv) = (char *)filename;
11237 assert((flags & XS_DYNAMIC_FILENAME) == 0 && PL_xsubfilename);
11238 CvFILE(cv) = (char*)PL_xsubfilename;
11241 CvXSUB(cv) = subaddr;
11242 #ifndef MULTIPLICITY
11243 CvHSCXT(cv) = &PL_stack_sp;
11249 evanescent = process_special_blocks(0, name, gv, cv);
11252 } /* <- not a conditional branch */
11255 assert(evanescent || SvREFCNT((SV*)cv) != 0);
11257 if (!evanescent) sv_setpv(MUTABLE_SV(cv), proto);
11258 if (interleave) LEAVE;
11259 assert(evanescent || SvREFCNT((SV*)cv) != 0);
11263 /* Add a stub CV to a typeglob.
11264 * This is the implementation of a forward declaration, 'sub foo';'
11268 Perl_newSTUB(pTHX_ GV *gv, bool fake)
11270 CV *cv = MUTABLE_CV(newSV_type(SVt_PVCV));
11272 PERL_ARGS_ASSERT_NEWSTUB;
11273 assert(!GvCVu(gv));
11276 if (!fake && GvSTASH(gv) && HvENAME_HEK(GvSTASH(gv)))
11277 gv_method_changed(gv);
11279 cvgv = gv_fetchsv((SV *)gv, GV_ADDMULTI, SVt_PVCV);
11283 CvGV_set(cv, cvgv);
11284 CvFILE_set_from_cop(cv, PL_curcop);
11285 CvSTASH_set(cv, PL_curstash);
11291 Perl_newFORM(pTHX_ I32 floor, OP *o, OP *block)
11298 if (PL_parser && PL_parser->error_count) {
11304 ? gv_fetchsv(cSVOPo->op_sv, GV_ADD, SVt_PVFM)
11305 : gv_fetchpvs("STDOUT", GV_ADD|GV_NOTQUAL, SVt_PVFM);
11308 if ((cv = GvFORM(gv))) {
11309 if (ckWARN(WARN_REDEFINE)) {
11310 const line_t oldline = CopLINE(PL_curcop);
11311 if (PL_parser && PL_parser->copline != NOLINE)
11312 CopLINE_set(PL_curcop, PL_parser->copline);
11314 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11315 "Format %" SVf " redefined", SVfARG(cSVOPo->op_sv));
11317 /* diag_listed_as: Format %s redefined */
11318 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
11319 "Format STDOUT redefined");
11321 CopLINE_set(PL_curcop, oldline);
11326 GvFORM(gv) = (CV *)SvREFCNT_inc_simple_NN(cv);
11328 CvFILE_set_from_cop(cv, PL_curcop);
11331 root = newUNOP(OP_LEAVEWRITE, 0, voidnonfinal(block));
11333 start = LINKLIST(root);
11335 S_process_optree(aTHX_ cv, root, start);
11336 cv_forget_slab(cv);
11341 PL_parser->copline = NOLINE;
11342 LEAVE_SCOPE(floor);
11343 PL_compiling.cop_seq = 0;
11347 Perl_newANONLIST(pTHX_ OP *o)
11349 return op_convert_list(OP_ANONLIST, OPf_SPECIAL, o);
11353 Perl_newANONHASH(pTHX_ OP *o)
11355 return op_convert_list(OP_ANONHASH, OPf_SPECIAL, o);
11359 Perl_newANONSUB(pTHX_ I32 floor, OP *proto, OP *block)
11361 return newANONATTRSUB(floor, proto, NULL, block);
11365 Perl_newANONATTRSUB(pTHX_ I32 floor, OP *proto, OP *attrs, OP *block)
11367 SV * const cv = MUTABLE_SV(newATTRSUB(floor, 0, proto, attrs, block));
11369 newSVOP(OP_ANONCODE, 0,
11371 if (CvANONCONST(cv))
11372 anoncode = newUNOP(OP_ANONCONST, 0,
11373 op_convert_list(OP_ENTERSUB,
11374 OPf_STACKED|OPf_WANT_SCALAR,
11376 return newUNOP(OP_REFGEN, 0, anoncode);
11380 Perl_oopsAV(pTHX_ OP *o)
11383 PERL_ARGS_ASSERT_OOPSAV;
11385 switch (o->op_type) {
11388 OpTYPE_set(o, OP_PADAV);
11389 return ref(o, OP_RV2AV);
11393 OpTYPE_set(o, OP_RV2AV);
11398 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsAV");
11405 Perl_oopsHV(pTHX_ OP *o)
11408 PERL_ARGS_ASSERT_OOPSHV;
11410 switch (o->op_type) {
11413 OpTYPE_set(o, OP_PADHV);
11414 return ref(o, OP_RV2HV);
11418 OpTYPE_set(o, OP_RV2HV);
11419 /* rv2hv steals the bottom bit for its own uses */
11420 o->op_private &= ~OPpARG1_MASK;
11425 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "oops: oopsHV");
11432 Perl_newAVREF(pTHX_ OP *o)
11435 PERL_ARGS_ASSERT_NEWAVREF;
11437 if (o->op_type == OP_PADANY) {
11438 OpTYPE_set(o, OP_PADAV);
11441 else if ((o->op_type == OP_RV2AV || o->op_type == OP_PADAV)) {
11442 Perl_croak(aTHX_ "Can't use an array as a reference");
11444 return newUNOP(OP_RV2AV, 0, scalar(o));
11448 Perl_newGVREF(pTHX_ I32 type, OP *o)
11450 if (type == OP_MAPSTART || type == OP_GREPSTART || type == OP_SORT)
11451 return newUNOP(OP_NULL, 0, o);
11453 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED &&
11454 ((PL_opargs[type] >> OASHIFT) & 7) == OA_FILEREF &&
11455 o->op_type == OP_CONST && (o->op_private & OPpCONST_BARE)) {
11456 no_bareword_filehandle(SvPVX(cSVOPo_sv));
11459 return ref(newUNOP(OP_RV2GV, OPf_REF, o), type);
11463 Perl_newHVREF(pTHX_ OP *o)
11466 PERL_ARGS_ASSERT_NEWHVREF;
11468 if (o->op_type == OP_PADANY) {
11469 OpTYPE_set(o, OP_PADHV);
11472 else if ((o->op_type == OP_RV2HV || o->op_type == OP_PADHV)) {
11473 Perl_croak(aTHX_ "Can't use a hash as a reference");
11475 return newUNOP(OP_RV2HV, 0, scalar(o));
11479 Perl_newCVREF(pTHX_ I32 flags, OP *o)
11481 if (o->op_type == OP_PADANY) {
11482 OpTYPE_set(o, OP_PADCV);
11484 return newUNOP(OP_RV2CV, flags, scalar(o));
11488 Perl_newSVREF(pTHX_ OP *o)
11491 PERL_ARGS_ASSERT_NEWSVREF;
11493 if (o->op_type == OP_PADANY) {
11494 OpTYPE_set(o, OP_PADSV);
11498 return newUNOP(OP_RV2SV, 0, scalar(o));
11501 /* Check routines. See the comments at the top of this file for details
11502 * on when these are called */
11505 Perl_ck_anoncode(pTHX_ OP *o)
11507 PERL_ARGS_ASSERT_CK_ANONCODE;
11509 cSVOPo->op_targ = pad_add_anon((CV*)cSVOPo->op_sv, o->op_type);
11510 cSVOPo->op_sv = NULL;
11515 S_io_hints(pTHX_ OP *o)
11517 #if O_BINARY != 0 || O_TEXT != 0
11519 PL_hints & HINT_LOCALIZE_HH ? GvHV(PL_hintgv) : NULL;;
11521 SV **svp = hv_fetchs(table, "open_IN", FALSE);
11524 const char *d = SvPV_const(*svp, len);
11525 const I32 mode = mode_from_discipline(d, len);
11526 /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11528 if (mode & O_BINARY)
11529 o->op_private |= OPpOPEN_IN_RAW;
11533 o->op_private |= OPpOPEN_IN_CRLF;
11537 svp = hv_fetchs(table, "open_OUT", FALSE);
11540 const char *d = SvPV_const(*svp, len);
11541 const I32 mode = mode_from_discipline(d, len);
11542 /* bit-and:ing with zero O_BINARY or O_TEXT would be useless. */
11544 if (mode & O_BINARY)
11545 o->op_private |= OPpOPEN_OUT_RAW;
11549 o->op_private |= OPpOPEN_OUT_CRLF;
11554 PERL_UNUSED_CONTEXT;
11555 PERL_UNUSED_ARG(o);
11560 Perl_ck_backtick(pTHX_ OP *o)
11565 PERL_ARGS_ASSERT_CK_BACKTICK;
11567 /* qx and `` have a null pushmark; CORE::readpipe has only one kid. */
11568 if (o->op_flags & OPf_KIDS && (sibl = OpSIBLING(cUNOPo->op_first))
11569 && (gv = gv_override("readpipe",8)))
11571 /* detach rest of siblings from o and its first child */
11572 op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
11573 newop = S_new_entersubop(aTHX_ gv, sibl);
11575 else if (!(o->op_flags & OPf_KIDS))
11576 newop = newUNOP(OP_BACKTICK, 0, newDEFSVOP());
11581 S_io_hints(aTHX_ o);
11586 Perl_ck_bitop(pTHX_ OP *o)
11588 PERL_ARGS_ASSERT_CK_BITOP;
11590 /* get rid of arg count and indicate if in the scope of 'use integer' */
11591 o->op_private = (PL_hints & HINT_INTEGER) ? OPpUSEINT : 0;
11593 if (!(o->op_flags & OPf_STACKED) /* Not an assignment */
11594 && OP_IS_INFIX_BIT(o->op_type))
11596 const OP * const left = cBINOPo->op_first;
11597 const OP * const right = OpSIBLING(left);
11598 if ((OP_IS_NUMCOMPARE(left->op_type) &&
11599 (left->op_flags & OPf_PARENS) == 0) ||
11600 (OP_IS_NUMCOMPARE(right->op_type) &&
11601 (right->op_flags & OPf_PARENS) == 0))
11602 Perl_ck_warner(aTHX_ packWARN(WARN_PRECEDENCE),
11603 "Possible precedence problem on bitwise %s operator",
11604 o->op_type == OP_BIT_OR
11605 ||o->op_type == OP_NBIT_OR ? "|"
11606 : o->op_type == OP_BIT_AND
11607 ||o->op_type == OP_NBIT_AND ? "&"
11608 : o->op_type == OP_BIT_XOR
11609 ||o->op_type == OP_NBIT_XOR ? "^"
11610 : o->op_type == OP_SBIT_OR ? "|."
11611 : o->op_type == OP_SBIT_AND ? "&." : "^."
11617 PERL_STATIC_INLINE bool
11618 is_dollar_bracket(pTHX_ const OP * const o)
11621 PERL_UNUSED_CONTEXT;
11622 return o->op_type == OP_RV2SV && o->op_flags & OPf_KIDS
11623 && (kid = cUNOPx(o)->op_first)
11624 && kid->op_type == OP_GV
11625 && strEQ(GvNAME(cGVOPx_gv(kid)), "[");
11628 /* for lt, gt, le, ge, eq, ne and their i_ variants */
11631 Perl_ck_cmp(pTHX_ OP *o)
11637 OP *indexop, *constop, *start;
11641 PERL_ARGS_ASSERT_CK_CMP;
11643 is_eq = ( o->op_type == OP_EQ
11644 || o->op_type == OP_NE
11645 || o->op_type == OP_I_EQ
11646 || o->op_type == OP_I_NE);
11648 if (!is_eq && ckWARN(WARN_SYNTAX)) {
11649 const OP *kid = cUNOPo->op_first;
11652 ( is_dollar_bracket(aTHX_ kid)
11653 && OpSIBLING(kid) && OpSIBLING(kid)->op_type == OP_CONST
11655 || ( kid->op_type == OP_CONST
11656 && (kid = OpSIBLING(kid)) && is_dollar_bracket(aTHX_ kid)
11660 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
11661 "$[ used in %s (did you mean $] ?)", OP_DESC(o));
11664 /* convert (index(...) == -1) and variations into
11665 * (r)index/BOOL(,NEG)
11670 indexop = cUNOPo->op_first;
11671 constop = OpSIBLING(indexop);
11673 if (indexop->op_type == OP_CONST) {
11675 indexop = OpSIBLING(constop);
11680 if (indexop->op_type != OP_INDEX && indexop->op_type != OP_RINDEX)
11683 /* ($lex = index(....)) == -1 */
11684 if (indexop->op_private & OPpTARGET_MY)
11687 if (constop->op_type != OP_CONST)
11690 sv = cSVOPx_sv(constop);
11691 if (!(sv && SvIOK_notUV(sv)))
11695 if (iv != -1 && iv != 0)
11699 if (o->op_type == OP_LT || o->op_type == OP_I_LT) {
11700 if (!(iv0 ^ reverse))
11704 else if (o->op_type == OP_LE || o->op_type == OP_I_LE) {
11709 else if (o->op_type == OP_GE || o->op_type == OP_I_GE) {
11710 if (!(iv0 ^ reverse))
11714 else if (o->op_type == OP_GT || o->op_type == OP_I_GT) {
11719 else if (o->op_type == OP_EQ || o->op_type == OP_I_EQ) {
11725 assert(o->op_type == OP_NE || o->op_type == OP_I_NE);
11731 indexop->op_flags &= ~OPf_PARENS;
11732 indexop->op_flags |= (o->op_flags & OPf_PARENS);
11733 indexop->op_private |= OPpTRUEBOOL;
11735 indexop->op_private |= OPpINDEX_BOOLNEG;
11736 /* cut out the index op and free the eq,const ops */
11737 (void)op_sibling_splice(o, start, 1, NULL);
11745 Perl_ck_concat(pTHX_ OP *o)
11747 const OP * const kid = cUNOPo->op_first;
11749 PERL_ARGS_ASSERT_CK_CONCAT;
11750 PERL_UNUSED_CONTEXT;
11752 /* reuse the padtmp returned by the concat child */
11753 if (kid->op_type == OP_CONCAT && !(kid->op_private & OPpTARGET_MY) &&
11754 !(kUNOP->op_first->op_flags & OPf_MOD))
11756 o->op_flags |= OPf_STACKED;
11757 o->op_private |= OPpCONCAT_NESTED;
11763 Perl_ck_spair(pTHX_ OP *o)
11766 PERL_ARGS_ASSERT_CK_SPAIR;
11768 if (o->op_flags & OPf_KIDS) {
11772 const OPCODE type = o->op_type;
11773 o = modkids(ck_fun(o), type);
11774 kid = cUNOPo->op_first;
11775 kidkid = kUNOP->op_first;
11776 newop = OpSIBLING(kidkid);
11778 const OPCODE type = newop->op_type;
11779 if (OpHAS_SIBLING(newop))
11781 if (o->op_type == OP_REFGEN
11782 && ( type == OP_RV2CV
11783 || ( !(newop->op_flags & OPf_PARENS)
11784 && ( type == OP_RV2AV || type == OP_PADAV
11785 || type == OP_RV2HV || type == OP_PADHV))))
11786 NOOP; /* OK (allow srefgen for \@a and \%h) */
11787 else if (OP_GIMME(newop,0) != G_SCALAR)
11790 /* excise first sibling */
11791 op_sibling_splice(kid, NULL, 1, NULL);
11794 /* transforms OP_REFGEN into OP_SREFGEN, OP_CHOP into OP_SCHOP,
11795 * and OP_CHOMP into OP_SCHOMP */
11796 o->op_ppaddr = PL_ppaddr[++o->op_type];
11801 Perl_ck_delete(pTHX_ OP *o)
11803 PERL_ARGS_ASSERT_CK_DELETE;
11807 if (o->op_flags & OPf_KIDS) {
11808 OP * const kid = cUNOPo->op_first;
11809 switch (kid->op_type) {
11811 o->op_flags |= OPf_SPECIAL;
11814 o->op_private |= OPpSLICE;
11817 o->op_flags |= OPf_SPECIAL;
11822 o->op_flags |= OPf_SPECIAL;
11825 o->op_private |= OPpKVSLICE;
11828 Perl_croak(aTHX_ "delete argument is not a HASH or ARRAY "
11829 "element or slice");
11831 if (kid->op_private & OPpLVAL_INTRO)
11832 o->op_private |= OPpLVAL_INTRO;
11839 Perl_ck_eof(pTHX_ OP *o)
11841 PERL_ARGS_ASSERT_CK_EOF;
11843 if (o->op_flags & OPf_KIDS) {
11845 if (cLISTOPo->op_first->op_type == OP_STUB) {
11847 = newUNOP(o->op_type, OPf_SPECIAL, newGVOP(OP_GV, 0, PL_argvgv));
11852 kid = cLISTOPo->op_first;
11853 if (kid->op_type == OP_RV2GV)
11854 kid->op_private |= OPpALLOW_FAKE;
11861 Perl_ck_eval(pTHX_ OP *o)
11864 PERL_ARGS_ASSERT_CK_EVAL;
11866 PL_hints |= HINT_BLOCK_SCOPE;
11867 if (o->op_flags & OPf_KIDS) {
11868 SVOP * const kid = cSVOPx(cUNOPo->op_first);
11871 if (o->op_type == OP_ENTERTRY) {
11874 /* cut whole sibling chain free from o */
11875 op_sibling_splice(o, NULL, -1, NULL);
11878 enter = alloc_LOGOP(OP_ENTERTRY, NULL, NULL);
11880 /* establish postfix order */
11881 enter->op_next = (OP*)enter;
11883 o = op_prepend_elem(OP_LINESEQ, (OP*)enter, (OP*)kid);
11884 OpTYPE_set(o, OP_LEAVETRY);
11885 enter->op_other = o;
11890 S_set_haseval(aTHX);
11894 const U8 priv = o->op_private;
11896 /* the newUNOP will recursively call ck_eval(), which will handle
11897 * all the stuff at the end of this function, like adding
11900 return newUNOP(OP_ENTEREVAL, priv <<8, newDEFSVOP());
11902 o->op_targ = (PADOFFSET)PL_hints;
11903 if (o->op_private & OPpEVAL_BYTES) o->op_targ &= ~HINT_UTF8;
11904 if ((PL_hints & HINT_LOCALIZE_HH) != 0
11905 && !(o->op_private & OPpEVAL_COPHH) && GvHV(PL_hintgv)) {
11906 /* Store a copy of %^H that pp_entereval can pick up. */
11907 HV *hh = hv_copy_hints_hv(GvHV(PL_hintgv));
11909 STOREFEATUREBITSHH(hh);
11910 hhop = newSVOP(OP_HINTSEVAL, 0, MUTABLE_SV(hh));
11911 /* append hhop to only child */
11912 op_sibling_splice(o, cUNOPo->op_first, 0, hhop);
11914 o->op_private |= OPpEVAL_HAS_HH;
11916 if (!(o->op_private & OPpEVAL_BYTES)
11917 && FEATURE_UNIEVAL_IS_ENABLED)
11918 o->op_private |= OPpEVAL_UNICODE;
11923 Perl_ck_trycatch(pTHX_ OP *o)
11926 OP *to_free = NULL;
11927 OP *trykid, *catchkid;
11928 OP *catchroot, *catchstart;
11930 PERL_ARGS_ASSERT_CK_TRYCATCH;
11932 trykid = cUNOPo->op_first;
11933 if(trykid->op_type == OP_NULL || trykid->op_type == OP_PUSHMARK) {
11935 trykid = OpSIBLING(trykid);
11937 catchkid = OpSIBLING(trykid);
11939 assert(trykid->op_type == OP_POPTRY);
11940 assert(catchkid->op_type == OP_CATCH);
11942 /* cut whole sibling chain free from o */
11943 op_sibling_splice(o, NULL, -1, NULL);
11948 enter = alloc_LOGOP(OP_ENTERTRYCATCH, NULL, NULL);
11950 /* establish postfix order */
11951 enter->op_next = (OP*)enter;
11953 o = op_prepend_elem(OP_LINESEQ, (OP*)enter, trykid);
11954 op_append_elem(OP_LINESEQ, (OP*)o, catchkid);
11956 OpTYPE_set(o, OP_LEAVETRYCATCH);
11958 /* The returned optree is actually threaded up slightly nonobviously in
11959 * terms of its ->op_next pointers.
11961 * This way, if the tryblock dies, its retop points at the OP_CATCH, but
11962 * if it does not then its leavetry skips over that and continues
11963 * execution past it.
11966 /* First, link up the actual body of the catch block */
11967 catchroot = OpSIBLING(cUNOPx(catchkid)->op_first);
11968 catchstart = LINKLIST(catchroot);
11969 cLOGOPx(catchkid)->op_other = catchstart;
11971 o->op_next = LINKLIST(o);
11973 /* die within try block should jump to the catch */
11974 enter->op_other = catchkid;
11976 /* after try block that doesn't die, just skip straight to leavetrycatch */
11977 trykid->op_next = o;
11979 /* after catch block, skip back up to the leavetrycatch */
11980 catchroot->op_next = o;
11986 Perl_ck_exec(pTHX_ OP *o)
11988 PERL_ARGS_ASSERT_CK_EXEC;
11990 if (o->op_flags & OPf_STACKED) {
11993 kid = OpSIBLING(cUNOPo->op_first);
11994 if (kid->op_type == OP_RV2GV)
12003 Perl_ck_exists(pTHX_ OP *o)
12005 PERL_ARGS_ASSERT_CK_EXISTS;
12008 if (o->op_flags & OPf_KIDS) {
12009 OP * const kid = cUNOPo->op_first;
12010 if (kid->op_type == OP_ENTERSUB) {
12011 (void) ref(kid, o->op_type);
12012 if (kid->op_type != OP_RV2CV
12013 && !(PL_parser && PL_parser->error_count))
12015 "exists argument is not a subroutine name");
12016 o->op_private |= OPpEXISTS_SUB;
12018 else if (kid->op_type == OP_AELEM)
12019 o->op_flags |= OPf_SPECIAL;
12020 else if (kid->op_type != OP_HELEM)
12021 Perl_croak(aTHX_ "exists argument is not a HASH or ARRAY "
12022 "element or a subroutine");
12029 Perl_ck_rvconst(pTHX_ OP *o)
12031 SVOP * const kid = cSVOPx(cUNOPo->op_first);
12033 PERL_ARGS_ASSERT_CK_RVCONST;
12035 if (o->op_type == OP_RV2HV)
12036 /* rv2hv steals the bottom bit for its own uses */
12037 o->op_private &= ~OPpARG1_MASK;
12039 o->op_private |= (PL_hints & HINT_STRICT_REFS);
12041 if (kid->op_type == OP_CONST) {
12044 SV * const kidsv = kid->op_sv;
12046 /* Is it a constant from cv_const_sv()? */
12047 if ((SvROK(kidsv) || isGV_with_GP(kidsv)) && SvREADONLY(kidsv)) {
12050 if (SvTYPE(kidsv) == SVt_PVAV) return o;
12051 if ((o->op_private & HINT_STRICT_REFS) && (kid->op_private & OPpCONST_BARE)) {
12052 const char *badthing;
12053 switch (o->op_type) {
12055 badthing = "a SCALAR";
12058 badthing = "an ARRAY";
12061 badthing = "a HASH";
12069 "Can't use bareword (\"%" SVf "\") as %s ref while \"strict refs\" in use",
12070 SVfARG(kidsv), badthing);
12073 * This is a little tricky. We only want to add the symbol if we
12074 * didn't add it in the lexer. Otherwise we get duplicate strict
12075 * warnings. But if we didn't add it in the lexer, we must at
12076 * least pretend like we wanted to add it even if it existed before,
12077 * or we get possible typo warnings. OPpCONST_ENTERED says
12078 * whether the lexer already added THIS instance of this symbol.
12080 iscv = o->op_type == OP_RV2CV ? GV_NOEXPAND|GV_ADDMULTI : 0;
12081 gv = gv_fetchsv(kidsv,
12082 o->op_type == OP_RV2CV
12083 && o->op_private & OPpMAY_RETURN_CONSTANT
12085 : iscv | !(kid->op_private & OPpCONST_ENTERED),
12088 : o->op_type == OP_RV2SV
12090 : o->op_type == OP_RV2AV
12092 : o->op_type == OP_RV2HV
12099 if (!(o->op_private & OPpMAY_RETURN_CONSTANT)
12100 && SvTYPE(SvRV(gv)) != SVt_PVCV)
12101 gv_fetchsv(kidsv, GV_ADDMULTI, SVt_PVCV);
12103 OpTYPE_set(kid, OP_GV);
12104 SvREFCNT_dec(kid->op_sv);
12105 #ifdef USE_ITHREADS
12106 /* XXX hack: dependence on sizeof(PADOP) <= sizeof(SVOP) */
12107 STATIC_ASSERT_STMT(sizeof(PADOP) <= sizeof(SVOP));
12108 kPADOP->op_padix = pad_alloc(OP_GV, SVf_READONLY);
12109 SvREFCNT_dec(PAD_SVl(kPADOP->op_padix));
12110 PAD_SETSV(kPADOP->op_padix, MUTABLE_SV(SvREFCNT_inc_simple_NN(gv)));
12112 kid->op_sv = SvREFCNT_inc_simple_NN(gv);
12114 kid->op_private = 0;
12115 /* FAKE globs in the symbol table cause weird bugs (#77810) */
12123 Perl_ck_ftst(pTHX_ OP *o)
12125 const I32 type = o->op_type;
12127 PERL_ARGS_ASSERT_CK_FTST;
12129 if (o->op_flags & OPf_REF) {
12132 else if (o->op_flags & OPf_KIDS && cUNOPo->op_first->op_type != OP_STUB) {
12133 SVOP * const kid = cSVOPx(cUNOPo->op_first);
12134 const OPCODE kidtype = kid->op_type;
12136 if (kidtype == OP_CONST && (kid->op_private & OPpCONST_BARE)
12137 && !kid->op_folded) {
12138 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
12139 no_bareword_filehandle(SvPVX(kSVOP_sv));
12141 OP * const newop = newGVOP(type, OPf_REF,
12142 gv_fetchsv(kid->op_sv, GV_ADD, SVt_PVIO));
12147 if ((kidtype == OP_RV2AV || kidtype == OP_PADAV) && ckWARN(WARN_SYNTAX)) {
12148 SV *name = S_op_varname_subscript(aTHX_ (OP*)kid, 2);
12150 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12151 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s (did you want stat %" SVf "?)",
12152 array_passed_to_stat, name);
12155 /* diag_listed_as: Array passed to stat will be coerced to a scalar%s */
12156 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "%s", array_passed_to_stat);
12159 scalar((OP *) kid);
12160 if ((PL_hints & HINT_FILETEST_ACCESS) && OP_IS_FILETEST_ACCESS(o->op_type))
12161 o->op_private |= OPpFT_ACCESS;
12162 if (OP_IS_FILETEST(type)
12163 && OP_IS_FILETEST(kidtype)
12165 o->op_private |= OPpFT_STACKED;
12166 kid->op_private |= OPpFT_STACKING;
12167 if (kidtype == OP_FTTTY && (
12168 !(kid->op_private & OPpFT_STACKED)
12169 || kid->op_private & OPpFT_AFTER_t
12171 o->op_private |= OPpFT_AFTER_t;
12176 if (type == OP_FTTTY)
12177 o = newGVOP(type, OPf_REF, PL_stdingv);
12179 o = newUNOP(type, 0, newDEFSVOP());
12185 Perl_ck_fun(pTHX_ OP *o)
12187 const int type = o->op_type;
12188 I32 oa = PL_opargs[type] >> OASHIFT;
12190 PERL_ARGS_ASSERT_CK_FUN;
12192 if (o->op_flags & OPf_STACKED) {
12193 if ((oa & OA_OPTIONAL) && (oa >> 4) && !((oa >> 4) & OA_OPTIONAL))
12194 oa &= ~OA_OPTIONAL;
12196 return no_fh_allowed(o);
12199 if (o->op_flags & OPf_KIDS) {
12200 OP *prev_kid = NULL;
12201 OP *kid = cLISTOPo->op_first;
12203 bool seen_optional = FALSE;
12205 if (kid->op_type == OP_PUSHMARK ||
12206 (kid->op_type == OP_NULL && kid->op_targ == OP_PUSHMARK))
12209 kid = OpSIBLING(kid);
12211 if (kid && kid->op_type == OP_COREARGS) {
12212 bool optional = FALSE;
12215 if (oa & OA_OPTIONAL) optional = TRUE;
12218 if (optional) o->op_private |= numargs;
12223 if (oa & OA_OPTIONAL || (oa & 7) == OA_LIST) {
12224 if (!kid && !seen_optional && PL_opargs[type] & OA_DEFGV) {
12225 kid = newDEFSVOP();
12226 /* append kid to chain */
12227 op_sibling_splice(o, prev_kid, 0, kid);
12229 seen_optional = TRUE;
12236 /* list seen where single (scalar) arg expected? */
12237 if (numargs == 1 && !(oa >> 4)
12238 && kid->op_type == OP_LIST && type != OP_SCALAR)
12240 return too_many_arguments_pv(o,PL_op_desc[type], 0);
12242 if (type != OP_DELETE) scalar(kid);
12253 if ((type == OP_PUSH || type == OP_UNSHIFT)
12254 && !OpHAS_SIBLING(kid))
12255 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
12256 "Useless use of %s with no values",
12259 if (kid->op_type == OP_CONST
12260 && ( !SvROK(cSVOPx_sv(kid))
12261 || SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV )
12263 bad_type_pv(numargs, "array", o, kid);
12264 else if (kid->op_type == OP_RV2HV || kid->op_type == OP_PADHV
12265 || kid->op_type == OP_RV2GV) {
12266 bad_type_pv(1, "array", o, kid);
12268 else if (kid->op_type != OP_RV2AV && kid->op_type != OP_PADAV) {
12269 yyerror_pv(Perl_form(aTHX_ "Experimental %s on scalar is now forbidden",
12270 PL_op_desc[type]), 0);
12273 op_lvalue(kid, type);
12277 if (kid->op_type != OP_RV2HV && kid->op_type != OP_PADHV)
12278 bad_type_pv(numargs, "hash", o, kid);
12279 op_lvalue(kid, type);
12283 /* replace kid with newop in chain */
12285 S_op_sibling_newUNOP(aTHX_ o, prev_kid, OP_NULL, 0);
12286 newop->op_next = newop;
12291 if (kid->op_type != OP_GV && kid->op_type != OP_RV2GV) {
12292 if (kid->op_type == OP_CONST &&
12293 (kid->op_private & OPpCONST_BARE))
12295 OP * const newop = newGVOP(OP_GV, 0,
12296 gv_fetchsv(kSVOP->op_sv, GV_ADD, SVt_PVIO));
12297 /* a first argument is handled by toke.c, ideally we'd
12298 just check here but several ops don't use ck_fun() */
12299 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
12300 no_bareword_filehandle(SvPVX(kSVOP_sv));
12302 /* replace kid with newop in chain */
12303 op_sibling_splice(o, prev_kid, 1, newop);
12307 else if (kid->op_type == OP_READLINE) {
12308 /* neophyte patrol: open(<FH>), close(<FH>) etc. */
12309 bad_type_pv(numargs, "HANDLE", o, kid);
12312 I32 flags = OPf_SPECIAL;
12314 PADOFFSET targ = 0;
12316 /* is this op a FH constructor? */
12317 if (is_handle_constructor(o,numargs)) {
12318 const char *name = NULL;
12321 bool want_dollar = TRUE;
12324 /* Set a flag to tell rv2gv to vivify
12325 * need to "prove" flag does not mean something
12326 * else already - NI-S 1999/05/07
12329 if (kid->op_type == OP_PADSV) {
12331 = PAD_COMPNAME_SV(kid->op_targ);
12332 name = PadnamePV (pn);
12333 len = PadnameLEN(pn);
12334 name_utf8 = PadnameUTF8(pn);
12336 else if (kid->op_type == OP_RV2SV
12337 && kUNOP->op_first->op_type == OP_GV)
12339 GV * const gv = cGVOPx_gv(kUNOP->op_first);
12341 len = GvNAMELEN(gv);
12342 name_utf8 = GvNAMEUTF8(gv) ? SVf_UTF8 : 0;
12344 else if (kid->op_type == OP_AELEM
12345 || kid->op_type == OP_HELEM)
12348 OP *op = kBINOP->op_first;
12352 const char * const a =
12353 kid->op_type == OP_AELEM ?
12355 if (((op->op_type == OP_RV2AV) ||
12356 (op->op_type == OP_RV2HV)) &&
12357 (firstop = cUNOPx(op)->op_first) &&
12358 (firstop->op_type == OP_GV)) {
12359 /* packagevar $a[] or $h{} */
12360 GV * const gv = cGVOPx_gv(firstop);
12363 Perl_newSVpvf(aTHX_
12368 else if (op->op_type == OP_PADAV
12369 || op->op_type == OP_PADHV) {
12370 /* lexicalvar $a[] or $h{} */
12371 const char * const padname =
12372 PAD_COMPNAME_PV(op->op_targ);
12375 Perl_newSVpvf(aTHX_
12381 name = SvPV_const(tmpstr, len);
12382 name_utf8 = SvUTF8(tmpstr);
12383 sv_2mortal(tmpstr);
12387 name = "__ANONIO__";
12389 want_dollar = FALSE;
12391 op_lvalue(kid, type);
12395 targ = pad_alloc(OP_RV2GV, SVf_READONLY);
12396 namesv = PAD_SVl(targ);
12397 if (want_dollar && *name != '$')
12398 sv_setpvs(namesv, "$");
12401 sv_catpvn(namesv, name, len);
12402 if ( name_utf8 ) SvUTF8_on(namesv);
12406 kid = S_op_sibling_newUNOP(aTHX_ o, prev_kid,
12408 kid->op_targ = targ;
12409 kid->op_private |= priv;
12415 if ((type == OP_UNDEF || type == OP_POS)
12416 && numargs == 1 && !(oa >> 4)
12417 && kid->op_type == OP_LIST)
12418 return too_many_arguments_pv(o,PL_op_desc[type], 0);
12419 op_lvalue(scalar(kid), type);
12424 kid = OpSIBLING(kid);
12426 /* FIXME - should the numargs or-ing move after the too many
12427 * arguments check? */
12428 o->op_private |= numargs;
12430 return too_many_arguments_pv(o,OP_DESC(o), 0);
12433 else if (PL_opargs[type] & OA_DEFGV) {
12434 /* Ordering of these two is important to keep f_map.t passing. */
12436 return newUNOP(type, 0, newDEFSVOP());
12440 while (oa & OA_OPTIONAL)
12442 if (oa && oa != OA_LIST)
12443 return too_few_arguments_pv(o,OP_DESC(o), 0);
12449 Perl_ck_glob(pTHX_ OP *o)
12453 PERL_ARGS_ASSERT_CK_GLOB;
12456 if ((o->op_flags & OPf_KIDS) && !OpHAS_SIBLING(cLISTOPo->op_first))
12457 op_append_elem(OP_GLOB, o, newDEFSVOP()); /* glob() => glob($_) */
12459 if (!(o->op_flags & OPf_SPECIAL) && (gv = gv_override("glob", 4)))
12463 * \ null - const(wildcard)
12468 * \ mark - glob - rv2cv
12469 * | \ gv(CORE::GLOBAL::glob)
12471 * \ null - const(wildcard)
12473 o->op_flags |= OPf_SPECIAL;
12474 o->op_targ = pad_alloc(OP_GLOB, SVs_PADTMP);
12475 o = S_new_entersubop(aTHX_ gv, o);
12476 o = newUNOP(OP_NULL, 0, o);
12477 o->op_targ = OP_GLOB; /* hint at what it used to be: eg in newWHILEOP */
12480 else o->op_flags &= ~OPf_SPECIAL;
12481 #if !defined(PERL_EXTERNAL_GLOB)
12482 if (!PL_globhook) {
12484 Perl_load_module(aTHX_ PERL_LOADMOD_NOIMPORT,
12485 newSVpvs("File::Glob"), NULL, NULL, NULL);
12488 #endif /* !PERL_EXTERNAL_GLOB */
12489 gv = (GV *)newSV_type(SVt_NULL);
12490 gv_init(gv, 0, "", 0, 0);
12492 op_append_elem(OP_GLOB, o, newGVOP(OP_GV, 0, gv));
12493 SvREFCNT_dec_NN(gv); /* newGVOP increased it */
12499 Perl_ck_grep(pTHX_ OP *o)
12503 const OPCODE type = o->op_type == OP_GREPSTART ? OP_GREPWHILE : OP_MAPWHILE;
12505 PERL_ARGS_ASSERT_CK_GREP;
12507 /* don't allocate gwop here, as we may leak it if PL_parser->error_count > 0 */
12509 if (o->op_flags & OPf_STACKED) {
12510 kid = cUNOPx(OpSIBLING(cLISTOPo->op_first))->op_first;
12511 if (kid->op_type != OP_SCOPE && kid->op_type != OP_LEAVE)
12512 return no_fh_allowed(o);
12513 o->op_flags &= ~OPf_STACKED;
12515 kid = OpSIBLING(cLISTOPo->op_first);
12516 if (type == OP_MAPWHILE)
12521 if (PL_parser && PL_parser->error_count)
12523 kid = OpSIBLING(cLISTOPo->op_first);
12524 if (kid->op_type != OP_NULL)
12525 Perl_croak(aTHX_ "panic: ck_grep, type=%u", (unsigned) kid->op_type);
12526 kid = kUNOP->op_first;
12528 gwop = alloc_LOGOP(type, o, LINKLIST(kid));
12529 kid->op_next = (OP*)gwop;
12530 o->op_private = gwop->op_private = 0;
12531 gwop->op_targ = pad_alloc(type, SVs_PADTMP);
12533 kid = OpSIBLING(cLISTOPo->op_first);
12534 for (kid = OpSIBLING(kid); kid; kid = OpSIBLING(kid))
12535 op_lvalue(kid, OP_GREPSTART);
12541 Perl_ck_index(pTHX_ OP *o)
12543 PERL_ARGS_ASSERT_CK_INDEX;
12545 if (o->op_flags & OPf_KIDS) {
12546 OP *kid = OpSIBLING(cLISTOPo->op_first); /* get past pushmark */
12548 kid = OpSIBLING(kid); /* get past "big" */
12549 if (kid && kid->op_type == OP_CONST) {
12550 const bool save_taint = TAINT_get;
12551 SV *sv = kSVOP->op_sv;
12552 if ( (!SvPOK(sv) || SvNIOKp(sv) || isREGEXP(sv))
12553 && SvOK(sv) && !SvROK(sv))
12555 sv = newSV_type(SVt_NULL);
12556 sv_copypv(sv, kSVOP->op_sv);
12557 SvREFCNT_dec_NN(kSVOP->op_sv);
12560 if (SvOK(sv)) fbm_compile(sv, 0);
12561 TAINT_set(save_taint);
12562 #ifdef NO_TAINT_SUPPORT
12563 PERL_UNUSED_VAR(save_taint);
12571 Perl_ck_lfun(pTHX_ OP *o)
12573 const OPCODE type = o->op_type;
12575 PERL_ARGS_ASSERT_CK_LFUN;
12577 return modkids(ck_fun(o), type);
12581 Perl_ck_defined(pTHX_ OP *o) /* 19990527 MJD */
12583 PERL_ARGS_ASSERT_CK_DEFINED;
12585 if ((o->op_flags & OPf_KIDS)) {
12586 switch (cUNOPo->op_first->op_type) {
12589 Perl_croak(aTHX_ "Can't use 'defined(@array)'"
12590 " (Maybe you should just omit the defined()?)");
12591 NOT_REACHED; /* NOTREACHED */
12595 Perl_croak(aTHX_ "Can't use 'defined(%%hash)'"
12596 " (Maybe you should just omit the defined()?)");
12597 NOT_REACHED; /* NOTREACHED */
12608 Perl_ck_readline(pTHX_ OP *o)
12610 PERL_ARGS_ASSERT_CK_READLINE;
12612 if (o->op_flags & OPf_KIDS) {
12613 OP *kid = cLISTOPo->op_first;
12614 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED
12615 && kid->op_type == OP_CONST && (kid->op_private & OPpCONST_BARE)) {
12616 no_bareword_filehandle(SvPVX(kSVOP_sv));
12618 if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
12623 = newUNOP(OP_READLINE, 0, newGVOP(OP_GV, 0, PL_argvgv));
12631 Perl_ck_rfun(pTHX_ OP *o)
12633 const OPCODE type = o->op_type;
12635 PERL_ARGS_ASSERT_CK_RFUN;
12637 return refkids(ck_fun(o), type);
12641 Perl_ck_listiob(pTHX_ OP *o)
12645 PERL_ARGS_ASSERT_CK_LISTIOB;
12647 kid = cLISTOPo->op_first;
12649 o = force_list(o, TRUE);
12650 kid = cLISTOPo->op_first;
12652 if (kid->op_type == OP_PUSHMARK)
12653 kid = OpSIBLING(kid);
12654 if (kid && o->op_flags & OPf_STACKED)
12655 kid = OpSIBLING(kid);
12656 else if (kid && !OpHAS_SIBLING(kid)) { /* print HANDLE; */
12657 if (kid->op_type == OP_CONST && kid->op_private & OPpCONST_BARE
12658 && !kid->op_folded) {
12659 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
12660 no_bareword_filehandle(SvPVX(kSVOP_sv));
12662 o->op_flags |= OPf_STACKED; /* make it a filehandle */
12664 /* replace old const op with new OP_RV2GV parent */
12665 kid = S_op_sibling_newUNOP(aTHX_ o, cLISTOPo->op_first,
12666 OP_RV2GV, OPf_REF);
12667 kid = OpSIBLING(kid);
12672 op_append_elem(o->op_type, o, newDEFSVOP());
12674 if (o->op_type == OP_PRTF) return modkids(listkids(o), OP_PRTF);
12675 return listkids(o);
12679 Perl_ck_smartmatch(pTHX_ OP *o)
12681 PERL_ARGS_ASSERT_CK_SMARTMATCH;
12682 if (0 == (o->op_flags & OPf_SPECIAL)) {
12683 OP *first = cBINOPo->op_first;
12684 OP *second = OpSIBLING(first);
12686 /* Implicitly take a reference to an array or hash */
12688 /* remove the original two siblings, then add back the
12689 * (possibly different) first and second sibs.
12691 op_sibling_splice(o, NULL, 1, NULL);
12692 op_sibling_splice(o, NULL, 1, NULL);
12693 first = ref_array_or_hash(first);
12694 second = ref_array_or_hash(second);
12695 op_sibling_splice(o, NULL, 0, second);
12696 op_sibling_splice(o, NULL, 0, first);
12698 /* Implicitly take a reference to a regular expression */
12699 if (first->op_type == OP_MATCH && !(first->op_flags & OPf_STACKED)) {
12700 OpTYPE_set(first, OP_QR);
12702 if (second->op_type == OP_MATCH && !(second->op_flags & OPf_STACKED)) {
12703 OpTYPE_set(second, OP_QR);
12712 S_maybe_targlex(pTHX_ OP *o)
12714 OP * const kid = cLISTOPo->op_first;
12715 /* has a disposable target? */
12716 if ((PL_opargs[kid->op_type] & OA_TARGLEX)
12717 && !(kid->op_flags & OPf_STACKED)
12718 /* Cannot steal the second time! */
12719 && !(kid->op_private & OPpTARGET_MY)
12722 OP * const kkid = OpSIBLING(kid);
12724 /* Can just relocate the target. */
12725 if (kkid && kkid->op_type == OP_PADSV
12726 && (!(kkid->op_private & OPpLVAL_INTRO)
12727 || kkid->op_private & OPpPAD_STATE))
12729 kid->op_targ = kkid->op_targ;
12731 /* Now we do not need PADSV and SASSIGN.
12732 * Detach kid and free the rest. */
12733 op_sibling_splice(o, NULL, 1, NULL);
12735 kid->op_private |= OPpTARGET_MY; /* Used for context settings */
12743 Perl_ck_sassign(pTHX_ OP *o)
12745 OP * const kid = cBINOPo->op_first;
12747 PERL_ARGS_ASSERT_CK_SASSIGN;
12749 if (OpHAS_SIBLING(kid)) {
12750 OP *kkid = OpSIBLING(kid);
12751 /* For state variable assignment with attributes, kkid is a list op
12752 whose op_last is a padsv. */
12753 if ((kkid->op_type == OP_PADSV ||
12754 (OP_TYPE_IS_OR_WAS(kkid, OP_LIST) &&
12755 (kkid = cLISTOPx(kkid)->op_last)->op_type == OP_PADSV
12758 && (kkid->op_private & (OPpLVAL_INTRO|OPpPAD_STATE))
12759 == (OPpLVAL_INTRO|OPpPAD_STATE)) {
12760 return S_newONCEOP(aTHX_ o, kkid);
12763 return S_maybe_targlex(aTHX_ o);
12768 Perl_ck_match(pTHX_ OP *o)
12770 PERL_UNUSED_CONTEXT;
12771 PERL_ARGS_ASSERT_CK_MATCH;
12777 Perl_ck_method(pTHX_ OP *o)
12779 SV *sv, *methsv, *rclass;
12780 const char* method;
12783 STRLEN len, nsplit = 0, i;
12785 OP * const kid = cUNOPo->op_first;
12787 PERL_ARGS_ASSERT_CK_METHOD;
12788 if (kid->op_type != OP_CONST) return o;
12792 /* replace ' with :: */
12793 while ((compatptr = (char *) memchr(SvPVX(sv), '\'',
12794 SvEND(sv) - SvPVX(sv) )))
12797 sv_insert(sv, compatptr - SvPVX_const(sv), 0, ":", 1);
12800 method = SvPVX_const(sv);
12802 utf8 = SvUTF8(sv) ? -1 : 1;
12804 for (i = len - 1; i > 0; --i) if (method[i] == ':') {
12809 methsv = newSVpvn_share(method+nsplit, utf8*(len - nsplit), 0);
12811 if (!nsplit) { /* $proto->method() */
12813 return newMETHOP_named(OP_METHOD_NAMED, 0, methsv);
12816 if (memEQs(method, nsplit, "SUPER::")) { /* $proto->SUPER::method() */
12818 return newMETHOP_named(OP_METHOD_SUPER, 0, methsv);
12821 /* $proto->MyClass::method() and $proto->MyClass::SUPER::method() */
12822 if (nsplit >= 9 && strBEGINs(method+nsplit-9, "::SUPER::")) {
12823 rclass = newSVpvn_share(method, utf8*(nsplit-9), 0);
12824 new_op = newMETHOP_named(OP_METHOD_REDIR_SUPER, 0, methsv);
12826 rclass = newSVpvn_share(method, utf8*(nsplit-2), 0);
12827 new_op = newMETHOP_named(OP_METHOD_REDIR, 0, methsv);
12829 #ifdef USE_ITHREADS
12830 op_relocate_sv(&rclass, &cMETHOPx(new_op)->op_rclass_targ);
12832 cMETHOPx(new_op)->op_rclass_sv = rclass;
12839 Perl_ck_null(pTHX_ OP *o)
12841 PERL_ARGS_ASSERT_CK_NULL;
12842 PERL_UNUSED_CONTEXT;
12847 Perl_ck_open(pTHX_ OP *o)
12849 PERL_ARGS_ASSERT_CK_OPEN;
12851 S_io_hints(aTHX_ o);
12853 /* In case of three-arg dup open remove strictness
12854 * from the last arg if it is a bareword. */
12855 OP * const first = cLISTOPx(o)->op_first; /* The pushmark. */
12856 OP * const last = cLISTOPx(o)->op_last; /* The bareword. */
12860 if ((last->op_type == OP_CONST) && /* The bareword. */
12861 (last->op_private & OPpCONST_BARE) &&
12862 (last->op_private & OPpCONST_STRICT) &&
12863 (oa = OpSIBLING(first)) && /* The fh. */
12864 (oa = OpSIBLING(oa)) && /* The mode. */
12865 (oa->op_type == OP_CONST) &&
12866 SvPOK(cSVOPx(oa)->op_sv) &&
12867 (mode = SvPVX_const(cSVOPx(oa)->op_sv)) &&
12868 mode[0] == '>' && mode[1] == '&' && /* A dup open. */
12869 (last == OpSIBLING(oa))) /* The bareword. */
12870 last->op_private &= ~OPpCONST_STRICT;
12876 Perl_ck_prototype(pTHX_ OP *o)
12878 PERL_ARGS_ASSERT_CK_PROTOTYPE;
12879 if (!(o->op_flags & OPf_KIDS)) {
12881 return newUNOP(OP_PROTOTYPE, 0, newDEFSVOP());
12887 Perl_ck_refassign(pTHX_ OP *o)
12889 OP * const right = cLISTOPo->op_first;
12890 OP * const left = OpSIBLING(right);
12891 OP *varop = cUNOPx(cUNOPx(left)->op_first)->op_first;
12894 PERL_ARGS_ASSERT_CK_REFASSIGN;
12896 assert (left->op_type == OP_SREFGEN);
12899 /* we use OPpPAD_STATE in refassign to mean either of those things,
12900 * and the code assumes the two flags occupy the same bit position
12901 * in the various ops below */
12902 assert(OPpPAD_STATE == OPpOUR_INTRO);
12904 switch (varop->op_type) {
12906 o->op_private |= OPpLVREF_AV;
12909 o->op_private |= OPpLVREF_HV;
12913 o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpPAD_STATE));
12914 o->op_targ = varop->op_targ;
12915 varop->op_targ = 0;
12916 PAD_COMPNAME_GEN_set(o->op_targ, PERL_INT_MAX);
12920 o->op_private |= OPpLVREF_AV;
12922 NOT_REACHED; /* NOTREACHED */
12924 o->op_private |= OPpLVREF_HV;
12928 o->op_private |= (varop->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO));
12929 if (cUNOPx(varop)->op_first->op_type != OP_GV) goto bad;
12931 /* Point varop to its GV kid, detached. */
12932 varop = op_sibling_splice(varop, NULL, -1, NULL);
12936 OP * const kidparent =
12937 OpSIBLING(cUNOPx(cUNOPx(varop)->op_first)->op_first);
12938 OP * const kid = cUNOPx(kidparent)->op_first;
12939 o->op_private |= OPpLVREF_CV;
12940 if (kid->op_type == OP_GV) {
12941 SV *sv = (SV*)cGVOPx_gv(kid);
12943 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
12944 /* a CVREF here confuses pp_refassign, so make sure
12946 CV *const cv = (CV*)SvRV(sv);
12947 SV *name_sv = newSVhek_mortal(CvNAME_HEK(cv));
12948 (void)gv_init_sv((GV*)sv, CvSTASH(cv), name_sv, 0);
12949 assert(SvTYPE(sv) == SVt_PVGV);
12951 goto detach_and_stack;
12953 if (kid->op_type != OP_PADCV) goto bad;
12954 o->op_targ = kid->op_targ;
12960 o->op_private |= (varop->op_private & OPpLVAL_INTRO);
12961 o->op_private |= OPpLVREF_ELEM;
12964 /* Detach varop. */
12965 op_sibling_splice(cUNOPx(left)->op_first, NULL, -1, NULL);
12969 /* diag_listed_as: Can't modify reference to %s in %s assignment */
12970 yyerror(Perl_form(aTHX_ "Can't modify reference to %s in scalar "
12975 if (!FEATURE_REFALIASING_IS_ENABLED)
12977 "Experimental aliasing via reference not enabled");
12978 Perl_ck_warner_d(aTHX_
12979 packWARN(WARN_EXPERIMENTAL__REFALIASING),
12980 "Aliasing via reference is experimental");
12982 o->op_flags |= OPf_STACKED;
12983 op_sibling_splice(o, right, 1, varop);
12986 o->op_flags &=~ OPf_STACKED;
12987 op_sibling_splice(o, right, 1, NULL);
12994 Perl_ck_repeat(pTHX_ OP *o)
12996 PERL_ARGS_ASSERT_CK_REPEAT;
12998 if (cBINOPo->op_first->op_flags & OPf_PARENS) {
13000 o->op_private |= OPpREPEAT_DOLIST;
13001 kids = op_sibling_splice(o, NULL, 1, NULL); /* detach first kid */
13002 kids = force_list(kids, TRUE); /* promote it to a list */
13003 op_sibling_splice(o, NULL, 0, kids); /* and add back */
13011 Perl_ck_require(pTHX_ OP *o)
13015 PERL_ARGS_ASSERT_CK_REQUIRE;
13017 if (o->op_flags & OPf_KIDS) { /* Shall we supply missing .pm? */
13018 SVOP * const kid = cSVOPx(cUNOPo->op_first);
13022 if (kid->op_type == OP_CONST) {
13023 SV * const sv = kid->op_sv;
13024 U32 const was_readonly = SvREADONLY(sv);
13025 if (kid->op_private & OPpCONST_BARE) {
13029 if (was_readonly) {
13030 SvREADONLY_off(sv);
13033 if (SvIsCOW(sv)) sv_force_normal_flags(sv, 0);
13038 /* treat ::foo::bar as foo::bar */
13039 if (len >= 2 && s[0] == ':' && s[1] == ':')
13040 DIE(aTHX_ "Bareword in require must not start with a double-colon: \"%s\"\n", s);
13042 DIE(aTHX_ "Bareword in require maps to empty filename");
13044 for (; s < end; s++) {
13045 if (*s == ':' && s[1] == ':') {
13047 Move(s+2, s+1, end - s - 1, char);
13051 SvEND_set(sv, end);
13052 sv_catpvs(sv, ".pm");
13053 PERL_HASH(hash, SvPVX(sv), SvCUR(sv));
13054 hek = share_hek(SvPVX(sv),
13055 (SSize_t)SvCUR(sv) * (SvUTF8(sv) ? -1 : 1),
13057 sv_sethek(sv, hek);
13059 SvFLAGS(sv) |= was_readonly;
13061 else if (SvPOK(sv) && !SvNIOK(sv) && !SvGMAGICAL(sv)
13064 if (SvREFCNT(sv) > 1) {
13065 kid->op_sv = newSVpvn_share(
13066 s, SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len, 0);
13067 SvREFCNT_dec_NN(sv);
13071 if (was_readonly) SvREADONLY_off(sv);
13072 PERL_HASH(hash, s, len);
13074 SvUTF8(sv) ? -(SSize_t)len : (SSize_t)len,
13076 sv_sethek(sv, hek);
13078 SvFLAGS(sv) |= was_readonly;
13084 if (!(o->op_flags & OPf_SPECIAL) /* Wasn't written as CORE::require */
13085 /* handle override, if any */
13086 && (gv = gv_override("require", 7))) {
13088 if (o->op_flags & OPf_KIDS) {
13089 kid = cUNOPo->op_first;
13090 op_sibling_splice(o, NULL, -1, NULL);
13093 kid = newDEFSVOP();
13096 newop = S_new_entersubop(aTHX_ gv, kid);
13104 Perl_ck_return(pTHX_ OP *o)
13108 PERL_ARGS_ASSERT_CK_RETURN;
13110 kid = OpSIBLING(cLISTOPo->op_first);
13111 if (PL_compcv && CvLVALUE(PL_compcv)) {
13112 for (; kid; kid = OpSIBLING(kid))
13113 op_lvalue(kid, OP_LEAVESUBLV);
13120 Perl_ck_select(pTHX_ OP *o)
13124 PERL_ARGS_ASSERT_CK_SELECT;
13126 if (o->op_flags & OPf_KIDS) {
13127 kid = OpSIBLING(cLISTOPo->op_first); /* get past pushmark */
13128 if (kid && OpHAS_SIBLING(kid)) {
13129 OpTYPE_set(o, OP_SSELECT);
13131 return fold_constants(op_integerize(op_std_init(o)));
13135 kid = OpSIBLING(cLISTOPo->op_first); /* get past pushmark */
13136 if (kid && kid->op_type == OP_RV2GV)
13137 kid->op_private &= ~HINT_STRICT_REFS;
13142 Perl_ck_shift(pTHX_ OP *o)
13144 const I32 type = o->op_type;
13146 PERL_ARGS_ASSERT_CK_SHIFT;
13148 if (!(o->op_flags & OPf_KIDS)) {
13151 if (!CvUNIQUE(PL_compcv)) {
13152 o->op_flags |= OPf_SPECIAL;
13156 argop = newUNOP(OP_RV2AV, 0, scalar(newGVOP(OP_GV, 0, PL_argvgv)));
13158 return newUNOP(type, 0, scalar(argop));
13160 return scalar(ck_fun(o));
13164 Perl_ck_sort(pTHX_ OP *o)
13170 PERL_ARGS_ASSERT_CK_SORT;
13172 if (o->op_flags & OPf_STACKED)
13174 firstkid = OpSIBLING(cLISTOPo->op_first); /* get past pushmark */
13177 return too_few_arguments_pv(o,OP_DESC(o), 0);
13179 if ((stacked = o->op_flags & OPf_STACKED)) { /* may have been cleared */
13180 OP *kid = cUNOPx(firstkid)->op_first; /* get past null */
13182 /* if the first arg is a code block, process it and mark sort as
13184 if (kid->op_type == OP_SCOPE || kid->op_type == OP_LEAVE) {
13186 if (kid->op_type == OP_LEAVE)
13187 op_null(kid); /* wipe out leave */
13188 /* Prevent execution from escaping out of the sort block. */
13191 /* provide scalar context for comparison function/block */
13192 kid = scalar(firstkid);
13193 kid->op_next = kid;
13194 o->op_flags |= OPf_SPECIAL;
13196 else if (kid->op_type == OP_CONST
13197 && kid->op_private & OPpCONST_BARE) {
13201 const char * const name = SvPV(kSVOP_sv, len);
13203 assert (len < 256);
13204 Copy(name, tmpbuf+1, len, char);
13205 off = pad_findmy_pvn(tmpbuf, len+1, 0);
13206 if (off != NOT_IN_PAD) {
13207 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
13209 newSVhek(HvNAME_HEK(PAD_COMPNAME_OURSTASH(off)));
13210 sv_catpvs(fq, "::");
13211 sv_catsv(fq, kSVOP_sv);
13212 SvREFCNT_dec_NN(kSVOP_sv);
13216 OP * const padop = newOP(OP_PADCV, 0);
13217 padop->op_targ = off;
13218 /* replace the const op with the pad op */
13219 op_sibling_splice(firstkid, NULL, 1, padop);
13225 firstkid = OpSIBLING(firstkid);
13228 for (kid = firstkid; kid; kid = OpSIBLING(kid)) {
13229 /* provide list context for arguments */
13232 op_lvalue(kid, OP_GREPSTART);
13238 /* for sort { X } ..., where X is one of
13239 * $a <=> $b, $b <=> $a, $a cmp $b, $b cmp $a
13240 * elide the second child of the sort (the one containing X),
13241 * and set these flags as appropriate
13245 * Also, check and warn on lexical $a, $b.
13249 S_simplify_sort(pTHX_ OP *o)
13251 OP *kid = OpSIBLING(cLISTOPo->op_first); /* get past pushmark */
13255 const char *gvname;
13258 PERL_ARGS_ASSERT_SIMPLIFY_SORT;
13260 kid = kUNOP->op_first; /* get past null */
13261 if (!(have_scopeop = kid->op_type == OP_SCOPE)
13262 && kid->op_type != OP_LEAVE)
13264 kid = kLISTOP->op_last; /* get past scope */
13265 switch(kid->op_type) {
13269 if (!have_scopeop) goto padkids;
13274 k = kid; /* remember this node*/
13275 if (kBINOP->op_first->op_type != OP_RV2SV
13276 || kBINOP->op_last ->op_type != OP_RV2SV)
13279 Warn about my($a) or my($b) in a sort block, *if* $a or $b is
13280 then used in a comparison. This catches most, but not
13281 all cases. For instance, it catches
13282 sort { my($a); $a <=> $b }
13284 sort { my($a); $a < $b ? -1 : $a == $b ? 0 : 1; }
13285 (although why you'd do that is anyone's guess).
13289 if (!ckWARN(WARN_SYNTAX)) return;
13290 kid = kBINOP->op_first;
13292 if (kid->op_type == OP_PADSV) {
13293 PADNAME * const name = PAD_COMPNAME(kid->op_targ);
13294 if (PadnameLEN(name) == 2 && *PadnamePV(name) == '$'
13295 && ( PadnamePV(name)[1] == 'a'
13296 || PadnamePV(name)[1] == 'b' ))
13297 /* diag_listed_as: "my %s" used in sort comparison */
13298 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13299 "\"%s %s\" used in sort comparison",
13300 PadnameIsSTATE(name)
13305 } while ((kid = OpSIBLING(kid)));
13308 kid = kBINOP->op_first; /* get past cmp */
13309 if (kUNOP->op_first->op_type != OP_GV)
13311 kid = kUNOP->op_first; /* get past rv2sv */
13313 if (GvSTASH(gv) != PL_curstash)
13315 gvname = GvNAME(gv);
13316 if (*gvname == 'a' && gvname[1] == '\0')
13318 else if (*gvname == 'b' && gvname[1] == '\0')
13323 kid = k; /* back to cmp */
13324 /* already checked above that it is rv2sv */
13325 kid = kBINOP->op_last; /* down to 2nd arg */
13326 if (kUNOP->op_first->op_type != OP_GV)
13328 kid = kUNOP->op_first; /* get past rv2sv */
13330 if (GvSTASH(gv) != PL_curstash)
13332 gvname = GvNAME(gv);
13334 ? !(*gvname == 'a' && gvname[1] == '\0')
13335 : !(*gvname == 'b' && gvname[1] == '\0'))
13337 o->op_flags &= ~(OPf_STACKED | OPf_SPECIAL);
13339 o->op_private |= OPpSORT_DESCEND;
13340 if (k->op_type == OP_NCMP)
13341 o->op_private |= OPpSORT_NUMERIC;
13342 if (k->op_type == OP_I_NCMP)
13343 o->op_private |= OPpSORT_NUMERIC | OPpSORT_INTEGER;
13344 kid = OpSIBLING(cLISTOPo->op_first);
13345 /* cut out and delete old block (second sibling) */
13346 op_sibling_splice(o, cLISTOPo->op_first, 1, NULL);
13351 Perl_ck_split(pTHX_ OP *o)
13356 PERL_ARGS_ASSERT_CK_SPLIT;
13358 assert(o->op_type == OP_LIST);
13360 if (o->op_flags & OPf_STACKED)
13361 return no_fh_allowed(o);
13363 kid = cLISTOPo->op_first;
13364 /* delete leading NULL node, then add a CONST if no other nodes */
13365 assert(kid->op_type == OP_NULL);
13366 op_sibling_splice(o, NULL, 1,
13367 OpHAS_SIBLING(kid) ? NULL : newSVOP(OP_CONST, 0, newSVpvs(" ")));
13369 kid = cLISTOPo->op_first;
13371 if (kid->op_type != OP_MATCH || kid->op_flags & OPf_STACKED) {
13372 /* remove match expression, and replace with new optree with
13373 * a match op at its head */
13374 op_sibling_splice(o, NULL, 1, NULL);
13375 /* pmruntime will handle split " " behavior with flag==2 */
13376 kid = pmruntime(newPMOP(OP_MATCH, 0), kid, NULL, 2, 0);
13377 op_sibling_splice(o, NULL, 0, kid);
13380 assert(kid->op_type == OP_MATCH || kid->op_type == OP_SPLIT);
13382 if (kPMOP->op_pmflags & PMf_GLOBAL) {
13383 Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
13384 "Use of /g modifier is meaningless in split");
13387 /* eliminate the split op, and move the match op (plus any children)
13388 * into its place, then convert the match op into a split op. i.e.
13390 * SPLIT MATCH SPLIT(ex-MATCH)
13392 * MATCH - A - B - C => R - A - B - C => R - A - B - C
13398 * (R, if it exists, will be a regcomp op)
13401 op_sibling_splice(o, NULL, 1, NULL); /* detach match op from o */
13402 sibs = op_sibling_splice(o, NULL, -1, NULL); /* detach any other sibs */
13403 op_sibling_splice(kid, cLISTOPx(kid)->op_last, 0, sibs); /* and reattach */
13404 OpTYPE_set(kid, OP_SPLIT);
13405 kid->op_flags = (o->op_flags | (kid->op_flags & OPf_KIDS));
13406 kid->op_private = o->op_private;
13409 kid = sibs; /* kid is now the string arg of the split */
13412 kid = newDEFSVOP();
13413 op_append_elem(OP_SPLIT, o, kid);
13417 kid = OpSIBLING(kid);
13419 kid = newSVOP(OP_CONST, 0, newSViv(0));
13420 op_append_elem(OP_SPLIT, o, kid);
13421 o->op_private |= OPpSPLIT_IMPLIM;
13425 if (OpHAS_SIBLING(kid))
13426 return too_many_arguments_pv(o,OP_DESC(o), 0);
13432 Perl_ck_stringify(pTHX_ OP *o)
13434 OP * const kid = OpSIBLING(cUNOPo->op_first);
13435 PERL_ARGS_ASSERT_CK_STRINGIFY;
13436 if (( kid->op_type == OP_JOIN || kid->op_type == OP_QUOTEMETA
13437 || kid->op_type == OP_LC || kid->op_type == OP_LCFIRST
13438 || kid->op_type == OP_UC || kid->op_type == OP_UCFIRST)
13439 && !OpHAS_SIBLING(kid)) /* syntax errs can leave extra children */
13441 op_sibling_splice(o, cUNOPo->op_first, -1, NULL);
13449 Perl_ck_join(pTHX_ OP *o)
13451 OP * const kid = OpSIBLING(cLISTOPo->op_first);
13453 PERL_ARGS_ASSERT_CK_JOIN;
13455 if (kid && kid->op_type == OP_MATCH) {
13456 if (ckWARN(WARN_SYNTAX)) {
13457 const REGEXP *re = PM_GETRE(kPMOP);
13459 ? newSVpvn_flags( RX_PRECOMP_const(re), RX_PRELEN(re),
13460 SVs_TEMP | ( RX_UTF8(re) ? SVf_UTF8 : 0 ) )
13461 : newSVpvs_flags( "STRING", SVs_TEMP );
13462 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
13463 "/%" SVf "/ should probably be written as \"%" SVf "\"",
13464 SVfARG(msg), SVfARG(msg));
13468 && (kid->op_type == OP_CONST /* an innocent, unsuspicious separator */
13469 || (kid->op_type == OP_PADSV && !(kid->op_private & OPpLVAL_INTRO))
13470 || ( kid->op_type==OP_RV2SV && kUNOP->op_first->op_type == OP_GV
13471 && !(kid->op_private & (OPpLVAL_INTRO|OPpOUR_INTRO)))))
13473 const OP * const bairn = OpSIBLING(kid); /* the list */
13474 if (bairn && !OpHAS_SIBLING(bairn) /* single-item list */
13475 && OP_GIMME(bairn,0) == G_SCALAR)
13477 OP * const ret = op_convert_list(OP_STRINGIFY, OPf_FOLDED,
13478 op_sibling_splice(o, kid, 1, NULL));
13488 =for apidoc rv2cv_op_cv
13490 Examines an op, which is expected to identify a subroutine at runtime,
13491 and attempts to determine at compile time which subroutine it identifies.
13492 This is normally used during Perl compilation to determine whether
13493 a prototype can be applied to a function call. C<cvop> is the op
13494 being considered, normally an C<rv2cv> op. A pointer to the identified
13495 subroutine is returned, if it could be determined statically, and a null
13496 pointer is returned if it was not possible to determine statically.
13498 Currently, the subroutine can be identified statically if the RV that the
13499 C<rv2cv> is to operate on is provided by a suitable C<gv> or C<const> op.
13500 A C<gv> op is suitable if the GV's CV slot is populated. A C<const> op is
13501 suitable if the constant value must be an RV pointing to a CV. Details of
13502 this process may change in future versions of Perl. If the C<rv2cv> op
13503 has the C<OPpENTERSUB_AMPER> flag set then no attempt is made to identify
13504 the subroutine statically: this flag is used to suppress compile-time
13505 magic on a subroutine call, forcing it to use default runtime behaviour.
13507 If C<flags> has the bit C<RV2CVOPCV_MARK_EARLY> set, then the handling
13508 of a GV reference is modified. If a GV was examined and its CV slot was
13509 found to be empty, then the C<gv> op has the C<OPpEARLY_CV> flag set.
13510 If the op is not optimised away, and the CV slot is later populated with
13511 a subroutine having a prototype, that flag eventually triggers the warning
13512 "called too early to check prototype".
13514 If C<flags> has the bit C<RV2CVOPCV_RETURN_NAME_GV> set, then instead
13515 of returning a pointer to the subroutine it returns a pointer to the
13516 GV giving the most appropriate name for the subroutine in this context.
13517 Normally this is just the C<CvGV> of the subroutine, but for an anonymous
13518 (C<CvANON>) subroutine that is referenced through a GV it will be the
13519 referencing GV. The resulting C<GV*> is cast to C<CV*> to be returned.
13520 A null pointer is returned as usual if there is no statically-determinable
13523 =for apidoc Amnh||OPpEARLY_CV
13524 =for apidoc Amnh||OPpENTERSUB_AMPER
13525 =for apidoc Amnh||RV2CVOPCV_MARK_EARLY
13526 =for apidoc Amnh||RV2CVOPCV_RETURN_NAME_GV
13531 /* shared by toke.c:yylex */
13533 Perl_find_lexical_cv(pTHX_ PADOFFSET off)
13535 PADNAME *name = PAD_COMPNAME(off);
13536 CV *compcv = PL_compcv;
13537 while (PadnameOUTER(name)) {
13538 assert(PARENT_PAD_INDEX(name));
13539 compcv = CvOUTSIDE(compcv);
13540 name = PadlistNAMESARRAY(CvPADLIST(compcv))
13541 [off = PARENT_PAD_INDEX(name)];
13543 assert(!PadnameIsOUR(name));
13544 if (!PadnameIsSTATE(name) && PadnamePROTOCV(name)) {
13545 return PadnamePROTOCV(name);
13547 return (CV *)AvARRAY(PadlistARRAY(CvPADLIST(compcv))[1])[off];
13551 Perl_rv2cv_op_cv(pTHX_ OP *cvop, U32 flags)
13556 PERL_ARGS_ASSERT_RV2CV_OP_CV;
13557 if (flags & ~RV2CVOPCV_FLAG_MASK)
13558 Perl_croak(aTHX_ "panic: rv2cv_op_cv bad flags %x", (unsigned)flags);
13559 if (cvop->op_type != OP_RV2CV)
13561 if (cvop->op_private & OPpENTERSUB_AMPER)
13563 if (!(cvop->op_flags & OPf_KIDS))
13565 rvop = cUNOPx(cvop)->op_first;
13566 switch (rvop->op_type) {
13568 gv = cGVOPx_gv(rvop);
13570 if (SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV) {
13571 cv = MUTABLE_CV(SvRV(gv));
13575 if (flags & RV2CVOPCV_RETURN_STUB)
13581 if (flags & RV2CVOPCV_MARK_EARLY)
13582 rvop->op_private |= OPpEARLY_CV;
13587 SV *rv = cSVOPx_sv(rvop);
13590 cv = (CV*)SvRV(rv);
13594 cv = find_lexical_cv(rvop->op_targ);
13599 } NOT_REACHED; /* NOTREACHED */
13601 if (SvTYPE((SV*)cv) != SVt_PVCV)
13603 if (flags & RV2CVOPCV_RETURN_NAME_GV) {
13604 if ((!CvANON(cv) && !CvLEXICAL(cv)) || !gv)
13608 else if (flags & RV2CVOPCV_MAYBE_NAME_GV) {
13609 if (CvLEXICAL(cv) || CvNAMED(cv))
13611 if (!CvANON(cv) || !gv)
13621 =for apidoc ck_entersub_args_list
13623 Performs the default fixup of the arguments part of an C<entersub>
13624 op tree. This consists of applying list context to each of the
13625 argument ops. This is the standard treatment used on a call marked
13626 with C<&>, or a method call, or a call through a subroutine reference,
13627 or any other call where the callee can't be identified at compile time,
13628 or a call where the callee has no prototype.
13634 Perl_ck_entersub_args_list(pTHX_ OP *entersubop)
13638 PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_LIST;
13640 aop = cUNOPx(entersubop)->op_first;
13641 if (!OpHAS_SIBLING(aop))
13642 aop = cUNOPx(aop)->op_first;
13643 for (aop = OpSIBLING(aop); OpHAS_SIBLING(aop); aop = OpSIBLING(aop)) {
13644 /* skip the extra attributes->import() call implicitly added in
13645 * something like foo(my $x : bar)
13647 if ( aop->op_type == OP_ENTERSUB
13648 && (aop->op_flags & OPf_WANT) == OPf_WANT_VOID
13652 op_lvalue(aop, OP_ENTERSUB);
13658 =for apidoc ck_entersub_args_proto
13660 Performs the fixup of the arguments part of an C<entersub> op tree
13661 based on a subroutine prototype. This makes various modifications to
13662 the argument ops, from applying context up to inserting C<refgen> ops,
13663 and checking the number and syntactic types of arguments, as directed by
13664 the prototype. This is the standard treatment used on a subroutine call,
13665 not marked with C<&>, where the callee can be identified at compile time
13666 and has a prototype.
13668 C<protosv> supplies the subroutine prototype to be applied to the call.
13669 It may be a normal defined scalar, of which the string value will be used.
13670 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13671 that has been cast to C<SV*>) which has a prototype. The prototype
13672 supplied, in whichever form, does not need to match the actual callee
13673 referenced by the op tree.
13675 If the argument ops disagree with the prototype, for example by having
13676 an unacceptable number of arguments, a valid op tree is returned anyway.
13677 The error is reflected in the parser state, normally resulting in a single
13678 exception at the top level of parsing which covers all the compilation
13679 errors that occurred. In the error message, the callee is referred to
13680 by the name defined by the C<namegv> parameter.
13686 Perl_ck_entersub_args_proto(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13689 const char *proto, *proto_end;
13690 OP *aop, *prev, *cvop, *parent;
13693 I32 contextclass = 0;
13694 const char *e = NULL;
13695 PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO;
13696 if (SvTYPE(protosv) == SVt_PVCV ? !SvPOK(protosv) : !SvOK(protosv))
13697 Perl_croak(aTHX_ "panic: ck_entersub_args_proto CV with no proto, "
13698 "flags=%lx", (unsigned long) SvFLAGS(protosv));
13699 if (SvTYPE(protosv) == SVt_PVCV)
13700 proto = CvPROTO(protosv), proto_len = CvPROTOLEN(protosv);
13701 else proto = SvPV(protosv, proto_len);
13702 proto = S_strip_spaces(aTHX_ proto, &proto_len);
13703 proto_end = proto + proto_len;
13704 parent = entersubop;
13705 aop = cUNOPx(entersubop)->op_first;
13706 if (!OpHAS_SIBLING(aop)) {
13708 aop = cUNOPx(aop)->op_first;
13711 aop = OpSIBLING(aop);
13712 for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13713 while (aop != cvop) {
13716 if (proto >= proto_end)
13718 SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13719 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13720 SVfARG(namesv)), SvUTF8(namesv));
13730 /* _ must be at the end */
13731 if (proto[1] && !memCHRs(";@%", proto[1]))
13747 if ( o3->op_type != OP_UNDEF
13748 && (o3->op_type != OP_SREFGEN
13749 || ( cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13751 && cUNOPx(cUNOPx(o3)->op_first)->op_first->op_type
13753 bad_type_gv(arg, namegv, o3,
13754 arg == 1 ? "block or sub {}" : "sub {}");
13757 /* '*' allows any scalar type, including bareword */
13760 if (o3->op_type == OP_RV2GV)
13761 goto wrapref; /* autoconvert GLOB -> GLOBref */
13762 else if (o3->op_type == OP_CONST)
13763 o3->op_private &= ~OPpCONST_STRICT;
13769 if (o3->op_type == OP_RV2AV ||
13770 o3->op_type == OP_PADAV ||
13771 o3->op_type == OP_RV2HV ||
13772 o3->op_type == OP_PADHV
13778 case '[': case ']':
13785 switch (*proto++) {
13787 if (contextclass++ == 0) {
13788 e = (char *) memchr(proto, ']', proto_end - proto);
13789 if (!e || e == proto)
13797 if (contextclass) {
13798 const char *p = proto;
13799 const char *const end = proto;
13801 while (*--p != '[')
13802 /* \[$] accepts any scalar lvalue */
13804 && Perl_op_lvalue_flags(aTHX_
13806 OP_READ, /* not entersub */
13809 bad_type_gv(arg, namegv, o3,
13810 Perl_form(aTHX_ "one of %.*s",(int)(end - p), p));
13815 if (o3->op_type == OP_RV2GV)
13818 bad_type_gv(arg, namegv, o3, "symbol");
13821 if (o3->op_type == OP_ENTERSUB
13822 && !(o3->op_flags & OPf_STACKED))
13825 bad_type_gv(arg, namegv, o3, "subroutine");
13828 if (o3->op_type == OP_RV2SV ||
13829 o3->op_type == OP_PADSV ||
13830 o3->op_type == OP_HELEM ||
13831 o3->op_type == OP_AELEM)
13833 if (!contextclass) {
13834 /* \$ accepts any scalar lvalue */
13835 if (Perl_op_lvalue_flags(aTHX_
13837 OP_READ, /* not entersub */
13840 bad_type_gv(arg, namegv, o3, "scalar");
13844 if (o3->op_type == OP_RV2AV ||
13845 o3->op_type == OP_PADAV)
13847 o3->op_flags &=~ OPf_PARENS;
13851 bad_type_gv(arg, namegv, o3, "array");
13854 if (o3->op_type == OP_RV2HV ||
13855 o3->op_type == OP_PADHV)
13857 o3->op_flags &=~ OPf_PARENS;
13861 bad_type_gv(arg, namegv, o3, "hash");
13864 aop = S_op_sibling_newUNOP(aTHX_ parent, prev,
13866 if (contextclass && e) {
13871 default: goto oops;
13881 Perl_croak(aTHX_ "Malformed prototype for %" SVf ": %" SVf,
13882 SVfARG(cv_name((CV *)namegv, NULL, 0)),
13887 op_lvalue(aop, OP_ENTERSUB);
13889 aop = OpSIBLING(aop);
13891 if (aop == cvop && *proto == '_') {
13892 /* generate an access to $_ */
13893 op_sibling_splice(parent, prev, 0, newDEFSVOP());
13895 if (!optional && proto_end > proto &&
13896 (*proto != '@' && *proto != '%' && *proto != ';' && *proto != '_'))
13898 SV * const namesv = cv_name((CV *)namegv, NULL, 0);
13899 yyerror_pv(Perl_form(aTHX_ "Not enough arguments for %" SVf,
13900 SVfARG(namesv)), SvUTF8(namesv));
13906 =for apidoc ck_entersub_args_proto_or_list
13908 Performs the fixup of the arguments part of an C<entersub> op tree either
13909 based on a subroutine prototype or using default list-context processing.
13910 This is the standard treatment used on a subroutine call, not marked
13911 with C<&>, where the callee can be identified at compile time.
13913 C<protosv> supplies the subroutine prototype to be applied to the call,
13914 or indicates that there is no prototype. It may be a normal scalar,
13915 in which case if it is defined then the string value will be used
13916 as a prototype, and if it is undefined then there is no prototype.
13917 Alternatively, for convenience, it may be a subroutine object (a C<CV*>
13918 that has been cast to C<SV*>), of which the prototype will be used if it
13919 has one. The prototype (or lack thereof) supplied, in whichever form,
13920 does not need to match the actual callee referenced by the op tree.
13922 If the argument ops disagree with the prototype, for example by having
13923 an unacceptable number of arguments, a valid op tree is returned anyway.
13924 The error is reflected in the parser state, normally resulting in a single
13925 exception at the top level of parsing which covers all the compilation
13926 errors that occurred. In the error message, the callee is referred to
13927 by the name defined by the C<namegv> parameter.
13933 Perl_ck_entersub_args_proto_or_list(pTHX_ OP *entersubop,
13934 GV *namegv, SV *protosv)
13936 PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_PROTO_OR_LIST;
13937 if (SvTYPE(protosv) == SVt_PVCV ? SvPOK(protosv) : SvOK(protosv))
13938 return ck_entersub_args_proto(entersubop, namegv, protosv);
13940 return ck_entersub_args_list(entersubop);
13944 Perl_ck_entersub_args_core(pTHX_ OP *entersubop, GV *namegv, SV *protosv)
13946 IV cvflags = SvIVX(protosv);
13947 int opnum = cvflags & 0xffff;
13948 OP *aop = cUNOPx(entersubop)->op_first;
13950 PERL_ARGS_ASSERT_CK_ENTERSUB_ARGS_CORE;
13954 if (!OpHAS_SIBLING(aop))
13955 aop = cUNOPx(aop)->op_first;
13956 aop = OpSIBLING(aop);
13957 for (cvop = aop; OpSIBLING(cvop); cvop = OpSIBLING(cvop)) ;
13959 SV *namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
13960 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
13961 SVfARG(namesv)), SvUTF8(namesv));
13964 op_free(entersubop);
13965 switch(cvflags >> 16) {
13966 case 'F': return newSVOP(OP_CONST, 0,
13967 newSVpv(CopFILE(PL_curcop),0));
13968 case 'L': return newSVOP(
13970 Perl_newSVpvf(aTHX_
13971 "%" IVdf, (IV)CopLINE(PL_curcop)
13974 case 'P': return newSVOP(OP_CONST, 0,
13976 ? newSVhek(HvNAME_HEK(PL_curstash))
13981 NOT_REACHED; /* NOTREACHED */
13984 OP *prev, *cvop, *first, *parent;
13987 parent = entersubop;
13988 if (!OpHAS_SIBLING(aop)) {
13990 aop = cUNOPx(aop)->op_first;
13993 first = prev = aop;
13994 aop = OpSIBLING(aop);
13995 /* find last sibling */
13997 OpHAS_SIBLING(cvop);
13998 prev = cvop, cvop = OpSIBLING(cvop))
14000 if (!(cvop->op_private & OPpENTERSUB_NOPAREN)
14001 /* Usually, OPf_SPECIAL on an op with no args means that it had
14002 * parens, but these have their own meaning for that flag: */
14003 && opnum != OP_VALUES && opnum != OP_KEYS && opnum != OP_EACH
14004 && opnum != OP_DELETE && opnum != OP_EXISTS)
14005 flags |= OPf_SPECIAL;
14006 /* excise cvop from end of sibling chain */
14007 op_sibling_splice(parent, prev, 1, NULL);
14009 if (aop == cvop) aop = NULL;
14011 /* detach remaining siblings from the first sibling, then
14012 * dispose of original optree */
14015 op_sibling_splice(parent, first, -1, NULL);
14016 op_free(entersubop);
14018 if (cvflags == (OP_ENTEREVAL | (1<<16)))
14019 flags |= OPpEVAL_BYTES <<8;
14021 switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14023 case OA_BASEOP_OR_UNOP:
14024 case OA_FILESTATOP:
14026 return newOP(opnum,flags); /* zero args */
14028 return newUNOP(opnum,flags,aop); /* one arg */
14029 /* too many args */
14036 namesv = cv_name((CV *)namegv, NULL, CV_NAME_NOTQUAL);
14037 yyerror_pv(Perl_form(aTHX_ "Too many arguments for %" SVf,
14038 SVfARG(namesv)), SvUTF8(namesv));
14040 nextop = OpSIBLING(aop);
14046 return opnum == OP_RUNCV
14047 ? newSVOP(OP_RUNCV, 0, &PL_sv_undef)
14050 return op_convert_list(opnum,0,aop);
14053 NOT_REACHED; /* NOTREACHED */
14058 =for apidoc cv_get_call_checker_flags
14060 Retrieves the function that will be used to fix up a call to C<cv>.
14061 Specifically, the function is applied to an C<entersub> op tree for a
14062 subroutine call, not marked with C<&>, where the callee can be identified
14063 at compile time as C<cv>.
14065 The C-level function pointer is returned in C<*ckfun_p>, an SV argument
14066 for it is returned in C<*ckobj_p>, and control flags are returned in
14067 C<*ckflags_p>. The function is intended to be called in this manner:
14069 entersubop = (*ckfun_p)(aTHX_ entersubop, namegv, (*ckobj_p));
14071 In this call, C<entersubop> is a pointer to the C<entersub> op,
14072 which may be replaced by the check function, and C<namegv> supplies
14073 the name that should be used by the check function to refer
14074 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14075 It is permitted to apply the check function in non-standard situations,
14076 such as to a call to a different subroutine or to a method call.
14078 C<namegv> may not actually be a GV. If the C<CALL_CHECKER_REQUIRE_GV>
14079 bit is clear in C<*ckflags_p>, it is permitted to pass a CV or other SV
14080 instead, anything that can be used as the first argument to L</cv_name>.
14081 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<*ckflags_p> then the
14082 check function requires C<namegv> to be a genuine GV.
14084 By default, the check function is
14085 L<Perl_ck_entersub_args_proto_or_list|/ck_entersub_args_proto_or_list>,
14086 the SV parameter is C<cv> itself, and the C<CALL_CHECKER_REQUIRE_GV>
14087 flag is clear. This implements standard prototype processing. It can
14088 be changed, for a particular subroutine, by L</cv_set_call_checker_flags>.
14090 If the C<CALL_CHECKER_REQUIRE_GV> bit is set in C<gflags> then it
14091 indicates that the caller only knows about the genuine GV version of
14092 C<namegv>, and accordingly the corresponding bit will always be set in
14093 C<*ckflags_p>, regardless of the check function's recorded requirements.
14094 If the C<CALL_CHECKER_REQUIRE_GV> bit is clear in C<gflags> then it
14095 indicates the caller knows about the possibility of passing something
14096 other than a GV as C<namegv>, and accordingly the corresponding bit may
14097 be either set or clear in C<*ckflags_p>, indicating the check function's
14098 recorded requirements.
14100 C<gflags> is a bitset passed into C<cv_get_call_checker_flags>, in which
14101 only the C<CALL_CHECKER_REQUIRE_GV> bit currently has a defined meaning
14102 (for which see above). All other bits should be clear.
14104 =for apidoc Amnh||CALL_CHECKER_REQUIRE_GV
14106 =for apidoc cv_get_call_checker
14108 The original form of L</cv_get_call_checker_flags>, which does not return
14109 checker flags. When using a checker function returned by this function,
14110 it is only safe to call it with a genuine GV as its C<namegv> argument.
14116 Perl_cv_get_call_checker_flags(pTHX_ CV *cv, U32 gflags,
14117 Perl_call_checker *ckfun_p, SV **ckobj_p, U32 *ckflags_p)
14120 PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER_FLAGS;
14121 PERL_UNUSED_CONTEXT;
14122 callmg = SvMAGICAL((SV*)cv) ? mg_find((SV*)cv, PERL_MAGIC_checkcall) : NULL;
14124 *ckfun_p = DPTR2FPTR(Perl_call_checker, callmg->mg_ptr);
14125 *ckobj_p = callmg->mg_obj;
14126 *ckflags_p = (callmg->mg_flags | gflags) & MGf_REQUIRE_GV;
14128 *ckfun_p = Perl_ck_entersub_args_proto_or_list;
14129 *ckobj_p = (SV*)cv;
14130 *ckflags_p = gflags & MGf_REQUIRE_GV;
14135 Perl_cv_get_call_checker(pTHX_ CV *cv, Perl_call_checker *ckfun_p, SV **ckobj_p)
14138 PERL_ARGS_ASSERT_CV_GET_CALL_CHECKER;
14139 PERL_UNUSED_CONTEXT;
14140 cv_get_call_checker_flags(cv, CALL_CHECKER_REQUIRE_GV, ckfun_p, ckobj_p,
14145 =for apidoc cv_set_call_checker_flags
14147 Sets the function that will be used to fix up a call to C<cv>.
14148 Specifically, the function is applied to an C<entersub> op tree for a
14149 subroutine call, not marked with C<&>, where the callee can be identified
14150 at compile time as C<cv>.
14152 The C-level function pointer is supplied in C<ckfun>, an SV argument for
14153 it is supplied in C<ckobj>, and control flags are supplied in C<ckflags>.
14154 The function should be defined like this:
14156 STATIC OP * ckfun(pTHX_ OP *op, GV *namegv, SV *ckobj)
14158 It is intended to be called in this manner:
14160 entersubop = ckfun(aTHX_ entersubop, namegv, ckobj);
14162 In this call, C<entersubop> is a pointer to the C<entersub> op,
14163 which may be replaced by the check function, and C<namegv> supplies
14164 the name that should be used by the check function to refer
14165 to the callee of the C<entersub> op if it needs to emit any diagnostics.
14166 It is permitted to apply the check function in non-standard situations,
14167 such as to a call to a different subroutine or to a method call.
14169 C<namegv> may not actually be a GV. For efficiency, perl may pass a
14170 CV or other SV instead. Whatever is passed can be used as the first
14171 argument to L</cv_name>. You can force perl to pass a GV by including
14172 C<CALL_CHECKER_REQUIRE_GV> in the C<ckflags>.
14174 C<ckflags> is a bitset, in which only the C<CALL_CHECKER_REQUIRE_GV>
14175 bit currently has a defined meaning (for which see above). All other
14176 bits should be clear.
14178 The current setting for a particular CV can be retrieved by
14179 L</cv_get_call_checker_flags>.
14181 =for apidoc cv_set_call_checker
14183 The original form of L</cv_set_call_checker_flags>, which passes it the
14184 C<CALL_CHECKER_REQUIRE_GV> flag for backward-compatibility. The effect
14185 of that flag setting is that the check function is guaranteed to get a
14186 genuine GV as its C<namegv> argument.
14192 Perl_cv_set_call_checker(pTHX_ CV *cv, Perl_call_checker ckfun, SV *ckobj)
14194 PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER;
14195 cv_set_call_checker_flags(cv, ckfun, ckobj, CALL_CHECKER_REQUIRE_GV);
14199 Perl_cv_set_call_checker_flags(pTHX_ CV *cv, Perl_call_checker ckfun,
14200 SV *ckobj, U32 ckflags)
14202 PERL_ARGS_ASSERT_CV_SET_CALL_CHECKER_FLAGS;
14203 if (ckfun == Perl_ck_entersub_args_proto_or_list && ckobj == (SV*)cv) {
14204 if (SvMAGICAL((SV*)cv))
14205 mg_free_type((SV*)cv, PERL_MAGIC_checkcall);
14208 sv_magic((SV*)cv, &PL_sv_undef, PERL_MAGIC_checkcall, NULL, 0);
14209 callmg = mg_find((SV*)cv, PERL_MAGIC_checkcall);
14211 if (callmg->mg_flags & MGf_REFCOUNTED) {
14212 SvREFCNT_dec(callmg->mg_obj);
14213 callmg->mg_flags &= ~MGf_REFCOUNTED;
14215 callmg->mg_ptr = FPTR2DPTR(char *, ckfun);
14216 callmg->mg_obj = ckobj;
14217 if (ckobj != (SV*)cv) {
14218 SvREFCNT_inc_simple_void_NN(ckobj);
14219 callmg->mg_flags |= MGf_REFCOUNTED;
14221 callmg->mg_flags = (callmg->mg_flags &~ MGf_REQUIRE_GV)
14222 | (U8)(ckflags & MGf_REQUIRE_GV) | MGf_COPY;
14227 S_entersub_alloc_targ(pTHX_ OP * const o)
14229 o->op_targ = pad_alloc(OP_ENTERSUB, SVs_PADTMP);
14230 o->op_private |= OPpENTERSUB_HASTARG;
14234 Perl_ck_subr(pTHX_ OP *o)
14239 SV **const_class = NULL;
14241 PERL_ARGS_ASSERT_CK_SUBR;
14243 aop = cUNOPx(o)->op_first;
14244 if (!OpHAS_SIBLING(aop))
14245 aop = cUNOPx(aop)->op_first;
14246 aop = OpSIBLING(aop);
14247 for (cvop = aop; OpHAS_SIBLING(cvop); cvop = OpSIBLING(cvop)) ;
14248 cv = rv2cv_op_cv(cvop, RV2CVOPCV_MARK_EARLY);
14249 namegv = cv ? (GV*)rv2cv_op_cv(cvop, RV2CVOPCV_MAYBE_NAME_GV) : NULL;
14251 o->op_private &= ~1;
14252 o->op_private |= (PL_hints & HINT_STRICT_REFS);
14253 if (PERLDB_SUB && PL_curstash != PL_debstash)
14254 o->op_private |= OPpENTERSUB_DB;
14255 switch (cvop->op_type) {
14257 o->op_private |= (cvop->op_private & OPpENTERSUB_AMPER);
14261 case OP_METHOD_NAMED:
14262 case OP_METHOD_SUPER:
14263 case OP_METHOD_REDIR:
14264 case OP_METHOD_REDIR_SUPER:
14265 o->op_flags |= OPf_REF;
14266 if (aop->op_type == OP_CONST) {
14267 aop->op_private &= ~OPpCONST_STRICT;
14268 const_class = &cSVOPx(aop)->op_sv;
14270 else if (aop->op_type == OP_LIST) {
14271 OP * const sib = OpSIBLING(cUNOPx(aop)->op_first);
14272 if (sib && sib->op_type == OP_CONST) {
14273 sib->op_private &= ~OPpCONST_STRICT;
14274 const_class = &cSVOPx(sib)->op_sv;
14277 /* make class name a shared cow string to speedup method calls */
14278 /* constant string might be replaced with object, f.e. bigint */
14279 if (const_class && SvPOK(*const_class)) {
14281 const char* str = SvPV(*const_class, len);
14283 SV* const shared = newSVpvn_share(
14284 str, SvUTF8(*const_class)
14285 ? -(SSize_t)len : (SSize_t)len,
14288 if (SvREADONLY(*const_class))
14289 SvREADONLY_on(shared);
14290 SvREFCNT_dec(*const_class);
14291 *const_class = shared;
14298 S_entersub_alloc_targ(aTHX_ o);
14299 return ck_entersub_args_list(o);
14301 Perl_call_checker ckfun;
14304 cv_get_call_checker_flags(cv, 0, &ckfun, &ckobj, &ckflags);
14305 if (CvISXSUB(cv) || !CvROOT(cv))
14306 S_entersub_alloc_targ(aTHX_ o);
14308 /* The original call checker API guarantees that a GV will
14309 be provided with the right name. So, if the old API was
14310 used (or the REQUIRE_GV flag was passed), we have to reify
14311 the CV’s GV, unless this is an anonymous sub. This is not
14312 ideal for lexical subs, as its stringification will include
14313 the package. But it is the best we can do. */
14314 if (ckflags & CALL_CHECKER_REQUIRE_GV) {
14315 if (!CvANON(cv) && (!CvNAMED(cv) || CvNAME_HEK(cv)))
14318 else namegv = MUTABLE_GV(cv);
14319 /* After a syntax error in a lexical sub, the cv that
14320 rv2cv_op_cv returns may be a nameless stub. */
14321 if (!namegv) return ck_entersub_args_list(o);
14324 return ckfun(aTHX_ o, namegv, ckobj);
14329 Perl_ck_svconst(pTHX_ OP *o)
14331 SV * const sv = cSVOPo->op_sv;
14332 PERL_ARGS_ASSERT_CK_SVCONST;
14333 PERL_UNUSED_CONTEXT;
14334 #ifdef PERL_COPY_ON_WRITE
14335 /* Since the read-only flag may be used to protect a string buffer, we
14336 cannot do copy-on-write with existing read-only scalars that are not
14337 already copy-on-write scalars. To allow $_ = "hello" to do COW with
14338 that constant, mark the constant as COWable here, if it is not
14339 already read-only. */
14340 if (!SvREADONLY(sv) && !SvIsCOW(sv) && SvCANCOW(sv)) {
14343 # ifdef PERL_DEBUG_READONLY_COW
14353 Perl_ck_trunc(pTHX_ OP *o)
14355 PERL_ARGS_ASSERT_CK_TRUNC;
14357 if (o->op_flags & OPf_KIDS) {
14358 SVOP *kid = cSVOPx(cUNOPo->op_first);
14360 if (kid->op_type == OP_NULL)
14361 kid = cSVOPx(OpSIBLING(kid));
14362 if (kid && kid->op_type == OP_CONST &&
14363 (kid->op_private & OPpCONST_BARE) &&
14366 o->op_flags |= OPf_SPECIAL;
14367 kid->op_private &= ~OPpCONST_STRICT;
14368 if (!FEATURE_BAREWORD_FILEHANDLES_IS_ENABLED) {
14369 no_bareword_filehandle(SvPVX(cSVOPx_sv(kid)));
14377 Perl_ck_substr(pTHX_ OP *o)
14379 PERL_ARGS_ASSERT_CK_SUBSTR;
14382 if ((o->op_flags & OPf_KIDS) && (o->op_private == 4)) {
14383 OP *kid = cLISTOPo->op_first;
14385 if (kid->op_type == OP_NULL)
14386 kid = OpSIBLING(kid);
14388 /* Historically, substr(delete $foo{bar},...) has been allowed
14389 with 4-arg substr. Keep it working by applying entersub
14391 op_lvalue(kid, OP_ENTERSUB);
14398 Perl_ck_tell(pTHX_ OP *o)
14400 PERL_ARGS_ASSERT_CK_TELL;
14402 if (o->op_flags & OPf_KIDS) {
14403 OP *kid = cLISTOPo->op_first;
14404 if (kid->op_type == OP_NULL && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid);
14405 if (kid->op_type == OP_RV2GV) kid->op_private |= OPpALLOW_FAKE;
14410 PERL_STATIC_INLINE OP *
14411 S_last_non_null_kid(OP *o) {
14413 if (cUNOPo->op_flags & OPf_KIDS) {
14414 OP *k = cLISTOPo->op_first;
14416 if (k->op_type != OP_NULL) {
14427 Perl_ck_each(pTHX_ OP *o)
14429 OP *kid = o->op_flags & OPf_KIDS ? cUNOPo->op_first : NULL;
14430 const unsigned orig_type = o->op_type;
14432 PERL_ARGS_ASSERT_CK_EACH;
14435 switch (kid->op_type) {
14440 /* Catch out an anonhash here, since the behaviour might be
14443 * The typical tree is:
14450 * If the contents of the block is more complex you might get:
14458 * Similarly for the anonlist version below.
14460 if (orig_type == OP_EACH &&
14461 ckWARN(WARN_SYNTAX) &&
14462 (cUNOPx(kid)->op_flags & OPf_KIDS) &&
14463 ( cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
14464 cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
14465 (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
14466 /* look for last non-null kid, since we might have:
14467 each %{ some code ; +{ anon hash } }
14469 OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
14470 if (k && k->op_type == OP_ANONHASH) {
14471 /* diag_listed_as: each on anonymous %s will always start from the beginning */
14472 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous hash will always start from the beginning");
14477 if (orig_type == OP_EACH &&
14478 ckWARN(WARN_SYNTAX) &&
14479 (cUNOPx(kid)->op_flags & OPf_KIDS) &&
14480 (cUNOPx(kid)->op_first->op_type == OP_SCOPE ||
14481 cUNOPx(kid)->op_first->op_type == OP_LEAVE) &&
14482 (cUNOPx(kid)->op_first->op_flags & OPf_KIDS)) {
14483 OP *k = S_last_non_null_kid(cUNOPx(kid)->op_first);
14484 if (k && k->op_type == OP_ANONLIST) {
14485 /* diag_listed_as: each on anonymous %s will always start from the beginning */
14486 Perl_warner(aTHX_ packWARN(WARN_SYNTAX), "each on anonymous array will always start from the beginning");
14491 OpTYPE_set(o, orig_type == OP_EACH ? OP_AEACH
14492 : orig_type == OP_KEYS ? OP_AKEYS
14496 if (kid->op_private == OPpCONST_BARE
14497 || !SvROK(cSVOPx_sv(kid))
14498 || ( SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVAV
14499 && SvTYPE(SvRV(cSVOPx_sv(kid))) != SVt_PVHV )
14504 qerror(Perl_mess(aTHX_
14505 "Experimental %s on scalar is now forbidden",
14506 PL_op_desc[orig_type]));
14508 bad_type_pv(1, "hash or array", o, kid);
14516 Perl_ck_length(pTHX_ OP *o)
14518 PERL_ARGS_ASSERT_CK_LENGTH;
14522 if (ckWARN(WARN_SYNTAX)) {
14523 const OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : NULL;
14527 const bool hash = kid->op_type == OP_PADHV
14528 || kid->op_type == OP_RV2HV;
14529 switch (kid->op_type) {
14534 name = op_varname(kid);
14540 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14541 "length() used on %" SVf " (did you mean \"scalar(%s%" SVf
14543 SVfARG(name), hash ? "keys " : "", SVfARG(name)
14546 /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
14547 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14548 "length() used on %%hash (did you mean \"scalar(keys %%hash)\"?)");
14550 /* diag_listed_as: length() used on %s (did you mean "scalar(%s)"?) */
14551 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
14552 "length() used on @array (did you mean \"scalar(@array)\"?)");
14561 Perl_ck_isa(pTHX_ OP *o)
14563 OP *classop = cBINOPo->op_last;
14565 PERL_ARGS_ASSERT_CK_ISA;
14567 /* Convert barename into PV */
14568 if(classop->op_type == OP_CONST && classop->op_private & OPpCONST_BARE) {
14569 /* TODO: Optionally convert package to raw HV here */
14570 classop->op_private &= ~(OPpCONST_BARE|OPpCONST_STRICT);
14577 /* Check for in place reverse and sort assignments like "@a = reverse @a"
14578 and modify the optree to make them work inplace */
14581 S_inplace_aassign(pTHX_ OP *o) {
14583 OP *modop, *modop_pushmark;
14585 OP *oleft, *oleft_pushmark;
14587 PERL_ARGS_ASSERT_INPLACE_AASSIGN;
14589 assert((o->op_flags & OPf_WANT) == OPf_WANT_VOID);
14591 assert(cUNOPo->op_first->op_type == OP_NULL);
14592 modop_pushmark = cUNOPx(cUNOPo->op_first)->op_first;
14593 assert(modop_pushmark->op_type == OP_PUSHMARK);
14594 modop = OpSIBLING(modop_pushmark);
14596 if (modop->op_type != OP_SORT && modop->op_type != OP_REVERSE)
14599 /* no other operation except sort/reverse */
14600 if (OpHAS_SIBLING(modop))
14603 assert(cUNOPx(modop)->op_first->op_type == OP_PUSHMARK);
14604 if (!(oright = OpSIBLING(cUNOPx(modop)->op_first))) return;
14606 if (modop->op_flags & OPf_STACKED) {
14607 /* skip sort subroutine/block */
14608 assert(oright->op_type == OP_NULL);
14609 oright = OpSIBLING(oright);
14612 assert(OpSIBLING(cUNOPo->op_first)->op_type == OP_NULL);
14613 oleft_pushmark = cUNOPx(OpSIBLING(cUNOPo->op_first))->op_first;
14614 assert(oleft_pushmark->op_type == OP_PUSHMARK);
14615 oleft = OpSIBLING(oleft_pushmark);
14617 /* Check the lhs is an array */
14619 (oleft->op_type != OP_RV2AV && oleft->op_type != OP_PADAV)
14620 || OpHAS_SIBLING(oleft)
14621 || (oleft->op_private & OPpLVAL_INTRO)
14625 /* Only one thing on the rhs */
14626 if (OpHAS_SIBLING(oright))
14629 /* check the array is the same on both sides */
14630 if (oleft->op_type == OP_RV2AV) {
14631 if (oright->op_type != OP_RV2AV
14632 || !cUNOPx(oright)->op_first
14633 || cUNOPx(oright)->op_first->op_type != OP_GV
14634 || cUNOPx(oleft )->op_first->op_type != OP_GV
14635 || cGVOPx_gv(cUNOPx(oleft)->op_first) !=
14636 cGVOPx_gv(cUNOPx(oright)->op_first)
14640 else if (oright->op_type != OP_PADAV
14641 || oright->op_targ != oleft->op_targ
14645 /* This actually is an inplace assignment */
14647 modop->op_private |= OPpSORT_INPLACE;
14649 /* transfer MODishness etc from LHS arg to RHS arg */
14650 oright->op_flags = oleft->op_flags;
14652 /* remove the aassign op and the lhs */
14654 op_null(oleft_pushmark);
14655 if (oleft->op_type == OP_RV2AV && cUNOPx(oleft)->op_first)
14656 op_null(cUNOPx(oleft)->op_first);
14662 =for apidoc_section $custom
14664 =for apidoc Perl_custom_op_xop
14665 Return the XOP structure for a given custom op. This macro should be
14666 considered internal to C<OP_NAME> and the other access macros: use them instead.
14667 This macro does call a function. Prior
14668 to 5.19.6, this was implemented as a
14675 /* use PERL_MAGIC_ext to call a function to free the xop structure when
14676 * freeing PL_custom_ops */
14679 custom_op_register_free(pTHX_ SV *sv, MAGIC *mg)
14683 PERL_UNUSED_ARG(mg);
14684 xop = INT2PTR(XOP *, SvIV(sv));
14685 Safefree(xop->xop_name);
14686 Safefree(xop->xop_desc);
14692 static const MGVTBL custom_op_register_vtbl = {
14697 custom_op_register_free, /* free */
14707 Perl_custom_op_get_field(pTHX_ const OP *o, const xop_flags_enum field)
14713 static const XOP xop_null = { 0, 0, 0, 0, 0 };
14715 PERL_ARGS_ASSERT_CUSTOM_OP_GET_FIELD;
14716 assert(o->op_type == OP_CUSTOM);
14718 /* This is wrong. It assumes a function pointer can be cast to IV,
14719 * which isn't guaranteed, but this is what the old custom OP code
14720 * did. In principle it should be safer to Copy the bytes of the
14721 * pointer into a PV: since the new interface is hidden behind
14722 * functions, this can be changed later if necessary. */
14723 /* Change custom_op_xop if this ever happens */
14724 keysv = sv_2mortal(newSViv(PTR2IV(o->op_ppaddr)));
14727 he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14729 /* See if the op isn't registered, but its name *is* registered.
14730 * That implies someone is using the pre-5.14 API,where only name and
14731 * description could be registered. If so, fake up a real
14733 * We only check for an existing name, and assume no one will have
14734 * just registered a desc */
14735 if (!he && PL_custom_op_names &&
14736 (he = hv_fetch_ent(PL_custom_op_names, keysv, 0, 0))
14741 /* XXX does all this need to be shared mem? */
14742 Newxz(xop, 1, XOP);
14743 pv = SvPV(HeVAL(he), l);
14744 XopENTRY_set(xop, xop_name, savepvn(pv, l));
14745 if (PL_custom_op_descs &&
14746 (he = hv_fetch_ent(PL_custom_op_descs, keysv, 0, 0))
14748 pv = SvPV(HeVAL(he), l);
14749 XopENTRY_set(xop, xop_desc, savepvn(pv, l));
14751 Perl_custom_op_register(aTHX_ o->op_ppaddr, xop);
14752 he = hv_fetch_ent(PL_custom_ops, keysv, 0, 0);
14753 /* add magic to the SV so that the xop struct (pointed to by
14754 * SvIV(sv)) is freed. Normally a static xop is registered, but
14755 * for this backcompat hack, we've alloced one */
14756 (void)sv_magicext(HeVAL(he), NULL, PERL_MAGIC_ext,
14757 &custom_op_register_vtbl, NULL, 0);
14762 xop = (XOP *)&xop_null;
14764 xop = INT2PTR(XOP *, SvIV(HeVAL(he)));
14769 if(field == XOPe_xop_ptr) {
14772 const U32 flags = XopFLAGS(xop);
14773 if(flags & field) {
14775 case XOPe_xop_name:
14776 any.xop_name = xop->xop_name;
14778 case XOPe_xop_desc:
14779 any.xop_desc = xop->xop_desc;
14781 case XOPe_xop_class:
14782 any.xop_class = xop->xop_class;
14784 case XOPe_xop_peep:
14785 any.xop_peep = xop->xop_peep;
14790 "panic: custom_op_get_field(): invalid field %d\n",
14796 case XOPe_xop_name:
14797 any.xop_name = XOPd_xop_name;
14799 case XOPe_xop_desc:
14800 any.xop_desc = XOPd_xop_desc;
14802 case XOPe_xop_class:
14803 any.xop_class = XOPd_xop_class;
14805 case XOPe_xop_peep:
14806 any.xop_peep = XOPd_xop_peep;
14819 =for apidoc custom_op_register
14820 Register a custom op. See L<perlguts/"Custom Operators">.
14826 Perl_custom_op_register(pTHX_ Perl_ppaddr_t ppaddr, const XOP *xop)
14830 PERL_ARGS_ASSERT_CUSTOM_OP_REGISTER;
14832 /* see the comment in custom_op_xop */
14833 keysv = sv_2mortal(newSViv(PTR2IV(ppaddr)));
14835 if (!PL_custom_ops)
14836 PL_custom_ops = newHV();
14838 if (!hv_store_ent(PL_custom_ops, keysv, newSViv(PTR2IV(xop)), 0))
14839 Perl_croak(aTHX_ "panic: can't register custom OP %s", xop->xop_name);
14844 =for apidoc core_prototype
14846 This function assigns the prototype of the named core function to C<sv>, or
14847 to a new mortal SV if C<sv> is C<NULL>. It returns the modified C<sv>, or
14848 C<NULL> if the core function has no prototype. C<code> is a code as returned
14849 by C<keyword()>. It must not be equal to 0.
14855 Perl_core_prototype(pTHX_ SV *sv, const char *name, const int code,
14858 int i = 0, n = 0, seen_question = 0, defgv = 0;
14860 #define MAX_ARGS_OP ((sizeof(I32) - 1) * 2)
14861 char str[ MAX_ARGS_OP * 2 + 2 ]; /* One ';', one '\0' */
14862 bool nullret = FALSE;
14864 PERL_ARGS_ASSERT_CORE_PROTOTYPE;
14868 if (!sv) sv = sv_newmortal();
14870 #define retsetpvs(x,y) sv_setpvs(sv, x); if(opnum) *opnum=(y); return sv
14872 switch (code < 0 ? -code : code) {
14873 case KEY_and : case KEY_chop: case KEY_chomp:
14874 case KEY_cmp : case KEY_defined: case KEY_delete: case KEY_exec :
14875 case KEY_exists: case KEY_eq : case KEY_ge : case KEY_goto :
14876 case KEY_grep : case KEY_gt : case KEY_last : case KEY_le :
14877 case KEY_lt : case KEY_map : case KEY_ne : case KEY_next :
14878 case KEY_or : case KEY_print : case KEY_printf: case KEY_qr :
14879 case KEY_redo : case KEY_require: case KEY_return: case KEY_say :
14880 case KEY_select: case KEY_sort : case KEY_split : case KEY_system:
14881 case KEY_x : case KEY_xor :
14882 if (!opnum) return NULL; nullret = TRUE; goto findopnum;
14883 case KEY_glob: retsetpvs("_;", OP_GLOB);
14884 case KEY_keys: retsetpvs("\\[%@]", OP_KEYS);
14885 case KEY_values: retsetpvs("\\[%@]", OP_VALUES);
14886 case KEY_each: retsetpvs("\\[%@]", OP_EACH);
14887 case KEY_pos: retsetpvs(";\\[$*]", OP_POS);
14888 case KEY___FILE__: case KEY___LINE__: case KEY___PACKAGE__:
14890 case KEY_evalbytes:
14891 name = "entereval"; break;
14899 while (i < MAXO) { /* The slow way. */
14900 if (strEQ(name, PL_op_name[i])
14901 || strEQ(name, PL_op_desc[i]))
14903 if (nullret) { assert(opnum); *opnum = i; return NULL; }
14910 defgv = PL_opargs[i] & OA_DEFGV;
14911 oa = PL_opargs[i] >> OASHIFT;
14913 if (oa & OA_OPTIONAL && !seen_question && (
14914 !defgv || (oa & (OA_OPTIONAL - 1)) == OA_FILEREF
14919 if ((oa & (OA_OPTIONAL - 1)) >= OA_AVREF
14920 && (oa & (OA_OPTIONAL - 1)) <= OA_SCALARREF
14921 /* But globs are already references (kinda) */
14922 && (oa & (OA_OPTIONAL - 1)) != OA_FILEREF
14926 if ((oa & (OA_OPTIONAL - 1)) == OA_SCALARREF
14927 && !scalar_mod_type(NULL, i)) {
14932 if (i == OP_LOCK || i == OP_UNDEF) str[n++] = '&';
14936 else str[n++] = ("?$@@%&*$")[oa & (OA_OPTIONAL - 1)];
14937 if (oa & OA_OPTIONAL && defgv && str[n-1] == '$') {
14938 str[n-1] = '_'; defgv = 0;
14942 if (code == -KEY_not || code == -KEY_getprotobynumber) str[n++] = ';';
14944 sv_setpvn(sv, str, n - 1);
14945 if (opnum) *opnum = i;
14950 Perl_coresub_op(pTHX_ SV * const coreargssv, const int code,
14953 OP * const argop = (opnum == OP_SELECT && code) ? NULL :
14954 newSVOP(OP_COREARGS,0,coreargssv);
14957 PERL_ARGS_ASSERT_CORESUB_OP;
14961 return op_append_elem(OP_LINESEQ,
14964 newSVOP(OP_CONST, 0, newSViv(-code % 3)),
14971 o = newUNOP(OP_AVHVSWITCH,0,argop);
14972 o->op_private = opnum-OP_EACH;
14974 case OP_SELECT: /* which represents OP_SSELECT as well */
14979 newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
14980 newSVOP(OP_CONST, 0, newSVuv(1))
14982 coresub_op(newSVuv((UV)OP_SSELECT), 0,
14984 coresub_op(coreargssv, 0, OP_SELECT)
14988 switch (PL_opargs[opnum] & OA_CLASS_MASK) {
14990 return op_append_elem(
14993 opnum == OP_WANTARRAY || opnum == OP_RUNCV
14994 ? OPpOFFBYONE << 8 : 0)
14996 case OA_BASEOP_OR_UNOP:
14997 if (opnum == OP_ENTEREVAL) {
14998 o = newUNOP(OP_ENTEREVAL,OPpEVAL_COPHH<<8,argop);
14999 if (code == -KEY_evalbytes) o->op_private |= OPpEVAL_BYTES;
15001 else o = newUNOP(opnum,0,argop);
15002 if (opnum == OP_CALLER) o->op_private |= OPpOFFBYONE;
15005 if (is_handle_constructor(o, 1))
15006 argop->op_private |= OPpCOREARGS_DEREF1;
15007 if (scalar_mod_type(NULL, opnum))
15008 argop->op_private |= OPpCOREARGS_SCALARMOD;
15012 o = op_convert_list(opnum,OPf_SPECIAL*(opnum == OP_GLOB),argop);
15013 if (is_handle_constructor(o, 2))
15014 argop->op_private |= OPpCOREARGS_DEREF2;
15015 if (opnum == OP_SUBSTR) {
15016 o->op_private |= OPpMAYBE_LVSUB;
15025 Perl_report_redefined_cv(pTHX_ const SV *name, const CV *old_cv,
15026 SV * const *new_const_svp)
15028 const char *hvname;
15029 bool is_const = cBOOL(CvCONST(old_cv));
15030 SV *old_const_sv = is_const ? cv_const_sv(old_cv) : NULL;
15032 PERL_ARGS_ASSERT_REPORT_REDEFINED_CV;
15034 if (is_const && new_const_svp && old_const_sv == *new_const_svp)
15036 /* They are 2 constant subroutines generated from
15037 the same constant. This probably means that
15038 they are really the "same" proxy subroutine
15039 instantiated in 2 places. Most likely this is
15040 when a constant is exported twice. Don't warn.
15043 (ckWARN(WARN_REDEFINE)
15045 CvGV(old_cv) && GvSTASH(CvGV(old_cv))
15046 && HvNAMELEN(GvSTASH(CvGV(old_cv))) == 7
15047 && (hvname = HvNAME(GvSTASH(CvGV(old_cv))),
15048 strEQ(hvname, "autouse"))
15052 && ckWARN_d(WARN_REDEFINE)
15053 && (!new_const_svp || sv_cmp(old_const_sv, *new_const_svp))
15056 Perl_warner(aTHX_ packWARN(WARN_REDEFINE),
15058 ? "Constant subroutine %" SVf " redefined"
15059 : "Subroutine %" SVf " redefined",
15064 =for apidoc_section $hook
15066 These functions provide convenient and thread-safe means of manipulating
15073 =for apidoc wrap_op_checker
15075 Puts a C function into the chain of check functions for a specified op
15076 type. This is the preferred way to manipulate the L</PL_check> array.
15077 C<opcode> specifies which type of op is to be affected. C<new_checker>
15078 is a pointer to the C function that is to be added to that opcode's
15079 check chain, and C<old_checker_p> points to the storage location where a
15080 pointer to the next function in the chain will be stored. The value of
15081 C<new_checker> is written into the L</PL_check> array, while the value
15082 previously stored there is written to C<*old_checker_p>.
15084 L</PL_check> is global to an entire process, and a module wishing to
15085 hook op checking may find itself invoked more than once per process,
15086 typically in different threads. To handle that situation, this function
15087 is idempotent. The location C<*old_checker_p> must initially (once
15088 per process) contain a null pointer. A C variable of static duration
15089 (declared at file scope, typically also marked C<static> to give
15090 it internal linkage) will be implicitly initialised appropriately,
15091 if it does not have an explicit initialiser. This function will only
15092 actually modify the check chain if it finds C<*old_checker_p> to be null.
15093 This function is also thread safe on the small scale. It uses appropriate
15094 locking to avoid race conditions in accessing L</PL_check>.
15096 When this function is called, the function referenced by C<new_checker>
15097 must be ready to be called, except for C<*old_checker_p> being unfilled.
15098 In a threading situation, C<new_checker> may be called immediately,
15099 even before this function has returned. C<*old_checker_p> will always
15100 be appropriately set before C<new_checker> is called. If C<new_checker>
15101 decides not to do anything special with an op that it is given (which
15102 is the usual case for most uses of op check hooking), it must chain the
15103 check function referenced by C<*old_checker_p>.
15105 Taken all together, XS code to hook an op checker should typically look
15106 something like this:
15108 static Perl_check_t nxck_frob;
15109 static OP *myck_frob(pTHX_ OP *op) {
15111 op = nxck_frob(aTHX_ op);
15116 wrap_op_checker(OP_FROB, myck_frob, &nxck_frob);
15118 If you want to influence compilation of calls to a specific subroutine,
15119 then use L</cv_set_call_checker_flags> rather than hooking checking of
15120 all C<entersub> ops.
15126 Perl_wrap_op_checker(pTHX_ Optype opcode,
15127 Perl_check_t new_checker, Perl_check_t *old_checker_p)
15130 PERL_UNUSED_CONTEXT;
15131 PERL_ARGS_ASSERT_WRAP_OP_CHECKER;
15132 if (*old_checker_p) return;
15133 OP_CHECK_MUTEX_LOCK;
15134 if (!*old_checker_p) {
15135 *old_checker_p = PL_check[opcode];
15136 PL_check[opcode] = new_checker;
15138 OP_CHECK_MUTEX_UNLOCK;
15143 /* Efficient sub that returns a constant scalar value. */
15145 const_sv_xsub(pTHX_ CV* cv)
15148 SV *const sv = MUTABLE_SV(XSANY.any_ptr);
15149 PERL_UNUSED_ARG(items);
15159 const_av_xsub(pTHX_ CV* cv)
15162 AV * const av = MUTABLE_AV(XSANY.any_ptr);
15170 if (SvRMAGICAL(av))
15171 Perl_croak(aTHX_ "Magical list constants are not supported");
15172 if (GIMME_V != G_LIST) {
15174 ST(0) = sv_2mortal(newSViv((IV)AvFILLp(av)+1));
15177 EXTEND(SP, AvFILLp(av)+1);
15178 Copy(AvARRAY(av), &ST(0), AvFILLp(av)+1, SV *);
15179 XSRETURN(AvFILLp(av)+1);
15182 /* Copy an existing cop->cop_warnings field.
15183 * If it's one of the standard addresses, just re-use the address.
15184 * This is the e implementation for the DUP_WARNINGS() macro
15188 Perl_dup_warnings(pTHX_ STRLEN* warnings)
15191 STRLEN *new_warnings;
15193 if (warnings == NULL || specialWARN(warnings))
15196 size = sizeof(*warnings) + *warnings;
15198 new_warnings = (STRLEN*)PerlMemShared_malloc(size);
15199 Copy(warnings, new_warnings, size, char);
15200 return new_warnings;
15204 * ex: set ts=8 sts=4 sw=4 et: