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