3 * Copyright (c) 1991-1997, Larry Wall
5 * You may distribute under the terms of either the GNU General Public
6 * License or the Artistic License, as specified in the README file.
11 * Now far ahead the Road has gone,
12 * And I must follow, if I can,
13 * Pursuing it with eager feet,
14 * Until it joins some larger way
15 * Where many paths and errands meet.
16 * And whither then? I cannot say.
23 #define WORD_ALIGN sizeof(U16)
26 #define DOCATCH(o) ((CATCH_GET == TRUE) ? docatch(o) : (o))
29 #define CALLOP this->*op
32 static OP *docatch _((OP *o));
33 static OP *dofindlabel _((OP *o, char *label, OP **opstack, OP **oplimit));
34 static void doparseform _((SV *sv));
35 static I32 dopoptoeval _((I32 startingblock));
36 static I32 dopoptolabel _((char *label));
37 static I32 dopoptoloop _((I32 startingblock));
38 static I32 dopoptosub _((I32 startingblock));
39 static void save_lines _((AV *array, SV *sv));
40 static I32 sortcv _((SV *a, SV *b));
41 static void qsortsv _((SV **array, size_t num_elts, I32 (*fun)(SV *a, SV *b)));
42 static OP *doeval _((int gimme, OP** startop));
51 cxix = dopoptosub(cxstack_ix);
55 switch (cxstack[cxix].blk_gimme) {
72 register PMOP *pm = (PMOP*)cLOGOP->op_other;
76 MAGIC *mg = Null(MAGIC*);
80 SV *sv = SvRV(tmpstr);
82 mg = mg_find(sv, 'r');
85 regexp *re = (regexp *)mg->mg_obj;
86 ReREFCNT_dec(pm->op_pmregexp);
87 pm->op_pmregexp = ReREFCNT_inc(re);
90 t = SvPV(tmpstr, len);
92 /* Check against the last compiled regexp. */
93 if (!pm->op_pmregexp || !pm->op_pmregexp->precomp ||
94 pm->op_pmregexp->prelen != len ||
95 memNE(pm->op_pmregexp->precomp, t, len))
97 if (pm->op_pmregexp) {
98 ReREFCNT_dec(pm->op_pmregexp);
99 pm->op_pmregexp = Null(REGEXP*); /* crucial if regcomp aborts */
102 pm->op_pmflags = pm->op_pmpermflags; /* reset case sensitivity */
103 pm->op_pmregexp = pregcomp(t, t + len, pm);
107 if (!pm->op_pmregexp->prelen && curpm)
109 else if (strEQ("\\s+", pm->op_pmregexp->precomp))
110 pm->op_pmflags |= PMf_WHITE;
112 if (pm->op_pmflags & PMf_KEEP) {
113 pm->op_private &= ~OPpRUNTIME; /* no point compiling again */
114 cLOGOP->op_first->op_next = op->op_next;
122 register PMOP *pm = (PMOP*) cLOGOP->op_other;
123 register PERL_CONTEXT *cx = &cxstack[cxstack_ix];
124 register SV *dstr = cx->sb_dstr;
125 register char *s = cx->sb_s;
126 register char *m = cx->sb_m;
127 char *orig = cx->sb_orig;
128 register REGEXP *rx = cx->sb_rx;
130 rxres_restore(&cx->sb_rxres, rx);
132 if (cx->sb_iters++) {
133 if (cx->sb_iters > cx->sb_maxiters)
134 DIE("Substitution loop");
136 if (!(cx->sb_rxtainted & 2) && SvTAINTED(TOPs))
137 cx->sb_rxtainted |= 2;
138 sv_catsv(dstr, POPs);
141 if (cx->sb_once || !regexec_flags(rx, s, cx->sb_strend, orig,
142 s == m, Nullsv, NULL,
143 cx->sb_safebase ? 0 : REXEC_COPY_STR))
145 SV *targ = cx->sb_targ;
146 sv_catpvn(dstr, s, cx->sb_strend - s);
148 TAINT_IF(cx->sb_rxtainted || RX_MATCH_TAINTED(rx));
149 cx->sb_rxtainted |= RX_MATCH_TAINTED(rx);
151 (void)SvOOK_off(targ);
152 Safefree(SvPVX(targ));
153 SvPVX(targ) = SvPVX(dstr);
154 SvCUR_set(targ, SvCUR(dstr));
155 SvLEN_set(targ, SvLEN(dstr));
159 TAINT_IF(cx->sb_rxtainted & 1);
160 PUSHs(sv_2mortal(newSViv((I32)cx->sb_iters - 1)));
162 (void)SvPOK_only(targ);
163 TAINT_IF(cx->sb_rxtainted);
167 LEAVE_SCOPE(cx->sb_oldsave);
169 RETURNOP(pm->op_next);
172 if (rx->subbase && rx->subbase != orig) {
175 cx->sb_orig = orig = rx->subbase;
177 cx->sb_strend = s + (cx->sb_strend - m);
179 cx->sb_m = m = rx->startp[0];
180 sv_catpvn(dstr, s, m-s);
181 cx->sb_s = rx->endp[0];
182 cx->sb_rxtainted |= RX_MATCH_TAINTED(rx);
183 rxres_save(&cx->sb_rxres, rx);
184 RETURNOP(pm->op_pmreplstart);
188 rxres_save(void **rsp, REGEXP *rx)
193 if (!p || p[1] < rx->nparens) {
194 i = 6 + rx->nparens * 2;
202 *p++ = (UV)rx->subbase;
203 rx->subbase = Nullch;
207 *p++ = (UV)rx->subbeg;
208 *p++ = (UV)rx->subend;
209 for (i = 0; i <= rx->nparens; ++i) {
210 *p++ = (UV)rx->startp[i];
211 *p++ = (UV)rx->endp[i];
216 rxres_restore(void **rsp, REGEXP *rx)
221 Safefree(rx->subbase);
222 rx->subbase = (char*)(*p);
227 rx->subbeg = (char*)(*p++);
228 rx->subend = (char*)(*p++);
229 for (i = 0; i <= rx->nparens; ++i) {
230 rx->startp[i] = (char*)(*p++);
231 rx->endp[i] = (char*)(*p++);
236 rxres_free(void **rsp)
241 Safefree((char*)(*p));
249 djSP; dMARK; dORIGMARK;
250 register SV *tmpForm = *++MARK;
262 bool chopspace = (strchr(chopset, ' ') != Nullch);
269 if (!SvMAGICAL(tmpForm) || !SvCOMPILED(tmpForm)) {
270 SvREADONLY_off(tmpForm);
271 doparseform(tmpForm);
274 SvPV_force(formtarget, len);
275 t = SvGROW(formtarget, len + SvCUR(tmpForm) + 1); /* XXX SvCUR bad */
277 f = SvPV(tmpForm, len);
278 /* need to jump to the next word */
279 s = f + len + WORD_ALIGN - SvCUR(tmpForm) % WORD_ALIGN;
288 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
289 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
290 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
291 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
292 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
294 case FF_CHECKNL: name = "CHECKNL"; break;
295 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
296 case FF_SPACE: name = "SPACE"; break;
297 case FF_HALFSPACE: name = "HALFSPACE"; break;
298 case FF_ITEM: name = "ITEM"; break;
299 case FF_CHOP: name = "CHOP"; break;
300 case FF_LINEGLOB: name = "LINEGLOB"; break;
301 case FF_NEWLINE: name = "NEWLINE"; break;
302 case FF_MORE: name = "MORE"; break;
303 case FF_LINEMARK: name = "LINEMARK"; break;
304 case FF_END: name = "END"; break;
307 PerlIO_printf(PerlIO_stderr(), "%-16s%ld\n", name, (long) arg);
309 PerlIO_printf(PerlIO_stderr(), "%-16s\n", name);
338 warn("Not enough format arguments");
343 item = s = SvPV(sv, len);
345 if (itemsize > fieldsize)
346 itemsize = fieldsize;
347 send = chophere = s + itemsize;
359 item = s = SvPV(sv, len);
361 if (itemsize <= fieldsize) {
362 send = chophere = s + itemsize;
373 itemsize = fieldsize;
374 send = chophere = s + itemsize;
375 while (s < send || (s == send && isSPACE(*s))) {
385 if (strchr(chopset, *s))
390 itemsize = chophere - item;
395 arg = fieldsize - itemsize;
404 arg = fieldsize - itemsize;
418 int ch = *t++ = *s++;
422 if ( !((*t++ = *s++) & ~31) )
432 while (*s && isSPACE(*s))
439 item = s = SvPV(sv, len);
452 SvCUR_set(formtarget, t - SvPVX(formtarget));
453 sv_catpvn(formtarget, item, itemsize);
454 SvGROW(formtarget, SvCUR(formtarget) + SvCUR(tmpForm) + 1);
455 t = SvPVX(formtarget) + SvCUR(formtarget);
460 /* If the field is marked with ^ and the value is undefined,
463 if ((arg & 512) && !SvOK(sv)) {
471 /* Formats aren't yet marked for locales, so assume "yes". */
474 sprintf(t, "%#*.*f", (int) fieldsize, (int) arg & 255, value);
476 sprintf(t, "%*.0f", (int) fieldsize, value);
483 while (t-- > linemark && *t == ' ') ;
491 if (arg) { /* repeat until fields exhausted? */
493 SvCUR_set(formtarget, t - SvPVX(formtarget));
494 lines += FmLINES(formtarget);
497 if (strnEQ(linemark, linemark - arg, arg))
498 DIE("Runaway format");
500 FmLINES(formtarget) = lines;
502 RETURNOP(cLISTOP->op_first);
513 arg = fieldsize - itemsize;
520 if (strnEQ(s," ",3)) {
521 while (s > SvPVX(formtarget) && isSPACE(s[-1]))
532 SvCUR_set(formtarget, t - SvPVX(formtarget));
533 FmLINES(formtarget) += lines;
545 if (stack_base + *markstack_ptr == SP) {
547 if (GIMME_V == G_SCALAR)
549 RETURNOP(op->op_next->op_next);
551 stack_sp = stack_base + *markstack_ptr + 1;
552 pp_pushmark(ARGS); /* push dst */
553 pp_pushmark(ARGS); /* push src */
554 ENTER; /* enter outer scope */
558 /* SAVE_DEFSV does *not* suffice here */
559 save_sptr(&THREADSV(0));
561 SAVESPTR(GvSV(defgv));
562 #endif /* USE_THREADS */
563 ENTER; /* enter inner scope */
566 src = stack_base[*markstack_ptr];
571 if (op->op_type == OP_MAPSTART)
572 pp_pushmark(ARGS); /* push top */
573 return ((LOGOP*)op->op_next)->op_other;
578 DIE("panic: mapstart"); /* uses grepstart */
584 I32 diff = (SP - stack_base) - *markstack_ptr;
592 if (diff > markstack_ptr[-1] - markstack_ptr[-2]) {
593 shift = diff - (markstack_ptr[-1] - markstack_ptr[-2]);
594 count = (SP - stack_base) - markstack_ptr[-1] + 2;
599 markstack_ptr[-1] += shift;
600 *markstack_ptr += shift;
604 dst = stack_base + (markstack_ptr[-2] += diff) - 1;
607 *dst-- = SvTEMP(TOPs) ? POPs : sv_mortalcopy(POPs);
609 LEAVE; /* exit inner scope */
612 if (markstack_ptr[-1] > *markstack_ptr) {
616 (void)POPMARK; /* pop top */
617 LEAVE; /* exit outer scope */
618 (void)POPMARK; /* pop src */
619 items = --*markstack_ptr - markstack_ptr[-1];
620 (void)POPMARK; /* pop dst */
621 SP = stack_base + POPMARK; /* pop original mark */
622 if (gimme == G_SCALAR) {
626 else if (gimme == G_ARRAY)
633 ENTER; /* enter inner scope */
636 src = stack_base[markstack_ptr[-1]];
640 RETURNOP(cLOGOP->op_other);
646 djSP; dMARK; dORIGMARK;
648 SV **myorigmark = ORIGMARK;
654 OP* nextop = op->op_next;
656 if (gimme != G_ARRAY) {
663 if (op->op_flags & OPf_STACKED) {
664 if (op->op_flags & OPf_SPECIAL) {
665 OP *kid = cLISTOP->op_first->op_sibling; /* pass pushmark */
666 kid = kUNOP->op_first; /* pass rv2gv */
667 kid = kUNOP->op_first; /* pass leave */
668 sortcop = kid->op_next;
669 stash = curcop->cop_stash;
672 cv = sv_2cv(*++MARK, &stash, &gv, 0);
673 if (!(cv && CvROOT(cv))) {
675 SV *tmpstr = sv_newmortal();
676 gv_efullname3(tmpstr, gv, Nullch);
677 if (cv && CvXSUB(cv))
678 DIE("Xsub \"%s\" called in sort", SvPVX(tmpstr));
679 DIE("Undefined sort subroutine \"%s\" called",
684 DIE("Xsub called in sort");
685 DIE("Undefined subroutine in sort");
687 DIE("Not a CODE reference in sort");
689 sortcop = CvSTART(cv);
690 SAVESPTR(CvROOT(cv)->op_ppaddr);
691 CvROOT(cv)->op_ppaddr = ppaddr[OP_NULL];
694 curpad = AvARRAY((AV*)AvARRAY(CvPADLIST(cv))[1]);
699 stash = curcop->cop_stash;
703 while (MARK < SP) { /* This may or may not shift down one here. */
705 if (*up = *++MARK) { /* Weed out nulls. */
707 if (!sortcop && !SvPOK(*up))
708 (void)sv_2pv(*up, &na);
712 max = --up - myorigmark;
717 bool oldcatch = CATCH_GET;
724 if (sortstash != stash) {
725 firstgv = gv_fetchpv("a", TRUE, SVt_PV);
726 secondgv = gv_fetchpv("b", TRUE, SVt_PV);
730 SAVESPTR(GvSV(firstgv));
731 SAVESPTR(GvSV(secondgv));
733 PUSHBLOCK(cx, CXt_NULL, stack_base);
734 if (!(op->op_flags & OPf_SPECIAL)) {
735 bool hasargs = FALSE;
736 cx->cx_type = CXt_SUB;
737 cx->blk_gimme = G_SCALAR;
740 (void)SvREFCNT_inc(cv); /* in preparation for POPSUB */
742 sortcxix = cxstack_ix;
743 qsortsv((myorigmark+1), max, FUNC_NAME_TO_PTR(sortcv));
752 MEXTEND(SP, 20); /* Can't afford stack realloc on signal. */
753 qsortsv(ORIGMARK+1, max,
754 (op->op_private & OPpLOCALE)
755 ? FUNC_NAME_TO_PTR(sv_cmp_locale)
756 : FUNC_NAME_TO_PTR(sv_cmp));
760 stack_sp = ORIGMARK + max;
768 if (GIMME == G_ARRAY)
769 return cCONDOP->op_true;
770 return SvTRUEx(PAD_SV(op->op_targ)) ? cCONDOP->op_false : cCONDOP->op_true;
777 if (GIMME == G_ARRAY) {
778 RETURNOP(((CONDOP*)cUNOP->op_first)->op_false);
782 SV *targ = PAD_SV(op->op_targ);
784 if ((op->op_private & OPpFLIP_LINENUM)
785 ? last_in_gv && SvIV(sv) == IoLINES(GvIOp(last_in_gv))
787 sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
788 if (op->op_flags & OPf_SPECIAL) {
796 RETURNOP(((CONDOP*)cUNOP->op_first)->op_false);
809 if (GIMME == G_ARRAY) {
815 if (SvNIOKp(left) || !SvPOKp(left) ||
816 (looks_like_number(left) && *SvPVX(left) != '0') )
818 if (SvNV(left) < IV_MIN || SvNV(right) >= IV_MAX)
819 croak("Range iterator outside integer range");
823 EXTEND_MORTAL(max - i + 1);
824 EXTEND(SP, max - i + 1);
827 sv = sv_2mortal(newSViv(i++));
832 SV *final = sv_mortalcopy(right);
834 char *tmps = SvPV(final, len);
836 sv = sv_mortalcopy(left);
837 while (!SvNIOKp(sv) && SvCUR(sv) <= len) {
839 if (strEQ(SvPVX(sv),tmps))
841 sv = sv_2mortal(newSVsv(sv));
848 SV *targ = PAD_SV(cUNOP->op_first->op_targ);
850 if ((op->op_private & OPpFLIP_LINENUM)
851 ? last_in_gv && SvIV(sv) == IoLINES(GvIOp(last_in_gv))
853 sv_setiv(PAD_SV(((UNOP*)cUNOP->op_first)->op_first->op_targ), 0);
854 sv_catpv(targ, "E0");
865 dopoptolabel(char *label)
869 register PERL_CONTEXT *cx;
871 for (i = cxstack_ix; i >= 0; i--) {
873 switch (cx->cx_type) {
876 warn("Exiting substitution via %s", op_name[op->op_type]);
880 warn("Exiting subroutine via %s", op_name[op->op_type]);
884 warn("Exiting eval via %s", op_name[op->op_type]);
888 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
891 if (!cx->blk_loop.label ||
892 strNE(label, cx->blk_loop.label) ) {
893 DEBUG_l(deb("(Skipping label #%ld %s)\n",
894 (long)i, cx->blk_loop.label));
897 DEBUG_l( deb("(Found label #%ld %s)\n", (long)i, label));
907 I32 gimme = block_gimme();
908 return (gimme == G_VOID) ? G_SCALAR : gimme;
917 cxix = dopoptosub(cxstack_ix);
921 switch (cxstack[cxix].blk_gimme) {
929 croak("panic: bad gimme: %d\n", cxstack[cxix].blk_gimme);
936 dopoptosub(I32 startingblock)
940 register PERL_CONTEXT *cx;
941 for (i = startingblock; i >= 0; i--) {
943 switch (cx->cx_type) {
948 DEBUG_l( deb("(Found sub #%ld)\n", (long)i));
956 dopoptoeval(I32 startingblock)
960 register PERL_CONTEXT *cx;
961 for (i = startingblock; i >= 0; i--) {
963 switch (cx->cx_type) {
967 DEBUG_l( deb("(Found eval #%ld)\n", (long)i));
975 dopoptoloop(I32 startingblock)
979 register PERL_CONTEXT *cx;
980 for (i = startingblock; i >= 0; i--) {
982 switch (cx->cx_type) {
985 warn("Exiting substitution via %s", op_name[op->op_type]);
989 warn("Exiting subroutine via %s", op_name[op->op_type]);
993 warn("Exiting eval via %s", op_name[op->op_type]);
997 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
1000 DEBUG_l( deb("(Found loop #%ld)\n", (long)i));
1011 register PERL_CONTEXT *cx;
1015 while (cxstack_ix > cxix) {
1016 cx = &cxstack[cxstack_ix];
1017 DEBUG_l(PerlIO_printf(Perl_debug_log, "Unwinding block %ld, type %s\n",
1018 (long) cxstack_ix, block_type[cx->cx_type]));
1019 /* Note: we don't need to restore the base context info till the end. */
1020 switch (cx->cx_type) {
1023 continue; /* not break */
1041 die_where(char *message)
1046 register PERL_CONTEXT *cx;
1053 STRLEN klen = strlen(message);
1055 svp = hv_fetch(ERRHV, message, klen, TRUE);
1058 static char prefix[] = "\t(in cleanup) ";
1060 sv_upgrade(*svp, SVt_IV);
1061 (void)SvIOK_only(*svp);
1064 SvGROW(err, SvCUR(err)+sizeof(prefix)+klen);
1065 sv_catpvn(err, prefix, sizeof(prefix)-1);
1066 sv_catpvn(err, message, klen);
1072 sv_setpv(ERRSV, message);
1075 message = SvPVx(ERRSV, na);
1077 while ((cxix = dopoptoeval(cxstack_ix)) < 0 && curstackinfo->si_prev) {
1085 if (cxix < cxstack_ix)
1089 if (cx->cx_type != CXt_EVAL) {
1090 PerlIO_printf(PerlIO_stderr(), "panic: die %s", message);
1095 if (gimme == G_SCALAR)
1096 *++newsp = &sv_undef;
1101 if (optype == OP_REQUIRE) {
1102 char* msg = SvPVx(ERRSV, na);
1103 DIE("%s", *msg ? msg : "Compilation failed in require");
1105 return pop_return();
1108 PerlIO_printf(PerlIO_stderr(), "%s",message);
1109 PerlIO_flush(PerlIO_stderr());
1118 if (SvTRUE(left) != SvTRUE(right))
1130 RETURNOP(cLOGOP->op_other);
1139 RETURNOP(cLOGOP->op_other);
1145 register I32 cxix = dopoptosub(cxstack_ix);
1146 register PERL_CONTEXT *cx;
1158 if (GIMME != G_ARRAY)
1162 if (DBsub && cxix >= 0 &&
1163 cxstack[cxix].blk_sub.cv == GvCV(DBsub))
1167 cxix = dopoptosub(cxix - 1);
1169 cx = &cxstack[cxix];
1170 if (cxstack[cxix].cx_type == CXt_SUB) {
1171 dbcxix = dopoptosub(cxix - 1);
1172 /* We expect that cxstack[dbcxix] is CXt_SUB, anyway, the
1173 field below is defined for any cx. */
1174 if (DBsub && dbcxix >= 0 && cxstack[dbcxix].blk_sub.cv == GvCV(DBsub))
1175 cx = &cxstack[dbcxix];
1178 if (GIMME != G_ARRAY) {
1179 hv = cx->blk_oldcop->cop_stash;
1184 sv_setpv(TARG, HvNAME(hv));
1190 hv = cx->blk_oldcop->cop_stash;
1194 PUSHs(sv_2mortal(newSVpv(HvNAME(hv), 0)));
1195 PUSHs(sv_2mortal(newSVpv(SvPVX(GvSV(cx->blk_oldcop->cop_filegv)), 0)));
1196 PUSHs(sv_2mortal(newSViv((I32)cx->blk_oldcop->cop_line)));
1199 if (cx->cx_type == CXt_SUB) { /* So is cxstack[dbcxix]. */
1201 gv_efullname3(sv, CvGV(cxstack[cxix].blk_sub.cv), Nullch);
1202 PUSHs(sv_2mortal(sv));
1203 PUSHs(sv_2mortal(newSViv((I32)cx->blk_sub.hasargs)));
1206 PUSHs(sv_2mortal(newSVpv("(eval)",0)));
1207 PUSHs(sv_2mortal(newSViv(0)));
1209 gimme = (I32)cx->blk_gimme;
1210 if (gimme == G_VOID)
1213 PUSHs(sv_2mortal(newSViv(gimme & G_ARRAY)));
1214 if (cx->cx_type == CXt_EVAL) {
1215 if (cx->blk_eval.old_op_type == OP_ENTEREVAL) {
1216 PUSHs(cx->blk_eval.cur_text);
1219 else if (cx->blk_eval.old_name) { /* Try blocks have old_name == 0. */
1220 /* Require, put the name. */
1221 PUSHs(sv_2mortal(newSVpv(cx->blk_eval.old_name, 0)));
1225 else if (cx->cx_type == CXt_SUB &&
1226 cx->blk_sub.hasargs &&
1227 curcop->cop_stash == debstash)
1229 AV *ary = cx->blk_sub.argarray;
1230 int off = AvARRAY(ary) - AvALLOC(ary);
1234 dbargs = GvAV(gv_AVadd(tmpgv = gv_fetchpv("DB::args", TRUE,
1237 AvREAL_off(dbargs); /* XXX Should be REIFY */
1240 if (AvMAX(dbargs) < AvFILLp(ary) + off)
1241 av_extend(dbargs, AvFILLp(ary) + off);
1242 Copy(AvALLOC(ary), AvARRAY(dbargs), AvFILLp(ary) + 1 + off, SV*);
1243 AvFILLp(dbargs) = AvFILLp(ary) + off;
1249 sortcv(SV *a, SV *b)
1252 I32 oldsaveix = savestack_ix;
1253 I32 oldscopeix = scopestack_ix;
1257 stack_sp = stack_base;
1260 if (stack_sp != stack_base + 1)
1261 croak("Sort subroutine didn't return single value");
1262 if (!SvNIOKp(*stack_sp))
1263 croak("Sort subroutine didn't return a numeric value");
1264 result = SvIV(*stack_sp);
1265 while (scopestack_ix > oldscopeix) {
1268 leave_scope(oldsaveix);
1281 sv_reset(tmps, curcop->cop_stash);
1294 TAINT_NOT; /* Each statement is presumed innocent */
1295 stack_sp = stack_base + cxstack[cxstack_ix].blk_oldsp;
1298 if (op->op_private || SvIV(DBsingle) || SvIV(DBsignal) || SvIV(DBtrace))
1302 register PERL_CONTEXT *cx;
1303 I32 gimme = G_ARRAY;
1310 DIE("No DB::DB routine defined");
1312 if (CvDEPTH(cv) >= 1 && !(debug & (1<<30))) /* don't do recursive DB::DB call */
1324 push_return(op->op_next);
1325 PUSHBLOCK(cx, CXt_SUB, SP);
1328 (void)SvREFCNT_inc(cv);
1330 curpad = AvARRAY((AV*)*av_fetch(CvPADLIST(cv),1,FALSE));
1331 RETURNOP(CvSTART(cv));
1345 register PERL_CONTEXT *cx;
1346 I32 gimme = GIMME_V;
1353 if (op->op_flags & OPf_SPECIAL)
1354 svp = save_threadsv(op->op_targ); /* per-thread variable */
1356 #endif /* USE_THREADS */
1358 svp = &curpad[op->op_targ]; /* "my" variable */
1363 (void)save_scalar(gv);
1364 svp = &GvSV(gv); /* symbol table variable */
1369 PUSHBLOCK(cx, CXt_LOOP, SP);
1370 PUSHLOOP(cx, svp, MARK);
1371 if (op->op_flags & OPf_STACKED) {
1372 cx->blk_loop.iterary = (AV*)SvREFCNT_inc(POPs);
1373 if (SvTYPE(cx->blk_loop.iterary) != SVt_PVAV) {
1375 if (SvNIOKp(sv) || !SvPOKp(sv) ||
1376 (looks_like_number(sv) && *SvPVX(sv) != '0')) {
1377 if (SvNV(sv) < IV_MIN ||
1378 SvNV((SV*)cx->blk_loop.iterary) >= IV_MAX)
1379 croak("Range iterator outside integer range");
1380 cx->blk_loop.iterix = SvIV(sv);
1381 cx->blk_loop.itermax = SvIV((SV*)cx->blk_loop.iterary);
1384 cx->blk_loop.iterlval = newSVsv(sv);
1388 cx->blk_loop.iterary = curstack;
1389 AvFILLp(curstack) = SP - stack_base;
1390 cx->blk_loop.iterix = MARK - stack_base;
1399 register PERL_CONTEXT *cx;
1400 I32 gimme = GIMME_V;
1406 PUSHBLOCK(cx, CXt_LOOP, SP);
1407 PUSHLOOP(cx, 0, SP);
1415 register PERL_CONTEXT *cx;
1416 struct block_loop cxloop;
1424 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1427 if (gimme == G_VOID)
1429 else if (gimme == G_SCALAR) {
1431 *++newsp = sv_mortalcopy(*SP);
1433 *++newsp = &sv_undef;
1437 *++newsp = sv_mortalcopy(*++mark);
1438 TAINT_NOT; /* Each item is independent */
1444 POPLOOP2(); /* Stack values are safe: release loop vars ... */
1445 curpm = newpm; /* ... and pop $1 et al */
1457 register PERL_CONTEXT *cx;
1458 struct block_sub cxsub;
1459 bool popsub2 = FALSE;
1465 if (curstackinfo->si_type == SI_SORT) {
1466 if (cxstack_ix == sortcxix || dopoptosub(cxstack_ix) <= sortcxix) {
1467 if (cxstack_ix > sortcxix)
1469 AvARRAY(curstack)[1] = *SP;
1470 stack_sp = stack_base + 1;
1475 cxix = dopoptosub(cxstack_ix);
1477 DIE("Can't return outside a subroutine");
1478 if (cxix < cxstack_ix)
1482 switch (cx->cx_type) {
1484 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1489 if (optype == OP_REQUIRE &&
1490 (MARK == SP || (gimme == G_SCALAR && !SvTRUE(*SP))) )
1492 /* Unassume the success we assumed earlier. */
1493 char *name = cx->blk_eval.old_name;
1494 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
1495 DIE("%s did not return a true value", name);
1499 DIE("panic: return");
1503 if (gimme == G_SCALAR) {
1506 if (cxsub.cv && CvDEPTH(cxsub.cv) > 1) {
1508 *++newsp = SvREFCNT_inc(*SP);
1513 *++newsp = sv_mortalcopy(*SP);
1516 *++newsp = (SvTEMP(*SP)) ? *SP : sv_mortalcopy(*SP);
1518 *++newsp = sv_mortalcopy(*SP);
1520 *++newsp = &sv_undef;
1522 else if (gimme == G_ARRAY) {
1523 while (++MARK <= SP) {
1524 *++newsp = (popsub2 && SvTEMP(*MARK))
1525 ? *MARK : sv_mortalcopy(*MARK);
1526 TAINT_NOT; /* Each item is independent */
1531 /* Stack values are safe: */
1533 POPSUB2(); /* release CV and @_ ... */
1535 curpm = newpm; /* ... and pop $1 et al */
1538 return pop_return();
1545 register PERL_CONTEXT *cx;
1546 struct block_loop cxloop;
1547 struct block_sub cxsub;
1554 SV **mark = stack_base + cxstack[cxstack_ix].blk_oldsp;
1556 if (op->op_flags & OPf_SPECIAL) {
1557 cxix = dopoptoloop(cxstack_ix);
1559 DIE("Can't \"last\" outside a block");
1562 cxix = dopoptolabel(cPVOP->op_pv);
1564 DIE("Label not found for \"last %s\"", cPVOP->op_pv);
1566 if (cxix < cxstack_ix)
1570 switch (cx->cx_type) {
1572 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1574 nextop = cxloop.last_op->op_next;
1577 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1579 nextop = pop_return();
1583 nextop = pop_return();
1590 if (gimme == G_SCALAR) {
1592 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*SP))
1593 ? *SP : sv_mortalcopy(*SP);
1595 *++newsp = &sv_undef;
1597 else if (gimme == G_ARRAY) {
1598 while (++MARK <= SP) {
1599 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*MARK))
1600 ? *MARK : sv_mortalcopy(*MARK);
1601 TAINT_NOT; /* Each item is independent */
1607 /* Stack values are safe: */
1610 POPLOOP2(); /* release loop vars ... */
1614 POPSUB2(); /* release CV and @_ ... */
1617 curpm = newpm; /* ... and pop $1 et al */
1626 register PERL_CONTEXT *cx;
1629 if (op->op_flags & OPf_SPECIAL) {
1630 cxix = dopoptoloop(cxstack_ix);
1632 DIE("Can't \"next\" outside a block");
1635 cxix = dopoptolabel(cPVOP->op_pv);
1637 DIE("Label not found for \"next %s\"", cPVOP->op_pv);
1639 if (cxix < cxstack_ix)
1643 oldsave = scopestack[scopestack_ix - 1];
1644 LEAVE_SCOPE(oldsave);
1645 return cx->blk_loop.next_op;
1651 register PERL_CONTEXT *cx;
1654 if (op->op_flags & OPf_SPECIAL) {
1655 cxix = dopoptoloop(cxstack_ix);
1657 DIE("Can't \"redo\" outside a block");
1660 cxix = dopoptolabel(cPVOP->op_pv);
1662 DIE("Label not found for \"redo %s\"", cPVOP->op_pv);
1664 if (cxix < cxstack_ix)
1668 oldsave = scopestack[scopestack_ix - 1];
1669 LEAVE_SCOPE(oldsave);
1670 return cx->blk_loop.redo_op;
1674 dofindlabel(OP *o, char *label, OP **opstack, OP **oplimit)
1678 static char too_deep[] = "Target of goto is too deeply nested";
1682 if (o->op_type == OP_LEAVE ||
1683 o->op_type == OP_SCOPE ||
1684 o->op_type == OP_LEAVELOOP ||
1685 o->op_type == OP_LEAVETRY)
1687 *ops++ = cUNOPo->op_first;
1692 if (o->op_flags & OPf_KIDS) {
1693 /* First try all the kids at this level, since that's likeliest. */
1694 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1695 if ((kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) &&
1696 kCOP->cop_label && strEQ(kCOP->cop_label, label))
1699 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1700 if (kid == lastgotoprobe)
1702 if ((kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) &&
1704 (ops[-1]->op_type != OP_NEXTSTATE &&
1705 ops[-1]->op_type != OP_DBSTATE)))
1707 if (o = dofindlabel(kid, label, ops, oplimit))
1717 return pp_goto(ARGS);
1726 register PERL_CONTEXT *cx;
1727 #define GOTO_DEPTH 64
1728 OP *enterops[GOTO_DEPTH];
1730 int do_dump = (op->op_type == OP_DUMP);
1733 if (op->op_flags & OPf_STACKED) {
1736 /* This egregious kludge implements goto &subroutine */
1737 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
1739 register PERL_CONTEXT *cx;
1740 CV* cv = (CV*)SvRV(sv);
1745 if (!CvROOT(cv) && !CvXSUB(cv)) {
1747 SV *tmpstr = sv_newmortal();
1748 gv_efullname3(tmpstr, CvGV(cv), Nullch);
1749 DIE("Goto undefined subroutine &%s",SvPVX(tmpstr));
1751 DIE("Goto undefined subroutine");
1754 /* First do some returnish stuff. */
1755 cxix = dopoptosub(cxstack_ix);
1757 DIE("Can't goto subroutine outside a subroutine");
1758 if (cxix < cxstack_ix)
1761 if (cx->cx_type == CXt_EVAL && cx->blk_eval.old_op_type == OP_ENTEREVAL)
1762 DIE("Can't goto subroutine from an eval-string");
1764 if (cx->cx_type == CXt_SUB &&
1765 cx->blk_sub.hasargs) { /* put @_ back onto stack */
1766 AV* av = cx->blk_sub.argarray;
1768 items = AvFILLp(av) + 1;
1770 EXTEND(stack_sp, items); /* @_ could have been extended. */
1771 Copy(AvARRAY(av), stack_sp, items, SV*);
1774 SvREFCNT_dec(GvAV(defgv));
1775 GvAV(defgv) = cx->blk_sub.savearray;
1776 #endif /* USE_THREADS */
1780 else if (CvXSUB(cv)) { /* put GvAV(defgv) back onto stack */
1784 av = (AV*)curpad[0];
1788 items = AvFILLp(av) + 1;
1790 EXTEND(stack_sp, items); /* @_ could have been extended. */
1791 Copy(AvARRAY(av), stack_sp, items, SV*);
1794 if (cx->cx_type == CXt_SUB &&
1795 !(CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth))
1796 SvREFCNT_dec(cx->blk_sub.cv);
1797 oldsave = scopestack[scopestack_ix - 1];
1798 LEAVE_SCOPE(oldsave);
1800 /* Now do some callish stuff. */
1803 if (CvOLDSTYLE(cv)) {
1804 I32 (*fp3)_((int,int,int));
1809 fp3 = (I32(*)_((int,int,int)))CvXSUB(cv);
1810 items = (*fp3)(CvXSUBANY(cv).any_i32,
1811 mark - stack_base + 1,
1813 SP = stack_base + items;
1819 stack_sp--; /* There is no cv arg. */
1820 /* Push a mark for the start of arglist */
1822 (void)(*CvXSUB(cv))(cv _PERL_OBJECT_THIS);
1823 /* Pop the current context like a decent sub should */
1824 POPBLOCK(cx, curpm);
1825 /* Do _not_ use PUTBACK, keep the XSUB's return stack! */
1828 return pop_return();
1831 AV* padlist = CvPADLIST(cv);
1832 SV** svp = AvARRAY(padlist);
1833 if (cx->cx_type == CXt_EVAL) {
1834 in_eval = cx->blk_eval.old_in_eval;
1835 eval_root = cx->blk_eval.old_eval_root;
1836 cx->cx_type = CXt_SUB;
1837 cx->blk_sub.hasargs = 0;
1839 cx->blk_sub.cv = cv;
1840 cx->blk_sub.olddepth = CvDEPTH(cv);
1842 if (CvDEPTH(cv) < 2)
1843 (void)SvREFCNT_inc(cv);
1844 else { /* save temporaries on recursion? */
1845 if (CvDEPTH(cv) == 100 && dowarn)
1846 sub_crush_depth(cv);
1847 if (CvDEPTH(cv) > AvFILLp(padlist)) {
1848 AV *newpad = newAV();
1849 SV **oldpad = AvARRAY(svp[CvDEPTH(cv)-1]);
1850 I32 ix = AvFILLp((AV*)svp[1]);
1851 svp = AvARRAY(svp[0]);
1852 for ( ;ix > 0; ix--) {
1853 if (svp[ix] != &sv_undef) {
1854 char *name = SvPVX(svp[ix]);
1855 if ((SvFLAGS(svp[ix]) & SVf_FAKE)
1858 /* outer lexical or anon code */
1859 av_store(newpad, ix,
1860 SvREFCNT_inc(oldpad[ix]) );
1862 else { /* our own lexical */
1864 av_store(newpad, ix, sv = (SV*)newAV());
1865 else if (*name == '%')
1866 av_store(newpad, ix, sv = (SV*)newHV());
1868 av_store(newpad, ix, sv = NEWSV(0,0));
1873 av_store(newpad, ix, sv = NEWSV(0,0));
1877 if (cx->blk_sub.hasargs) {
1880 av_store(newpad, 0, (SV*)av);
1881 AvFLAGS(av) = AVf_REIFY;
1883 av_store(padlist, CvDEPTH(cv), (SV*)newpad);
1884 AvFILLp(padlist) = CvDEPTH(cv);
1885 svp = AvARRAY(padlist);
1889 if (!cx->blk_sub.hasargs) {
1890 AV* av = (AV*)curpad[0];
1892 items = AvFILLp(av) + 1;
1894 /* Mark is at the end of the stack. */
1896 Copy(AvARRAY(av), SP + 1, items, SV*);
1901 #endif /* USE_THREADS */
1903 curpad = AvARRAY((AV*)svp[CvDEPTH(cv)]);
1905 if (cx->blk_sub.hasargs)
1906 #endif /* USE_THREADS */
1908 AV* av = (AV*)curpad[0];
1912 cx->blk_sub.savearray = GvAV(defgv);
1913 GvAV(defgv) = (AV*)SvREFCNT_inc(av);
1914 #endif /* USE_THREADS */
1915 cx->blk_sub.argarray = av;
1918 if (items >= AvMAX(av) + 1) {
1920 if (AvARRAY(av) != ary) {
1921 AvMAX(av) += AvARRAY(av) - AvALLOC(av);
1922 SvPVX(av) = (char*)ary;
1924 if (items >= AvMAX(av) + 1) {
1925 AvMAX(av) = items - 1;
1926 Renew(ary,items+1,SV*);
1928 SvPVX(av) = (char*)ary;
1931 Copy(mark,AvARRAY(av),items,SV*);
1932 AvFILLp(av) = items - 1;
1940 if (PERLDB_SUB) { /* Checking curstash breaks DProf. */
1942 * We do not care about using sv to call CV;
1943 * it's for informational purposes only.
1945 SV *sv = GvSV(DBsub);
1948 if (PERLDB_SUB_NN) {
1949 SvIVX(sv) = (IV)cv; /* Already upgraded, saved */
1952 gv_efullname3(sv, CvGV(cv), Nullch);
1955 && (gotocv = perl_get_cv("DB::goto", FALSE)) ) {
1956 PUSHMARK( stack_sp );
1957 perl_call_sv((SV*)gotocv, G_SCALAR | G_NODEBUG);
1961 RETURNOP(CvSTART(cv));
1965 label = SvPV(sv,na);
1967 else if (op->op_flags & OPf_SPECIAL) {
1969 DIE("goto must have label");
1972 label = cPVOP->op_pv;
1974 if (label && *label) {
1981 for (ix = cxstack_ix; ix >= 0; ix--) {
1983 switch (cx->cx_type) {
1985 gotoprobe = eval_root; /* XXX not good for nested eval */
1988 gotoprobe = cx->blk_oldcop->op_sibling;
1994 gotoprobe = cx->blk_oldcop->op_sibling;
1996 gotoprobe = main_root;
1999 if (CvDEPTH(cx->blk_sub.cv)) {
2000 gotoprobe = CvROOT(cx->blk_sub.cv);
2005 DIE("Can't \"goto\" outside a block");
2009 gotoprobe = main_root;
2012 retop = dofindlabel(gotoprobe, label,
2013 enterops, enterops + GOTO_DEPTH);
2016 lastgotoprobe = gotoprobe;
2019 DIE("Can't find label %s", label);
2021 /* pop unwanted frames */
2023 if (ix < cxstack_ix) {
2030 oldsave = scopestack[scopestack_ix];
2031 LEAVE_SCOPE(oldsave);
2034 /* push wanted frames */
2036 if (*enterops && enterops[1]) {
2038 for (ix = 1; enterops[ix]; ix++) {
2040 /* Eventually we may want to stack the needed arguments
2041 * for each op. For now, we punt on the hard ones. */
2042 if (op->op_type == OP_ENTERITER)
2043 DIE("Can't \"goto\" into the middle of a foreach loop",
2045 (CALLOP->op_ppaddr)(ARGS);
2053 if (!retop) retop = main_start;
2060 restartop = 0; /* hmm, must be GNU unexec().. */
2064 if (top_env->je_prev) {
2082 if (anum == 1 && VMSISH_EXIT)
2095 double value = SvNVx(GvSV(cCOP->cop_gv));
2096 register I32 match = I_32(value);
2099 if (((double)match) > value)
2100 --match; /* was fractional--truncate other way */
2102 match -= cCOP->uop.scop.scop_offset;
2105 else if (match > cCOP->uop.scop.scop_max)
2106 match = cCOP->uop.scop.scop_max;
2107 op = cCOP->uop.scop.scop_next[match];
2117 op = op->op_next; /* can't assume anything */
2119 match = *(SvPVx(GvSV(cCOP->cop_gv), na)) & 255;
2120 match -= cCOP->uop.scop.scop_offset;
2123 else if (match > cCOP->uop.scop.scop_max)
2124 match = cCOP->uop.scop.scop_max;
2125 op = cCOP->uop.scop.scop_next[match];
2134 save_lines(AV *array, SV *sv)
2136 register char *s = SvPVX(sv);
2137 register char *send = SvPVX(sv) + SvCUR(sv);
2139 register I32 line = 1;
2141 while (s && s < send) {
2142 SV *tmpstr = NEWSV(85,0);
2144 sv_upgrade(tmpstr, SVt_PVMG);
2145 t = strchr(s, '\n');
2151 sv_setpvn(tmpstr, s, t - s);
2152 av_store(array, line++, tmpstr);
2167 assert(CATCH_GET == TRUE);
2168 DEBUG_l(deb("Setting up local jumplevel %p, was %p\n", &cur_env, top_env));
2172 default: /* topmost level handles it */
2179 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2195 sv_compile_2op(SV *sv, OP** startop, char *code, AV** avp)
2196 /* sv Text to convert to OP tree. */
2197 /* startop op_free() this to undo. */
2198 /* code Short string id of the caller. */
2200 dSP; /* Make POPBLOCK work. */
2203 I32 gimme = 0; /* SUSPECT - INITIALZE TO WHAT? NI-S */
2207 char tmpbuf[TYPE_DIGITS(long) + 12 + 10];
2213 /* switch to eval mode */
2215 SAVESPTR(compiling.cop_filegv);
2216 SAVEI16(compiling.cop_line);
2217 sprintf(tmpbuf, "_<(%.10s_eval %lu)", code, (unsigned long)++evalseq);
2218 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2219 compiling.cop_line = 1;
2220 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2221 deleting the eval's FILEGV from the stash before gv_check() runs
2222 (i.e. before run-time proper). To work around the coredump that
2223 ensues, we always turn GvMULTI_on for any globals that were
2224 introduced within evals. See force_ident(). GSAR 96-10-12 */
2225 safestr = savepv(tmpbuf);
2226 SAVEDELETE(defstash, safestr, strlen(safestr));
2228 #ifdef OP_IN_REGISTER
2236 op->op_type = 0; /* Avoid uninit warning. */
2237 op->op_flags = 0; /* Avoid uninit warning. */
2238 PUSHBLOCK(cx, CXt_EVAL, SP);
2239 PUSHEVAL(cx, 0, compiling.cop_filegv);
2240 rop = doeval(G_SCALAR, startop);
2244 (*startop)->op_type = OP_NULL;
2245 (*startop)->op_ppaddr = ppaddr[OP_NULL];
2247 *avp = (AV*)SvREFCNT_inc(comppad);
2249 #ifdef OP_IN_REGISTER
2255 /* With USE_THREADS, eval_owner must be held on entry to doeval */
2257 doeval(int gimme, OP** startop)
2270 /* set up a scratch pad */
2275 SAVESPTR(comppad_name);
2276 SAVEI32(comppad_name_fill);
2277 SAVEI32(min_intro_pending);
2278 SAVEI32(max_intro_pending);
2281 for (i = cxstack_ix - 1; i >= 0; i--) {
2282 PERL_CONTEXT *cx = &cxstack[i];
2283 if (cx->cx_type == CXt_EVAL)
2285 else if (cx->cx_type == CXt_SUB) {
2286 caller = cx->blk_sub.cv;
2292 compcv = (CV*)NEWSV(1104,0);
2293 sv_upgrade((SV *)compcv, SVt_PVCV);
2294 CvUNIQUE_on(compcv);
2296 CvOWNER(compcv) = 0;
2297 New(666, CvMUTEXP(compcv), 1, perl_mutex);
2298 MUTEX_INIT(CvMUTEXP(compcv));
2299 #endif /* USE_THREADS */
2302 av_push(comppad, Nullsv);
2303 curpad = AvARRAY(comppad);
2304 comppad_name = newAV();
2305 comppad_name_fill = 0;
2306 min_intro_pending = 0;
2309 av_store(comppad_name, 0, newSVpv("@_", 2));
2310 curpad[0] = (SV*)newAV();
2311 SvPADMY_on(curpad[0]); /* XXX Needed? */
2312 #endif /* USE_THREADS */
2314 comppadlist = newAV();
2315 AvREAL_off(comppadlist);
2316 av_store(comppadlist, 0, (SV*)comppad_name);
2317 av_store(comppadlist, 1, (SV*)comppad);
2318 CvPADLIST(compcv) = comppadlist;
2320 if (!saveop || saveop->op_type != OP_REQUIRE)
2321 CvOUTSIDE(compcv) = (CV*)SvREFCNT_inc(caller);
2325 /* make sure we compile in the right package */
2327 newstash = curcop->cop_stash;
2328 if (curstash != newstash) {
2330 curstash = newstash;
2334 SAVEFREESV(beginav);
2336 /* try to compile it */
2340 curcop = &compiling;
2341 curcop->cop_arybase = 0;
2343 rs = newSVpv("\n", 1);
2344 if (saveop && saveop->op_flags & OPf_SPECIAL)
2348 if (yyparse() || error_count || !eval_root) {
2352 I32 optype = 0; /* Might be reset by POPEVAL. */
2359 SP = stack_base + POPMARK; /* pop original mark */
2367 if (optype == OP_REQUIRE) {
2368 char* msg = SvPVx(ERRSV, na);
2369 DIE("%s", *msg ? msg : "Compilation failed in require");
2370 } else if (startop) {
2371 char* msg = SvPVx(ERRSV, na);
2375 croak("%sCompilation failed in regexp", (*msg ? msg : "Unknown error\n"));
2378 rs = SvREFCNT_inc(nrs);
2380 MUTEX_LOCK(&eval_mutex);
2382 COND_SIGNAL(&eval_cond);
2383 MUTEX_UNLOCK(&eval_mutex);
2384 #endif /* USE_THREADS */
2388 rs = SvREFCNT_inc(nrs);
2389 compiling.cop_line = 0;
2391 *startop = eval_root;
2392 SvREFCNT_dec(CvOUTSIDE(compcv));
2393 CvOUTSIDE(compcv) = Nullcv;
2395 SAVEFREEOP(eval_root);
2397 scalarvoid(eval_root);
2398 else if (gimme & G_ARRAY)
2403 DEBUG_x(dump_eval());
2405 /* Register with debugger: */
2406 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
2407 CV *cv = perl_get_cv("DB::postponed", FALSE);
2411 XPUSHs((SV*)compiling.cop_filegv);
2413 perl_call_sv((SV*)cv, G_DISCARD);
2417 /* compiled okay, so do it */
2419 CvDEPTH(compcv) = 1;
2420 SP = stack_base + POPMARK; /* pop original mark */
2421 op = saveop; /* The caller may need it. */
2423 MUTEX_LOCK(&eval_mutex);
2425 COND_SIGNAL(&eval_cond);
2426 MUTEX_UNLOCK(&eval_mutex);
2427 #endif /* USE_THREADS */
2429 RETURNOP(eval_start);
2435 register PERL_CONTEXT *cx;
2440 SV *namesv = Nullsv;
2442 I32 gimme = G_SCALAR;
2443 PerlIO *tryrsfp = 0;
2446 if (SvNIOKp(sv) && !SvPOKp(sv)) {
2447 SET_NUMERIC_STANDARD();
2448 if (atof(patchlevel) + 0.00000999 < SvNV(sv))
2449 DIE("Perl %s required--this is only version %s, stopped",
2450 SvPV(sv,na),patchlevel);
2453 name = SvPV(sv, len);
2454 if (!(name && len > 0 && *name))
2455 DIE("Null filename used");
2456 TAINT_PROPER("require");
2457 if (op->op_type == OP_REQUIRE &&
2458 (svp = hv_fetch(GvHVn(incgv), name, len, 0)) &&
2462 /* prepare to compile file */
2467 (name[1] == '.' && name[2] == '/')))
2469 || (name[0] && name[1] == ':')
2472 || (name[0] == '\\' && name[1] == '\\') /* UNC path */
2475 || (strchr(name,':') || ((*name == '[' || *name == '<') &&
2476 (isALNUM(name[1]) || strchr("$-_]>",name[1]))))
2481 tryrsfp = PerlIO_open(name,PERL_SCRIPT_MODE);
2484 AV *ar = GvAVn(incgv);
2488 if ((unixname = tounixspec(name, Nullch)) != Nullch)
2491 namesv = NEWSV(806, 0);
2492 for (i = 0; i <= AvFILL(ar); i++) {
2493 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2496 if ((unixdir = tounixpath(dir, Nullch)) == Nullch)
2498 sv_setpv(namesv, unixdir);
2499 sv_catpv(namesv, unixname);
2501 sv_setpvf(namesv, "%s/%s", dir, name);
2503 tryname = SvPVX(namesv);
2504 tryrsfp = PerlIO_open(tryname, PERL_SCRIPT_MODE);
2506 if (tryname[0] == '.' && tryname[1] == '/')
2513 SAVESPTR(compiling.cop_filegv);
2514 compiling.cop_filegv = gv_fetchfile(tryrsfp ? tryname : name);
2515 SvREFCNT_dec(namesv);
2517 if (op->op_type == OP_REQUIRE) {
2518 SV *msg = sv_2mortal(newSVpvf("Can't locate %s in @INC", name));
2519 SV *dirmsgsv = NEWSV(0, 0);
2520 AV *ar = GvAVn(incgv);
2522 if (instr(SvPVX(msg), ".h "))
2523 sv_catpv(msg, " (change .h to .ph maybe?)");
2524 if (instr(SvPVX(msg), ".ph "))
2525 sv_catpv(msg, " (did you run h2ph?)");
2526 sv_catpv(msg, " (@INC contains:");
2527 for (i = 0; i <= AvFILL(ar); i++) {
2528 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2529 sv_setpvf(dirmsgsv, " %s", dir);
2530 sv_catsv(msg, dirmsgsv);
2532 sv_catpvn(msg, ")", 1);
2533 SvREFCNT_dec(dirmsgsv);
2540 /* Assume success here to prevent recursive requirement. */
2541 (void)hv_store(GvHVn(incgv), name, strlen(name),
2542 newSVsv(GvSV(compiling.cop_filegv)), 0 );
2546 lex_start(sv_2mortal(newSVpv("",0)));
2548 save_aptr(&rsfp_filters);
2549 rsfp_filters = NULL;
2553 name = savepv(name);
2558 /* switch to eval mode */
2560 push_return(op->op_next);
2561 PUSHBLOCK(cx, CXt_EVAL, SP);
2562 PUSHEVAL(cx, name, compiling.cop_filegv);
2564 compiling.cop_line = 0;
2568 MUTEX_LOCK(&eval_mutex);
2569 if (eval_owner && eval_owner != thr)
2571 COND_WAIT(&eval_cond, &eval_mutex);
2573 MUTEX_UNLOCK(&eval_mutex);
2574 #endif /* USE_THREADS */
2575 return DOCATCH(doeval(G_SCALAR, NULL));
2580 return pp_require(ARGS);
2586 register PERL_CONTEXT *cx;
2588 I32 gimme = GIMME_V, was = sub_generation;
2589 char tmpbuf[TYPE_DIGITS(long) + 12];
2594 if (!SvPV(sv,len) || !len)
2596 TAINT_PROPER("eval");
2602 /* switch to eval mode */
2604 SAVESPTR(compiling.cop_filegv);
2605 sprintf(tmpbuf, "_<(eval %lu)", (unsigned long)++evalseq);
2606 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2607 compiling.cop_line = 1;
2608 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2609 deleting the eval's FILEGV from the stash before gv_check() runs
2610 (i.e. before run-time proper). To work around the coredump that
2611 ensues, we always turn GvMULTI_on for any globals that were
2612 introduced within evals. See force_ident(). GSAR 96-10-12 */
2613 safestr = savepv(tmpbuf);
2614 SAVEDELETE(defstash, safestr, strlen(safestr));
2616 hints = op->op_targ;
2618 push_return(op->op_next);
2619 PUSHBLOCK(cx, CXt_EVAL, SP);
2620 PUSHEVAL(cx, 0, compiling.cop_filegv);
2622 /* prepare to compile string */
2624 if (PERLDB_LINE && curstash != debstash)
2625 save_lines(GvAV(compiling.cop_filegv), linestr);
2628 MUTEX_LOCK(&eval_mutex);
2629 if (eval_owner && eval_owner != thr)
2631 COND_WAIT(&eval_cond, &eval_mutex);
2633 MUTEX_UNLOCK(&eval_mutex);
2634 #endif /* USE_THREADS */
2635 ret = doeval(gimme, NULL);
2636 if (PERLDB_INTER && was != sub_generation /* Some subs defined here. */
2637 && ret != op->op_next) { /* Successive compilation. */
2638 strcpy(safestr, "_<(eval )"); /* Anything fake and short. */
2640 return DOCATCH(ret);
2650 register PERL_CONTEXT *cx;
2652 U8 save_flags = op -> op_flags;
2657 retop = pop_return();
2660 if (gimme == G_VOID)
2662 else if (gimme == G_SCALAR) {
2665 if (SvFLAGS(TOPs) & SVs_TEMP)
2668 *MARK = sv_mortalcopy(TOPs);
2676 /* in case LEAVE wipes old return values */
2677 for (mark = newsp + 1; mark <= SP; mark++) {
2678 if (!(SvFLAGS(*mark) & SVs_TEMP)) {
2679 *mark = sv_mortalcopy(*mark);
2680 TAINT_NOT; /* Each item is independent */
2684 curpm = newpm; /* Don't pop $1 et al till now */
2687 * Closures mentioned at top level of eval cannot be referenced
2688 * again, and their presence indirectly causes a memory leak.
2689 * (Note that the fact that compcv and friends are still set here
2690 * is, AFAIK, an accident.) --Chip
2692 if (AvFILLp(comppad_name) >= 0) {
2693 SV **svp = AvARRAY(comppad_name);
2695 for (ix = AvFILLp(comppad_name); ix >= 0; ix--) {
2697 if (sv && sv != &sv_undef && *SvPVX(sv) == '&') {
2699 svp[ix] = &sv_undef;
2703 SvREFCNT_dec(CvOUTSIDE(sv));
2704 CvOUTSIDE(sv) = Nullcv;
2717 assert(CvDEPTH(compcv) == 1);
2719 CvDEPTH(compcv) = 0;
2722 if (optype == OP_REQUIRE &&
2723 !(gimme == G_SCALAR ? SvTRUE(*SP) : SP > newsp))
2725 /* Unassume the success we assumed earlier. */
2726 char *name = cx->blk_eval.old_name;
2727 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
2728 retop = die("%s did not return a true value", name);
2729 /* die_where() did LEAVE, or we won't be here */
2733 if (!(save_flags & OPf_SPECIAL))
2743 register PERL_CONTEXT *cx;
2744 I32 gimme = GIMME_V;
2749 push_return(cLOGOP->op_other->op_next);
2750 PUSHBLOCK(cx, CXt_EVAL, SP);
2752 eval_root = op; /* Only needed so that goto works right. */
2757 return DOCATCH(op->op_next);
2767 register PERL_CONTEXT *cx;
2775 if (gimme == G_VOID)
2777 else if (gimme == G_SCALAR) {
2780 if (SvFLAGS(TOPs) & (SVs_PADTMP|SVs_TEMP))
2783 *MARK = sv_mortalcopy(TOPs);
2792 /* in case LEAVE wipes old return values */
2793 for (mark = newsp + 1; mark <= SP; mark++) {
2794 if (!(SvFLAGS(*mark) & (SVs_PADTMP|SVs_TEMP))) {
2795 *mark = sv_mortalcopy(*mark);
2796 TAINT_NOT; /* Each item is independent */
2800 curpm = newpm; /* Don't pop $1 et al till now */
2811 register char *s = SvPV_force(sv, len);
2812 register char *send = s + len;
2813 register char *base;
2814 register I32 skipspaces = 0;
2817 bool postspace = FALSE;
2825 croak("Null picture in formline");
2827 New(804, fops, (send - s)*3+10, U16); /* Almost certainly too long... */
2832 *fpc++ = FF_LINEMARK;
2833 noblank = repeat = FALSE;
2851 case ' ': case '\t':
2862 *fpc++ = FF_LITERAL;
2870 *fpc++ = skipspaces;
2874 *fpc++ = FF_NEWLINE;
2878 arg = fpc - linepc + 1;
2885 *fpc++ = FF_LINEMARK;
2886 noblank = repeat = FALSE;
2895 ischop = s[-1] == '^';
2901 arg = (s - base) - 1;
2903 *fpc++ = FF_LITERAL;
2912 *fpc++ = FF_LINEGLOB;
2914 else if (*s == '#' || (*s == '.' && s[1] == '#')) {
2915 arg = ischop ? 512 : 0;
2925 arg |= 256 + (s - f);
2927 *fpc++ = s - base; /* fieldsize for FETCH */
2928 *fpc++ = FF_DECIMAL;
2933 bool ismore = FALSE;
2936 while (*++s == '>') ;
2937 prespace = FF_SPACE;
2939 else if (*s == '|') {
2940 while (*++s == '|') ;
2941 prespace = FF_HALFSPACE;
2946 while (*++s == '<') ;
2949 if (*s == '.' && s[1] == '.' && s[2] == '.') {
2953 *fpc++ = s - base; /* fieldsize for FETCH */
2955 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
2973 { /* need to jump to the next word */
2975 z = WORD_ALIGN - SvCUR(sv) % WORD_ALIGN;
2976 SvGROW(sv, SvCUR(sv) + z + arg * sizeof(U16) + 4);
2977 s = SvPVX(sv) + SvCUR(sv) + z;
2979 Copy(fops, s, arg, U16);
2981 sv_magic(sv, Nullsv, 'f', Nullch, 0);
2986 * The rest of this file was derived from source code contributed
2989 * NOTE: this code was derived from Tom Horsley's qsort replacement
2990 * and should not be confused with the original code.
2993 /* Copyright (C) Tom Horsley, 1997. All rights reserved.
2995 Permission granted to distribute under the same terms as perl which are
2998 This program is free software; you can redistribute it and/or modify
2999 it under the terms of either:
3001 a) the GNU General Public License as published by the Free
3002 Software Foundation; either version 1, or (at your option) any
3005 b) the "Artistic License" which comes with this Kit.
3007 Details on the perl license can be found in the perl source code which
3008 may be located via the www.perl.com web page.
3010 This is the most wonderfulest possible qsort I can come up with (and
3011 still be mostly portable) My (limited) tests indicate it consistently
3012 does about 20% fewer calls to compare than does the qsort in the Visual
3013 C++ library, other vendors may vary.
3015 Some of the ideas in here can be found in "Algorithms" by Sedgewick,
3016 others I invented myself (or more likely re-invented since they seemed
3017 pretty obvious once I watched the algorithm operate for a while).
3019 Most of this code was written while watching the Marlins sweep the Giants
3020 in the 1997 National League Playoffs - no Braves fans allowed to use this
3021 code (just kidding :-).
3023 I realize that if I wanted to be true to the perl tradition, the only
3024 comment in this file would be something like:
3026 ...they shuffled back towards the rear of the line. 'No, not at the
3027 rear!' the slave-driver shouted. 'Three files up. And stay there...
3029 However, I really needed to violate that tradition just so I could keep
3030 track of what happens myself, not to mention some poor fool trying to
3031 understand this years from now :-).
3034 /* ********************************************************** Configuration */
3036 #ifndef QSORT_ORDER_GUESS
3037 #define QSORT_ORDER_GUESS 2 /* Select doubling version of the netBSD trick */
3040 /* QSORT_MAX_STACK is the largest number of partitions that can be stacked up for
3041 future processing - a good max upper bound is log base 2 of memory size
3042 (32 on 32 bit machines, 64 on 64 bit machines, etc). In reality can
3043 safely be smaller than that since the program is taking up some space and
3044 most operating systems only let you grab some subset of contiguous
3045 memory (not to mention that you are normally sorting data larger than
3046 1 byte element size :-).
3048 #ifndef QSORT_MAX_STACK
3049 #define QSORT_MAX_STACK 32
3052 /* QSORT_BREAK_EVEN is the size of the largest partition we should insertion sort.
3053 Anything bigger and we use qsort. If you make this too small, the qsort
3054 will probably break (or become less efficient), because it doesn't expect
3055 the middle element of a partition to be the same as the right or left -
3056 you have been warned).
3058 #ifndef QSORT_BREAK_EVEN
3059 #define QSORT_BREAK_EVEN 6
3062 /* ************************************************************* Data Types */
3064 /* hold left and right index values of a partition waiting to be sorted (the
3065 partition includes both left and right - right is NOT one past the end or
3066 anything like that).
3068 struct partition_stack_entry {
3071 #ifdef QSORT_ORDER_GUESS
3072 int qsort_break_even;
3076 /* ******************************************************* Shorthand Macros */
3078 /* Note that these macros will be used from inside the qsort function where
3079 we happen to know that the variable 'elt_size' contains the size of an
3080 array element and the variable 'temp' points to enough space to hold a
3081 temp element and the variable 'array' points to the array being sorted
3082 and 'compare' is the pointer to the compare routine.
3084 Also note that there are very many highly architecture specific ways
3085 these might be sped up, but this is simply the most generally portable
3086 code I could think of.
3089 /* Return < 0 == 0 or > 0 as the value of elt1 is < elt2, == elt2, > elt2
3092 #define qsort_cmp(elt1, elt2) \
3093 ((this->*compare)(array[elt1], array[elt2]))
3095 #define qsort_cmp(elt1, elt2) \
3096 ((*compare)(array[elt1], array[elt2]))
3099 #ifdef QSORT_ORDER_GUESS
3100 #define QSORT_NOTICE_SWAP swapped++;
3102 #define QSORT_NOTICE_SWAP
3105 /* swaps contents of array elements elt1, elt2.
3107 #define qsort_swap(elt1, elt2) \
3110 temp = array[elt1]; \
3111 array[elt1] = array[elt2]; \
3112 array[elt2] = temp; \
3115 /* rotate contents of elt1, elt2, elt3 such that elt1 gets elt2, elt2 gets
3116 elt3 and elt3 gets elt1.
3118 #define qsort_rotate(elt1, elt2, elt3) \
3121 temp = array[elt1]; \
3122 array[elt1] = array[elt2]; \
3123 array[elt2] = array[elt3]; \
3124 array[elt3] = temp; \
3127 /* ************************************************************ Debug stuff */
3134 return; /* good place to set a breakpoint */
3137 #define qsort_assert(t) (void)( (t) || (break_here(), 0) )
3140 doqsort_all_asserts(
3144 int (*compare)(const void * elt1, const void * elt2),
3145 int pc_left, int pc_right, int u_left, int u_right)
3149 qsort_assert(pc_left <= pc_right);
3150 qsort_assert(u_right < pc_left);
3151 qsort_assert(pc_right < u_left);
3152 for (i = u_right + 1; i < pc_left; ++i) {
3153 qsort_assert(qsort_cmp(i, pc_left) < 0);
3155 for (i = pc_left; i < pc_right; ++i) {
3156 qsort_assert(qsort_cmp(i, pc_right) == 0);
3158 for (i = pc_right + 1; i < u_left; ++i) {
3159 qsort_assert(qsort_cmp(pc_right, i) < 0);
3163 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) \
3164 doqsort_all_asserts(array, num_elts, elt_size, compare, \
3165 PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT)
3169 #define qsort_assert(t) ((void)0)
3171 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) ((void)0)
3175 /* ****************************************************************** qsort */
3179 qsortsv(SV ** array, size_t num_elts, SVCOMPARE compare)
3184 I32 (*compare)(SV *a, SV *b))
3189 struct partition_stack_entry partition_stack[QSORT_MAX_STACK];
3190 int next_stack_entry = 0;
3194 #ifdef QSORT_ORDER_GUESS
3195 int qsort_break_even;
3199 /* Make sure we actually have work to do.
3201 if (num_elts <= 1) {
3205 /* Setup the initial partition definition and fall into the sorting loop
3208 part_right = (int)(num_elts - 1);
3209 #ifdef QSORT_ORDER_GUESS
3210 qsort_break_even = QSORT_BREAK_EVEN;
3212 #define qsort_break_even QSORT_BREAK_EVEN
3215 if ((part_right - part_left) >= qsort_break_even) {
3216 /* OK, this is gonna get hairy, so lets try to document all the
3217 concepts and abbreviations and variables and what they keep
3220 pc: pivot chunk - the set of array elements we accumulate in the
3221 middle of the partition, all equal in value to the original
3222 pivot element selected. The pc is defined by:
3224 pc_left - the leftmost array index of the pc
3225 pc_right - the rightmost array index of the pc
3227 we start with pc_left == pc_right and only one element
3228 in the pivot chunk (but it can grow during the scan).
3230 u: uncompared elements - the set of elements in the partition
3231 we have not yet compared to the pivot value. There are two
3232 uncompared sets during the scan - one to the left of the pc
3233 and one to the right.
3235 u_right - the rightmost index of the left side's uncompared set
3236 u_left - the leftmost index of the right side's uncompared set
3238 The leftmost index of the left sides's uncompared set
3239 doesn't need its own variable because it is always defined
3240 by the leftmost edge of the whole partition (part_left). The
3241 same goes for the rightmost edge of the right partition
3244 We know there are no uncompared elements on the left once we
3245 get u_right < part_left and no uncompared elements on the
3246 right once u_left > part_right. When both these conditions
3247 are met, we have completed the scan of the partition.
3249 Any elements which are between the pivot chunk and the
3250 uncompared elements should be less than the pivot value on
3251 the left side and greater than the pivot value on the right
3252 side (in fact, the goal of the whole algorithm is to arrange
3253 for that to be true and make the groups of less-than and
3254 greater-then elements into new partitions to sort again).
3256 As you marvel at the complexity of the code and wonder why it
3257 has to be so confusing. Consider some of the things this level
3258 of confusion brings:
3260 Once I do a compare, I squeeze every ounce of juice out of it. I
3261 never do compare calls I don't have to do, and I certainly never
3264 I also never swap any elements unless I can prove there is a
3265 good reason. Many sort algorithms will swap a known value with
3266 an uncompared value just to get things in the right place (or
3267 avoid complexity :-), but that uncompared value, once it gets
3268 compared, may then have to be swapped again. A lot of the
3269 complexity of this code is due to the fact that it never swaps
3270 anything except compared values, and it only swaps them when the
3271 compare shows they are out of position.
3273 int pc_left, pc_right;
3274 int u_right, u_left;
3278 pc_left = ((part_left + part_right) / 2);
3280 u_right = pc_left - 1;
3281 u_left = pc_right + 1;
3283 /* Qsort works best when the pivot value is also the median value
3284 in the partition (unfortunately you can't find the median value
3285 without first sorting :-), so to give the algorithm a helping
3286 hand, we pick 3 elements and sort them and use the median value
3287 of that tiny set as the pivot value.
3289 Some versions of qsort like to use the left middle and right as
3290 the 3 elements to sort so they can insure the ends of the
3291 partition will contain values which will stop the scan in the
3292 compare loop, but when you have to call an arbitrarily complex
3293 routine to do a compare, its really better to just keep track of
3294 array index values to know when you hit the edge of the
3295 partition and avoid the extra compare. An even better reason to
3296 avoid using a compare call is the fact that you can drop off the
3297 edge of the array if someone foolishly provides you with an
3298 unstable compare function that doesn't always provide consistent
3301 So, since it is simpler for us to compare the three adjacent
3302 elements in the middle of the partition, those are the ones we
3303 pick here (conveniently pointed at by u_right, pc_left, and
3304 u_left). The values of the left, center, and right elements
3305 are refered to as l c and r in the following comments.
3308 #ifdef QSORT_ORDER_GUESS
3311 s = qsort_cmp(u_right, pc_left);
3314 s = qsort_cmp(pc_left, u_left);
3315 /* if l < c, c < r - already in order - nothing to do */
3317 /* l < c, c == r - already in order, pc grows */
3319 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3321 /* l < c, c > r - need to know more */
3322 s = qsort_cmp(u_right, u_left);
3324 /* l < c, c > r, l < r - swap c & r to get ordered */
3325 qsort_swap(pc_left, u_left);
3326 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3327 } else if (s == 0) {
3328 /* l < c, c > r, l == r - swap c&r, grow pc */
3329 qsort_swap(pc_left, u_left);
3331 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3333 /* l < c, c > r, l > r - make lcr into rlc to get ordered */
3334 qsort_rotate(pc_left, u_right, u_left);
3335 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3338 } else if (s == 0) {
3340 s = qsort_cmp(pc_left, u_left);
3342 /* l == c, c < r - already in order, grow pc */
3344 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3345 } else if (s == 0) {
3346 /* l == c, c == r - already in order, grow pc both ways */
3349 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3351 /* l == c, c > r - swap l & r, grow pc */
3352 qsort_swap(u_right, u_left);
3354 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3358 s = qsort_cmp(pc_left, u_left);
3360 /* l > c, c < r - need to know more */
3361 s = qsort_cmp(u_right, u_left);
3363 /* l > c, c < r, l < r - swap l & c to get ordered */
3364 qsort_swap(u_right, pc_left);
3365 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3366 } else if (s == 0) {
3367 /* l > c, c < r, l == r - swap l & c, grow pc */
3368 qsort_swap(u_right, pc_left);
3370 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3372 /* l > c, c < r, l > r - rotate lcr into crl to order */
3373 qsort_rotate(u_right, pc_left, u_left);
3374 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3376 } else if (s == 0) {
3377 /* l > c, c == r - swap ends, grow pc */
3378 qsort_swap(u_right, u_left);
3380 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3382 /* l > c, c > r - swap ends to get in order */
3383 qsort_swap(u_right, u_left);
3384 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3387 /* We now know the 3 middle elements have been compared and
3388 arranged in the desired order, so we can shrink the uncompared
3393 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3395 /* The above massive nested if was the simple part :-). We now have
3396 the middle 3 elements ordered and we need to scan through the
3397 uncompared sets on either side, swapping elements that are on
3398 the wrong side or simply shuffling equal elements around to get
3399 all equal elements into the pivot chunk.
3403 int still_work_on_left;
3404 int still_work_on_right;
3406 /* Scan the uncompared values on the left. If I find a value
3407 equal to the pivot value, move it over so it is adjacent to
3408 the pivot chunk and expand the pivot chunk. If I find a value
3409 less than the pivot value, then just leave it - its already
3410 on the correct side of the partition. If I find a greater
3411 value, then stop the scan.
3413 while (still_work_on_left = (u_right >= part_left)) {
3414 s = qsort_cmp(u_right, pc_left);
3417 } else if (s == 0) {
3419 if (pc_left != u_right) {
3420 qsort_swap(u_right, pc_left);
3426 qsort_assert(u_right < pc_left);
3427 qsort_assert(pc_left <= pc_right);
3428 qsort_assert(qsort_cmp(u_right + 1, pc_left) <= 0);
3429 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3432 /* Do a mirror image scan of uncompared values on the right
3434 while (still_work_on_right = (u_left <= part_right)) {
3435 s = qsort_cmp(pc_right, u_left);
3438 } else if (s == 0) {
3440 if (pc_right != u_left) {
3441 qsort_swap(pc_right, u_left);
3447 qsort_assert(u_left > pc_right);
3448 qsort_assert(pc_left <= pc_right);
3449 qsort_assert(qsort_cmp(pc_right, u_left - 1) <= 0);
3450 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3453 if (still_work_on_left) {
3454 /* I know I have a value on the left side which needs to be
3455 on the right side, but I need to know more to decide
3456 exactly the best thing to do with it.
3458 if (still_work_on_right) {
3459 /* I know I have values on both side which are out of
3460 position. This is a big win because I kill two birds
3461 with one swap (so to speak). I can advance the
3462 uncompared pointers on both sides after swapping both
3463 of them into the right place.
3465 qsort_swap(u_right, u_left);
3468 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3470 /* I have an out of position value on the left, but the
3471 right is fully scanned, so I "slide" the pivot chunk
3472 and any less-than values left one to make room for the
3473 greater value over on the right. If the out of position
3474 value is immediately adjacent to the pivot chunk (there
3475 are no less-than values), I can do that with a swap,
3476 otherwise, I have to rotate one of the less than values
3477 into the former position of the out of position value
3478 and the right end of the pivot chunk into the left end
3482 if (pc_left == u_right) {
3483 qsort_swap(u_right, pc_right);
3484 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3486 qsort_rotate(u_right, pc_left, pc_right);
3487 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3492 } else if (still_work_on_right) {
3493 /* Mirror image of complex case above: I have an out of
3494 position value on the right, but the left is fully
3495 scanned, so I need to shuffle things around to make room
3496 for the right value on the left.
3499 if (pc_right == u_left) {
3500 qsort_swap(u_left, pc_left);
3501 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3503 qsort_rotate(pc_right, pc_left, u_left);
3504 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3509 /* No more scanning required on either side of partition,
3510 break out of loop and figure out next set of partitions
3516 /* The elements in the pivot chunk are now in the right place. They
3517 will never move or be compared again. All I have to do is decide
3518 what to do with the stuff to the left and right of the pivot
3521 Notes on the QSORT_ORDER_GUESS ifdef code:
3523 1. If I just built these partitions without swapping any (or
3524 very many) elements, there is a chance that the elements are
3525 already ordered properly (being properly ordered will
3526 certainly result in no swapping, but the converse can't be
3529 2. A (properly written) insertion sort will run faster on
3530 already ordered data than qsort will.
3532 3. Perhaps there is some way to make a good guess about
3533 switching to an insertion sort earlier than partition size 6
3534 (for instance - we could save the partition size on the stack
3535 and increase the size each time we find we didn't swap, thus
3536 switching to insertion sort earlier for partitions with a
3537 history of not swapping).
3539 4. Naturally, if I just switch right away, it will make
3540 artificial benchmarks with pure ascending (or descending)
3541 data look really good, but is that a good reason in general?
3545 #ifdef QSORT_ORDER_GUESS
3547 #if QSORT_ORDER_GUESS == 1
3548 qsort_break_even = (part_right - part_left) + 1;
3550 #if QSORT_ORDER_GUESS == 2
3551 qsort_break_even *= 2;
3553 #if QSORT_ORDER_GUESS == 3
3554 int prev_break = qsort_break_even;
3555 qsort_break_even *= qsort_break_even;
3556 if (qsort_break_even < prev_break) {
3557 qsort_break_even = (part_right - part_left) + 1;
3561 qsort_break_even = QSORT_BREAK_EVEN;
3565 if (part_left < pc_left) {
3566 /* There are elements on the left which need more processing.
3567 Check the right as well before deciding what to do.
3569 if (pc_right < part_right) {
3570 /* We have two partitions to be sorted. Stack the biggest one
3571 and process the smallest one on the next iteration. This
3572 minimizes the stack height by insuring that any additional
3573 stack entries must come from the smallest partition which
3574 (because it is smallest) will have the fewest
3575 opportunities to generate additional stack entries.
3577 if ((part_right - pc_right) > (pc_left - part_left)) {
3578 /* stack the right partition, process the left */
3579 partition_stack[next_stack_entry].left = pc_right + 1;
3580 partition_stack[next_stack_entry].right = part_right;
3581 #ifdef QSORT_ORDER_GUESS
3582 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3584 part_right = pc_left - 1;
3586 /* stack the left partition, process the right */
3587 partition_stack[next_stack_entry].left = part_left;
3588 partition_stack[next_stack_entry].right = pc_left - 1;
3589 #ifdef QSORT_ORDER_GUESS
3590 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3592 part_left = pc_right + 1;
3594 qsort_assert(next_stack_entry < QSORT_MAX_STACK);
3597 /* The elements on the left are the only remaining elements
3598 that need sorting, arrange for them to be processed as the
3601 part_right = pc_left - 1;
3603 } else if (pc_right < part_right) {
3604 /* There is only one chunk on the right to be sorted, make it
3605 the new partition and loop back around.
3607 part_left = pc_right + 1;
3609 /* This whole partition wound up in the pivot chunk, so
3610 we need to get a new partition off the stack.
3612 if (next_stack_entry == 0) {
3613 /* the stack is empty - we are done */
3617 part_left = partition_stack[next_stack_entry].left;
3618 part_right = partition_stack[next_stack_entry].right;
3619 #ifdef QSORT_ORDER_GUESS
3620 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3624 /* This partition is too small to fool with qsort complexity, just
3625 do an ordinary insertion sort to minimize overhead.
3628 /* Assume 1st element is in right place already, and start checking
3629 at 2nd element to see where it should be inserted.
3631 for (i = part_left + 1; i <= part_right; ++i) {
3633 /* Scan (backwards - just in case 'i' is already in right place)
3634 through the elements already sorted to see if the ith element
3635 belongs ahead of one of them.
3637 for (j = i - 1; j >= part_left; --j) {
3638 if (qsort_cmp(i, j) >= 0) {
3639 /* i belongs right after j
3646 /* Looks like we really need to move some things
3650 for (k = i - 1; k >= j; --k)
3651 array[k + 1] = array[k];
3656 /* That partition is now sorted, grab the next one, or get out
3657 of the loop if there aren't any more.
3660 if (next_stack_entry == 0) {
3661 /* the stack is empty - we are done */
3665 part_left = partition_stack[next_stack_entry].left;
3666 part_right = partition_stack[next_stack_entry].right;
3667 #ifdef QSORT_ORDER_GUESS
3668 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3673 /* Believe it or not, the array is sorted at this point! */