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