]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - Upper.xs
Fix numerous localizations in the same scope not happening
[perl/modules/Scope-Upper.git] / Upper.xs
1 /* This file is part of the Scope::Upper Perl module.
2  * See http://search.cpan.org/dist/Scope-Upper/ */
3
4 #define PERL_NO_GET_CONTEXT
5 #include "EXTERN.h"
6 #include "perl.h" 
7 #include "XSUB.h"
8
9 #define __PACKAGE__ "Scope::Upper"
10
11 #ifndef SU_DEBUG
12 # define SU_DEBUG 0
13 #endif
14
15 /* --- Compatibility ------------------------------------------------------- */
16
17 #ifndef PERL_UNUSED_VAR
18 # define PERL_UNUSED_VAR(V)
19 #endif
20
21 #ifndef STMT_START
22 # define STMT_START do
23 #endif
24
25 #ifndef STMT_END
26 # define STMT_END while (0)
27 #endif
28
29 #if SU_DEBUG
30 # define SU_D(X) STMT_START X STMT_END
31 #else
32 # define SU_D(X)
33 #endif
34
35 #ifndef Newx
36 # define Newx(v, n, c) New(0, v, n, c)
37 #endif
38
39 #ifndef SvPV_const
40 # define SvPV_const(S, L) SvPV(S, L)
41 #endif
42
43 #ifndef SvPV_nolen_const
44 # define SvPV_nolen_const(S) SvPV_nolen(S)
45 #endif
46
47 #ifndef SvREFCNT_inc_simple_void
48 # define SvREFCNT_inc_simple_void(sv) SvREFCNT_inc(sv)
49 #endif
50
51 #ifndef HvNAME_get
52 # define HvNAME_get(H) HvNAME(H)
53 #endif
54
55 #ifndef gv_fetchpvn_flags
56 # define gv_fetchpvn_flags(A, B, C, D) gv_fetchpv((A), (C), (D))
57 #endif
58
59 #ifndef PERL_MAGIC_tied
60 # define PERL_MAGIC_tied 'P'
61 #endif
62
63 #ifndef PERL_MAGIC_env
64 # define PERL_MAGIC_env 'E'
65 #endif
66
67 #ifndef NEGATIVE_INDICES_VAR
68 # define NEGATIVE_INDICES_VAR "NEGATIVE_INDICES"
69 #endif
70
71 #define SU_HAS_PERL(R, V, S) (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
72
73 /* --- Threads and multiplicity -------------------------------------------- */
74
75 #ifndef NOOP
76 # define NOOP
77 #endif
78
79 #ifndef dNOOP
80 # define dNOOP
81 #endif
82
83 #ifndef SU_MULTIPLICITY
84 # if defined(MULTIPLICITY) || defined(PERL_IMPLICIT_CONTEXT)
85 #  define SU_MULTIPLICITY 1
86 # else
87 #  define SU_MULTIPLICITY 0
88 # endif
89 #endif
90 #if SU_MULTIPLICITY && !defined(tTHX)
91 # define tTHX PerlInterpreter*
92 #endif
93
94 #if SU_MULTIPLICITY && defined(USE_ITHREADS) && defined(dMY_CXT) && defined(MY_CXT) && defined(START_MY_CXT) && defined(MY_CXT_INIT) && (defined(MY_CXT_CLONE) || defined(dMY_CXT_SV))
95 # define SU_THREADSAFE 1
96 # ifndef MY_CXT_CLONE
97 #  define MY_CXT_CLONE \
98     dMY_CXT_SV;                                                      \
99     my_cxt_t *my_cxtp = (my_cxt_t*)SvPVX(newSV(sizeof(my_cxt_t)-1)); \
100     Copy(INT2PTR(my_cxt_t*, SvUV(my_cxt_sv)), my_cxtp, 1, my_cxt_t); \
101     sv_setuv(my_cxt_sv, PTR2UV(my_cxtp))
102 # endif
103 #else
104 # define SU_THREADSAFE 0
105 # undef  dMY_CXT
106 # define dMY_CXT      dNOOP
107 # undef  MY_CXT
108 # define MY_CXT       su_globaldata
109 # undef  START_MY_CXT
110 # define START_MY_CXT STATIC my_cxt_t MY_CXT;
111 # undef  MY_CXT_INIT
112 # define MY_CXT_INIT  NOOP
113 # undef  MY_CXT_CLONE
114 # define MY_CXT_CLONE NOOP
115 #endif
116
117 /* --- Global data --------------------------------------------------------- */
118
119 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
120
121 typedef struct {
122  int stack_placeholder;
123  I32 cxix;
124  I32 items;
125  SV  **savesp;
126  OP  fakeop;
127 } my_cxt_t;
128
129 START_MY_CXT
130
131 /* --- Stack manipulations ------------------------------------------------- */
132
133 #define SU_SAVE_DESTRUCTOR_SIZE 3
134 #define SU_SAVE_INT_SIZE        3
135
136 #ifndef SvCANEXISTDELETE
137 # define SvCANEXISTDELETE(sv) \
138   (!SvRMAGICAL(sv)            \
139    || ((mg = mg_find((SV *) sv, PERL_MAGIC_tied))            \
140        && (stash = SvSTASH(SvRV(SvTIED_obj((SV *) sv, mg)))) \
141        && gv_fetchmethod_autoload(stash, "EXISTS", TRUE)     \
142        && gv_fetchmethod_autoload(stash, "DELETE", TRUE)     \
143       )                       \
144    )
145 #endif
146
147 /* ... Saving array elements ............................................... */
148
149 STATIC I32 su_av_key2idx(pTHX_ AV *av, I32 key) {
150 #define su_av_key2idx(A, K) su_av_key2idx(aTHX_ (A), (K))
151  I32 idx;
152
153  if (key >= 0)
154   return key;
155
156 /* Added by MJD in perl-5.8.1 with 6f12eb6d2a1dfaf441504d869b27d2e40ef4966a */
157 #if SU_HAS_PERL(5, 8, 1)
158  if (SvRMAGICAL(av)) {
159   const MAGIC * const tied_magic = mg_find((SV *) av, PERL_MAGIC_tied);
160   if (tied_magic) {
161    SV * const * const negative_indices_glob =
162                     hv_fetch(SvSTASH(SvRV(SvTIED_obj((SV *) (av), tied_magic))),
163                              NEGATIVE_INDICES_VAR, 16, 0);
164    if (negative_indices_glob && SvTRUE(GvSV(*negative_indices_glob)))
165     return key;
166   }
167  }
168 #endif
169
170  idx = key + av_len(av) + 1;
171  if (idx < 0)
172   return key;
173
174  return idx;
175 }
176
177 #ifndef SAVEADELETE
178
179 typedef struct {
180  AV *av;
181  I32 idx;
182 } su_ud_adelete;
183
184 STATIC void su_adelete(pTHX_ void *ud_) {
185  su_ud_adelete *ud = (su_ud_adelete *) ud_;
186
187  av_delete(ud->av, ud->idx, G_DISCARD);
188  SvREFCNT_dec(ud->av);
189
190  Safefree(ud);
191 }
192
193 STATIC void su_save_adelete(pTHX_ AV *av, I32 idx) {
194 #define su_save_adelete(A, K) su_save_adelete(aTHX_ (A), (K))
195  su_ud_adelete *ud;
196
197  Newx(ud, 1, su_ud_adelete);
198  ud->av  = av;
199  ud->idx = idx;
200  SvREFCNT_inc_simple_void(av);
201
202  SAVEDESTRUCTOR_X(su_adelete, ud);
203 }
204
205 #define SAVEADELETE(A, K) su_save_adelete((A), (K))
206
207 #endif /* SAVEADELETE */
208
209 STATIC void su_save_aelem(pTHX_ AV *av, SV *key, SV *val) {
210 #define su_save_aelem(A, K, V) su_save_aelem(aTHX_ (A), (K), (V))
211  I32 idx;
212  I32 preeminent = 1;
213  SV **svp;
214  HV *stash;
215  MAGIC *mg;
216
217  idx = su_av_key2idx(av, SvIV(key));
218
219  if (SvCANEXISTDELETE(av))
220   preeminent = av_exists(av, idx);
221
222  svp = av_fetch(av, idx, 1);
223  if (!svp || *svp == &PL_sv_undef) croak(PL_no_aelem, idx);
224
225  if (preeminent)
226   save_aelem(av, idx, svp);
227  else
228   SAVEADELETE(av, idx);
229
230  if (val) { /* local $x[$idx] = $val; */
231   SvSetMagicSV(*svp, val);
232  } else {   /* local $x[$idx]; delete $x[$idx]; */
233   av_delete(av, idx, G_DISCARD);
234  }
235 }
236
237 /* ... Saving hash elements ................................................ */
238
239 STATIC void su_save_helem(pTHX_ HV *hv, SV *keysv, SV *val) {
240 #define su_save_helem(H, K, V) su_save_helem(aTHX_ (H), (K), (V))
241  I32 preeminent = 1;
242  HE *he;
243  SV **svp;
244  HV *stash;
245  MAGIC *mg;
246
247  if (SvCANEXISTDELETE(hv) || mg_find((SV *) hv, PERL_MAGIC_env))
248   preeminent = hv_exists_ent(hv, keysv, 0);
249
250  he  = hv_fetch_ent(hv, keysv, 1, 0);
251  svp = he ? &HeVAL(he) : NULL;
252  if (!svp || *svp == &PL_sv_undef) croak("Modification of non-creatable hash value attempted, subscript \"%s\"", SvPV_nolen_const(*svp));
253
254  if (HvNAME_get(hv) && isGV(*svp)) {
255   save_gp((GV *) *svp, 0);
256   return;
257  }
258
259  if (preeminent)
260   save_helem(hv, keysv, svp);
261  else {
262   STRLEN keylen;
263   const char * const key = SvPV_const(keysv, keylen);
264   SAVEDELETE(hv, savepvn(key, keylen),
265                  SvUTF8(keysv) ? -(I32)keylen : (I32)keylen);
266  }
267
268  if (val) { /* local $x{$keysv} = $val; */
269   SvSetMagicSV(*svp, val);
270  } else {   /* local $x{$keysv}; delete $x{$keysv}; */
271   (void)hv_delete_ent(hv, keysv, G_DISCARD, HeHASH(he));
272  }
273 }
274
275 /* --- Actions ------------------------------------------------------------- */
276
277 typedef struct {
278  I32 depth;
279  I32 pad;
280  I32 *origin;
281  void (*handler)(pTHX_ void *);
282 } su_ud_common;
283
284 #define SU_UD_DEPTH(U)   (((su_ud_common *) (U))->depth)
285 #define SU_UD_PAD(U)     (((su_ud_common *) (U))->pad)
286 #define SU_UD_ORIGIN(U)  (((su_ud_common *) (U))->origin)
287 #define SU_UD_HANDLER(U) (((su_ud_common *) (U))->handler)
288
289 #define SU_UD_FREE(U) STMT_START { \
290  if (SU_UD_ORIGIN(U)) Safefree(SU_UD_ORIGIN(U)); \
291  Safefree(U); \
292 } STMT_END
293
294 /* ... Reap ................................................................ */
295
296 typedef struct {
297  su_ud_common ci;
298  SV *cb;
299 } su_ud_reap;
300
301 STATIC void su_call(pTHX_ void *ud_) {
302  su_ud_reap *ud = (su_ud_reap *) ud_;
303 #if SU_HAS_PERL(5, 9, 5)
304  PERL_CONTEXT saved_cx;
305  I32 cxix;
306 #endif
307
308  dSP;
309
310  SU_D({
311   PerlIO_printf(Perl_debug_log,
312                 "%p: @@@ call\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
313                  ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
314  });
315
316  ENTER;
317  SAVETMPS;
318
319  PUSHMARK(SP);
320  PUTBACK;
321
322  /* If the recently popped context isn't saved there, it will be overwritten by
323   * the sub scope from call_sv, although it's still needed in our caller. */
324
325 #if SU_HAS_PERL(5, 9, 5)
326  if (cxstack_ix < cxstack_max)
327   cxix = cxstack_ix + 1;
328  else
329   cxix = Perl_cxinc(aTHX);
330  saved_cx = cxstack[cxix];
331 #endif
332
333  call_sv(ud->cb, G_VOID);
334
335 #if SU_HAS_PERL(5, 9, 5)
336  cxstack[cxix] = saved_cx;
337 #endif
338
339  PUTBACK;
340
341  FREETMPS;
342  LEAVE;
343
344  SvREFCNT_dec(ud->cb);
345  SU_UD_FREE(ud);
346 }
347
348 STATIC void su_reap(pTHX_ void *ud) {
349 #define su_reap(U) su_reap(aTHX_ (U))
350  SU_D({
351   PerlIO_printf(Perl_debug_log,
352                 "%p: === reap\n%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
353                  ud, ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
354  });
355
356  SAVEDESTRUCTOR_X(su_call, ud);
357 }
358
359 /* ... Localize & localize array/hash element .............................. */
360
361 typedef struct {
362  su_ud_common ci;
363  SV    *sv;
364  SV    *val;
365  SV    *elem;
366  svtype type;
367 } su_ud_localize;
368
369 STATIC void su_ud_localize_init(pTHX_ su_ud_localize *ud, SV *sv, SV *val, SV *elem) {
370 #define su_ud_localize_init(UD, S, V, E) su_ud_localize_init(aTHX_ (UD), (S), (V), (E))
371  UV deref = 0;
372  svtype t = SVt_NULL;
373
374  SvREFCNT_inc_simple_void(sv);
375
376  if (SvTYPE(sv) >= SVt_PVGV) {
377   if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
378    t = SVt_PVGV;
379   } else {                   /* local *x = \$val; */
380    t = SvTYPE(SvRV(val));
381    deref = 1;
382   }
383  } else {
384   STRLEN len, l;
385   const char *p = SvPV_const(sv, len), *s;
386   for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
387   if (!l) {
388    l = len;
389    s = p;
390   }
391   switch (*s) {
392    case '$': t = SVt_PV;   break;
393    case '@': t = SVt_PVAV; break;
394    case '%': t = SVt_PVHV; break;
395    case '&': t = SVt_PVCV; break;
396    case '*': t = SVt_PVGV; break;
397   }
398   if (t != SVt_NULL) {
399    ++s;
400    --l;
401   } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
402    if (SvROK(val) && !sv_isobject(val)) {
403     t = SvTYPE(SvRV(val));
404     deref = 1;
405    } else {
406     t = SvTYPE(val);
407    }
408   }
409   SvREFCNT_dec(sv);
410   sv = newSVpvn(s, l);
411  }
412
413  switch (t) {
414   case SVt_PVAV:
415   case SVt_PVHV:
416   case SVt_PVCV:
417   case SVt_PVGV:
418    deref = 0;
419   default:
420    break;
421  }
422  /* When deref is set, val isn't NULL */
423
424  ud->sv   = sv;
425  ud->val  = val ? newSVsv(deref ? SvRV(val) : val) : NULL;
426  ud->elem = SvREFCNT_inc(elem);
427  ud->type = t;
428 }
429
430 STATIC void su_localize(pTHX_ void *ud_) {
431 #define su_localize(U) su_localize(aTHX_ (U))
432  su_ud_localize *ud = (su_ud_localize *) ud_;
433  SV *sv   = ud->sv;
434  SV *val  = ud->val;
435  SV *elem = ud->elem;
436  svtype t = ud->type;
437  GV *gv;
438
439  if (SvTYPE(sv) >= SVt_PVGV) {
440   gv = (GV *) sv;
441  } else {
442 #ifdef gv_fetchsv
443   gv = gv_fetchsv(sv, GV_ADDMULTI, t);
444 #else
445   STRLEN len;
446   const char *name = SvPV_const(sv, len);
447   gv = gv_fetchpvn_flags(name, len, GV_ADDMULTI, t);
448 #endif
449  }
450
451  SU_D({
452   SV *z = newSV(0);
453   SvUPGRADE(z, t);
454   PerlIO_printf(Perl_debug_log, "%p: === localize a %s\n",ud, sv_reftype(z, 0));
455   PerlIO_printf(Perl_debug_log,
456                 "%p: depth=%2d scope_ix=%2d save_ix=%2d\n",
457                  ud, SU_UD_DEPTH(ud), PL_scopestack_ix, PL_savestack_ix);
458   SvREFCNT_dec(z);
459  });
460
461  /* Inspired from Alias.pm */
462  switch (t) {
463   case SVt_PVAV:
464    if (elem) {
465     su_save_aelem(GvAV(gv), elem, val);
466     goto done;
467    } else
468     save_ary(gv);
469    break;
470   case SVt_PVHV:
471    if (elem) {
472     su_save_helem(GvHV(gv), elem, val);
473     goto done;
474    } else
475     save_hash(gv);
476    break;
477   case SVt_PVGV:
478    save_gp(gv, 1); /* hide previous entry in symtab */
479    break;
480   case SVt_PVCV:
481    SAVESPTR(GvCV(gv));
482    GvCV(gv) = NULL;
483    break;
484   default:
485    gv = (GV *) save_scalar(gv);
486    break;
487  }
488
489  if (val)
490   SvSetMagicSV((SV *) gv, val);
491
492 done:
493  SvREFCNT_dec(ud->elem);
494  SvREFCNT_dec(ud->val);
495  SvREFCNT_dec(ud->sv);
496  SU_UD_FREE(ud);
497 }
498
499 /* --- Pop a context back -------------------------------------------------- */
500
501 #if SU_DEBUG
502 # ifdef DEBUGGING
503 #  define SU_CXNAME PL_block_type[CxTYPE(&cxstack[cxstack_ix])]
504 # else
505 #  define SU_CXNAME "XXX"
506 # endif
507 #endif
508
509 STATIC void su_pop(pTHX_ void *ud) {
510 #define su_pop(U) su_pop(aTHX_ (U))
511  I32 depth, base, mark, *origin;
512  depth = SU_UD_DEPTH(ud);
513
514  SU_D(
515   PerlIO_printf(Perl_debug_log,
516    "%p: --- pop a %s\n"
517    "%p: leave scope     at depth=%2d scope_ix=%2d cur_top=%2d cur_base=%2d\n",
518     ud, SU_CXNAME,
519     ud, depth, PL_scopestack_ix,PL_savestack_ix,PL_scopestack[PL_scopestack_ix])
520  );
521
522  origin = SU_UD_ORIGIN(ud);
523  mark   = origin[depth];
524  base   = origin[depth - 1];
525
526  SU_D(PerlIO_printf(Perl_debug_log,
527                     "%p: original scope was %*c top=%2d     base=%2d\n",
528                      ud,                24, ' ',    mark,        base));
529
530  if (base < mark) {
531   SU_D(PerlIO_printf(Perl_debug_log, "%p: clear leftovers\n", ud));
532   PL_savestack_ix = mark;
533   leave_scope(base);
534  }
535  PL_savestack_ix = base;
536
537  SU_UD_DEPTH(ud) = --depth;
538
539  if (depth > 0) {
540   I32 i = 1, pad;
541
542   if (pad = SU_UD_PAD(ud)) {
543    dMY_CXT;
544    do {
545     save_int(&MY_CXT.stack_placeholder);
546    } while (--pad);
547   }
548   SAVEDESTRUCTOR_X(su_pop, ud);
549
550   /* Skip depths corresponding to scopes for which leave_scope() might not be
551    * called. */
552   while (depth > 1 && PL_scopestack_ix >= i) {
553    I32 j = PL_scopestack[PL_scopestack_ix - i];
554
555    if (j < PL_savestack_ix)
556     break;
557
558    SU_D(PerlIO_printf(Perl_debug_log,
559     "%p: skip scope%*cat depth=%2d scope_ix=%2d new_top=%2d >= cur_base=%2d\n",
560      ud,           6, ' ',   depth, PL_scopestack_ix - i, j, PL_savestack_ix));
561
562    SU_UD_DEPTH(ud) = --depth;
563
564    ++i;
565   }
566
567   SU_D(PerlIO_printf(Perl_debug_log,
568           "%p: push destructor at depth=%2d scope_ix=%2d save_ix=%2d\n",
569            ud,                       depth, PL_scopestack_ix, PL_savestack_ix));
570  } else {
571   SU_UD_HANDLER(ud)(aTHX_ ud);
572  }
573
574  SU_D(PerlIO_printf(Perl_debug_log,
575                     "%p: --- end pop: cur_top=%2d == cur_base=%2d\n",
576                      ud, PL_savestack_ix, PL_scopestack[PL_scopestack_ix]));
577 }
578
579 /* --- Initialize the stack and the action userdata ------------------------ */
580
581 STATIC I32 su_init(pTHX_ I32 cxix, void *ud, I32 size) {
582 #define su_init(L, U, S) su_init(aTHX_ (L), (U), (S))
583  I32 i, depth = 1, pad, offset, *origin;
584
585  SU_D(PerlIO_printf(Perl_debug_log, "%p: ### init for cx %d\n", ud, cxix));
586
587  if (size <= SU_SAVE_DESTRUCTOR_SIZE)
588   pad = 0;
589  else {
590   I32 extra = size - SU_SAVE_DESTRUCTOR_SIZE;
591   pad = extra / SU_SAVE_INT_SIZE + ((extra % SU_SAVE_INT_SIZE) ? 1 : 0);
592  }
593  offset = SU_SAVE_DESTRUCTOR_SIZE + SU_SAVE_INT_SIZE * pad;
594
595  SU_D(PerlIO_printf(Perl_debug_log, "%p: size=%d pad=%d offset=%d\n",
596                                      ud,    size,   pad,   offset));
597
598  for (i = cxstack_ix; i > cxix; --i) {
599   PERL_CONTEXT *cx = cxstack + i;
600   switch (CxTYPE(cx)) {
601 #if SU_HAS_PERL(5, 10, 0)
602    case CXt_BLOCK:
603     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is block\n", ud, i));
604     /* Given and when blocks are actually followed by a simple block, so skip
605      * it if needed. */
606     if (cxix > 0) { /* Implies i > 0 */
607      PERL_CONTEXT *next = cx - 1;
608      if (CxTYPE(next) == CXt_GIVEN || CxTYPE(next) == CXt_WHEN)
609       --cxix;
610     }
611     depth++;
612     break;
613 #endif
614 #if SU_HAS_PERL(5, 11, 0)
615    case CXt_LOOP_FOR:
616    case CXt_LOOP_PLAIN:
617    case CXt_LOOP_LAZYSV:
618    case CXt_LOOP_LAZYIV:
619 #else
620    case CXt_LOOP:
621 #endif
622     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is loop\n", ud, i));
623     depth += 2;
624     break;
625    default:
626     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is other\n", ud, i));
627     depth++;
628     break;
629   }
630  }
631  SU_D(PerlIO_printf(Perl_debug_log, "%p: going down to depth %d\n", ud, depth));
632
633  Newx(origin, depth + 1, I32);
634  origin[0] = PL_scopestack[PL_scopestack_ix - depth];
635  PL_scopestack[PL_scopestack_ix - depth] += size;
636  for (i = depth - 1; i >= 1; --i) {
637   I32 j = PL_scopestack_ix - i;
638   origin[depth - i] = PL_scopestack[j];
639   PL_scopestack[j] += offset;
640  }
641  origin[depth] = PL_savestack_ix;
642
643  SU_UD_ORIGIN(ud) = origin;
644  SU_UD_DEPTH(ud)  = depth;
645  SU_UD_PAD(ud)    = pad;
646
647  /* Make sure the first destructor fires by pushing enough fake slots on the
648   * stack. */
649  if (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
650                                        <= PL_scopestack[PL_scopestack_ix - 1]) {
651   dMY_CXT;
652   do {
653    SU_D(PerlIO_printf(Perl_debug_log,
654                   "%p: push a fake slot      at scope_ix=%2d  save_ix=%2d\n",
655                    ud,                      PL_scopestack_ix, PL_savestack_ix));
656    save_int(&MY_CXT.stack_placeholder);
657   } while (PL_savestack_ix + SU_SAVE_DESTRUCTOR_SIZE
658                                         <= PL_scopestack[PL_scopestack_ix - 1]);
659  }
660  SU_D(PerlIO_printf(Perl_debug_log,
661                   "%p: push first destructor at scope_ix=%2d  save_ix=%2d\n",
662                    ud,                      PL_scopestack_ix, PL_savestack_ix));
663  SAVEDESTRUCTOR_X(su_pop, ud);
664
665  SU_D({
666   for (i = 0; i <= depth; ++i) {
667    I32 j = PL_scopestack_ix  - i;
668    PerlIO_printf(Perl_debug_log,
669                  "%p: depth=%2d scope_ix=%2d saved_floor=%2d new_floor=%2d\n",
670                   ud,        i, j, origin[depth - i],
671                                    i == 0 ? PL_savestack_ix : PL_scopestack[j]);
672   }
673  });
674
675  return depth;
676 }
677
678 /* --- Unwind stack -------------------------------------------------------- */
679
680 STATIC void su_unwind(pTHX_ void *ud_) {
681  dMY_CXT;
682  I32 cxix    = MY_CXT.cxix;
683  I32 items   = MY_CXT.items - 1;
684  SV **savesp = MY_CXT.savesp;
685  I32 mark;
686
687  PERL_UNUSED_VAR(ud_);
688
689  if (savesp)
690   PL_stack_sp = savesp;
691
692  if (cxstack_ix > cxix)
693   dounwind(cxix);
694
695  /* Hide the level */
696  if (items >= 0)
697   PL_stack_sp--;
698
699  mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
700  *PL_markstack_ptr = PL_stack_sp - PL_stack_base - items;
701
702  SU_D({
703   I32 gimme = GIMME_V;
704   PerlIO_printf(Perl_debug_log,
705                 "%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
706                 &MY_CXT, cxix,
707                 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
708                 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
709  });
710
711  PL_op = PL_ppaddr[OP_RETURN](aTHX);
712  *PL_markstack_ptr = mark;
713
714  MY_CXT.fakeop.op_next = PL_op;
715  PL_op = &(MY_CXT.fakeop);
716 }
717
718 /* --- XS ------------------------------------------------------------------ */
719
720 #if SU_HAS_PERL(5, 8, 9)
721 # define SU_SKIP_DB_MAX 2
722 #else
723 # define SU_SKIP_DB_MAX 3
724 #endif
725
726 /* Skip context sequences of 1 to SU_SKIP_DB_MAX (included) block contexts
727  * followed by a DB sub */
728
729 #define SU_SKIP_DB(C) \
730  STMT_START {         \
731   I32 skipped = 0;    \
732   PERL_CONTEXT *base = cxstack;      \
733   PERL_CONTEXT *cx   = base + (C);   \
734   while (cx >= base && (C) > skipped && CxTYPE(cx) == CXt_BLOCK) \
735    --cx, ++skipped;                  \
736   if (cx >= base && (C) > skipped) { \
737    switch (CxTYPE(cx)) {  \
738     case CXt_SUB:         \
739      if (skipped <= SU_SKIP_DB_MAX && cx->blk_sub.cv == GvCV(PL_DBsub)) \
740       (C) -= skipped + 1; \
741       break;              \
742     default:              \
743      break;               \
744    }                      \
745   }                       \
746  } STMT_END
747
748 #define SU_GET_CONTEXT(A, B)   \
749  STMT_START {                  \
750   if (items > A) {             \
751    SV *csv = ST(B);            \
752    if (!SvOK(csv))             \
753     goto default_cx;           \
754    cxix = SvIV(csv);           \
755    if (cxix < 0)               \
756     cxix = 0;                  \
757    else if (cxix > cxstack_ix) \
758     cxix = cxstack_ix;         \
759   } else {                     \
760 default_cx:                    \
761    cxix = cxstack_ix;          \
762    if (PL_DBsub)               \
763     SU_SKIP_DB(cxix);          \
764   }                            \
765  } STMT_END
766
767 #define SU_GET_LEVEL(A, B) \
768  STMT_START {              \
769   level = 0;               \
770   if (items > 0) {         \
771    SV *lsv = ST(B);        \
772    if (SvOK(lsv)) {        \
773     level = SvIV(lsv);     \
774     if (level < 0)         \
775      level = 0;            \
776    }                       \
777   }                        \
778  } STMT_END
779
780 XS(XS_Scope__Upper_unwind); /* prototype to pass -Wmissing-prototypes */
781
782 XS(XS_Scope__Upper_unwind) {
783 #ifdef dVAR
784  dVAR; dXSARGS;
785 #else
786  dXSARGS;
787 #endif
788  dMY_CXT;
789  I32 cxix;
790
791  PERL_UNUSED_VAR(cv); /* -W */
792  PERL_UNUSED_VAR(ax); /* -Wall */
793
794  SU_GET_CONTEXT(0, items - 1);
795  do {
796   PERL_CONTEXT *cx = cxstack + cxix;
797   switch (CxTYPE(cx)) {
798    case CXt_SUB:
799     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
800      continue;
801    case CXt_EVAL:
802    case CXt_FORMAT:
803     MY_CXT.cxix  = cxix;
804     MY_CXT.items = items;
805     /* pp_entersub will want to sanitize the stack after returning from there
806      * Screw that, we're insane */
807     if (GIMME_V == G_SCALAR) {
808      MY_CXT.savesp = PL_stack_sp;
809      /* dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
810      PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
811     } else {
812      MY_CXT.savesp = NULL;
813     }
814     SAVEDESTRUCTOR_X(su_unwind, NULL);
815     return;
816    default:
817     break;
818   }
819  } while (--cxix >= 0);
820  croak("Can't return outside a subroutine");
821 }
822
823 MODULE = Scope::Upper            PACKAGE = Scope::Upper
824
825 PROTOTYPES: ENABLE
826
827 BOOT:
828 {
829  HV *stash;
830
831  MY_CXT_INIT;
832  MY_CXT.stack_placeholder = 0;
833
834  stash = gv_stashpv(__PACKAGE__, 1);
835  newCONSTSUB(stash, "TOP",           newSViv(0));
836  newCONSTSUB(stash, "SU_THREADSAFE", newSVuv(SU_THREADSAFE));
837
838  newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
839 }
840
841 #if SU_THREADSAFE
842
843 void
844 CLONE(...)
845 PROTOTYPE: DISABLE
846 CODE:
847  PERL_UNUSED_VAR(items);
848  {
849   MY_CXT_CLONE;
850  }
851
852 #endif /* SU_THREADSAFE */
853
854 SV *
855 HERE()
856 PROTOTYPE:
857 PREINIT:
858  I32 cxix = cxstack_ix;
859 CODE:
860  if (PL_DBsub)
861   SU_SKIP_DB(cxix);
862  RETVAL = newSViv(cxix);
863 OUTPUT:
864  RETVAL
865
866 SV *
867 UP(...)
868 PROTOTYPE: ;$
869 PREINIT:
870  I32 cxix;
871 CODE:
872  SU_GET_CONTEXT(0, 0);
873  if (--cxix < 0)
874   cxix = 0;
875  if (PL_DBsub)
876   SU_SKIP_DB(cxix);
877  RETVAL = newSViv(cxix);
878 OUTPUT:
879  RETVAL
880
881 void
882 SUB(...)
883 PROTOTYPE: ;$
884 PREINIT:
885  I32 cxix;
886 PPCODE:
887  SU_GET_CONTEXT(0, 0);
888  for (; cxix >= 0; --cxix) {
889   PERL_CONTEXT *cx = cxstack + cxix;
890   switch (CxTYPE(cx)) {
891    default:
892     continue;
893    case CXt_SUB:
894     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
895      continue;
896     ST(0) = sv_2mortal(newSViv(cxix));
897     XSRETURN(1);
898   }
899  }
900  XSRETURN_UNDEF;
901
902 void
903 EVAL(...)
904 PROTOTYPE: ;$
905 PREINIT:
906  I32 cxix;
907 PPCODE:
908  SU_GET_CONTEXT(0, 0);
909  for (; cxix >= 0; --cxix) {
910   PERL_CONTEXT *cx = cxstack + cxix;
911   switch (CxTYPE(cx)) {
912    default:
913     continue;
914    case CXt_EVAL:
915     ST(0) = sv_2mortal(newSViv(cxix));
916     XSRETURN(1);
917   }
918  }
919  XSRETURN_UNDEF;
920
921 void
922 SCOPE(...)
923 PROTOTYPE: ;$
924 PREINIT:
925  I32 cxix, level;
926 PPCODE:
927  SU_GET_LEVEL(0, 0);
928  cxix = cxstack_ix;
929  if (PL_DBsub) {
930   SU_SKIP_DB(cxix);
931   while (cxix > 0) {
932    if (--level < 0)
933     break;
934    --cxix;
935    SU_SKIP_DB(cxix);
936   }
937  } else {
938   cxix -= level;
939   if (cxix < 0)
940    cxix = 0;
941  }
942  ST(0) = sv_2mortal(newSViv(cxix));
943  XSRETURN(1);
944
945 void
946 CALLER(...)
947 PROTOTYPE: ;$
948 PREINIT:
949  I32 cxix, level;
950 PPCODE:
951  SU_GET_LEVEL(0, 0);
952  for (cxix = cxstack_ix; cxix > 0; --cxix) {
953   PERL_CONTEXT *cx = cxstack + cxix;
954   switch (CxTYPE(cx)) {
955    case CXt_SUB:
956     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
957      continue;
958    case CXt_EVAL:
959    case CXt_FORMAT:
960     if (--level < 0)
961      goto done;
962     break;
963   }
964  }
965 done:
966  ST(0) = sv_2mortal(newSViv(cxix));
967  XSRETURN(1);
968
969 void
970 want_at(...)
971 PROTOTYPE: ;$
972 PREINIT:
973  I32 cxix;
974 PPCODE:
975  SU_GET_CONTEXT(0, 0);
976  while (cxix > 0) {
977   PERL_CONTEXT *cx = cxstack + cxix--;
978   switch (CxTYPE(cx)) {
979    case CXt_SUB:
980    case CXt_EVAL:
981    case CXt_FORMAT: {
982     I32 gimme = cx->blk_gimme;
983     switch (gimme) {
984      case G_VOID:   XSRETURN_UNDEF; break;
985      case G_SCALAR: XSRETURN_NO;    break;
986      case G_ARRAY:  XSRETURN_YES;   break;
987     }
988     break;
989    }
990   }
991  }
992  XSRETURN_UNDEF;
993
994 void
995 reap(SV *hook, ...)
996 PROTOTYPE: &;$
997 PREINIT:
998  I32 cxix;
999  su_ud_reap *ud;
1000 CODE:
1001  SU_GET_CONTEXT(1, 1);
1002  Newx(ud, 1, su_ud_reap);
1003  SU_UD_ORIGIN(ud)  = NULL;
1004  SU_UD_HANDLER(ud) = su_reap;
1005  ud->cb = newSVsv(hook);
1006  su_init(cxix, ud, 3);
1007
1008 void
1009 localize(SV *sv, SV *val, ...)
1010 PROTOTYPE: $$;$
1011 PREINIT:
1012  I32 cxix;
1013  I32 size = 3;
1014  su_ud_localize *ud;
1015 CODE:
1016  SU_GET_CONTEXT(2, 2);
1017  Newx(ud, 1, su_ud_localize);
1018  SU_UD_ORIGIN(ud)  = NULL;
1019  SU_UD_HANDLER(ud) = su_localize;
1020  su_ud_localize_init(ud, sv, val, NULL);
1021 #if !SU_HAS_PERL(5, 8, 9)
1022  if (ud->type >= SVt_PVGV)
1023   size = 6;
1024 #endif
1025  su_init(cxix, ud, size);
1026
1027 void
1028 localize_elem(SV *sv, SV *elem, SV *val, ...)
1029 PROTOTYPE: $$$;$
1030 PREINIT:
1031  I32 cxix;
1032  su_ud_localize *ud;
1033 CODE:
1034  SU_GET_CONTEXT(3, 3);
1035  Newx(ud, 1, su_ud_localize);
1036  SU_UD_ORIGIN(ud)  = NULL;
1037  SU_UD_HANDLER(ud) = su_localize;
1038  su_ud_localize_init(ud, sv, val, elem);
1039  su_init(cxix, ud, 4);
1040
1041 void
1042 localize_delete(SV *sv, SV *elem, ...)
1043 PROTOTYPE: $$;$
1044 PREINIT:
1045  I32 cxix;
1046  I32 size = 4;
1047  su_ud_localize *ud;
1048 CODE:
1049  SU_GET_CONTEXT(2, 2);
1050  Newx(ud, 1, su_ud_localize);
1051  SU_UD_ORIGIN(ud)  = NULL;
1052  SU_UD_HANDLER(ud) = su_localize;
1053  su_ud_localize_init(ud, sv, NULL, elem);
1054 #if !SU_HAS_PERL(5, 8, 9)
1055  if (ud->type >= SVt_PVGV)
1056   size = 6;
1057 #endif
1058  su_init(cxix, ud, size);