This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
amigaos4: add amigaos the glue code
[perl5.git] / pad.c
1 /*    pad.c
2  *
3  *    Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007, 2008
4  *    by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  */
9
10 /*
11  *  'Anyway: there was this Mr. Frodo left an orphan and stranded, as you
12  *   might say, among those queer Bucklanders, being brought up anyhow in
13  *   Brandy Hall.  A regular warren, by all accounts.  Old Master Gorbadoc
14  *   never had fewer than a couple of hundred relations in the place.
15  *   Mr. Bilbo never did a kinder deed than when he brought the lad back
16  *   to live among decent folk.'                           --the Gaffer
17  *
18  *     [p.23 of _The Lord of the Rings_, I/i: "A Long-Expected Party"]
19  */
20
21 /* XXX DAPM
22  * As of Sept 2002, this file is new and may be in a state of flux for
23  * a while. I've marked things I intent to come back and look at further
24  * with an 'XXX DAPM' comment.
25  */
26
27 /*
28 =head1 Pad Data Structures
29
30 =for apidoc Amx|PADLIST *|CvPADLIST|CV *cv
31
32 CV's can have CvPADLIST(cv) set to point to a PADLIST.  This is the CV's
33 scratchpad, which stores lexical variables and opcode temporary and
34 per-thread values.
35
36 For these purposes "formats" are a kind-of CV; eval""s are too (except they're
37 not callable at will and are always thrown away after the eval"" is done
38 executing).  Require'd files are simply evals without any outer lexical
39 scope.
40
41 XSUBs do not have a C<CvPADLIST>.  C<dXSTARG> fetches values from C<PL_curpad>,
42 but that is really the callers pad (a slot of which is allocated by
43 every entersub). Do not get or set C<CvPADLIST> if a CV is an XSUB (as
44 determined by C<CvISXSUB()>), C<CvPADLIST> slot is reused for a different
45 internal purpose in XSUBs.
46
47 The PADLIST has a C array where pads are stored.
48
49 The 0th entry of the PADLIST is a PADNAMELIST
50 which represents the "names" or rather
51 the "static type information" for lexicals.  The individual elements of a
52 PADNAMELIST are PADNAMEs.  Future
53 refactorings might stop the PADNAMELIST from being stored in the PADLIST's
54 array, so don't rely on it.  See L</PadlistNAMES>.
55
56 The CvDEPTH'th entry of a PADLIST is a PAD (an AV) which is the stack frame
57 at that depth of recursion into the CV.  The 0th slot of a frame AV is an
58 AV which is C<@_>.  Other entries are storage for variables and op targets.
59
60 Iterating over the PADNAMELIST iterates over all possible pad
61 items.  Pad slots for targets (C<SVs_PADTMP>)
62 and GVs end up having &PL_padname_undef "names", while slots for constants 
63 have C<&PL_padname_const> "names" (see C<L</pad_alloc>>).  That
64 C<&PL_padname_undef>
65 and C<&PL_padname_const> are used is an implementation detail subject to
66 change.  To test for them, use C<!PadnamePV(name)> and
67 S<C<PadnamePV(name) && !PadnameLEN(name)>>, respectively.
68
69 Only C<my>/C<our> variable slots get valid names.
70 The rest are op targets/GVs/constants which are statically allocated
71 or resolved at compile time.  These don't have names by which they
72 can be looked up from Perl code at run time through eval"" the way
73 C<my>/C<our> variables can be.  Since they can't be looked up by "name"
74 but only by their index allocated at compile time (which is usually
75 in C<PL_op->op_targ>), wasting a name SV for them doesn't make sense.
76
77 The pad names in the PADNAMELIST have their PV holding the name of
78 the variable.  The C<COP_SEQ_RANGE_LOW> and C<_HIGH> fields form a range
79 (low+1..high inclusive) of cop_seq numbers for which the name is
80 valid.  During compilation, these fields may hold the special value
81 PERL_PADSEQ_INTRO to indicate various stages:
82
83  COP_SEQ_RANGE_LOW        _HIGH
84  -----------------        -----
85  PERL_PADSEQ_INTRO            0   variable not yet introduced:
86                                   { my ($x
87  valid-seq#   PERL_PADSEQ_INTRO   variable in scope:
88                                   { my ($x)
89  valid-seq#          valid-seq#   compilation of scope complete:
90                                   { my ($x) }
91
92 For typed lexicals C<PadnameTYPE> points at the type stash.  For C<our>
93 lexicals, C<PadnameOURSTASH> points at the stash of the associated global (so
94 that duplicate C<our> declarations in the same package can be detected).
95 C<PadnameGEN> is sometimes used to store the generation number during
96 compilation.
97
98 If C<PadnameOUTER> is set on the pad name, then that slot in the frame AV
99 is a REFCNT'ed reference to a lexical from "outside".  Such entries
100 are sometimes referred to as 'fake'.  In this case, the name does not
101 use 'low' and 'high' to store a cop_seq range, since it is in scope
102 throughout.  Instead 'high' stores some flags containing info about
103 the real lexical (is it declared in an anon, and is it capable of being
104 instantiated multiple times?), and for fake ANONs, 'low' contains the index
105 within the parent's pad where the lexical's value is stored, to make
106 cloning quicker.
107
108 If the 'name' is C<&> the corresponding entry in the PAD
109 is a CV representing a possible closure.
110
111 Note that formats are treated as anon subs, and are cloned each time
112 write is called (if necessary).
113
114 The flag C<SVs_PADSTALE> is cleared on lexicals each time the C<my()> is executed,
115 and set on scope exit.  This allows the
116 C<"Variable $x is not available"> warning
117 to be generated in evals, such as 
118
119     { my $x = 1; sub f { eval '$x'} } f();
120
121 For state vars, C<SVs_PADSTALE> is overloaded to mean 'not yet initialised',
122 but this internal state is stored in a separate pad entry.
123
124 =for apidoc AmxU|PADNAMELIST *|PL_comppad_name
125
126 During compilation, this points to the array containing the names part
127 of the pad for the currently-compiling code.
128
129 =for apidoc AmxU|PAD *|PL_comppad
130
131 During compilation, this points to the array containing the values
132 part of the pad for the currently-compiling code.  (At runtime a CV may
133 have many such value arrays; at compile time just one is constructed.)
134 At runtime, this points to the array containing the currently-relevant
135 values for the pad for the currently-executing code.
136
137 =for apidoc AmxU|SV **|PL_curpad
138
139 Points directly to the body of the L</PL_comppad> array.
140 (I.e., this is C<PAD_ARRAY(PL_comppad)>.)
141
142 =cut
143 */
144
145
146 #include "EXTERN.h"
147 #define PERL_IN_PAD_C
148 #include "perl.h"
149 #include "keywords.h"
150
151 #define COP_SEQ_RANGE_LOW_set(sv,val)           \
152   STMT_START { (sv)->xpadn_low = (val); } STMT_END
153 #define COP_SEQ_RANGE_HIGH_set(sv,val)          \
154   STMT_START { (sv)->xpadn_high = (val); } STMT_END
155
156 #define PARENT_PAD_INDEX_set            COP_SEQ_RANGE_LOW_set
157 #define PARENT_FAKELEX_FLAGS_set        COP_SEQ_RANGE_HIGH_set
158
159 #ifdef DEBUGGING
160 void
161 Perl_set_padlist(CV * cv, PADLIST *padlist){
162     PERL_ARGS_ASSERT_SET_PADLIST;
163 #  if PTRSIZE == 8
164     assert((Size_t)padlist != UINT64_C(0xEFEFEFEFEFEFEFEF));
165 #  elif PTRSIZE == 4
166     assert((Size_t)padlist != 0xEFEFEFEF);
167 #  else
168 #    error unknown pointer size
169 #  endif
170     assert(!CvISXSUB(cv));
171     ((XPVCV*)MUTABLE_PTR(SvANY(cv)))->xcv_padlist_u.xcv_padlist = padlist;
172 }
173 #endif
174
175 /*
176 =for apidoc Am|PADLIST *|pad_new|int flags
177
178 Create a new padlist, updating the global variables for the
179 currently-compiling padlist to point to the new padlist.  The following
180 flags can be OR'ed together:
181
182     padnew_CLONE        this pad is for a cloned CV
183     padnew_SAVE         save old globals on the save stack
184     padnew_SAVESUB      also save extra stuff for start of sub
185
186 =cut
187 */
188
189 PADLIST *
190 Perl_pad_new(pTHX_ int flags)
191 {
192     PADLIST *padlist;
193     PADNAMELIST *padname;
194     PAD *pad;
195     PAD **ary;
196
197     ASSERT_CURPAD_LEGAL("pad_new");
198
199     /* XXX DAPM really need a new SAVEt_PAD which restores all or most
200      * vars (based on flags) rather than storing vals + addresses for
201      * each individually. Also see pad_block_start.
202      * XXX DAPM Try to see whether all these conditionals are required
203      */
204
205     /* save existing state, ... */
206
207     if (flags & padnew_SAVE) {
208         SAVECOMPPAD();
209         if (! (flags & padnew_CLONE)) {
210             SAVESPTR(PL_comppad_name);
211             SAVEI32(PL_padix);
212             SAVEI32(PL_constpadix);
213             SAVEI32(PL_comppad_name_fill);
214             SAVEI32(PL_min_intro_pending);
215             SAVEI32(PL_max_intro_pending);
216             SAVEBOOL(PL_cv_has_eval);
217             if (flags & padnew_SAVESUB) {
218                 SAVEBOOL(PL_pad_reset_pending);
219             }
220         }
221     }
222     /* XXX DAPM interestingly, PL_comppad_name_floor never seems to be
223      * saved - check at some pt that this is okay */
224
225     /* ... create new pad ... */
226
227     Newxz(padlist, 1, PADLIST);
228     pad         = newAV();
229
230     if (flags & padnew_CLONE) {
231         /* XXX DAPM  I dont know why cv_clone needs it
232          * doing differently yet - perhaps this separate branch can be
233          * dispensed with eventually ???
234          */
235
236         AV * const a0 = newAV();                        /* will be @_ */
237         av_store(pad, 0, MUTABLE_SV(a0));
238         AvREIFY_only(a0);
239
240         PadnamelistREFCNT(padname = PL_comppad_name)++;
241     }
242     else {
243         padlist->xpadl_id = PL_padlist_generation++;
244         av_store(pad, 0, NULL);
245         padname = newPADNAMELIST(0);
246         padnamelist_store(padname, 0, &PL_padname_undef);
247     }
248
249     /* Most subroutines never recurse, hence only need 2 entries in the padlist
250        array - names, and depth=1.  The default for av_store() is to allocate
251        0..3, and even an explicit call to av_extend() with <3 will be rounded
252        up, so we inline the allocation of the array here.  */
253     Newx(ary, 2, PAD *);
254     PadlistMAX(padlist) = 1;
255     PadlistARRAY(padlist) = ary;
256     ary[0] = (PAD *)padname;
257     ary[1] = pad;
258
259     /* ... then update state variables */
260
261     PL_comppad          = pad;
262     PL_curpad           = AvARRAY(pad);
263
264     if (! (flags & padnew_CLONE)) {
265         PL_comppad_name      = padname;
266         PL_comppad_name_fill = 0;
267         PL_min_intro_pending = 0;
268         PL_padix             = 0;
269         PL_constpadix        = 0;
270         PL_cv_has_eval       = 0;
271     }
272
273     DEBUG_X(PerlIO_printf(Perl_debug_log,
274           "Pad 0x%"UVxf"[0x%"UVxf"] new:       compcv=0x%"UVxf
275               " name=0x%"UVxf" flags=0x%"UVxf"\n",
276           PTR2UV(PL_comppad), PTR2UV(PL_curpad), PTR2UV(PL_compcv),
277               PTR2UV(padname), (UV)flags
278         )
279     );
280
281     return (PADLIST*)padlist;
282 }
283
284
285 /*
286 =head1 Embedding Functions
287
288 =for apidoc cv_undef
289
290 Clear out all the active components of a CV.  This can happen either
291 by an explicit C<undef &foo>, or by the reference count going to zero.
292 In the former case, we keep the C<CvOUTSIDE> pointer, so that any anonymous
293 children can still follow the full lexical scope chain.
294
295 =cut
296 */
297
298 void
299 Perl_cv_undef(pTHX_ CV *cv)
300 {
301     PERL_ARGS_ASSERT_CV_UNDEF;
302     cv_undef_flags(cv, 0);
303 }
304
305 void
306 Perl_cv_undef_flags(pTHX_ CV *cv, U32 flags)
307 {
308     CV cvbody;/*CV body will never be realloced inside this func,
309                so dont read it more than once, use fake CV so existing macros
310                will work, the indirection and CV head struct optimized away*/
311     SvANY(&cvbody) = SvANY(cv);
312
313     PERL_ARGS_ASSERT_CV_UNDEF_FLAGS;
314
315     DEBUG_X(PerlIO_printf(Perl_debug_log,
316           "CV undef: cv=0x%"UVxf" comppad=0x%"UVxf"\n",
317             PTR2UV(cv), PTR2UV(PL_comppad))
318     );
319
320     if (CvFILE(&cvbody)) {
321         char * file = CvFILE(&cvbody);
322         CvFILE(&cvbody) = NULL;
323         if(CvDYNFILE(&cvbody))
324             Safefree(file);
325     }
326
327     /* CvSLABBED_off(&cvbody); *//* turned off below */
328     /* release the sub's body */
329     if (!CvISXSUB(&cvbody)) {
330         if(CvROOT(&cvbody)) {
331             assert(SvTYPE(cv) == SVt_PVCV || SvTYPE(cv) == SVt_PVFM); /*unsafe is safe */
332             if (CvDEPTHunsafe(&cvbody)) {
333                 assert(SvTYPE(cv) == SVt_PVCV);
334                 Perl_croak_nocontext("Can't undef active subroutine");
335             }
336             ENTER;
337
338             PAD_SAVE_SETNULLPAD();
339
340             if (CvSLABBED(&cvbody)) OpslabREFCNT_dec_padok(OpSLAB(CvROOT(&cvbody)));
341             op_free(CvROOT(&cvbody));
342             CvROOT(&cvbody) = NULL;
343             CvSTART(&cvbody) = NULL;
344             LEAVE;
345         }
346         else if (CvSLABBED(&cvbody)) {
347             if( CvSTART(&cvbody)) {
348                 ENTER;
349                 PAD_SAVE_SETNULLPAD();
350
351                 /* discard any leaked ops */
352                 if (PL_parser)
353                     parser_free_nexttoke_ops(PL_parser, (OPSLAB *)CvSTART(&cvbody));
354                 opslab_force_free((OPSLAB *)CvSTART(&cvbody));
355                 CvSTART(&cvbody) = NULL;
356
357                 LEAVE;
358             }
359 #ifdef DEBUGGING
360             else Perl_warn(aTHX_ "Slab leaked from cv %p", (void*)cv);
361 #endif
362         }
363     }
364     else { /* dont bother checking if CvXSUB(cv) is true, less branching */
365         CvXSUB(&cvbody) = NULL;
366     }
367     SvPOK_off(MUTABLE_SV(cv));          /* forget prototype */
368     sv_unmagic((SV *)cv, PERL_MAGIC_checkcall);
369     if (!(flags & CV_UNDEF_KEEP_NAME)) {
370         if (CvNAMED(&cvbody)) {
371             CvNAME_HEK_set(&cvbody, NULL);
372             CvNAMED_off(&cvbody);
373         }
374         else CvGV_set(cv, NULL);
375     }
376
377     /* This statement and the subsequence if block was pad_undef().  */
378     pad_peg("pad_undef");
379
380     if (!CvISXSUB(&cvbody) && CvPADLIST(&cvbody)) {
381         I32 ix;
382         const PADLIST *padlist = CvPADLIST(&cvbody);
383
384         /* Free the padlist associated with a CV.
385            If parts of it happen to be current, we null the relevant PL_*pad*
386            global vars so that we don't have any dangling references left.
387            We also repoint the CvOUTSIDE of any about-to-be-orphaned inner
388            subs to the outer of this cv.  */
389
390         DEBUG_X(PerlIO_printf(Perl_debug_log,
391                               "Pad undef: cv=0x%"UVxf" padlist=0x%"UVxf" comppad=0x%"UVxf"\n",
392                               PTR2UV(cv), PTR2UV(padlist), PTR2UV(PL_comppad))
393                 );
394
395         /* detach any '&' anon children in the pad; if afterwards they
396          * are still live, fix up their CvOUTSIDEs to point to our outside,
397          * bypassing us. */
398         /* XXX DAPM for efficiency, we should only do this if we know we have
399          * children, or integrate this loop with general cleanup */
400
401         if (PL_phase != PERL_PHASE_DESTRUCT) { /* don't bother during global destruction */
402             CV * const outercv = CvOUTSIDE(&cvbody);
403             const U32 seq = CvOUTSIDE_SEQ(&cvbody);
404             PADNAMELIST * const comppad_name = PadlistNAMES(padlist);
405             PADNAME ** const namepad = PadnamelistARRAY(comppad_name);
406             PAD * const comppad = PadlistARRAY(padlist)[1];
407             SV ** const curpad = AvARRAY(comppad);
408             for (ix = PadnamelistMAX(comppad_name); ix > 0; ix--) {
409                 PADNAME * const name = namepad[ix];
410                 if (name && PadnamePV(name) && *PadnamePV(name) == '&')
411                     {
412                         CV * const innercv = MUTABLE_CV(curpad[ix]);
413                         U32 inner_rc = SvREFCNT(innercv);
414                         assert(inner_rc);
415                         assert(SvTYPE(innercv) != SVt_PVFM);
416
417                         if (SvREFCNT(comppad) < 2) { /* allow for /(?{ sub{} })/  */
418                             curpad[ix] = NULL;
419                             SvREFCNT_dec_NN(innercv);
420                             inner_rc--;
421                         }
422
423                         /* in use, not just a prototype */
424                         if (inner_rc && SvTYPE(innercv) == SVt_PVCV
425                          && (CvOUTSIDE(innercv) == cv))
426                         {
427                             assert(CvWEAKOUTSIDE(innercv));
428                             /* don't relink to grandfather if he's being freed */
429                             if (outercv && SvREFCNT(outercv)) {
430                                 CvWEAKOUTSIDE_off(innercv);
431                                 CvOUTSIDE(innercv) = outercv;
432                                 CvOUTSIDE_SEQ(innercv) = seq;
433                                 SvREFCNT_inc_simple_void_NN(outercv);
434                             }
435                             else {
436                                 CvOUTSIDE(innercv) = NULL;
437                             }
438                         }
439                     }
440             }
441         }
442
443         ix = PadlistMAX(padlist);
444         while (ix > 0) {
445             PAD * const sv = PadlistARRAY(padlist)[ix--];
446             if (sv) {
447                 if (sv == PL_comppad) {
448                     PL_comppad = NULL;
449                     PL_curpad = NULL;
450                 }
451                 SvREFCNT_dec_NN(sv);
452             }
453         }
454         {
455             PADNAMELIST * const names = PadlistNAMES(padlist);
456             if (names == PL_comppad_name && PadnamelistREFCNT(names) == 1)
457                 PL_comppad_name = NULL;
458             PadnamelistREFCNT_dec(names);
459         }
460         if (PadlistARRAY(padlist)) Safefree(PadlistARRAY(padlist));
461         Safefree(padlist);
462         CvPADLIST_set(&cvbody, NULL);
463     }
464     else if (CvISXSUB(&cvbody))
465         CvHSCXT(&cvbody) = NULL;
466     /* else is (!CvISXSUB(&cvbody) && !CvPADLIST(&cvbody)) {do nothing;} */
467
468
469     /* remove CvOUTSIDE unless this is an undef rather than a free */
470     if (!SvREFCNT(cv)) {
471         CV * outside = CvOUTSIDE(&cvbody);
472         if(outside) {
473             CvOUTSIDE(&cvbody) = NULL;
474             if (!CvWEAKOUTSIDE(&cvbody))
475                 SvREFCNT_dec_NN(outside);
476         }
477     }
478     if (CvCONST(&cvbody)) {
479         SvREFCNT_dec(MUTABLE_SV(CvXSUBANY(&cvbody).any_ptr));
480         /* CvCONST_off(cv); *//* turned off below */
481     }
482     /* delete all flags except WEAKOUTSIDE and CVGV_RC, which indicate the
483      * ref status of CvOUTSIDE and CvGV, and ANON, NAMED and
484      * LEXICAL, which are used to determine the sub's name.  */
485     CvFLAGS(&cvbody) &= (CVf_WEAKOUTSIDE|CVf_CVGV_RC|CVf_ANON|CVf_LEXICAL
486                    |CVf_NAMED);
487 }
488
489 /*
490 =for apidoc cv_forget_slab
491
492 When a CV has a reference count on its slab (C<CvSLABBED>), it is responsible
493 for making sure it is freed.  (Hence, no two CVs should ever have a
494 reference count on the same slab.)  The CV only needs to reference the slab
495 during compilation.  Once it is compiled and C<CvROOT> attached, it has
496 finished its job, so it can forget the slab.
497
498 =cut
499 */
500
501 void
502 Perl_cv_forget_slab(pTHX_ CV *cv)
503 {
504     bool slabbed;
505     OPSLAB *slab = NULL;
506
507     if (!cv)
508         return;
509     slabbed = cBOOL(CvSLABBED(cv));
510     if (!slabbed) return;
511
512     CvSLABBED_off(cv);
513
514     if      (CvROOT(cv))  slab = OpSLAB(CvROOT(cv));
515     else if (CvSTART(cv)) slab = (OPSLAB *)CvSTART(cv);
516 #ifdef DEBUGGING
517     else if (slabbed)     Perl_warn(aTHX_ "Slab leaked from cv %p", (void*)cv);
518 #endif
519
520     if (slab) {
521 #ifdef PERL_DEBUG_READONLY_OPS
522         const size_t refcnt = slab->opslab_refcnt;
523 #endif
524         OpslabREFCNT_dec(slab);
525 #ifdef PERL_DEBUG_READONLY_OPS
526         if (refcnt > 1) Slab_to_ro(slab);
527 #endif
528     }
529 }
530
531 /*
532 =for apidoc m|PADOFFSET|pad_alloc_name|PADNAME *name|U32 flags|HV *typestash|HV *ourstash
533
534 Allocates a place in the currently-compiling
535 pad (via L<perlapi/pad_alloc>) and
536 then stores a name for that entry.  C<name> is adopted and
537 becomes the name entry; it must already contain the name
538 string.  C<typestash> and C<ourstash> and the C<padadd_STATE>
539 flag get added to C<name>.  None of the other
540 processing of L<perlapi/pad_add_name_pvn>
541 is done.  Returns the offset of the allocated pad slot.
542
543 =cut
544 */
545
546 static PADOFFSET
547 S_pad_alloc_name(pTHX_ PADNAME *name, U32 flags, HV *typestash,
548                        HV *ourstash)
549 {
550     const PADOFFSET offset = pad_alloc(OP_PADSV, SVs_PADMY);
551
552     PERL_ARGS_ASSERT_PAD_ALLOC_NAME;
553
554     ASSERT_CURPAD_ACTIVE("pad_alloc_name");
555
556     if (typestash) {
557         SvPAD_TYPED_on(name);
558         PadnameTYPE(name) =
559             MUTABLE_HV(SvREFCNT_inc_simple_NN(MUTABLE_SV(typestash)));
560     }
561     if (ourstash) {
562         SvPAD_OUR_on(name);
563         SvOURSTASH_set(name, ourstash);
564         SvREFCNT_inc_simple_void_NN(ourstash);
565     }
566     else if (flags & padadd_STATE) {
567         SvPAD_STATE_on(name);
568     }
569
570     padnamelist_store(PL_comppad_name, offset, name);
571     if (PadnameLEN(name) > 1)
572         PadnamelistMAXNAMED(PL_comppad_name) = offset;
573     return offset;
574 }
575
576 /*
577 =for apidoc Am|PADOFFSET|pad_add_name_pvn|const char *namepv|STRLEN namelen|U32 flags|HV *typestash|HV *ourstash
578
579 Allocates a place in the currently-compiling pad for a named lexical
580 variable.  Stores the name and other metadata in the name part of the
581 pad, and makes preparations to manage the variable's lexical scoping.
582 Returns the offset of the allocated pad slot.
583
584 C<namepv>/C<namelen> specify the variable's name, including leading sigil.
585 If C<typestash> is non-null, the name is for a typed lexical, and this
586 identifies the type.  If C<ourstash> is non-null, it's a lexical reference
587 to a package variable, and this identifies the package.  The following
588 flags can be OR'ed together:
589
590  padadd_OUR          redundantly specifies if it's a package var
591  padadd_STATE        variable will retain value persistently
592  padadd_NO_DUP_CHECK skip check for lexical shadowing
593
594 =cut
595 */
596
597 PADOFFSET
598 Perl_pad_add_name_pvn(pTHX_ const char *namepv, STRLEN namelen,
599                 U32 flags, HV *typestash, HV *ourstash)
600 {
601     PADOFFSET offset;
602     PADNAME *name;
603
604     PERL_ARGS_ASSERT_PAD_ADD_NAME_PVN;
605
606     if (flags & ~(padadd_OUR|padadd_STATE|padadd_NO_DUP_CHECK))
607         Perl_croak(aTHX_ "panic: pad_add_name_pvn illegal flag bits 0x%" UVxf,
608                    (UV)flags);
609
610     name = newPADNAMEpvn(namepv, namelen);
611
612     if ((flags & padadd_NO_DUP_CHECK) == 0) {
613         ENTER;
614         SAVEFREEPADNAME(name); /* in case of fatal warnings */
615         /* check for duplicate declaration */
616         pad_check_dup(name, flags & padadd_OUR, ourstash);
617         PadnameREFCNT(name)++;
618         LEAVE;
619     }
620
621     offset = pad_alloc_name(name, flags, typestash, ourstash);
622
623     /* not yet introduced */
624     COP_SEQ_RANGE_LOW_set(name, PERL_PADSEQ_INTRO);
625     COP_SEQ_RANGE_HIGH_set(name, 0);
626
627     if (!PL_min_intro_pending)
628         PL_min_intro_pending = offset;
629     PL_max_intro_pending = offset;
630     /* if it's not a simple scalar, replace with an AV or HV */
631     assert(SvTYPE(PL_curpad[offset]) == SVt_NULL);
632     assert(SvREFCNT(PL_curpad[offset]) == 1);
633     if (namelen != 0 && *namepv == '@')
634         sv_upgrade(PL_curpad[offset], SVt_PVAV);
635     else if (namelen != 0 && *namepv == '%')
636         sv_upgrade(PL_curpad[offset], SVt_PVHV);
637     else if (namelen != 0 && *namepv == '&')
638         sv_upgrade(PL_curpad[offset], SVt_PVCV);
639     assert(SvPADMY(PL_curpad[offset]));
640     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
641                            "Pad addname: %ld \"%s\" new lex=0x%"UVxf"\n",
642                            (long)offset, PadnamePV(name),
643                            PTR2UV(PL_curpad[offset])));
644
645     return offset;
646 }
647
648 /*
649 =for apidoc Am|PADOFFSET|pad_add_name_pv|const char *name|U32 flags|HV *typestash|HV *ourstash
650
651 Exactly like L</pad_add_name_pvn>, but takes a nul-terminated string
652 instead of a string/length pair.
653
654 =cut
655 */
656
657 PADOFFSET
658 Perl_pad_add_name_pv(pTHX_ const char *name,
659                      const U32 flags, HV *typestash, HV *ourstash)
660 {
661     PERL_ARGS_ASSERT_PAD_ADD_NAME_PV;
662     return pad_add_name_pvn(name, strlen(name), flags, typestash, ourstash);
663 }
664
665 /*
666 =for apidoc Am|PADOFFSET|pad_add_name_sv|SV *name|U32 flags|HV *typestash|HV *ourstash
667
668 Exactly like L</pad_add_name_pvn>, but takes the name string in the form
669 of an SV instead of a string/length pair.
670
671 =cut
672 */
673
674 PADOFFSET
675 Perl_pad_add_name_sv(pTHX_ SV *name, U32 flags, HV *typestash, HV *ourstash)
676 {
677     char *namepv;
678     STRLEN namelen;
679     PERL_ARGS_ASSERT_PAD_ADD_NAME_SV;
680     namepv = SvPVutf8(name, namelen);
681     return pad_add_name_pvn(namepv, namelen, flags, typestash, ourstash);
682 }
683
684 /*
685 =for apidoc Amx|PADOFFSET|pad_alloc|I32 optype|U32 tmptype
686
687 Allocates a place in the currently-compiling pad,
688 returning the offset of the allocated pad slot.
689 No name is initially attached to the pad slot.
690 C<tmptype> is a set of flags indicating the kind of pad entry required,
691 which will be set in the value SV for the allocated pad entry:
692
693     SVs_PADMY    named lexical variable ("my", "our", "state")
694     SVs_PADTMP   unnamed temporary store
695     SVf_READONLY constant shared between recursion levels
696
697 C<SVf_READONLY> has been supported here only since perl 5.20.  To work with
698 earlier versions as well, use C<SVf_READONLY|SVs_PADTMP>.  C<SVf_READONLY>
699 does not cause the SV in the pad slot to be marked read-only, but simply
700 tells C<pad_alloc> that it I<will> be made read-only (by the caller), or at
701 least should be treated as such.
702
703 C<optype> should be an opcode indicating the type of operation that the
704 pad entry is to support.  This doesn't affect operational semantics,
705 but is used for debugging.
706
707 =cut
708 */
709
710 /* XXX DAPM integrate alloc(), add_name() and add_anon(),
711  * or at least rationalise ??? */
712
713 PADOFFSET
714 Perl_pad_alloc(pTHX_ I32 optype, U32 tmptype)
715 {
716     SV *sv;
717     I32 retval;
718
719     PERL_UNUSED_ARG(optype);
720     ASSERT_CURPAD_ACTIVE("pad_alloc");
721
722     if (AvARRAY(PL_comppad) != PL_curpad)
723         Perl_croak(aTHX_ "panic: pad_alloc, %p!=%p",
724                    AvARRAY(PL_comppad), PL_curpad);
725     if (PL_pad_reset_pending)
726         pad_reset();
727     if (tmptype == SVs_PADMY) { /* Not & because this ‘flag’ is 0.  */
728         /* For a my, simply push a null SV onto the end of PL_comppad. */
729         sv = *av_fetch(PL_comppad, AvFILLp(PL_comppad) + 1, TRUE);
730         retval = AvFILLp(PL_comppad);
731     }
732     else {
733         /* For a tmp, scan the pad from PL_padix upwards
734          * for a slot which has no name and no active value.
735          * For a constant, likewise, but use PL_constpadix.
736          */
737         PADNAME * const * const names = PadnamelistARRAY(PL_comppad_name);
738         const SSize_t names_fill = PadnamelistMAX(PL_comppad_name);
739         const bool konst = cBOOL(tmptype & SVf_READONLY);
740         retval = konst ? PL_constpadix : PL_padix;
741         for (;;) {
742             /*
743              * Entries that close over unavailable variables
744              * in outer subs contain values not marked PADMY.
745              * Thus we must skip, not just pad values that are
746              * marked as current pad values, but also those with names.
747              * If pad_reset is enabled, ‘current’ means different
748              * things depending on whether we are allocating a con-
749              * stant or a target.  For a target, things marked PADTMP
750              * can be reused; not so for constants.
751              */
752             PADNAME *pn;
753             if (++retval <= names_fill &&
754                    (pn = names[retval]) && PadnamePV(pn))
755                 continue;
756             sv = *av_fetch(PL_comppad, retval, TRUE);
757             if (!(SvFLAGS(sv) &
758 #ifdef USE_PAD_RESET
759                     (konst ? SVs_PADTMP : 0))
760 #else
761                     SVs_PADTMP
762 #endif
763                  ))
764                 break;
765         }
766         if (konst) {
767             padnamelist_store(PL_comppad_name, retval, &PL_padname_const);
768             tmptype &= ~SVf_READONLY;
769             tmptype |= SVs_PADTMP;
770         }
771         *(konst ? &PL_constpadix : &PL_padix) = retval;
772     }
773     SvFLAGS(sv) |= tmptype;
774     PL_curpad = AvARRAY(PL_comppad);
775
776     DEBUG_X(PerlIO_printf(Perl_debug_log,
777           "Pad 0x%"UVxf"[0x%"UVxf"] alloc:   %ld for %s\n",
778           PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long) retval,
779           PL_op_name[optype]));
780 #ifdef DEBUG_LEAKING_SCALARS
781     sv->sv_debug_optype = optype;
782     sv->sv_debug_inpad = 1;
783 #endif
784     return (PADOFFSET)retval;
785 }
786
787 /*
788 =for apidoc Am|PADOFFSET|pad_add_anon|CV *func|I32 optype
789
790 Allocates a place in the currently-compiling pad (via L</pad_alloc>)
791 for an anonymous function that is lexically scoped inside the
792 currently-compiling function.
793 The function C<func> is linked into the pad, and its C<CvOUTSIDE> link
794 to the outer scope is weakened to avoid a reference loop.
795
796 One reference count is stolen, so you may need to do C<SvREFCNT_inc(func)>.
797
798 C<optype> should be an opcode indicating the type of operation that the
799 pad entry is to support.  This doesn't affect operational semantics,
800 but is used for debugging.
801
802 =cut
803 */
804
805 PADOFFSET
806 Perl_pad_add_anon(pTHX_ CV* func, I32 optype)
807 {
808     PADOFFSET ix;
809     PADNAME * const name = newPADNAMEpvn("&", 1);
810
811     PERL_ARGS_ASSERT_PAD_ADD_ANON;
812     assert (SvTYPE(func) == SVt_PVCV);
813
814     pad_peg("add_anon");
815     /* These two aren't used; just make sure they're not equal to
816      * PERL_PADSEQ_INTRO.  They should be 0 by default.  */
817     assert(COP_SEQ_RANGE_LOW (name) != PERL_PADSEQ_INTRO);
818     assert(COP_SEQ_RANGE_HIGH(name) != PERL_PADSEQ_INTRO);
819     ix = pad_alloc(optype, SVs_PADMY);
820     padnamelist_store(PL_comppad_name, ix, name);
821     /* XXX DAPM use PL_curpad[] ? */
822     av_store(PL_comppad, ix, (SV*)func);
823
824     /* to avoid ref loops, we never have parent + child referencing each
825      * other simultaneously */
826     if (CvOUTSIDE(func)) {
827         assert(!CvWEAKOUTSIDE(func));
828         CvWEAKOUTSIDE_on(func);
829         SvREFCNT_dec_NN(CvOUTSIDE(func));
830     }
831     return ix;
832 }
833
834 void
835 Perl_pad_add_weakref(pTHX_ CV* func)
836 {
837     const PADOFFSET ix = pad_alloc(OP_NULL, SVs_PADMY);
838     PADNAME * const name = newPADNAMEpvn("&", 1);
839     SV * const rv = newRV_inc((SV *)func);
840
841     PERL_ARGS_ASSERT_PAD_ADD_WEAKREF;
842
843     /* These two aren't used; just make sure they're not equal to
844      * PERL_PADSEQ_INTRO.  They should be 0 by default.  */
845     assert(COP_SEQ_RANGE_LOW (name) != PERL_PADSEQ_INTRO);
846     assert(COP_SEQ_RANGE_HIGH(name) != PERL_PADSEQ_INTRO);
847     padnamelist_store(PL_comppad_name, ix, name);
848     sv_rvweaken(rv);
849     av_store(PL_comppad, ix, rv);
850 }
851
852 /*
853 =for apidoc pad_check_dup
854
855 Check for duplicate declarations: report any of:
856
857      * a 'my' in the current scope with the same name;
858      * an 'our' (anywhere in the pad) with the same name and the
859        same stash as 'ourstash'
860
861 C<is_our> indicates that the name to check is an C<"our"> declaration.
862
863 =cut
864 */
865
866 STATIC void
867 S_pad_check_dup(pTHX_ PADNAME *name, U32 flags, const HV *ourstash)
868 {
869     PADNAME     **svp;
870     PADOFFSET   top, off;
871     const U32   is_our = flags & padadd_OUR;
872
873     PERL_ARGS_ASSERT_PAD_CHECK_DUP;
874
875     ASSERT_CURPAD_ACTIVE("pad_check_dup");
876
877     assert((flags & ~padadd_OUR) == 0);
878
879     if (PadnamelistMAX(PL_comppad_name) < 0 || !ckWARN(WARN_MISC))
880         return; /* nothing to check */
881
882     svp = PadnamelistARRAY(PL_comppad_name);
883     top = PadnamelistMAX(PL_comppad_name);
884     /* check the current scope */
885     /* XXX DAPM - why the (I32) cast - shouldn't we ensure they're the same
886      * type ? */
887     for (off = top; (I32)off > PL_comppad_name_floor; off--) {
888         PADNAME * const sv = svp[off];
889         if (sv
890             && PadnameLEN(sv) == PadnameLEN(name)
891             && !PadnameOUTER(sv)
892             && (   COP_SEQ_RANGE_LOW(sv)  == PERL_PADSEQ_INTRO
893                 || COP_SEQ_RANGE_HIGH(sv) == PERL_PADSEQ_INTRO)
894             && memEQ(PadnamePV(sv), PadnamePV(name), PadnameLEN(name)))
895         {
896             if (is_our && (SvPAD_OUR(sv)))
897                 break; /* "our" masking "our" */
898             /* diag_listed_as: "%s" variable %s masks earlier declaration in same %s */
899             Perl_warner(aTHX_ packWARN(WARN_MISC),
900                 "\"%s\" %s %"PNf" masks earlier declaration in same %s",
901                 (is_our ? "our" : PL_parser->in_my == KEY_my ? "my" : "state"),
902                 *PadnamePV(sv) == '&' ? "subroutine" : "variable",
903                 PNfARG(sv),
904                 (COP_SEQ_RANGE_HIGH(sv) == PERL_PADSEQ_INTRO
905                     ? "scope" : "statement"));
906             --off;
907             break;
908         }
909     }
910     /* check the rest of the pad */
911     if (is_our) {
912         while (off > 0) {
913             PADNAME * const sv = svp[off];
914             if (sv
915                 && PadnameLEN(sv) == PadnameLEN(name)
916                 && !PadnameOUTER(sv)
917                 && (   COP_SEQ_RANGE_LOW(sv)  == PERL_PADSEQ_INTRO
918                     || COP_SEQ_RANGE_HIGH(sv) == PERL_PADSEQ_INTRO)
919                 && SvOURSTASH(sv) == ourstash
920                 && memEQ(PadnamePV(sv), PadnamePV(name), PadnameLEN(name)))
921             {
922                 Perl_warner(aTHX_ packWARN(WARN_MISC),
923                     "\"our\" variable %"PNf" redeclared", PNfARG(sv));
924                 if ((I32)off <= PL_comppad_name_floor)
925                     Perl_warner(aTHX_ packWARN(WARN_MISC),
926                         "\t(Did you mean \"local\" instead of \"our\"?)\n");
927                 break;
928             }
929             --off;
930         }
931     }
932 }
933
934
935 /*
936 =for apidoc Am|PADOFFSET|pad_findmy_pvn|const char *namepv|STRLEN namelen|U32 flags
937
938 Given the name of a lexical variable, find its position in the
939 currently-compiling pad.
940 C<namepv>/C<namelen> specify the variable's name, including leading sigil.
941 C<flags> is reserved and must be zero.
942 If it is not in the current pad but appears in the pad of any lexically
943 enclosing scope, then a pseudo-entry for it is added in the current pad.
944 Returns the offset in the current pad,
945 or C<NOT_IN_PAD> if no such lexical is in scope.
946
947 =cut
948 */
949
950 PADOFFSET
951 Perl_pad_findmy_pvn(pTHX_ const char *namepv, STRLEN namelen, U32 flags)
952 {
953     PADNAME *out_pn;
954     int out_flags;
955     I32 offset;
956     const PADNAMELIST *namelist;
957     PADNAME **name_p;
958
959     PERL_ARGS_ASSERT_PAD_FINDMY_PVN;
960
961     pad_peg("pad_findmy_pvn");
962
963     if (flags)
964         Perl_croak(aTHX_ "panic: pad_findmy_pvn illegal flag bits 0x%" UVxf,
965                    (UV)flags);
966
967     /* compilation errors can zero PL_compcv */
968     if (!PL_compcv)
969         return NOT_IN_PAD;
970
971     offset = pad_findlex(namepv, namelen, flags,
972                 PL_compcv, PL_cop_seqmax, 1, NULL, &out_pn, &out_flags);
973     if ((PADOFFSET)offset != NOT_IN_PAD) 
974         return offset;
975
976     /* Skip the ‘our’ hack for subroutines, as the warning does not apply.
977      */
978     if (*namepv == '&') return NOT_IN_PAD;
979
980     /* look for an our that's being introduced; this allows
981      *    our $foo = 0 unless defined $foo;
982      * to not give a warning. (Yes, this is a hack) */
983
984     namelist = PadlistNAMES(CvPADLIST(PL_compcv));
985     name_p = PadnamelistARRAY(namelist);
986     for (offset = PadnamelistMAXNAMED(namelist); offset > 0; offset--) {
987         const PADNAME * const name = name_p[offset];
988         if (name && PadnameLEN(name) == namelen
989             && !PadnameOUTER(name)
990             && (PadnameIsOUR(name))
991             && (  PadnamePV(name) == namepv
992                || memEQ(PadnamePV(name), namepv, namelen)  )
993             && COP_SEQ_RANGE_LOW(name) == PERL_PADSEQ_INTRO
994         )
995             return offset;
996     }
997     return NOT_IN_PAD;
998 }
999
1000 /*
1001 =for apidoc Am|PADOFFSET|pad_findmy_pv|const char *name|U32 flags
1002
1003 Exactly like L</pad_findmy_pvn>, but takes a nul-terminated string
1004 instead of a string/length pair.
1005
1006 =cut
1007 */
1008
1009 PADOFFSET
1010 Perl_pad_findmy_pv(pTHX_ const char *name, U32 flags)
1011 {
1012     PERL_ARGS_ASSERT_PAD_FINDMY_PV;
1013     return pad_findmy_pvn(name, strlen(name), flags);
1014 }
1015
1016 /*
1017 =for apidoc Am|PADOFFSET|pad_findmy_sv|SV *name|U32 flags
1018
1019 Exactly like L</pad_findmy_pvn>, but takes the name string in the form
1020 of an SV instead of a string/length pair.
1021
1022 =cut
1023 */
1024
1025 PADOFFSET
1026 Perl_pad_findmy_sv(pTHX_ SV *name, U32 flags)
1027 {
1028     char *namepv;
1029     STRLEN namelen;
1030     PERL_ARGS_ASSERT_PAD_FINDMY_SV;
1031     namepv = SvPVutf8(name, namelen);
1032     return pad_findmy_pvn(namepv, namelen, flags);
1033 }
1034
1035 /*
1036 =for apidoc Amp|PADOFFSET|find_rundefsvoffset
1037
1038 Find the position of the lexical C<$_> in the pad of the
1039 currently-executing function.  Returns the offset in the current pad,
1040 or C<NOT_IN_PAD> if there is no lexical C<$_> in scope (in which case
1041 the global one should be used instead).
1042 L</find_rundefsv> is likely to be more convenient.
1043
1044 =cut
1045 */
1046
1047 PADOFFSET
1048 Perl_find_rundefsvoffset(pTHX)
1049 {
1050     PADNAME *out_pn;
1051     int out_flags;
1052     return pad_findlex("$_", 2, 0, find_runcv(NULL), PL_curcop->cop_seq, 1,
1053             NULL, &out_pn, &out_flags);
1054 }
1055
1056 /*
1057 =for apidoc Am|SV *|find_rundefsv
1058
1059 Find and return the variable that is named C<$_> in the lexical scope
1060 of the currently-executing function.  This may be a lexical C<$_>,
1061 or will otherwise be the global one.
1062
1063 =cut
1064 */
1065
1066 SV *
1067 Perl_find_rundefsv(pTHX)
1068 {
1069     PADNAME *name;
1070     int flags;
1071     PADOFFSET po;
1072
1073     po = pad_findlex("$_", 2, 0, find_runcv(NULL), PL_curcop->cop_seq, 1,
1074             NULL, &name, &flags);
1075
1076     if (po == NOT_IN_PAD || PadnameIsOUR(name))
1077         return DEFSV;
1078
1079     return PAD_SVl(po);
1080 }
1081
1082 SV *
1083 Perl_find_rundefsv2(pTHX_ CV *cv, U32 seq)
1084 {
1085     PADNAME *name;
1086     int flags;
1087     PADOFFSET po;
1088
1089     PERL_ARGS_ASSERT_FIND_RUNDEFSV2;
1090
1091     po = pad_findlex("$_", 2, 0, cv, seq, 1,
1092             NULL, &name, &flags);
1093
1094     if (po == NOT_IN_PAD || PadnameIsOUR(name))
1095         return DEFSV;
1096
1097     return AvARRAY(PadlistARRAY(CvPADLIST(cv))[CvDEPTH(cv)])[po];
1098 }
1099
1100 /*
1101 =for apidoc m|PADOFFSET|pad_findlex|const char *namepv|STRLEN namelen|U32 flags|const CV* cv|U32 seq|int warn|SV** out_capture|PADNAME** out_name|int *out_flags
1102
1103 Find a named lexical anywhere in a chain of nested pads.  Add fake entries
1104 in the inner pads if it's found in an outer one.
1105
1106 Returns the offset in the bottom pad of the lex or the fake lex.
1107 C<cv> is the CV in which to start the search, and seq is the current C<cop_seq>
1108 to match against.  If C<warn> is true, print appropriate warnings.  The C<out_>*
1109 vars return values, and so are pointers to where the returned values
1110 should be stored.  C<out_capture>, if non-null, requests that the innermost
1111 instance of the lexical is captured; C<out_name> is set to the innermost
1112 matched pad name or fake pad name; C<out_flags> returns the flags normally
1113 associated with the C<PARENT_FAKELEX_FLAGS> field of a fake pad name.
1114
1115 Note that C<pad_findlex()> is recursive; it recurses up the chain of CVs,
1116 then comes back down, adding fake entries
1117 as it goes.  It has to be this way
1118 because fake names in anon protoypes have to store in C<xlow> the index into
1119 the parent pad.
1120
1121 =cut
1122 */
1123
1124 /* the CV has finished being compiled. This is not a sufficient test for
1125  * all CVs (eg XSUBs), but suffices for the CVs found in a lexical chain */
1126 #define CvCOMPILED(cv)  CvROOT(cv)
1127
1128 /* the CV does late binding of its lexicals */
1129 #define CvLATE(cv) (CvANON(cv) || CvCLONE(cv) || SvTYPE(cv) == SVt_PVFM)
1130
1131 static void
1132 S_unavailable(pTHX_ PADNAME *name)
1133 {
1134     /* diag_listed_as: Variable "%s" is not available */
1135     Perl_ck_warner(aTHX_ packWARN(WARN_CLOSURE),
1136                         "%se \"%"PNf"\" is not available",
1137                          *PadnamePV(name) == '&'
1138                                          ? "Subroutin"
1139                                          : "Variabl",
1140                          PNfARG(name));
1141 }
1142
1143 STATIC PADOFFSET
1144 S_pad_findlex(pTHX_ const char *namepv, STRLEN namelen, U32 flags, const CV* cv, U32 seq,
1145         int warn, SV** out_capture, PADNAME** out_name, int *out_flags)
1146 {
1147     I32 offset, new_offset;
1148     SV *new_capture;
1149     SV **new_capturep;
1150     const PADLIST * const padlist = CvPADLIST(cv);
1151     const bool staleok = !!(flags & padadd_STALEOK);
1152
1153     PERL_ARGS_ASSERT_PAD_FINDLEX;
1154
1155     flags &= ~ padadd_STALEOK; /* one-shot flag */
1156     if (flags)
1157         Perl_croak(aTHX_ "panic: pad_findlex illegal flag bits 0x%" UVxf,
1158                    (UV)flags);
1159
1160     *out_flags = 0;
1161
1162     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1163         "Pad findlex cv=0x%"UVxf" searching \"%.*s\" seq=%d%s\n",
1164                            PTR2UV(cv), (int)namelen, namepv, (int)seq,
1165         out_capture ? " capturing" : "" ));
1166
1167     /* first, search this pad */
1168
1169     if (padlist) { /* not an undef CV */
1170         I32 fake_offset = 0;
1171         const PADNAMELIST * const names = PadlistNAMES(padlist);
1172         PADNAME * const * const name_p = PadnamelistARRAY(names);
1173
1174         for (offset = PadnamelistMAXNAMED(names); offset > 0; offset--) {
1175             const PADNAME * const name = name_p[offset];
1176             if (name && PadnameLEN(name) == namelen
1177                      && (  PadnamePV(name) == namepv
1178                         || memEQ(PadnamePV(name), namepv, namelen)  ))
1179             {
1180                 if (PadnameOUTER(name)) {
1181                     fake_offset = offset; /* in case we don't find a real one */
1182                     continue;
1183                 }
1184                 if (PadnameIN_SCOPE(name, seq))
1185                     break;
1186             }
1187         }
1188
1189         if (offset > 0 || fake_offset > 0 ) { /* a match! */
1190             if (offset > 0) { /* not fake */
1191                 fake_offset = 0;
1192                 *out_name = name_p[offset]; /* return the name */
1193
1194                 /* set PAD_FAKELEX_MULTI if this lex can have multiple
1195                  * instances. For now, we just test !CvUNIQUE(cv), but
1196                  * ideally, we should detect my's declared within loops
1197                  * etc - this would allow a wider range of 'not stayed
1198                  * shared' warnings. We also treated already-compiled
1199                  * lexes as not multi as viewed from evals. */
1200
1201                 *out_flags = CvANON(cv) ?
1202                         PAD_FAKELEX_ANON :
1203                             (!CvUNIQUE(cv) && ! CvCOMPILED(cv))
1204                                 ? PAD_FAKELEX_MULTI : 0;
1205
1206                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1207                     "Pad findlex cv=0x%"UVxf" matched: offset=%ld (%lu,%lu)\n",
1208                     PTR2UV(cv), (long)offset,
1209                     (unsigned long)COP_SEQ_RANGE_LOW(*out_name),
1210                     (unsigned long)COP_SEQ_RANGE_HIGH(*out_name)));
1211             }
1212             else { /* fake match */
1213                 offset = fake_offset;
1214                 *out_name = name_p[offset]; /* return the name */
1215                 *out_flags = PARENT_FAKELEX_FLAGS(*out_name);
1216                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1217                     "Pad findlex cv=0x%"UVxf" matched: offset=%ld flags=0x%lx index=%lu\n",
1218                     PTR2UV(cv), (long)offset, (unsigned long)*out_flags,
1219                     (unsigned long) PARENT_PAD_INDEX(*out_name) 
1220                 ));
1221             }
1222
1223             /* return the lex? */
1224
1225             if (out_capture) {
1226
1227                 /* our ? */
1228                 if (PadnameIsOUR(*out_name)) {
1229                     *out_capture = NULL;
1230                     return offset;
1231                 }
1232
1233                 /* trying to capture from an anon prototype? */
1234                 if (CvCOMPILED(cv)
1235                         ? CvANON(cv) && CvCLONE(cv) && !CvCLONED(cv)
1236                         : *out_flags & PAD_FAKELEX_ANON)
1237                 {
1238                     if (warn)
1239                         S_unavailable(aTHX_
1240                                       *out_name);
1241
1242                     *out_capture = NULL;
1243                 }
1244
1245                 /* real value */
1246                 else {
1247                     int newwarn = warn;
1248                     if (!CvCOMPILED(cv) && (*out_flags & PAD_FAKELEX_MULTI)
1249                          && !PadnameIsSTATE(name_p[offset])
1250                          && warn && ckWARN(WARN_CLOSURE)) {
1251                         newwarn = 0;
1252                         /* diag_listed_as: Variable "%s" will not stay
1253                                            shared */
1254                         Perl_warner(aTHX_ packWARN(WARN_CLOSURE),
1255                             "%se \"%"UTF8f"\" will not stay shared",
1256                              *namepv == '&' ? "Subroutin" : "Variabl",
1257                              UTF8fARG(1, namelen, namepv));
1258                     }
1259
1260                     if (fake_offset && CvANON(cv)
1261                             && CvCLONE(cv) &&!CvCLONED(cv))
1262                     {
1263                         PADNAME *n;
1264                         /* not yet caught - look further up */
1265                         DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1266                             "Pad findlex cv=0x%"UVxf" chasing lex in outer pad\n",
1267                             PTR2UV(cv)));
1268                         n = *out_name;
1269                         (void) pad_findlex(namepv, namelen, flags, CvOUTSIDE(cv),
1270                             CvOUTSIDE_SEQ(cv),
1271                             newwarn, out_capture, out_name, out_flags);
1272                         *out_name = n;
1273                         return offset;
1274                     }
1275
1276                     *out_capture = AvARRAY(PadlistARRAY(padlist)[
1277                                     CvDEPTH(cv) ? CvDEPTH(cv) : 1])[offset];
1278                     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1279                         "Pad findlex cv=0x%"UVxf" found lex=0x%"UVxf"\n",
1280                         PTR2UV(cv), PTR2UV(*out_capture)));
1281
1282                     if (SvPADSTALE(*out_capture)
1283                         && (!CvDEPTH(cv) || !staleok)
1284                         && !PadnameIsSTATE(name_p[offset]))
1285                     {
1286                         S_unavailable(aTHX_
1287                                       name_p[offset]);
1288                         *out_capture = NULL;
1289                     }
1290                 }
1291                 if (!*out_capture) {
1292                     if (namelen != 0 && *namepv == '@')
1293                         *out_capture = sv_2mortal(MUTABLE_SV(newAV()));
1294                     else if (namelen != 0 && *namepv == '%')
1295                         *out_capture = sv_2mortal(MUTABLE_SV(newHV()));
1296                     else if (namelen != 0 && *namepv == '&')
1297                         *out_capture = sv_2mortal(newSV_type(SVt_PVCV));
1298                     else
1299                         *out_capture = sv_newmortal();
1300                 }
1301             }
1302
1303             return offset;
1304         }
1305     }
1306
1307     /* it's not in this pad - try above */
1308
1309     if (!CvOUTSIDE(cv))
1310         return NOT_IN_PAD;
1311
1312     /* out_capture non-null means caller wants us to capture lex; in
1313      * addition we capture ourselves unless it's an ANON/format */
1314     new_capturep = out_capture ? out_capture :
1315                 CvLATE(cv) ? NULL : &new_capture;
1316
1317     offset = pad_findlex(namepv, namelen,
1318                 flags | padadd_STALEOK*(new_capturep == &new_capture),
1319                 CvOUTSIDE(cv), CvOUTSIDE_SEQ(cv), 1,
1320                 new_capturep, out_name, out_flags);
1321     if ((PADOFFSET)offset == NOT_IN_PAD)
1322         return NOT_IN_PAD;
1323
1324     /* found in an outer CV. Add appropriate fake entry to this pad */
1325
1326     /* don't add new fake entries (via eval) to CVs that we have already
1327      * finished compiling, or to undef CVs */
1328     if (CvCOMPILED(cv) || !padlist)
1329         return 0; /* this dummy (and invalid) value isnt used by the caller */
1330
1331     {
1332         PADNAME *new_name = newPADNAMEouter(*out_name);
1333         PADNAMELIST * const ocomppad_name = PL_comppad_name;
1334         PAD * const ocomppad = PL_comppad;
1335         PL_comppad_name = PadlistNAMES(padlist);
1336         PL_comppad = PadlistARRAY(padlist)[1];
1337         PL_curpad = AvARRAY(PL_comppad);
1338
1339         new_offset
1340             = pad_alloc_name(new_name,
1341                               PadnameIsSTATE(*out_name) ? padadd_STATE : 0,
1342                               PadnameTYPE(*out_name),
1343                               PadnameOURSTASH(*out_name)
1344                               );
1345
1346         DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1347                                "Pad addname: %ld \"%.*s\" FAKE\n",
1348                                (long)new_offset,
1349                                (int) PadnameLEN(new_name),
1350                                PadnamePV(new_name)));
1351         PARENT_FAKELEX_FLAGS_set(new_name, *out_flags);
1352
1353         PARENT_PAD_INDEX_set(new_name, 0);
1354         if (PadnameIsOUR(new_name)) {
1355             NOOP;   /* do nothing */
1356         }
1357         else if (CvLATE(cv)) {
1358             /* delayed creation - just note the offset within parent pad */
1359             PARENT_PAD_INDEX_set(new_name, offset);
1360             CvCLONE_on(cv);
1361         }
1362         else {
1363             /* immediate creation - capture outer value right now */
1364             av_store(PL_comppad, new_offset, SvREFCNT_inc(*new_capturep));
1365             /* But also note the offset, as newMYSUB needs it */
1366             PARENT_PAD_INDEX_set(new_name, offset);
1367             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1368                 "Pad findlex cv=0x%"UVxf" saved captured sv 0x%"UVxf" at offset %ld\n",
1369                 PTR2UV(cv), PTR2UV(*new_capturep), (long)new_offset));
1370         }
1371         *out_name = new_name;
1372         *out_flags = PARENT_FAKELEX_FLAGS(new_name);
1373
1374         PL_comppad_name = ocomppad_name;
1375         PL_comppad = ocomppad;
1376         PL_curpad = ocomppad ? AvARRAY(ocomppad) : NULL;
1377     }
1378     return new_offset;
1379 }
1380
1381 #ifdef DEBUGGING
1382
1383 /*
1384 =for apidoc Am|SV *|pad_sv|PADOFFSET po
1385
1386 Get the value at offset C<po> in the current (compiling or executing) pad.
1387 Use macro C<PAD_SV> instead of calling this function directly.
1388
1389 =cut
1390 */
1391
1392 SV *
1393 Perl_pad_sv(pTHX_ PADOFFSET po)
1394 {
1395     ASSERT_CURPAD_ACTIVE("pad_sv");
1396
1397     if (!po)
1398         Perl_croak(aTHX_ "panic: pad_sv po");
1399     DEBUG_X(PerlIO_printf(Perl_debug_log,
1400         "Pad 0x%"UVxf"[0x%"UVxf"] sv:      %ld sv=0x%"UVxf"\n",
1401         PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po, PTR2UV(PL_curpad[po]))
1402     );
1403     return PL_curpad[po];
1404 }
1405
1406 /*
1407 =for apidoc Am|void|pad_setsv|PADOFFSET po|SV *sv
1408
1409 Set the value at offset C<po> in the current (compiling or executing) pad.
1410 Use the macro C<PAD_SETSV()> rather than calling this function directly.
1411
1412 =cut
1413 */
1414
1415 void
1416 Perl_pad_setsv(pTHX_ PADOFFSET po, SV* sv)
1417 {
1418     PERL_ARGS_ASSERT_PAD_SETSV;
1419
1420     ASSERT_CURPAD_ACTIVE("pad_setsv");
1421
1422     DEBUG_X(PerlIO_printf(Perl_debug_log,
1423         "Pad 0x%"UVxf"[0x%"UVxf"] setsv:   %ld sv=0x%"UVxf"\n",
1424         PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po, PTR2UV(sv))
1425     );
1426     PL_curpad[po] = sv;
1427 }
1428
1429 #endif /* DEBUGGING */
1430
1431 /*
1432 =for apidoc m|void|pad_block_start|int full
1433
1434 Update the pad compilation state variables on entry to a new block.
1435
1436 =cut
1437 */
1438
1439 /* XXX DAPM perhaps:
1440  *      - integrate this in general state-saving routine ???
1441  *      - combine with the state-saving going on in pad_new ???
1442  *      - introduce a new SAVE type that does all this in one go ?
1443  */
1444
1445 void
1446 Perl_pad_block_start(pTHX_ int full)
1447 {
1448     ASSERT_CURPAD_ACTIVE("pad_block_start");
1449     SAVEI32(PL_comppad_name_floor);
1450     PL_comppad_name_floor = PadnamelistMAX(PL_comppad_name);
1451     if (full)
1452         PL_comppad_name_fill = PL_comppad_name_floor;
1453     if (PL_comppad_name_floor < 0)
1454         PL_comppad_name_floor = 0;
1455     SAVEI32(PL_min_intro_pending);
1456     SAVEI32(PL_max_intro_pending);
1457     PL_min_intro_pending = 0;
1458     SAVEI32(PL_comppad_name_fill);
1459     SAVEI32(PL_padix_floor);
1460     /* PL_padix_floor is what PL_padix is reset to at the start of each
1461        statement, by pad_reset().  We set it when entering a new scope
1462        to keep things like this working:
1463             print "$foo$bar", do { this(); that() . "foo" };
1464        We must not let "$foo$bar" and the later concatenation share the
1465        same target.  */
1466     PL_padix_floor = PL_padix;
1467     PL_pad_reset_pending = FALSE;
1468 }
1469
1470 /*
1471 =for apidoc Am|U32|intro_my
1472
1473 "Introduce" C<my> variables to visible status.  This is called during parsing
1474 at the end of each statement to make lexical variables visible to subsequent
1475 statements.
1476
1477 =cut
1478 */
1479
1480 U32
1481 Perl_intro_my(pTHX)
1482 {
1483     PADNAME **svp;
1484     I32 i;
1485     U32 seq;
1486
1487     ASSERT_CURPAD_ACTIVE("intro_my");
1488     if (PL_compiling.cop_seq) {
1489         seq = PL_compiling.cop_seq;
1490         PL_compiling.cop_seq = 0;
1491     }
1492     else
1493         seq = PL_cop_seqmax;
1494     if (! PL_min_intro_pending)
1495         return seq;
1496
1497     svp = PadnamelistARRAY(PL_comppad_name);
1498     for (i = PL_min_intro_pending; i <= PL_max_intro_pending; i++) {
1499         PADNAME * const sv = svp[i];
1500
1501         if (sv && PadnameLEN(sv) && !PadnameOUTER(sv)
1502             && COP_SEQ_RANGE_LOW(sv) == PERL_PADSEQ_INTRO)
1503         {
1504             COP_SEQ_RANGE_HIGH_set(sv, PERL_PADSEQ_INTRO); /* Don't know scope end yet. */
1505             COP_SEQ_RANGE_LOW_set(sv, PL_cop_seqmax);
1506             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1507                 "Pad intromy: %ld \"%s\", (%lu,%lu)\n",
1508                 (long)i, PadnamePV(sv),
1509                 (unsigned long)COP_SEQ_RANGE_LOW(sv),
1510                 (unsigned long)COP_SEQ_RANGE_HIGH(sv))
1511             );
1512         }
1513     }
1514     COP_SEQMAX_INC;
1515     PL_min_intro_pending = 0;
1516     PL_comppad_name_fill = PL_max_intro_pending; /* Needn't search higher */
1517     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1518                 "Pad intromy: seq -> %ld\n", (long)(PL_cop_seqmax)));
1519
1520     return seq;
1521 }
1522
1523 /*
1524 =for apidoc m|void|pad_leavemy
1525
1526 Cleanup at end of scope during compilation: set the max seq number for
1527 lexicals in this scope and warn of any lexicals that never got introduced.
1528
1529 =cut
1530 */
1531
1532 OP *
1533 Perl_pad_leavemy(pTHX)
1534 {
1535     I32 off;
1536     OP *o = NULL;
1537     PADNAME * const * const svp = PadnamelistARRAY(PL_comppad_name);
1538
1539     PL_pad_reset_pending = FALSE;
1540
1541     ASSERT_CURPAD_ACTIVE("pad_leavemy");
1542     if (PL_min_intro_pending && PL_comppad_name_fill < PL_min_intro_pending) {
1543         for (off = PL_max_intro_pending; off >= PL_min_intro_pending; off--) {
1544             const PADNAME * const name = svp[off];
1545             if (name && PadnameLEN(name) && !PadnameOUTER(name))
1546                 Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL),
1547                                       "%"PNf" never introduced",
1548                                        PNfARG(name));
1549         }
1550     }
1551     /* "Deintroduce" my variables that are leaving with this scope. */
1552     for (off = PadnamelistMAX(PL_comppad_name);
1553          off > PL_comppad_name_fill; off--) {
1554         PADNAME * const sv = svp[off];
1555         if (sv && PadnameLEN(sv) && !PadnameOUTER(sv)
1556             && COP_SEQ_RANGE_HIGH(sv) == PERL_PADSEQ_INTRO)
1557         {
1558             COP_SEQ_RANGE_HIGH_set(sv, PL_cop_seqmax);
1559             DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1560                 "Pad leavemy: %ld \"%s\", (%lu,%lu)\n",
1561                 (long)off, PadnamePV(sv),
1562                 (unsigned long)COP_SEQ_RANGE_LOW(sv),
1563                 (unsigned long)COP_SEQ_RANGE_HIGH(sv))
1564             );
1565             if (!PadnameIsSTATE(sv) && !PadnameIsOUR(sv)
1566              && *PadnamePV(sv) == '&' && PadnameLEN(sv) > 1) {
1567                 OP *kid = newOP(OP_INTROCV, 0);
1568                 kid->op_targ = off;
1569                 o = op_prepend_elem(OP_LINESEQ, kid, o);
1570             }
1571         }
1572     }
1573     COP_SEQMAX_INC;
1574     DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1575             "Pad leavemy: seq = %ld\n", (long)PL_cop_seqmax));
1576     return o;
1577 }
1578
1579 /*
1580 =for apidoc m|void|pad_swipe|PADOFFSET po|bool refadjust
1581
1582 Abandon the tmp in the current pad at offset C<po> and replace with a
1583 new one.
1584
1585 =cut
1586 */
1587
1588 void
1589 Perl_pad_swipe(pTHX_ PADOFFSET po, bool refadjust)
1590 {
1591     ASSERT_CURPAD_LEGAL("pad_swipe");
1592     if (!PL_curpad)
1593         return;
1594     if (AvARRAY(PL_comppad) != PL_curpad)
1595         Perl_croak(aTHX_ "panic: pad_swipe curpad, %p!=%p",
1596                    AvARRAY(PL_comppad), PL_curpad);
1597     if (!po || ((SSize_t)po) > AvFILLp(PL_comppad))
1598         Perl_croak(aTHX_ "panic: pad_swipe po=%ld, fill=%ld",
1599                    (long)po, (long)AvFILLp(PL_comppad));
1600
1601     DEBUG_X(PerlIO_printf(Perl_debug_log,
1602                 "Pad 0x%"UVxf"[0x%"UVxf"] swipe:   %ld\n",
1603                 PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po));
1604
1605     if (refadjust)
1606         SvREFCNT_dec(PL_curpad[po]);
1607
1608
1609     /* if pad tmps aren't shared between ops, then there's no need to
1610      * create a new tmp when an existing op is freed */
1611 #ifdef USE_PAD_RESET
1612     PL_curpad[po] = newSV(0);
1613     SvPADTMP_on(PL_curpad[po]);
1614 #else
1615     PL_curpad[po] = NULL;
1616 #endif
1617     if (PadnamelistMAX(PL_comppad_name) != -1
1618      && (PADOFFSET)PadnamelistMAX(PL_comppad_name) >= po) {
1619         if (PadnamelistARRAY(PL_comppad_name)[po]) {
1620             assert(!PadnameLEN(PadnamelistARRAY(PL_comppad_name)[po]));
1621         }
1622         PadnamelistARRAY(PL_comppad_name)[po] = &PL_padname_undef;
1623     }
1624     /* Use PL_constpadix here, not PL_padix.  The latter may have been
1625        reset by pad_reset.  We don’t want pad_alloc to have to scan the
1626        whole pad when allocating a constant. */
1627     if ((I32)po < PL_constpadix)
1628         PL_constpadix = po - 1;
1629 }
1630
1631 /*
1632 =for apidoc m|void|pad_reset
1633
1634 Mark all the current temporaries for reuse
1635
1636 =cut
1637 */
1638
1639 /* pad_reset() causes pad temp TARGs (operator targets) to be shared
1640  * between OPs from different statements.  During compilation, at the start
1641  * of each statement pad_reset resets PL_padix back to its previous value.
1642  * When allocating a target, pad_alloc begins its scan through the pad at
1643  * PL_padix+1.  */
1644 static void
1645 S_pad_reset(pTHX)
1646 {
1647 #ifdef USE_PAD_RESET
1648     if (AvARRAY(PL_comppad) != PL_curpad)
1649         Perl_croak(aTHX_ "panic: pad_reset curpad, %p!=%p",
1650                    AvARRAY(PL_comppad), PL_curpad);
1651
1652     DEBUG_X(PerlIO_printf(Perl_debug_log,
1653             "Pad 0x%"UVxf"[0x%"UVxf"] reset:     padix %ld -> %ld",
1654             PTR2UV(PL_comppad), PTR2UV(PL_curpad),
1655                 (long)PL_padix, (long)PL_padix_floor
1656             )
1657     );
1658
1659     if (!TAINTING_get) {        /* Can't mix tainted and non-tainted temporaries. */
1660         PL_padix = PL_padix_floor;
1661     }
1662 #endif
1663     PL_pad_reset_pending = FALSE;
1664 }
1665
1666 /*
1667 =for apidoc Amx|void|pad_tidy|padtidy_type type
1668
1669 Tidy up a pad at the end of compilation of the code to which it belongs.
1670 Jobs performed here are: remove most stuff from the pads of anonsub
1671 prototypes; give it a C<@_>; mark temporaries as such.  C<type> indicates
1672 the kind of subroutine:
1673
1674     padtidy_SUB        ordinary subroutine
1675     padtidy_SUBCLONE   prototype for lexical closure
1676     padtidy_FORMAT     format
1677
1678 =cut
1679 */
1680
1681 /* XXX DAPM surely most of this stuff should be done properly
1682  * at the right time beforehand, rather than going around afterwards
1683  * cleaning up our mistakes ???
1684  */
1685
1686 void
1687 Perl_pad_tidy(pTHX_ padtidy_type type)
1688 {
1689     dVAR;
1690
1691     ASSERT_CURPAD_ACTIVE("pad_tidy");
1692
1693     /* If this CV has had any 'eval-capable' ops planted in it:
1694      * i.e. it contains any of:
1695      *
1696      *     * eval '...',
1697      *     * //ee,
1698      *     * use re 'eval'; /$var/
1699      *     * /(?{..})/),
1700      *
1701      * Then any anon prototypes in the chain of CVs should be marked as
1702      * cloneable, so that for example the eval's CV in
1703      *
1704      *    sub { eval '$x' }
1705      *
1706      * gets the right CvOUTSIDE.  If running with -d, *any* sub may
1707      * potentially have an eval executed within it.
1708      */
1709
1710     if (PL_cv_has_eval || PL_perldb) {
1711         const CV *cv;
1712         for (cv = PL_compcv ;cv; cv = CvOUTSIDE(cv)) {
1713             if (cv != PL_compcv && CvCOMPILED(cv))
1714                 break; /* no need to mark already-compiled code */
1715             if (CvANON(cv)) {
1716                 DEBUG_Xv(PerlIO_printf(Perl_debug_log,
1717                     "Pad clone on cv=0x%"UVxf"\n", PTR2UV(cv)));
1718                 CvCLONE_on(cv);
1719             }
1720             CvHASEVAL_on(cv);
1721         }
1722     }
1723
1724     /* extend namepad to match curpad */
1725     if (PadnamelistMAX(PL_comppad_name) < AvFILLp(PL_comppad))
1726         padnamelist_store(PL_comppad_name, AvFILLp(PL_comppad), NULL);
1727
1728     if (type == padtidy_SUBCLONE) {
1729         PADNAME ** const namep = PadnamelistARRAY(PL_comppad_name);
1730         PADOFFSET ix;
1731
1732         for (ix = AvFILLp(PL_comppad); ix > 0; ix--) {
1733             PADNAME *namesv;
1734             if (!namep[ix]) namep[ix] = &PL_padname_undef;
1735
1736             /*
1737              * The only things that a clonable function needs in its
1738              * pad are anonymous subs, constants and GVs.
1739              * The rest are created anew during cloning.
1740              */
1741             if (!PL_curpad[ix] || SvIMMORTAL(PL_curpad[ix]))
1742                 continue;
1743             namesv = namep[ix];
1744             if (!(PadnamePV(namesv) &&
1745                    (!PadnameLEN(namesv) || *PadnamePV(namesv) == '&')))
1746             {
1747                 SvREFCNT_dec(PL_curpad[ix]);
1748                 PL_curpad[ix] = NULL;
1749             }
1750         }
1751     }
1752     else if (type == padtidy_SUB) {
1753         /* XXX DAPM this same bit of code keeps appearing !!! Rationalise? */
1754         AV * const av = newAV();                        /* Will be @_ */
1755         av_store(PL_comppad, 0, MUTABLE_SV(av));
1756         AvREIFY_only(av);
1757     }
1758
1759     if (type == padtidy_SUB || type == padtidy_FORMAT) {
1760         PADNAME ** const namep = PadnamelistARRAY(PL_comppad_name);
1761         PADOFFSET ix;
1762         for (ix = AvFILLp(PL_comppad); ix > 0; ix--) {
1763             if (!namep[ix]) namep[ix] = &PL_padname_undef;
1764             if (!PL_curpad[ix] || SvIMMORTAL(PL_curpad[ix]))
1765                 continue;
1766             if (SvPADMY(PL_curpad[ix]) && !PadnameOUTER(namep[ix])) {
1767                 /* This is a work around for how the current implementation of
1768                    ?{ } blocks in regexps interacts with lexicals.
1769
1770                    One of our lexicals.
1771                    Can't do this on all lexicals, otherwise sub baz() won't
1772                    compile in
1773
1774                    my $foo;
1775
1776                    sub bar { ++$foo; }
1777
1778                    sub baz { ++$foo; }
1779
1780                    because completion of compiling &bar calling pad_tidy()
1781                    would cause (top level) $foo to be marked as stale, and
1782                    "no longer available".  */
1783                 SvPADSTALE_on(PL_curpad[ix]);
1784             }
1785         }
1786     }
1787     PL_curpad = AvARRAY(PL_comppad);
1788 }
1789
1790 /*
1791 =for apidoc m|void|pad_free|PADOFFSET po
1792
1793 Free the SV at offset po in the current pad.
1794
1795 =cut
1796 */
1797
1798 /* XXX DAPM integrate with pad_swipe ???? */
1799 void
1800 Perl_pad_free(pTHX_ PADOFFSET po)
1801 {
1802 #ifndef USE_PAD_RESET
1803     SV *sv;
1804 #endif
1805     ASSERT_CURPAD_LEGAL("pad_free");
1806     if (!PL_curpad)
1807         return;
1808     if (AvARRAY(PL_comppad) != PL_curpad)
1809         Perl_croak(aTHX_ "panic: pad_free curpad, %p!=%p",
1810                    AvARRAY(PL_comppad), PL_curpad);
1811     if (!po)
1812         Perl_croak(aTHX_ "panic: pad_free po");
1813
1814     DEBUG_X(PerlIO_printf(Perl_debug_log,
1815             "Pad 0x%"UVxf"[0x%"UVxf"] free:    %ld\n",
1816             PTR2UV(PL_comppad), PTR2UV(PL_curpad), (long)po)
1817     );
1818
1819 #ifndef USE_PAD_RESET
1820     sv = PL_curpad[po];
1821     if (sv && sv != &PL_sv_undef && !SvPADMY(sv))
1822         SvFLAGS(sv) &= ~SVs_PADTMP;
1823
1824     if ((I32)po < PL_padix)
1825         PL_padix = po - 1;
1826 #endif
1827 }
1828
1829 /*
1830 =for apidoc m|void|do_dump_pad|I32 level|PerlIO *file|PADLIST *padlist|int full
1831
1832 Dump the contents of a padlist
1833
1834 =cut
1835 */
1836
1837 void
1838 Perl_do_dump_pad(pTHX_ I32 level, PerlIO *file, PADLIST *padlist, int full)
1839 {
1840     const PADNAMELIST *pad_name;
1841     const AV *pad;
1842     PADNAME **pname;
1843     SV **ppad;
1844     I32 ix;
1845
1846     PERL_ARGS_ASSERT_DO_DUMP_PAD;
1847
1848     if (!padlist) {
1849         return;
1850     }
1851     pad_name = PadlistNAMES(padlist);
1852     pad = PadlistARRAY(padlist)[1];
1853     pname = PadnamelistARRAY(pad_name);
1854     ppad = AvARRAY(pad);
1855     Perl_dump_indent(aTHX_ level, file,
1856             "PADNAME = 0x%"UVxf"(0x%"UVxf") PAD = 0x%"UVxf"(0x%"UVxf")\n",
1857             PTR2UV(pad_name), PTR2UV(pname), PTR2UV(pad), PTR2UV(ppad)
1858     );
1859
1860     for (ix = 1; ix <= PadnamelistMAX(pad_name); ix++) {
1861         const PADNAME *namesv = pname[ix];
1862         if (namesv && !PadnameLEN(namesv)) {
1863             namesv = NULL;
1864         }
1865         if (namesv) {
1866             if (PadnameOUTER(namesv))
1867                 Perl_dump_indent(aTHX_ level+1, file,
1868                     "%2d. 0x%"UVxf"<%lu> FAKE \"%s\" flags=0x%lx index=%lu\n",
1869                     (int) ix,
1870                     PTR2UV(ppad[ix]),
1871                     (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0),
1872                     PadnamePV(namesv),
1873                     (unsigned long)PARENT_FAKELEX_FLAGS(namesv),
1874                     (unsigned long)PARENT_PAD_INDEX(namesv)
1875
1876                 );
1877             else
1878                 Perl_dump_indent(aTHX_ level+1, file,
1879                     "%2d. 0x%"UVxf"<%lu> (%lu,%lu) \"%s\"\n",
1880                     (int) ix,
1881                     PTR2UV(ppad[ix]),
1882                     (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0),
1883                     (unsigned long)COP_SEQ_RANGE_LOW(namesv),
1884                     (unsigned long)COP_SEQ_RANGE_HIGH(namesv),
1885                     PadnamePV(namesv)
1886                 );
1887         }
1888         else if (full) {
1889             Perl_dump_indent(aTHX_ level+1, file,
1890                 "%2d. 0x%"UVxf"<%lu>\n",
1891                 (int) ix,
1892                 PTR2UV(ppad[ix]),
1893                 (unsigned long) (ppad[ix] ? SvREFCNT(ppad[ix]) : 0)
1894             );
1895         }
1896     }
1897 }
1898
1899 #ifdef DEBUGGING
1900
1901 /*
1902 =for apidoc m|void|cv_dump|CV *cv|const char *title
1903
1904 dump the contents of a CV
1905
1906 =cut
1907 */
1908
1909 STATIC void
1910 S_cv_dump(pTHX_ const CV *cv, const char *title)
1911 {
1912     const CV * const outside = CvOUTSIDE(cv);
1913     PADLIST* const padlist = CvPADLIST(cv);
1914
1915     PERL_ARGS_ASSERT_CV_DUMP;
1916
1917     PerlIO_printf(Perl_debug_log,
1918                   "  %s: CV=0x%"UVxf" (%s), OUTSIDE=0x%"UVxf" (%s)\n",
1919                   title,
1920                   PTR2UV(cv),
1921                   (CvANON(cv) ? "ANON"
1922                    : (SvTYPE(cv) == SVt_PVFM) ? "FORMAT"
1923                    : (cv == PL_main_cv) ? "MAIN"
1924                    : CvUNIQUE(cv) ? "UNIQUE"
1925                    : CvGV(cv) ? GvNAME(CvGV(cv)) : "UNDEFINED"),
1926                   PTR2UV(outside),
1927                   (!outside ? "null"
1928                    : CvANON(outside) ? "ANON"
1929                    : (outside == PL_main_cv) ? "MAIN"
1930                    : CvUNIQUE(outside) ? "UNIQUE"
1931                    : CvGV(outside) ? GvNAME(CvGV(outside)) : "UNDEFINED"));
1932
1933     PerlIO_printf(Perl_debug_log,
1934                     "    PADLIST = 0x%"UVxf"\n", PTR2UV(padlist));
1935     do_dump_pad(1, Perl_debug_log, padlist, 1);
1936 }
1937
1938 #endif /* DEBUGGING */
1939
1940 /*
1941 =for apidoc Am|CV *|cv_clone|CV *proto
1942
1943 Clone a CV, making a lexical closure.  C<proto> supplies the prototype
1944 of the function: its code, pad structure, and other attributes.
1945 The prototype is combined with a capture of outer lexicals to which the
1946 code refers, which are taken from the currently-executing instance of
1947 the immediately surrounding code.
1948
1949 =cut
1950 */
1951
1952 static CV *S_cv_clone(pTHX_ CV *proto, CV *cv, CV *outside, HV *cloned);
1953
1954 static CV *
1955 S_cv_clone_pad(pTHX_ CV *proto, CV *cv, CV *outside, HV *cloned,
1956                      bool newcv)
1957 {
1958     I32 ix;
1959     PADLIST* const protopadlist = CvPADLIST(proto);
1960     PADNAMELIST *const protopad_name = PadlistNAMES(protopadlist);
1961     const PAD *const protopad = PadlistARRAY(protopadlist)[1];
1962     PADNAME** const pname = PadnamelistARRAY(protopad_name);
1963     SV** const ppad = AvARRAY(protopad);
1964     const I32 fname = PadnamelistMAX(protopad_name);
1965     const I32 fpad = AvFILLp(protopad);
1966     SV** outpad;
1967     long depth;
1968     U32 subclones = 0;
1969     bool trouble = FALSE;
1970
1971     assert(!CvUNIQUE(proto));
1972
1973     /* Anonymous subs have a weak CvOUTSIDE pointer, so its value is not
1974      * reliable.  The currently-running sub is always the one we need to
1975      * close over.
1976      * For my subs, the currently-running sub may not be the one we want.
1977      * We have to check whether it is a clone of CvOUTSIDE.
1978      * Note that in general for formats, CvOUTSIDE != find_runcv.
1979      * Since formats may be nested inside closures, CvOUTSIDE may point
1980      * to a prototype; we instead want the cloned parent who called us.
1981      */
1982
1983     if (!outside) {
1984       if (CvWEAKOUTSIDE(proto))
1985         outside = find_runcv(NULL);
1986       else {
1987         outside = CvOUTSIDE(proto);
1988         if ((CvCLONE(outside) && ! CvCLONED(outside))
1989             || !CvPADLIST(outside)
1990             || CvPADLIST(outside)->xpadl_id != protopadlist->xpadl_outid) {
1991             outside = find_runcv_where(
1992                 FIND_RUNCV_padid_eq, PTR2IV(protopadlist->xpadl_outid), NULL
1993             );
1994             /* outside could be null */
1995         }
1996       }
1997     }
1998     depth = outside ? CvDEPTH(outside) : 0;
1999     if (!depth)
2000         depth = 1;
2001
2002     ENTER;
2003     SAVESPTR(PL_compcv);
2004     PL_compcv = cv;
2005     if (newcv) SAVEFREESV(cv); /* in case of fatal warnings */
2006
2007     if (CvHASEVAL(cv))
2008         CvOUTSIDE(cv)   = MUTABLE_CV(SvREFCNT_inc_simple(outside));
2009
2010     SAVESPTR(PL_comppad_name);
2011     PL_comppad_name = protopad_name;
2012     CvPADLIST_set(cv, pad_new(padnew_CLONE|padnew_SAVE));
2013     CvPADLIST(cv)->xpadl_id = protopadlist->xpadl_id;
2014
2015     av_fill(PL_comppad, fpad);
2016
2017     PL_curpad = AvARRAY(PL_comppad);
2018
2019     outpad = outside && CvPADLIST(outside)
2020         ? AvARRAY(PadlistARRAY(CvPADLIST(outside))[depth])
2021         : NULL;
2022     if (outpad) CvPADLIST(cv)->xpadl_outid = CvPADLIST(outside)->xpadl_id;
2023
2024     for (ix = fpad; ix > 0; ix--) {
2025         PADNAME* const namesv = (ix <= fname) ? pname[ix] : NULL;
2026         SV *sv = NULL;
2027         if (namesv && PadnameLEN(namesv)) { /* lexical */
2028           if (PadnameIsOUR(namesv)) { /* or maybe not so lexical */
2029                 NOOP;
2030           }
2031           else {
2032             if (PadnameOUTER(namesv)) {   /* lexical from outside? */
2033                 /* formats may have an inactive, or even undefined, parent;
2034                    but state vars are always available. */
2035                 if (!outpad || !(sv = outpad[PARENT_PAD_INDEX(namesv)])
2036                  || (  SvPADSTALE(sv) && !SvPAD_STATE(namesv)
2037                     && (!outside || !CvDEPTH(outside)))  ) {
2038                     S_unavailable(aTHX_ namesv);
2039                     sv = NULL;
2040                 }
2041                 else 
2042                     SvREFCNT_inc_simple_void_NN(sv);
2043             }
2044             if (!sv) {
2045                 const char sigil = PadnamePV(namesv)[0];
2046                 if (sigil == '&')
2047                     /* If there are state subs, we need to clone them, too.
2048                        But they may need to close over variables we have
2049                        not cloned yet.  So we will have to do a second
2050                        pass.  Furthermore, there may be state subs clos-
2051                        ing over other state subs’ entries, so we have
2052                        to put a stub here and then clone into it on the
2053                        second pass. */
2054                     if (SvPAD_STATE(namesv) && !CvCLONED(ppad[ix])) {
2055                         assert(SvTYPE(ppad[ix]) == SVt_PVCV);
2056                         subclones ++;
2057                         if (CvOUTSIDE(ppad[ix]) != proto)
2058                              trouble = TRUE;
2059                         sv = newSV_type(SVt_PVCV);
2060                         CvLEXICAL_on(sv);
2061                     }
2062                     else if (PadnameLEN(namesv)>1 && !PadnameIsOUR(namesv))
2063                     {
2064                         /* my sub */
2065                         /* Just provide a stub, but name it.  It will be
2066                            upgrade to the real thing on scope entry. */
2067                         dVAR;
2068                         U32 hash;
2069                         PERL_HASH(hash, PadnamePV(namesv)+1,
2070                                   PadnameLEN(namesv) - 1);
2071                         sv = newSV_type(SVt_PVCV);
2072                         CvNAME_HEK_set(
2073                             sv,
2074                             share_hek(PadnamePV(namesv)+1,
2075                                       1 - PadnameLEN(namesv),
2076                                       hash)
2077                         );
2078                         CvLEXICAL_on(sv);
2079                     }
2080                     else sv = SvREFCNT_inc(ppad[ix]);
2081                 else if (sigil == '@')
2082                     sv = MUTABLE_SV(newAV());
2083                 else if (sigil == '%')
2084                     sv = MUTABLE_SV(newHV());
2085                 else
2086                     sv = newSV(0);
2087                 /* reset the 'assign only once' flag on each state var */
2088                 if (sigil != '&' && SvPAD_STATE(namesv))
2089                     SvPADSTALE_on(sv);
2090             }
2091           }
2092         }
2093         else if (namesv && PadnamePV(namesv)) {
2094             sv = SvREFCNT_inc_NN(ppad[ix]);
2095         }
2096         else {
2097             sv = newSV(0);
2098             SvPADTMP_on(sv);
2099         }
2100         PL_curpad[ix] = sv;
2101     }
2102
2103     if (subclones)
2104     {
2105         if (trouble || cloned) {
2106             /* Uh-oh, we have trouble!  At least one of the state subs here
2107                has its CvOUTSIDE pointer pointing somewhere unexpected.  It
2108                could be pointing to another state protosub that we are
2109                about to clone.  So we have to track which sub clones come
2110                from which protosubs.  If the CvOUTSIDE pointer for a parti-
2111                cular sub points to something we have not cloned yet, we
2112                delay cloning it.  We must loop through the pad entries,
2113                until we get a full pass with no cloning.  If any uncloned
2114                subs remain (probably nested inside anonymous or ‘my’ subs),
2115                then they get cloned in a final pass.
2116              */
2117             bool cloned_in_this_pass;
2118             if (!cloned)
2119                 cloned = (HV *)sv_2mortal((SV *)newHV());
2120             do {
2121                 cloned_in_this_pass = FALSE;
2122                 for (ix = fpad; ix > 0; ix--) {
2123                     PADNAME * const name =
2124                         (ix <= fname) ? pname[ix] : NULL;
2125                     if (name && name != &PL_padname_undef
2126                      && !PadnameOUTER(name) && PadnamePV(name)[0] == '&'
2127                      && PadnameIsSTATE(name) && !CvCLONED(PL_curpad[ix]))
2128                     {
2129                         CV * const protokey = CvOUTSIDE(ppad[ix]);
2130                         CV ** const cvp = protokey == proto
2131                             ? &cv
2132                             : (CV **)hv_fetch(cloned, (char *)&protokey,
2133                                               sizeof(CV *), 0);
2134                         if (cvp && *cvp) {
2135                             S_cv_clone(aTHX_ (CV *)ppad[ix],
2136                                              (CV *)PL_curpad[ix],
2137                                              *cvp, cloned);
2138                             (void)hv_store(cloned, (char *)&ppad[ix],
2139                                      sizeof(CV *),
2140                                      SvREFCNT_inc_simple_NN(PL_curpad[ix]),
2141                                      0);
2142                             subclones--;
2143                             cloned_in_this_pass = TRUE;
2144                         }
2145                     }
2146                 }
2147             } while (cloned_in_this_pass);
2148             if (subclones)
2149                 for (ix = fpad; ix > 0; ix--) {
2150                     PADNAME * const name =
2151                         (ix <= fname) ? pname[ix] : NULL;
2152                     if (name && name != &PL_padname_undef
2153                      && !PadnameOUTER(name) && PadnamePV(name)[0] == '&'
2154                      && PadnameIsSTATE(name) && !CvCLONED(PL_curpad[ix]))
2155                         S_cv_clone(aTHX_ (CV *)ppad[ix],
2156                                          (CV *)PL_curpad[ix],
2157                                          CvOUTSIDE(ppad[ix]), cloned);
2158                 }
2159         }
2160         else for (ix = fpad; ix > 0; ix--) {
2161             PADNAME * const name = (ix <= fname) ? pname[ix] : NULL;
2162             if (name && name != &PL_padname_undef && !PadnameOUTER(name)
2163              && PadnamePV(name)[0] == '&' && PadnameIsSTATE(name))
2164                 S_cv_clone(aTHX_ (CV *)ppad[ix], (CV *)PL_curpad[ix], cv,
2165                                  NULL);
2166         }
2167     }
2168
2169     if (newcv) SvREFCNT_inc_simple_void_NN(cv);
2170     LEAVE;
2171
2172     if (CvCONST(cv)) {
2173         /* Constant sub () { $x } closing over $x:
2174          * The prototype was marked as a candiate for const-ization,
2175          * so try to grab the current const value, and if successful,
2176          * turn into a const sub:
2177          */
2178         SV* const_sv;
2179         OP *o = CvSTART(cv);
2180         assert(newcv);
2181         for (; o; o = o->op_next)
2182             if (o->op_type == OP_PADSV)
2183                 break;
2184         ASSUME(o->op_type == OP_PADSV);
2185         const_sv = PAD_BASE_SV(CvPADLIST(cv), o->op_targ);
2186         /* the candidate should have 1 ref from this pad and 1 ref
2187          * from the parent */
2188         if (const_sv && SvREFCNT(const_sv) == 2) {
2189             const bool was_method = cBOOL(CvMETHOD(cv));
2190             bool copied = FALSE;
2191             if (outside) {
2192                 PADNAME * const pn =
2193                     PadlistNAMESARRAY(CvPADLIST(outside))
2194                         [PARENT_PAD_INDEX(PadlistNAMESARRAY(
2195                             CvPADLIST(cv))[o->op_targ])];
2196                 assert(PadnameOUTER(PadlistNAMESARRAY(CvPADLIST(cv))
2197                                         [o->op_targ]));
2198                 if (PadnameLVALUE(pn)) {
2199                     /* We have a lexical that is potentially modifiable
2200                        elsewhere, so making a constant will break clo-
2201                        sure behaviour.  If this is a ‘simple lexical
2202                        op tree’, i.e., sub(){$x}, emit a deprecation
2203                        warning, but continue to exhibit the old behav-
2204                        iour of making it a constant based on the ref-
2205                        count of the candidate variable.
2206
2207                        A simple lexical op tree looks like this:
2208
2209                          leavesub
2210                            lineseq
2211                              nextstate
2212                              padsv
2213                      */
2214                     if (OpSIBLING(
2215                          cUNOPx(cUNOPx(CvROOT(cv))->op_first)->op_first
2216                         ) == o
2217                      && !OpSIBLING(o))
2218                     {
2219                         Perl_ck_warner_d(aTHX_
2220                                           packWARN(WARN_DEPRECATED),
2221                                          "Constants from lexical "
2222                                          "variables potentially "
2223                                          "modified elsewhere are "
2224                                          "deprecated");
2225                         /* We *copy* the lexical variable, and donate the
2226                            copy to newCONSTSUB.  Yes, this is ugly, and
2227                            should be killed.  We need to do this for the
2228                            time being, however, because turning on SvPADTMP
2229                            on a lexical will have observable effects
2230                            elsewhere.  */
2231                         const_sv = newSVsv(const_sv);
2232                         copied = TRUE;
2233                     }
2234                     else
2235                         goto constoff;
2236                 }
2237             }
2238             if (!copied)
2239                 SvREFCNT_inc_simple_void_NN(const_sv);
2240             /* If the lexical is not used elsewhere, it is safe to turn on
2241                SvPADTMP, since it is only when it is used in lvalue con-
2242                text that the difference is observable.  */
2243             SvREADONLY_on(const_sv);
2244             SvPADTMP_on(const_sv);
2245             SvREFCNT_dec_NN(cv);
2246             cv = newCONSTSUB(CvSTASH(proto), NULL, const_sv);
2247             if (was_method)
2248                 CvMETHOD_on(cv);
2249         }
2250         else {
2251           constoff:
2252             CvCONST_off(cv);
2253         }
2254     }
2255
2256     return cv;
2257 }
2258
2259 static CV *
2260 S_cv_clone(pTHX_ CV *proto, CV *cv, CV *outside, HV *cloned)
2261 {
2262 #ifdef USE_ITHREADS
2263     dVAR;
2264 #endif
2265     const bool newcv = !cv;
2266
2267     assert(!CvUNIQUE(proto));
2268
2269     if (!cv) cv = MUTABLE_CV(newSV_type(SvTYPE(proto)));
2270     CvFLAGS(cv) = CvFLAGS(proto) & ~(CVf_CLONE|CVf_WEAKOUTSIDE|CVf_CVGV_RC
2271                                     |CVf_SLABBED);
2272     CvCLONED_on(cv);
2273
2274     CvFILE(cv)          = CvDYNFILE(proto) ? savepv(CvFILE(proto))
2275                                            : CvFILE(proto);
2276     if (CvNAMED(proto))
2277          CvNAME_HEK_set(cv, share_hek_hek(CvNAME_HEK(proto)));
2278     else CvGV_set(cv,CvGV(proto));
2279     CvSTASH_set(cv, CvSTASH(proto));
2280     OP_REFCNT_LOCK;
2281     CvROOT(cv)          = OpREFCNT_inc(CvROOT(proto));
2282     OP_REFCNT_UNLOCK;
2283     CvSTART(cv)         = CvSTART(proto);
2284     CvOUTSIDE_SEQ(cv) = CvOUTSIDE_SEQ(proto);
2285
2286     if (SvPOK(proto)) {
2287         sv_setpvn(MUTABLE_SV(cv), SvPVX_const(proto), SvCUR(proto));
2288         if (SvUTF8(proto))
2289            SvUTF8_on(MUTABLE_SV(cv));
2290     }
2291     if (SvMAGIC(proto))
2292         mg_copy((SV *)proto, (SV *)cv, 0, 0);
2293
2294     if (CvPADLIST(proto))
2295         cv = S_cv_clone_pad(aTHX_ proto, cv, outside, cloned, newcv);
2296
2297     DEBUG_Xv(
2298         PerlIO_printf(Perl_debug_log, "\nPad CV clone\n");
2299         if (CvOUTSIDE(cv)) cv_dump(CvOUTSIDE(cv), "Outside");
2300         cv_dump(proto,   "Proto");
2301         cv_dump(cv,      "To");
2302     );
2303
2304     return cv;
2305 }
2306
2307 CV *
2308 Perl_cv_clone(pTHX_ CV *proto)
2309 {
2310     PERL_ARGS_ASSERT_CV_CLONE;
2311
2312     if (!CvPADLIST(proto)) Perl_croak(aTHX_ "panic: no pad in cv_clone");
2313     return S_cv_clone(aTHX_ proto, NULL, NULL, NULL);
2314 }
2315
2316 /* Called only by pp_clonecv */
2317 CV *
2318 Perl_cv_clone_into(pTHX_ CV *proto, CV *target)
2319 {
2320     PERL_ARGS_ASSERT_CV_CLONE_INTO;
2321     cv_undef(target);
2322     return S_cv_clone(aTHX_ proto, target, NULL, NULL);
2323 }
2324
2325 /*
2326 =for apidoc cv_name
2327
2328 Returns an SV containing the name of the CV, mainly for use in error
2329 reporting.  The CV may actually be a GV instead, in which case the returned
2330 SV holds the GV's name.  Anything other than a GV or CV is treated as a
2331 string already holding the sub name, but this could change in the future.
2332
2333 An SV may be passed as a second argument.  If so, the name will be assigned
2334 to it and it will be returned.  Otherwise the returned SV will be a new
2335 mortal.
2336
2337 If C<flags> has the C<CV_NAME_NOTQUAL> bit set, then the package name will not be
2338 included.  If the first argument is neither a CV nor a GV, this flag is
2339 ignored (subject to change).
2340
2341 =cut
2342 */
2343
2344 SV *
2345 Perl_cv_name(pTHX_ CV *cv, SV *sv, U32 flags)
2346 {
2347     PERL_ARGS_ASSERT_CV_NAME;
2348     if (!isGV_with_GP(cv) && SvTYPE(cv) != SVt_PVCV) {
2349         if (sv) sv_setsv(sv,(SV *)cv);
2350         return sv ? (sv) : (SV *)cv;
2351     }
2352     {
2353         SV * const retsv = sv ? (sv) : sv_newmortal();
2354         if (SvTYPE(cv) == SVt_PVCV) {
2355             if (CvNAMED(cv)) {
2356                 if (CvLEXICAL(cv) || flags & CV_NAME_NOTQUAL)
2357                     sv_sethek(retsv, CvNAME_HEK(cv));
2358                 else {
2359                     sv_sethek(retsv, HvNAME_HEK(CvSTASH(cv)));
2360                     sv_catpvs(retsv, "::");
2361                     sv_cathek(retsv, CvNAME_HEK(cv));
2362                 }
2363             }
2364             else if (CvLEXICAL(cv) || flags & CV_NAME_NOTQUAL)
2365                 sv_sethek(retsv, GvNAME_HEK(GvEGV(CvGV(cv))));
2366             else gv_efullname3(retsv, CvGV(cv), NULL);
2367         }
2368         else if (flags & CV_NAME_NOTQUAL) sv_sethek(retsv, GvNAME_HEK(cv));
2369         else gv_efullname3(retsv,(GV *)cv,NULL);
2370         return retsv;
2371     }
2372 }
2373
2374 /*
2375 =for apidoc m|void|pad_fixup_inner_anons|PADLIST *padlist|CV *old_cv|CV *new_cv
2376
2377 For any anon CVs in the pad, change C<CvOUTSIDE> of that CV from
2378 C<old_cv> to C<new_cv> if necessary.  Needed when a newly-compiled CV has to be
2379 moved to a pre-existing CV struct.
2380
2381 =cut
2382 */
2383
2384 void
2385 Perl_pad_fixup_inner_anons(pTHX_ PADLIST *padlist, CV *old_cv, CV *new_cv)
2386 {
2387     I32 ix;
2388     PADNAMELIST * const comppad_name = PadlistNAMES(padlist);
2389     AV * const comppad = PadlistARRAY(padlist)[1];
2390     PADNAME ** const namepad = PadnamelistARRAY(comppad_name);
2391     SV ** const curpad = AvARRAY(comppad);
2392
2393     PERL_ARGS_ASSERT_PAD_FIXUP_INNER_ANONS;
2394     PERL_UNUSED_ARG(old_cv);
2395
2396     for (ix = PadnamelistMAX(comppad_name); ix > 0; ix--) {
2397         const PADNAME *name = namepad[ix];
2398         if (name && name != &PL_padname_undef && !PadnameIsOUR(name)
2399             && *PadnamePV(name) == '&')
2400         {
2401           CV *innercv = MUTABLE_CV(curpad[ix]);
2402           if (UNLIKELY(PadnameOUTER(name))) {
2403             CV *cv = new_cv;
2404             PADNAME **names = namepad;
2405             PADOFFSET i = ix;
2406             while (PadnameOUTER(name)) {
2407                 cv = CvOUTSIDE(cv);
2408                 names = PadlistNAMESARRAY(CvPADLIST(cv));
2409                 i = PARENT_PAD_INDEX(name);
2410                 name = names[i];
2411             }
2412             innercv = (CV *)PadARRAY(PadlistARRAY(CvPADLIST(cv))[1])[i];
2413           }
2414           if (SvTYPE(innercv) == SVt_PVCV) {
2415             /* XXX 0afba48f added code here to check for a proto CV
2416                    attached to the pad entry by magic.  But shortly there-
2417                    after 81df9f6f95 moved the magic to the pad name.  The
2418                    code here was never updated, so it wasn’t doing anything
2419                    and got deleted when PADNAME became a distinct type.  Is
2420                    there any bug as a result?  */
2421             if (CvOUTSIDE(innercv) == old_cv) {
2422                 if (!CvWEAKOUTSIDE(innercv)) {
2423                     SvREFCNT_dec(old_cv);
2424                     SvREFCNT_inc_simple_void_NN(new_cv);
2425                 }
2426                 CvOUTSIDE(innercv) = new_cv;
2427             }
2428           }
2429           else { /* format reference */
2430             SV * const rv = curpad[ix];
2431             CV *innercv;
2432             if (!SvOK(rv)) continue;
2433             assert(SvROK(rv));
2434             assert(SvWEAKREF(rv));
2435             innercv = (CV *)SvRV(rv);
2436             assert(!CvWEAKOUTSIDE(innercv));
2437             SvREFCNT_dec(CvOUTSIDE(innercv));
2438             CvOUTSIDE(innercv) = (CV *)SvREFCNT_inc_simple_NN(new_cv);
2439           }
2440         }
2441     }
2442 }
2443
2444 /*
2445 =for apidoc m|void|pad_push|PADLIST *padlist|int depth
2446
2447 Push a new pad frame onto the padlist, unless there's already a pad at
2448 this depth, in which case don't bother creating a new one.  Then give
2449 the new pad an C<@_> in slot zero.
2450
2451 =cut
2452 */
2453
2454 void
2455 Perl_pad_push(pTHX_ PADLIST *padlist, int depth)
2456 {
2457     PERL_ARGS_ASSERT_PAD_PUSH;
2458
2459     if (depth > PadlistMAX(padlist) || !PadlistARRAY(padlist)[depth]) {
2460         PAD** const svp = PadlistARRAY(padlist);
2461         AV* const newpad = newAV();
2462         SV** const oldpad = AvARRAY(svp[depth-1]);
2463         I32 ix = AvFILLp((const AV *)svp[1]);
2464         const I32 names_fill = PadnamelistMAX((PADNAMELIST *)svp[0]);
2465         PADNAME ** const names = PadnamelistARRAY((PADNAMELIST *)svp[0]);
2466         AV *av;
2467
2468         for ( ;ix > 0; ix--) {
2469             if (names_fill >= ix && PadnameLEN(names[ix])) {
2470                 const char sigil = PadnamePV(names[ix])[0];
2471                 if (PadnameOUTER(names[ix])
2472                         || PadnameIsSTATE(names[ix])
2473                         || sigil == '&')
2474                 {
2475                     /* outer lexical or anon code */
2476                     av_store(newpad, ix, SvREFCNT_inc(oldpad[ix]));
2477                 }
2478                 else {          /* our own lexical */
2479                     SV *sv; 
2480                     if (sigil == '@')
2481                         sv = MUTABLE_SV(newAV());
2482                     else if (sigil == '%')
2483                         sv = MUTABLE_SV(newHV());
2484                     else
2485                         sv = newSV(0);
2486                     av_store(newpad, ix, sv);
2487                 }
2488             }
2489             else if (PadnamePV(names[ix])) {
2490                 av_store(newpad, ix, SvREFCNT_inc_NN(oldpad[ix]));
2491             }
2492             else {
2493                 /* save temporaries on recursion? */
2494                 SV * const sv = newSV(0);
2495                 av_store(newpad, ix, sv);
2496                 SvPADTMP_on(sv);
2497             }
2498         }
2499         av = newAV();
2500         av_store(newpad, 0, MUTABLE_SV(av));
2501         AvREIFY_only(av);
2502
2503         padlist_store(padlist, depth, newpad);
2504     }
2505 }
2506
2507 #if defined(USE_ITHREADS)
2508
2509 #  define av_dup_inc(s,t)       MUTABLE_AV(sv_dup_inc((const SV *)s,t))
2510
2511 /*
2512 =for apidoc padlist_dup
2513
2514 Duplicates a pad.
2515
2516 =cut
2517 */
2518
2519 PADLIST *
2520 Perl_padlist_dup(pTHX_ PADLIST *srcpad, CLONE_PARAMS *param)
2521 {
2522     PADLIST *dstpad;
2523     bool cloneall;
2524     PADOFFSET max;
2525
2526     PERL_ARGS_ASSERT_PADLIST_DUP;
2527
2528     cloneall = cBOOL(param->flags & CLONEf_COPY_STACKS);
2529     assert (SvREFCNT(PadlistARRAY(srcpad)[1]) == 1);
2530
2531     max = cloneall ? PadlistMAX(srcpad) : 1;
2532
2533     Newx(dstpad, 1, PADLIST);
2534     ptr_table_store(PL_ptr_table, srcpad, dstpad);
2535     PadlistMAX(dstpad) = max;
2536     Newx(PadlistARRAY(dstpad), max + 1, PAD *);
2537
2538     PadlistARRAY(dstpad)[0] = (PAD *)
2539             padnamelist_dup(PadlistNAMES(srcpad), param);
2540     PadnamelistREFCNT(PadlistNAMES(dstpad))++;
2541     if (cloneall) {
2542         PADOFFSET depth;
2543         for (depth = 1; depth <= max; ++depth)
2544             PadlistARRAY(dstpad)[depth] =
2545                 av_dup_inc(PadlistARRAY(srcpad)[depth], param);
2546     } else {
2547         /* CvDEPTH() on our subroutine will be set to 0, so there's no need
2548            to build anything other than the first level of pads.  */
2549         I32 ix = AvFILLp(PadlistARRAY(srcpad)[1]);
2550         AV *pad1;
2551         const I32 names_fill = PadnamelistMAX(PadlistNAMES(srcpad));
2552         const PAD *const srcpad1 = PadlistARRAY(srcpad)[1];
2553         SV **oldpad = AvARRAY(srcpad1);
2554         PADNAME ** const names = PadnamelistARRAY(PadlistNAMES(dstpad));
2555         SV **pad1a;
2556         AV *args;
2557
2558         pad1 = newAV();
2559
2560         av_extend(pad1, ix);
2561         PadlistARRAY(dstpad)[1] = pad1;
2562         pad1a = AvARRAY(pad1);
2563
2564         if (ix > -1) {
2565             AvFILLp(pad1) = ix;
2566
2567             for ( ;ix > 0; ix--) {
2568                 if (!oldpad[ix]) {
2569                     pad1a[ix] = NULL;
2570                 } else if (names_fill >= ix && names[ix] &&
2571                            PadnameLEN(names[ix])) {
2572                     const char sigil = PadnamePV(names[ix])[0];
2573                     if (PadnameOUTER(names[ix])
2574                         || PadnameIsSTATE(names[ix])
2575                         || sigil == '&')
2576                         {
2577                             /* outer lexical or anon code */
2578                             pad1a[ix] = sv_dup_inc(oldpad[ix], param);
2579                         }
2580                     else {              /* our own lexical */
2581                         if(SvPADSTALE(oldpad[ix]) && SvREFCNT(oldpad[ix]) > 1) {
2582                             /* This is a work around for how the current
2583                                implementation of ?{ } blocks in regexps
2584                                interacts with lexicals.  */
2585                             pad1a[ix] = sv_dup_inc(oldpad[ix], param);
2586                         } else {
2587                             SV *sv; 
2588                             
2589                             if (sigil == '@')
2590                                 sv = MUTABLE_SV(newAV());
2591                             else if (sigil == '%')
2592                                 sv = MUTABLE_SV(newHV());
2593                             else
2594                                 sv = newSV(0);
2595                             pad1a[ix] = sv;
2596                         }
2597                     }
2598                 }
2599                 else if ((  names_fill >= ix && names[ix]
2600                          && PadnamePV(names[ix])  )) {
2601                     pad1a[ix] = sv_dup_inc(oldpad[ix], param);
2602                 }
2603                 else {
2604                     /* save temporaries on recursion? */
2605                     SV * const sv = newSV(0);
2606                     pad1a[ix] = sv;
2607
2608                     /* SvREFCNT(oldpad[ix]) != 1 for some code in threads.xs
2609                        FIXTHAT before merging this branch.
2610                        (And I know how to) */
2611                     if (SvPADTMP(oldpad[ix]))
2612                         SvPADTMP_on(sv);
2613                 }
2614             }
2615
2616             if (oldpad[0]) {
2617                 args = newAV();                 /* Will be @_ */
2618                 AvREIFY_only(args);
2619                 pad1a[0] = (SV *)args;
2620             }
2621         }
2622     }
2623
2624     return dstpad;
2625 }
2626
2627 #endif /* USE_ITHREADS */
2628
2629 PAD **
2630 Perl_padlist_store(pTHX_ PADLIST *padlist, I32 key, PAD *val)
2631 {
2632     PAD **ary;
2633     SSize_t const oldmax = PadlistMAX(padlist);
2634
2635     PERL_ARGS_ASSERT_PADLIST_STORE;
2636
2637     assert(key >= 0);
2638
2639     if (key > PadlistMAX(padlist)) {
2640         av_extend_guts(NULL,key,&PadlistMAX(padlist),
2641                        (SV ***)&PadlistARRAY(padlist),
2642                        (SV ***)&PadlistARRAY(padlist));
2643         Zero(PadlistARRAY(padlist)+oldmax+1, PadlistMAX(padlist)-oldmax,
2644              PAD *);
2645     }
2646     ary = PadlistARRAY(padlist);
2647     SvREFCNT_dec(ary[key]);
2648     ary[key] = val;
2649     return &ary[key];
2650 }
2651
2652 /*
2653 =for apidoc newPADNAMELIST
2654
2655 Creates a new pad name list.  C<max> is the highest index for which space
2656 is allocated.
2657
2658 =cut
2659 */
2660
2661 PADNAMELIST *
2662 Perl_newPADNAMELIST(size_t max)
2663 {
2664     PADNAMELIST *pnl;
2665     Newx(pnl, 1, PADNAMELIST);
2666     Newxz(PadnamelistARRAY(pnl), max+1, PADNAME *);
2667     PadnamelistMAX(pnl) = -1;
2668     PadnamelistREFCNT(pnl) = 1;
2669     PadnamelistMAXNAMED(pnl) = 0;
2670     pnl->xpadnl_max = max;
2671     return pnl;
2672 }
2673
2674 /*
2675 =for apidoc padnamelist_store
2676
2677 Stores the pad name (which may be null) at the given index, freeing any
2678 existing pad name in that slot.
2679
2680 =cut
2681 */
2682
2683 PADNAME **
2684 Perl_padnamelist_store(pTHX_ PADNAMELIST *pnl, SSize_t key, PADNAME *val)
2685 {
2686     PADNAME **ary;
2687
2688     PERL_ARGS_ASSERT_PADNAMELIST_STORE;
2689
2690     assert(key >= 0);
2691
2692     if (key > pnl->xpadnl_max)
2693         av_extend_guts(NULL,key,&pnl->xpadnl_max,
2694                        (SV ***)&PadnamelistARRAY(pnl),
2695                        (SV ***)&PadnamelistARRAY(pnl));
2696     if (PadnamelistMAX(pnl) < key) {
2697         Zero(PadnamelistARRAY(pnl)+PadnamelistMAX(pnl)+1,
2698              key-PadnamelistMAX(pnl), PADNAME *);
2699         PadnamelistMAX(pnl) = key;
2700     }
2701     ary = PadnamelistARRAY(pnl);
2702     if (ary[key])
2703         PadnameREFCNT_dec(ary[key]);
2704     ary[key] = val;
2705     return &ary[key];
2706 }
2707
2708 /*
2709 =for apidoc padnamelist_fetch
2710
2711 Fetches the pad name from the given index.
2712
2713 =cut
2714 */
2715
2716 PADNAME *
2717 Perl_padnamelist_fetch(PADNAMELIST *pnl, SSize_t key)
2718 {
2719     PERL_ARGS_ASSERT_PADNAMELIST_FETCH;
2720     ASSUME(key >= 0);
2721
2722     return key > PadnamelistMAX(pnl) ? NULL : PadnamelistARRAY(pnl)[key];
2723 }
2724
2725 void
2726 Perl_padnamelist_free(pTHX_ PADNAMELIST *pnl)
2727 {
2728     PERL_ARGS_ASSERT_PADNAMELIST_FREE;
2729     if (!--PadnamelistREFCNT(pnl)) {
2730         while(PadnamelistMAX(pnl) >= 0)
2731         {
2732             PADNAME * const pn =
2733                 PadnamelistARRAY(pnl)[PadnamelistMAX(pnl)--];
2734             if (pn)
2735                 PadnameREFCNT_dec(pn);
2736         }
2737         Safefree(PadnamelistARRAY(pnl));
2738         Safefree(pnl);
2739     }
2740 }
2741
2742 #if defined(USE_ITHREADS)
2743
2744 /*
2745 =for apidoc padnamelist_dup
2746
2747 Duplicates a pad name list.
2748
2749 =cut
2750 */
2751
2752 PADNAMELIST *
2753 Perl_padnamelist_dup(pTHX_ PADNAMELIST *srcpad, CLONE_PARAMS *param)
2754 {
2755     PADNAMELIST *dstpad;
2756     SSize_t max = PadnamelistMAX(srcpad);
2757
2758     PERL_ARGS_ASSERT_PADNAMELIST_DUP;
2759
2760     /* look for it in the table first */
2761     dstpad = (PADNAMELIST *)ptr_table_fetch(PL_ptr_table, srcpad);
2762     if (dstpad)
2763         return dstpad;
2764
2765     dstpad = newPADNAMELIST(max);
2766     PadnamelistREFCNT(dstpad) = 0; /* The caller will increment it.  */
2767     PadnamelistMAXNAMED(dstpad) = PadnamelistMAXNAMED(srcpad);
2768     PadnamelistMAX(dstpad) = max;
2769
2770     ptr_table_store(PL_ptr_table, srcpad, dstpad);
2771     for (; max >= 0; max--)
2772       if (PadnamelistARRAY(srcpad)[max]) {
2773         PadnamelistARRAY(dstpad)[max] =
2774             padname_dup(PadnamelistARRAY(srcpad)[max], param);
2775         PadnameREFCNT(PadnamelistARRAY(dstpad)[max])++;
2776       }
2777
2778     return dstpad;
2779 }
2780
2781 #endif /* USE_ITHREADS */
2782
2783 /*
2784 =for apidoc newPADNAMEpvn
2785
2786 Constructs and returns a new pad name.  C<s> must be a UTF-8 string.  Do not
2787 use this for pad names that point to outer lexicals.  See
2788 C<L</newPADNAMEouter>>.
2789
2790 =cut
2791 */
2792
2793 PADNAME *
2794 Perl_newPADNAMEpvn(const char *s, STRLEN len)
2795 {
2796     struct padname_with_str *alloc;
2797     char *alloc2; /* for Newxz */
2798     PADNAME *pn;
2799     PERL_ARGS_ASSERT_NEWPADNAMEPVN;
2800     Newxz(alloc2,
2801           STRUCT_OFFSET(struct padname_with_str, xpadn_str[0]) + len + 1,
2802           char);
2803     alloc = (struct padname_with_str *)alloc2;
2804     pn = (PADNAME *)alloc;
2805     PadnameREFCNT(pn) = 1;
2806     PadnamePV(pn) = alloc->xpadn_str;
2807     Copy(s, PadnamePV(pn), len, char);
2808     *(PadnamePV(pn) + len) = '\0';
2809     PadnameLEN(pn) = len;
2810     return pn;
2811 }
2812
2813 /*
2814 =for apidoc newPADNAMEouter
2815
2816 Constructs and returns a new pad name.  Only use this function for names
2817 that refer to outer lexicals.  (See also L</newPADNAMEpvn>.)  C<outer> is
2818 the outer pad name that this one mirrors.  The returned pad name has the
2819 C<PADNAMEt_OUTER> flag already set.
2820
2821 =cut
2822 */
2823
2824 PADNAME *
2825 Perl_newPADNAMEouter(PADNAME *outer)
2826 {
2827     PADNAME *pn;
2828     PERL_ARGS_ASSERT_NEWPADNAMEOUTER;
2829     Newxz(pn, 1, PADNAME);
2830     PadnameREFCNT(pn) = 1;
2831     PadnamePV(pn) = PadnamePV(outer);
2832     /* Not PadnameREFCNT(outer), because ‘outer’ may itself close over
2833        another entry.  The original pad name owns the buffer.  */
2834     PadnameREFCNT(PADNAME_FROM_PV(PadnamePV(outer)))++;
2835     PadnameFLAGS(pn) = PADNAMEt_OUTER;
2836     PadnameLEN(pn) = PadnameLEN(outer);
2837     return pn;
2838 }
2839
2840 void
2841 Perl_padname_free(pTHX_ PADNAME *pn)
2842 {
2843     PERL_ARGS_ASSERT_PADNAME_FREE;
2844     if (!--PadnameREFCNT(pn)) {
2845         if (UNLIKELY(pn == &PL_padname_undef || pn == &PL_padname_const)) {
2846             PadnameREFCNT(pn) = SvREFCNT_IMMORTAL;
2847             return;
2848         }
2849         SvREFCNT_dec(PadnameTYPE(pn)); /* Takes care of protocv, too.  */
2850         SvREFCNT_dec(PadnameOURSTASH(pn));
2851         if (PadnameOUTER(pn))
2852             PadnameREFCNT_dec(PADNAME_FROM_PV(PadnamePV(pn)));
2853         Safefree(pn);
2854     }
2855 }
2856
2857 #if defined(USE_ITHREADS)
2858
2859 /*
2860 =for apidoc padname_dup
2861
2862 Duplicates a pad name.
2863
2864 =cut
2865 */
2866
2867 PADNAME *
2868 Perl_padname_dup(pTHX_ PADNAME *src, CLONE_PARAMS *param)
2869 {
2870     PADNAME *dst;
2871
2872     PERL_ARGS_ASSERT_PADNAME_DUP;
2873
2874     /* look for it in the table first */
2875     dst = (PADNAME *)ptr_table_fetch(PL_ptr_table, src);
2876     if (dst)
2877         return dst;
2878
2879     if (!PadnamePV(src)) {
2880         dst = &PL_padname_undef;
2881         ptr_table_store(PL_ptr_table, src, dst);
2882         return dst;
2883     }
2884
2885     dst = PadnameOUTER(src)
2886      ? newPADNAMEouter(padname_dup(PADNAME_FROM_PV(PadnamePV(src)), param))
2887      : newPADNAMEpvn(PadnamePV(src), PadnameLEN(src));
2888     ptr_table_store(PL_ptr_table, src, dst);
2889     PadnameLEN(dst) = PadnameLEN(src);
2890     PadnameFLAGS(dst) = PadnameFLAGS(src);
2891     PadnameREFCNT(dst) = 0; /* The caller will increment it.  */
2892     PadnameTYPE   (dst) = (HV *)sv_dup_inc((SV *)PadnameTYPE(src), param);
2893     PadnameOURSTASH(dst) = (HV *)sv_dup_inc((SV *)PadnameOURSTASH(src),
2894                                             param);
2895     dst->xpadn_low  = src->xpadn_low;
2896     dst->xpadn_high = src->xpadn_high;
2897     dst->xpadn_gen  = src->xpadn_gen;
2898     return dst;
2899 }
2900
2901 #endif /* USE_ITHREADS */
2902
2903 /*
2904  * ex: set ts=8 sts=4 sw=4 et:
2905  */