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