]> git.vpit.fr Git - perl/modules/Scope-Upper.git/blob - Upper.xs
A saner workaround for the "call_sv() during LEAVE clobbers the still used last poppe...
[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, 10, 0)
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(PerlIO_printf(Perl_debug_log, "%p: @@@ call at %d (save is %d)\n",
289                                      ud, PL_scopestack_ix, PL_savestack_ix));
290  ENTER;
291  SAVETMPS;
292
293  PUSHMARK(SP);
294  PUTBACK;
295
296  /* If cxstack_ix isn't incremented there, the eval context will be overwritten
297   * when the new sub scope will be created in call_sv. */
298
299 #if SU_HAS_PERL(5, 10, 0)
300  if (dieing) {
301   if (cxstack_ix < cxstack_max)
302    cxix = cxstack_ix + 1;
303   else
304    cxix = Perl_cxinc(aTHX);
305   saved_cx = cxstack[cxix];
306  }
307 #endif
308
309  call_sv(ud->cb, G_VOID);
310
311 #if SU_HAS_PERL(5, 10, 0)
312  if (dieing)
313   cxstack[cxix] = saved_cx;
314 #endif
315
316  PUTBACK;
317
318  FREETMPS;
319  LEAVE;
320
321  SvREFCNT_dec(ud->cb);
322  SU_UD_FREE(ud);
323 }
324
325 STATIC void su_reap(pTHX_ void *ud) {
326 #define su_reap(U) su_reap(aTHX_ (U))
327  SU_D(PerlIO_printf(Perl_debug_log, "%p: === reap at %d (save is %d)\n",
328                                      ud, PL_scopestack_ix, PL_savestack_ix));
329  SAVEDESTRUCTOR_X(su_call, ud);
330  SU_D(PerlIO_printf(Perl_debug_log, "%p: savestack is now at %d, base at %d\n",
331                                      ud, PL_savestack_ix,
332                                          PL_scopestack[PL_scopestack_ix]));
333 }
334
335 /* ... Localize & localize array/hash element .............................. */
336
337 typedef struct {
338  su_ud_common ci;
339  SV *sv;
340  SV *val;
341  SV *elem;
342 } su_ud_localize;
343
344 STATIC void su_localize(pTHX_ void *ud_) {
345 #define su_localize(U) su_localize(aTHX_ (U))
346  su_ud_localize *ud = (su_ud_localize *) ud_;
347  SV *sv   = ud->sv;
348  SV *val  = ud->val;
349  SV *elem = ud->elem;
350  GV *gv;
351  UV deref = 0;
352  svtype t = SVt_NULL;
353
354  if (SvTYPE(sv) >= SVt_PVGV) {
355   gv = (GV *) sv;
356   if (!val || !SvROK(val)) { /* local *x; or local *x = $val; */
357    t = SVt_PVGV;
358   } else {                   /* local *x = \$val; */
359    t = SvTYPE(SvRV(val));
360    deref = 1;
361   }
362  } else {
363   STRLEN len, l;
364   const char *p = SvPV_const(sv, len), *s;
365   for (s = p, l = len; l > 0 && isSPACE(*s); ++s, --l) { }
366   if (!l) {
367    l = len;
368    s = p;
369   }
370   switch (*s) {
371    case '$': t = SVt_PV;   break;
372    case '@': t = SVt_PVAV; break;
373    case '%': t = SVt_PVHV; break;
374    case '&': t = SVt_PVCV; break;
375    case '*': t = SVt_PVGV; break;
376   }
377   if (t != SVt_NULL) {
378    ++s;
379    --l;
380   } else if (val) { /* t == SVt_NULL, type can't be inferred from the sigil */
381    if (SvROK(val) && !sv_isobject(val)) {
382     t = SvTYPE(SvRV(val));
383     deref = 1;
384    } else {
385     t = SvTYPE(val);
386    }
387   }
388   gv = gv_fetchpvn_flags(s, l, GV_ADDMULTI, SVt_PVGV);
389  }
390
391  SU_D({
392   SV *z = newSV_type(t);
393   PerlIO_printf(Perl_debug_log, "%p: === localize a %s at %d (save is %d)\n",
394                                  ud, sv_reftype(z, 0),
395                                      PL_scopestack_ix, PL_savestack_ix);
396   SvREFCNT_dec(z);
397  });
398
399  /* Inspired from Alias.pm */
400  switch (t) {
401   case SVt_PVAV:
402    if (elem) {
403     su_save_aelem(GvAV(gv), elem, val);
404     goto done;
405    } else
406     save_ary(gv);
407    break;
408   case SVt_PVHV:
409    if (elem) {
410     su_save_helem(GvHV(gv), elem, val);
411     goto done;
412    } else
413     save_hash(gv);
414    break;
415   case SVt_PVGV:
416    save_gp(gv, 1); /* hide previous entry in symtab */
417    break;
418   case SVt_PVCV:
419    SAVESPTR(GvCV(gv));
420    GvCV(gv) = NULL;
421    break;
422   default:
423    gv = (GV *) save_scalar(gv);
424    if (deref) /* val != NULL */
425     val = SvRV(val);
426    break;
427  }
428
429  SU_D(PerlIO_printf(Perl_debug_log, "%p: savestack is now at %d, base at %d\n",
430                                      ud, PL_savestack_ix,
431                                          PL_scopestack[PL_scopestack_ix]));
432
433  if (val)
434   SvSetMagicSV((SV *) gv, val);
435
436 done:
437  SvREFCNT_dec(ud->elem);
438  SvREFCNT_dec(ud->val);
439  SvREFCNT_dec(ud->sv);
440  SU_UD_FREE(ud);
441 }
442
443 /* --- Pop a context back -------------------------------------------------- */
444
445 #if SU_DEBUG
446 # ifdef DEBUGGING
447 #  define SU_CXNAME PL_block_type[CxTYPE(&cxstack[cxstack_ix])]
448 # else
449 #  define SU_CXNAME "XXX"
450 # endif
451 #endif
452
453 STATIC void su_pop(pTHX_ void *ud) {
454 #define su_pop(U) su_pop(aTHX_ (U))
455  I32 depth, base, mark, *origin;
456  depth = SU_UD_DEPTH(ud);
457
458  SU_D(PerlIO_printf(Perl_debug_log, "%p: --- pop %s at %d from %d to %d [%d]\n",
459                                      ud, SU_CXNAME,
460                                          PL_scopestack_ix, PL_savestack_ix,
461                                          PL_scopestack[PL_scopestack_ix],
462                                          depth));
463
464  origin = SU_UD_ORIGIN(ud);
465  mark   = origin[depth];
466  base   = origin[depth - 1];
467
468  SU_D(PerlIO_printf(Perl_debug_log, "%p: clean from %d down to %d\n",
469                                      ud, mark, base));
470
471  if (base < mark) {
472   PL_savestack_ix = mark;
473   leave_scope(base);
474  }
475  PL_savestack_ix = base;
476  if (--depth > 0) {
477   SU_UD_DEPTH(ud) = depth;
478   SU_D(PerlIO_printf(Perl_debug_log, "%p: save new destructor at %d [%d]\n",
479                                       ud, PL_savestack_ix, depth));
480   SAVEDESTRUCTOR_X(su_pop, ud);
481   SU_D(PerlIO_printf(Perl_debug_log, "%p: pop end at at %d [%d]\n",
482                                       ud, PL_savestack_ix, depth));
483  } else {
484   SU_UD_HANDLER(ud)(aTHX_ ud);
485  }
486 }
487
488 /* --- Initialize the stack and the action userdata ------------------------ */
489
490 STATIC I32 su_init(pTHX_ I32 cxix, void *ud, I32 size) {
491 #define su_init(L, U, S) su_init(aTHX_ (L), (U), (S))
492  I32 i, depth = 0, *origin;
493
494  LEAVE;
495
496  if (cxix >= cxstack_ix) {
497   SU_UD_HANDLER(ud)(aTHX_ ud);
498   goto done;
499  }
500
501  SU_D(PerlIO_printf(Perl_debug_log, "%p: ### init for cx %d\n", ud, cxix));
502
503  for (i = cxstack_ix; i > cxix; --i) {
504   PERL_CONTEXT *cx = cxstack + i;
505   switch (CxTYPE(cx)) {
506 #if SU_HAS_PERL(5, 11, 0)
507    case CXt_LOOP_FOR:
508    case CXt_LOOP_PLAIN:
509    case CXt_LOOP_LAZYSV:
510    case CXt_LOOP_LAZYIV:
511 #else
512    case CXt_LOOP:
513 #endif
514     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is loop\n", ud, i));
515     depth += 2;
516     break;
517    default:
518     SU_D(PerlIO_printf(Perl_debug_log, "%p: cx %d is normal\n", ud, i));
519     depth++;
520     break;
521   }
522  }
523  SU_D(PerlIO_printf(Perl_debug_log, "%p: depth is %d\n", ud, depth));
524
525  Newx(origin, depth + 1, I32);
526  origin[0] = PL_scopestack[PL_scopestack_ix - depth];
527  PL_scopestack[PL_scopestack_ix - depth] += size;
528  for (i = depth - 1; i >= 1; --i) {
529   I32 j = PL_scopestack_ix - i;
530   origin[depth - i] = PL_scopestack[j];
531   PL_scopestack[j] += 3;
532  }
533  origin[depth] = PL_savestack_ix;
534
535  SU_D({
536   PerlIO_printf(Perl_debug_log, "%p: d=%d s=%d x=%d c=%d o=%d\n", ud,
537                 depth, 0, PL_scopestack_ix - 1, PL_savestack_ix, origin[depth]);
538   for (i = depth - 1; i >= 0; --i) {
539    I32 x = PL_scopestack_ix  - depth + i;
540    PerlIO_printf(Perl_debug_log, "%p: d=%d s=%d x=%d c=%d o=%d\n", ud,
541                                   i, depth - i, x, PL_scopestack[x], origin[i]);
542   }
543  });
544
545  SU_UD_ORIGIN(ud) = origin;
546  SU_UD_DEPTH(ud)  = depth;
547
548  SU_D(PerlIO_printf(Perl_debug_log, "%p: set original destructor at %d [%d]\n",
549                                      ud, PL_savestack_ix, depth));
550
551  SAVEDESTRUCTOR_X(su_pop, ud);
552
553 done:
554  ENTER;
555
556  return depth;
557 }
558
559 /* --- Global data --------------------------------------------------------- */
560
561 #define MY_CXT_KEY __PACKAGE__ "::_guts" XS_VERSION
562
563 typedef struct {
564  I32 cxix;
565  I32 items;
566  SV  **savesp;
567  OP  fakeop;
568 } my_cxt_t;
569
570 START_MY_CXT
571
572 /* --- Unwind stack -------------------------------------------------------- */
573
574 STATIC void su_unwind(pTHX_ void *ud_) {
575  dMY_CXT;
576  I32 cxix    = MY_CXT.cxix;
577  I32 items   = MY_CXT.items - 1;
578  SV **savesp = MY_CXT.savesp;
579  I32 mark;
580
581  PERL_UNUSED_VAR(ud_);
582
583  if (savesp)
584   PL_stack_sp = savesp;
585
586  if (cxstack_ix > cxix)
587   dounwind(cxix);
588
589  /* Hide the level */
590  if (items >= 0)
591   PL_stack_sp--;
592
593  mark = PL_markstack[cxstack[cxix].blk_oldmarksp];
594  *PL_markstack_ptr = PL_stack_sp - PL_stack_base - items;
595
596  SU_D({
597   I32 gimme = GIMME_V;
598   PerlIO_printf(Perl_debug_log,
599                 "%p: cx=%d gimme=%s items=%d sp=%d oldmark=%d mark=%d\n",
600                 &MY_CXT, cxix,
601                 gimme == G_VOID ? "void" : gimme == G_ARRAY ? "list" : "scalar",
602                 items, PL_stack_sp - PL_stack_base, *PL_markstack_ptr, mark);
603  });
604
605  PL_op = PL_ppaddr[OP_RETURN](aTHX);
606  *PL_markstack_ptr = mark;
607
608  MY_CXT.fakeop.op_next = PL_op;
609  PL_op = &(MY_CXT.fakeop);
610 }
611
612 /* --- XS ------------------------------------------------------------------ */
613
614 #if SU_HAS_PERL(5, 8, 9)
615 # define SU_SKIP_DB_MAX 2
616 #else
617 # define SU_SKIP_DB_MAX 3
618 #endif
619
620 /* Skip context sequences of 1 to SU_SKIP_DB_MAX (included) block contexts
621  * followed by a DB sub */
622
623 #define SU_SKIP_DB(C) \
624  STMT_START {         \
625   I32 i = 1;          \
626   PERL_CONTEXT *cx = cxstack + (C); \
627   do {                              \
628    if (CxTYPE(cx) == CXt_BLOCK && (C) >= i) { \
629     --cx;                                     \
630     if (CxTYPE(cx) == CXt_SUB && cx->blk_sub.cv == GvCV(PL_DBsub)) { \
631      (C) -= i + 1;                 \
632      break;                        \
633     }                              \
634    } else                          \
635     break;                         \
636   } while (++i <= SU_SKIP_DB_MAX); \
637  } STMT_END
638
639 #define SU_GET_CONTEXT(A, B)   \
640  STMT_START {                  \
641   if (items > A) {             \
642    SV *csv = ST(B);            \
643    if (!SvOK(csv))             \
644     goto default_cx;           \
645    cxix = SvIV(csv);           \
646    if (cxix < 0)               \
647     cxix = 0;                  \
648    else if (cxix > cxstack_ix) \
649     cxix = cxstack_ix;         \
650   } else {                     \
651 default_cx:                    \
652    cxix = cxstack_ix;          \
653    if (PL_DBsub)               \
654     SU_SKIP_DB(cxix);          \
655   }                            \
656  } STMT_END
657
658 #define SU_GET_LEVEL(A, B) \
659  STMT_START {              \
660   level = 0;               \
661   if (items > 0) {         \
662    SV *lsv = ST(B);        \
663    if (SvOK(lsv)) {        \
664     level = SvIV(lsv);     \
665     if (level < 0)         \
666      level = 0;            \
667    }                       \
668   }                        \
669  } STMT_END
670
671 XS(XS_Scope__Upper_unwind); /* prototype to pass -Wmissing-prototypes */
672
673 XS(XS_Scope__Upper_unwind) {
674 #ifdef dVAR
675  dVAR; dXSARGS;
676 #else
677  dXSARGS;
678 #endif
679  dMY_CXT;
680  I32 cxix;
681
682  PERL_UNUSED_VAR(cv); /* -W */
683  PERL_UNUSED_VAR(ax); /* -Wall */
684
685  SU_GET_CONTEXT(0, items - 1);
686  do {
687   PERL_CONTEXT *cx = cxstack + cxix;
688   switch (CxTYPE(cx)) {
689    case CXt_SUB:
690     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
691      continue;
692    case CXt_EVAL:
693    case CXt_FORMAT:
694     MY_CXT.cxix  = cxix;
695     MY_CXT.items = items;
696     /* pp_entersub will want to sanitize the stack after returning from there
697      * Screw that, we're insane */
698     if (GIMME_V == G_SCALAR) {
699      MY_CXT.savesp = PL_stack_sp;
700      /* dXSARGS calls POPMARK, so we need to match PL_markstack_ptr[1] */
701      PL_stack_sp = PL_stack_base + PL_markstack_ptr[1] + 1;
702     } else {
703      MY_CXT.savesp = NULL;
704     }
705     SAVEDESTRUCTOR_X(su_unwind, NULL);
706     return;
707    default:
708     break;
709   }
710  } while (--cxix >= 0);
711  croak("Can't return outside a subroutine");
712 }
713
714 MODULE = Scope::Upper            PACKAGE = Scope::Upper
715
716 PROTOTYPES: ENABLE
717
718 BOOT:
719 {
720  HV *stash;
721  MY_CXT_INIT;
722  stash = gv_stashpv(__PACKAGE__, 1);
723  newCONSTSUB(stash, "TOP", newSViv(0));
724  newXSproto("Scope::Upper::unwind", XS_Scope__Upper_unwind, file, NULL);
725 }
726
727 #if SU_THREADSAFE
728
729 void
730 CLONE(...)
731 PROTOTYPE: DISABLE
732 CODE:
733  PERL_UNUSED_VAR(items);
734  {
735   MY_CXT_CLONE;
736  }
737
738 #endif /* SU_THREADSAFE */
739
740 SV *
741 HERE()
742 PROTOTYPE:
743 PREINIT:
744  I32 cxix = cxstack_ix;
745 CODE:
746  if (PL_DBsub)
747   SU_SKIP_DB(cxix);
748  RETVAL = newSViv(cxix);
749 OUTPUT:
750  RETVAL
751
752 SV *
753 UP(...)
754 PROTOTYPE: ;$
755 PREINIT:
756  I32 cxix;
757 CODE:
758  SU_GET_CONTEXT(0, 0);
759  if (--cxix < 0)
760   cxix = 0;
761  if (PL_DBsub)
762   SU_SKIP_DB(cxix);
763  RETVAL = newSViv(cxix);
764 OUTPUT:
765  RETVAL
766
767 void
768 SUB(...)
769 PROTOTYPE: ;$
770 PREINIT:
771  I32 cxix;
772 PPCODE:
773  SU_GET_CONTEXT(0, 0);
774  for (; cxix >= 0; --cxix) {
775   PERL_CONTEXT *cx = cxstack + cxix;
776   switch (CxTYPE(cx)) {
777    default:
778     continue;
779    case CXt_SUB:
780     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
781      continue;
782     ST(0) = sv_2mortal(newSViv(cxix));
783     XSRETURN(1);
784   }
785  }
786  XSRETURN_UNDEF;
787
788 void
789 EVAL(...)
790 PROTOTYPE: ;$
791 PREINIT:
792  I32 cxix;
793 PPCODE:
794  SU_GET_CONTEXT(0, 0);
795  for (; cxix >= 0; --cxix) {
796   PERL_CONTEXT *cx = cxstack + cxix;
797   switch (CxTYPE(cx)) {
798    default:
799     continue;
800    case CXt_EVAL:
801     ST(0) = sv_2mortal(newSViv(cxix));
802     XSRETURN(1);
803   }
804  }
805  XSRETURN_UNDEF;
806
807 void
808 SCOPE(...)
809 PROTOTYPE: ;$
810 PREINIT:
811  I32 cxix, level;
812 PPCODE:
813  SU_GET_LEVEL(0, 0);
814  cxix = cxstack_ix;
815  if (PL_DBsub) {
816   SU_SKIP_DB(cxix);
817   while (cxix > 0) {
818    if (--level < 0)
819     break;
820    --cxix;
821    SU_SKIP_DB(cxix);
822   }
823  } else {
824   cxix -= level;
825   if (cxix < 0)
826    cxix = 0;
827  }
828  ST(0) = sv_2mortal(newSViv(cxix));
829  XSRETURN(1);
830
831 void
832 CALLER(...)
833 PROTOTYPE: ;$
834 PREINIT:
835  I32 cxix, level;
836 PPCODE:
837  SU_GET_LEVEL(0, 0);
838  for (cxix = cxstack_ix; cxix > 0; --cxix) {
839   PERL_CONTEXT *cx = cxstack + cxix;
840   switch (CxTYPE(cx)) {
841    case CXt_SUB:
842     if (PL_DBsub && cx->blk_sub.cv == GvCV(PL_DBsub))
843      continue;
844    case CXt_EVAL:
845    case CXt_FORMAT:
846     if (--level < 0)
847      goto done;
848     break;
849   }
850  }
851 done:
852  ST(0) = sv_2mortal(newSViv(cxix));
853  XSRETURN(1);
854
855 void
856 want_at(...)
857 PROTOTYPE: ;$
858 PREINIT:
859  I32 cxix;
860 PPCODE:
861  SU_GET_CONTEXT(0, 0);
862  while (cxix > 0) {
863   PERL_CONTEXT *cx = cxstack + cxix--;
864   switch (CxTYPE(cx)) {
865    case CXt_SUB:
866    case CXt_EVAL:
867    case CXt_FORMAT: {
868     I32 gimme = cx->blk_gimme;
869     switch (gimme) {
870      case G_VOID:   XSRETURN_UNDEF; break;
871      case G_SCALAR: XSRETURN_NO;    break;
872      case G_ARRAY:  XSRETURN_YES;   break;
873     }
874     break;
875    }
876   }
877  }
878  XSRETURN_UNDEF;
879
880 void
881 reap(SV *hook, ...)
882 PROTOTYPE: &;$
883 PREINIT:
884  I32 cxix;
885  su_ud_reap *ud;
886 CODE:
887  SU_GET_CONTEXT(1, 1);
888  Newx(ud, 1, su_ud_reap);
889  SU_UD_ORIGIN(ud)  = NULL;
890  SU_UD_HANDLER(ud) = su_reap;
891  ud->cb = newSVsv(hook);
892  su_init(cxix, ud, 3);
893
894 void
895 localize(SV *sv, SV *val, ...)
896 PROTOTYPE: $$;$
897 PREINIT:
898  I32 cxix;
899  su_ud_localize *ud;
900 CODE:
901  SU_GET_CONTEXT(2, 2);
902  Newx(ud, 1, su_ud_localize);
903  SU_UD_ORIGIN(ud)  = NULL;
904  SU_UD_HANDLER(ud) = su_localize;
905  SvREFCNT_inc(sv);
906  ud->sv   = sv;
907  ud->val  = newSVsv(val);
908  ud->elem = NULL;
909  su_init(cxix, ud, 3);
910
911 void
912 localize_elem(SV *sv, SV *elem, SV *val, ...)
913 PROTOTYPE: $$$;$
914 PREINIT:
915  I32 cxix;
916  su_ud_localize *ud;
917 CODE:
918  SU_GET_CONTEXT(3, 3);
919  Newx(ud, 1, su_ud_localize);
920  SU_UD_ORIGIN(ud)  = NULL;
921  SU_UD_HANDLER(ud) = su_localize;
922  SvREFCNT_inc(sv);
923  ud->sv   = sv;
924  ud->val  = newSVsv(val);
925  SvREFCNT_inc(elem);
926  ud->elem = elem;
927  su_init(cxix, ud, 4);
928
929 void
930 localize_delete(SV *sv, SV *elem, ...)
931 PROTOTYPE: $$;$
932 PREINIT:
933  I32 cxix;
934  su_ud_localize *ud;
935 CODE:
936  SU_GET_CONTEXT(2, 2);
937  Newx(ud, 1, su_ud_localize);
938  SU_UD_ORIGIN(ud)  = NULL;
939  SU_UD_HANDLER(ud) = su_localize;
940  SvREFCNT_inc(sv);
941  ud->sv   = sv;
942  ud->val  = NULL;
943  SvREFCNT_inc(elem);
944  ud->elem = elem;
945  su_init(cxix, ud, 4);