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 /* JMR: Check against the last compiled regexp
93 To know for sure, we'd need the length of precomp.
94 But we don't have it, so we must ... take a guess. */
95 if (!pm->op_pmregexp || !pm->op_pmregexp->precomp ||
96 memNE(pm->op_pmregexp->precomp, t, len + 1))
98 if (pm->op_pmregexp) {
99 ReREFCNT_dec(pm->op_pmregexp);
100 pm->op_pmregexp = Null(REGEXP*); /* crucial if regcomp aborts */
103 pm->op_pmflags = pm->op_pmpermflags; /* reset case sensitivity */
104 pm->op_pmregexp = pregcomp(t, t + len, pm);
108 if (!pm->op_pmregexp->prelen && curpm)
110 else if (strEQ("\\s+", pm->op_pmregexp->precomp))
111 pm->op_pmflags |= PMf_WHITE;
113 if (pm->op_pmflags & PMf_KEEP) {
114 pm->op_private &= ~OPpRUNTIME; /* no point compiling again */
115 cLOGOP->op_first->op_next = op->op_next;
123 register PMOP *pm = (PMOP*) cLOGOP->op_other;
124 register PERL_CONTEXT *cx = &cxstack[cxstack_ix];
125 register SV *dstr = cx->sb_dstr;
126 register char *s = cx->sb_s;
127 register char *m = cx->sb_m;
128 char *orig = cx->sb_orig;
129 register REGEXP *rx = cx->sb_rx;
131 rxres_restore(&cx->sb_rxres, rx);
133 if (cx->sb_iters++) {
134 if (cx->sb_iters > cx->sb_maxiters)
135 DIE("Substitution loop");
137 if (!cx->sb_rxtainted)
138 cx->sb_rxtainted = SvTAINTED(TOPs);
139 sv_catsv(dstr, POPs);
142 if (cx->sb_once || !regexec_flags(rx, s, cx->sb_strend, orig,
143 s == m, Nullsv, NULL,
144 cx->sb_safebase ? 0 : REXEC_COPY_STR))
146 SV *targ = cx->sb_targ;
147 sv_catpvn(dstr, s, cx->sb_strend - s);
149 TAINT_IF(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));
158 (void)SvPOK_only(targ);
162 PUSHs(sv_2mortal(newSViv((I32)cx->sb_iters - 1)));
163 LEAVE_SCOPE(cx->sb_oldsave);
165 RETURNOP(pm->op_next);
168 if (rx->subbase && rx->subbase != orig) {
171 cx->sb_orig = orig = rx->subbase;
173 cx->sb_strend = s + (cx->sb_strend - m);
175 cx->sb_m = m = rx->startp[0];
176 sv_catpvn(dstr, s, m-s);
177 cx->sb_s = rx->endp[0];
178 cx->sb_rxtainted |= RX_MATCH_TAINTED(rx);
179 rxres_save(&cx->sb_rxres, rx);
180 RETURNOP(pm->op_pmreplstart);
184 rxres_save(void **rsp, REGEXP *rx)
189 if (!p || p[1] < rx->nparens) {
190 i = 6 + rx->nparens * 2;
198 *p++ = (UV)rx->subbase;
199 rx->subbase = Nullch;
203 *p++ = (UV)rx->subbeg;
204 *p++ = (UV)rx->subend;
205 for (i = 0; i <= rx->nparens; ++i) {
206 *p++ = (UV)rx->startp[i];
207 *p++ = (UV)rx->endp[i];
212 rxres_restore(void **rsp, REGEXP *rx)
217 Safefree(rx->subbase);
218 rx->subbase = (char*)(*p);
223 rx->subbeg = (char*)(*p++);
224 rx->subend = (char*)(*p++);
225 for (i = 0; i <= rx->nparens; ++i) {
226 rx->startp[i] = (char*)(*p++);
227 rx->endp[i] = (char*)(*p++);
232 rxres_free(void **rsp)
237 Safefree((char*)(*p));
245 djSP; dMARK; dORIGMARK;
246 register SV *tmpForm = *++MARK;
258 bool chopspace = (strchr(chopset, ' ') != Nullch);
265 if (!SvMAGICAL(tmpForm) || !SvCOMPILED(tmpForm)) {
266 SvREADONLY_off(tmpForm);
267 doparseform(tmpForm);
270 SvPV_force(formtarget, len);
271 t = SvGROW(formtarget, len + SvCUR(tmpForm) + 1); /* XXX SvCUR bad */
273 f = SvPV(tmpForm, len);
274 /* need to jump to the next word */
275 s = f + len + WORD_ALIGN - SvCUR(tmpForm) % WORD_ALIGN;
284 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
285 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
286 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
287 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
288 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
290 case FF_CHECKNL: name = "CHECKNL"; break;
291 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
292 case FF_SPACE: name = "SPACE"; break;
293 case FF_HALFSPACE: name = "HALFSPACE"; break;
294 case FF_ITEM: name = "ITEM"; break;
295 case FF_CHOP: name = "CHOP"; break;
296 case FF_LINEGLOB: name = "LINEGLOB"; break;
297 case FF_NEWLINE: name = "NEWLINE"; break;
298 case FF_MORE: name = "MORE"; break;
299 case FF_LINEMARK: name = "LINEMARK"; break;
300 case FF_END: name = "END"; break;
303 PerlIO_printf(PerlIO_stderr(), "%-16s%ld\n", name, (long) arg);
305 PerlIO_printf(PerlIO_stderr(), "%-16s\n", name);
334 warn("Not enough format arguments");
339 item = s = SvPV(sv, len);
341 if (itemsize > fieldsize)
342 itemsize = fieldsize;
343 send = chophere = s + itemsize;
355 item = s = SvPV(sv, len);
357 if (itemsize <= fieldsize) {
358 send = chophere = s + itemsize;
369 itemsize = fieldsize;
370 send = chophere = s + itemsize;
371 while (s < send || (s == send && isSPACE(*s))) {
381 if (strchr(chopset, *s))
386 itemsize = chophere - item;
391 arg = fieldsize - itemsize;
400 arg = fieldsize - itemsize;
414 int ch = *t++ = *s++;
418 if ( !((*t++ = *s++) & ~31) )
428 while (*s && isSPACE(*s))
435 item = s = SvPV(sv, len);
448 SvCUR_set(formtarget, t - SvPVX(formtarget));
449 sv_catpvn(formtarget, item, itemsize);
450 SvGROW(formtarget, SvCUR(formtarget) + SvCUR(tmpForm) + 1);
451 t = SvPVX(formtarget) + SvCUR(formtarget);
456 /* If the field is marked with ^ and the value is undefined,
459 if ((arg & 512) && !SvOK(sv)) {
467 /* Formats aren't yet marked for locales, so assume "yes". */
470 sprintf(t, "%#*.*f", (int) fieldsize, (int) arg & 255, value);
472 sprintf(t, "%*.0f", (int) fieldsize, value);
479 while (t-- > linemark && *t == ' ') ;
487 if (arg) { /* repeat until fields exhausted? */
489 SvCUR_set(formtarget, t - SvPVX(formtarget));
490 lines += FmLINES(formtarget);
493 if (strnEQ(linemark, linemark - arg, arg))
494 DIE("Runaway format");
496 FmLINES(formtarget) = lines;
498 RETURNOP(cLISTOP->op_first);
509 arg = fieldsize - itemsize;
516 if (strnEQ(s," ",3)) {
517 while (s > SvPVX(formtarget) && isSPACE(s[-1]))
528 SvCUR_set(formtarget, t - SvPVX(formtarget));
529 FmLINES(formtarget) += lines;
541 if (stack_base + *markstack_ptr == sp) {
543 if (GIMME_V == G_SCALAR)
545 RETURNOP(op->op_next->op_next);
547 stack_sp = stack_base + *markstack_ptr + 1;
548 pp_pushmark(ARGS); /* push dst */
549 pp_pushmark(ARGS); /* push src */
550 ENTER; /* enter outer scope */
554 /* SAVE_DEFSV does *not* suffice here */
555 save_sptr(&THREADSV(0));
557 SAVESPTR(GvSV(defgv));
558 #endif /* USE_THREADS */
559 ENTER; /* enter inner scope */
562 src = stack_base[*markstack_ptr];
567 if (op->op_type == OP_MAPSTART)
568 pp_pushmark(ARGS); /* push top */
569 return ((LOGOP*)op->op_next)->op_other;
574 DIE("panic: mapstart"); /* uses grepstart */
580 I32 diff = (sp - stack_base) - *markstack_ptr;
588 if (diff > markstack_ptr[-1] - markstack_ptr[-2]) {
589 shift = diff - (markstack_ptr[-1] - markstack_ptr[-2]);
590 count = (sp - stack_base) - markstack_ptr[-1] + 2;
595 markstack_ptr[-1] += shift;
596 *markstack_ptr += shift;
600 dst = stack_base + (markstack_ptr[-2] += diff) - 1;
603 *dst-- = SvTEMP(TOPs) ? POPs : sv_mortalcopy(POPs);
605 LEAVE; /* exit inner scope */
608 if (markstack_ptr[-1] > *markstack_ptr) {
612 (void)POPMARK; /* pop top */
613 LEAVE; /* exit outer scope */
614 (void)POPMARK; /* pop src */
615 items = --*markstack_ptr - markstack_ptr[-1];
616 (void)POPMARK; /* pop dst */
617 SP = stack_base + POPMARK; /* pop original mark */
618 if (gimme == G_SCALAR) {
622 else if (gimme == G_ARRAY)
629 ENTER; /* enter inner scope */
632 src = stack_base[markstack_ptr[-1]];
636 RETURNOP(cLOGOP->op_other);
642 djSP; dMARK; dORIGMARK;
644 SV **myorigmark = ORIGMARK;
650 OP* nextop = op->op_next;
652 if (gimme != G_ARRAY) {
657 if (op->op_flags & OPf_STACKED) {
659 if (op->op_flags & OPf_SPECIAL) {
660 OP *kid = cLISTOP->op_first->op_sibling; /* pass pushmark */
661 kid = kUNOP->op_first; /* pass rv2gv */
662 kid = kUNOP->op_first; /* pass leave */
663 sortcop = kid->op_next;
664 stash = curcop->cop_stash;
667 cv = sv_2cv(*++MARK, &stash, &gv, 0);
668 if (!(cv && CvROOT(cv))) {
670 SV *tmpstr = sv_newmortal();
671 gv_efullname3(tmpstr, gv, Nullch);
672 if (cv && CvXSUB(cv))
673 DIE("Xsub \"%s\" called in sort", SvPVX(tmpstr));
674 DIE("Undefined sort subroutine \"%s\" called",
679 DIE("Xsub called in sort");
680 DIE("Undefined subroutine in sort");
682 DIE("Not a CODE reference in sort");
684 sortcop = CvSTART(cv);
685 SAVESPTR(CvROOT(cv)->op_ppaddr);
686 CvROOT(cv)->op_ppaddr = ppaddr[OP_NULL];
689 curpad = AvARRAY((AV*)AvARRAY(CvPADLIST(cv))[1]);
694 stash = curcop->cop_stash;
698 while (MARK < SP) { /* This may or may not shift down one here. */
700 if (*up = *++MARK) { /* Weed out nulls. */
702 if (!sortcop && !SvPOK(*up))
703 (void)sv_2pv(*up, &na);
707 max = --up - myorigmark;
713 bool oldcatch = CATCH_GET;
721 AvREAL_off(sortstack);
722 av_extend(sortstack, 32);
725 SWITCHSTACK(curstack, sortstack);
726 if (sortstash != stash) {
727 firstgv = gv_fetchpv("a", TRUE, SVt_PV);
728 secondgv = gv_fetchpv("b", TRUE, SVt_PV);
732 SAVESPTR(GvSV(firstgv));
733 SAVESPTR(GvSV(secondgv));
735 PUSHBLOCK(cx, CXt_NULL, stack_base);
736 if (!(op->op_flags & OPf_SPECIAL)) {
737 bool hasargs = FALSE;
738 cx->cx_type = CXt_SUB;
739 cx->blk_gimme = G_SCALAR;
742 (void)SvREFCNT_inc(cv); /* in preparation for POPSUB */
744 sortcxix = cxstack_ix;
745 qsortsv((myorigmark+1), max, sortcv);
748 SWITCHSTACK(sortstack, oldstack);
755 MEXTEND(SP, 20); /* Can't afford stack realloc on signal. */
756 qsortsv(ORIGMARK+1, max,
757 (op->op_private & OPpLOCALE) ? sv_cmp_locale : 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') )
821 EXTEND_MORTAL(max - i + 1);
822 EXTEND(SP, max - i + 1);
825 sv = sv_2mortal(newSViv(i++));
830 SV *final = sv_mortalcopy(right);
832 char *tmps = SvPV(final, len);
834 sv = sv_mortalcopy(left);
835 while (!SvNIOKp(sv) && SvCUR(sv) <= len &&
836 strNE(SvPVX(sv),tmps) ) {
838 sv = sv_2mortal(newSVsv(sv));
841 if (strEQ(SvPVX(sv),tmps))
847 SV *targ = PAD_SV(cUNOP->op_first->op_targ);
849 if ((op->op_private & OPpFLIP_LINENUM)
850 ? last_in_gv && SvIV(sv) == IoLINES(GvIOp(last_in_gv))
852 sv_setiv(PAD_SV(((UNOP*)cUNOP->op_first)->op_first->op_targ), 0);
853 sv_catpv(targ, "E0");
864 dopoptolabel(char *label)
868 register PERL_CONTEXT *cx;
870 for (i = cxstack_ix; i >= 0; i--) {
872 switch (cx->cx_type) {
875 warn("Exiting substitution via %s", op_name[op->op_type]);
879 warn("Exiting subroutine via %s", op_name[op->op_type]);
883 warn("Exiting eval via %s", op_name[op->op_type]);
887 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
890 if (!cx->blk_loop.label ||
891 strNE(label, cx->blk_loop.label) ) {
892 DEBUG_l(deb("(Skipping label #%ld %s)\n",
893 (long)i, cx->blk_loop.label));
896 DEBUG_l( deb("(Found label #%ld %s)\n", (long)i, label));
906 I32 gimme = block_gimme();
907 return (gimme == G_VOID) ? G_SCALAR : gimme;
916 cxix = dopoptosub(cxstack_ix);
920 switch (cxstack[cxix].blk_gimme) {
926 croak("panic: bad gimme: %d\n", cxstack[cxix].blk_gimme);
933 dopoptosub(I32 startingblock)
937 register PERL_CONTEXT *cx;
938 for (i = startingblock; i >= 0; i--) {
940 switch (cx->cx_type) {
945 DEBUG_l( deb("(Found sub #%ld)\n", (long)i));
953 dopoptoeval(I32 startingblock)
957 register PERL_CONTEXT *cx;
958 for (i = startingblock; i >= 0; i--) {
960 switch (cx->cx_type) {
964 DEBUG_l( deb("(Found eval #%ld)\n", (long)i));
972 dopoptoloop(I32 startingblock)
976 register PERL_CONTEXT *cx;
977 for (i = startingblock; i >= 0; i--) {
979 switch (cx->cx_type) {
982 warn("Exiting substitution via %s", op_name[op->op_type]);
986 warn("Exiting subroutine via %s", op_name[op->op_type]);
990 warn("Exiting eval via %s", op_name[op->op_type]);
994 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
997 DEBUG_l( deb("(Found loop #%ld)\n", (long)i));
1008 register PERL_CONTEXT *cx;
1012 while (cxstack_ix > cxix) {
1013 cx = &cxstack[cxstack_ix];
1014 DEBUG_l(PerlIO_printf(Perl_debug_log, "Unwinding block %ld, type %s\n",
1015 (long) cxstack_ix+1, block_type[cx->cx_type]));
1016 /* Note: we don't need to restore the base context info till the end. */
1017 switch (cx->cx_type) {
1020 continue; /* not break */
1038 die_where(char *message)
1043 register PERL_CONTEXT *cx;
1049 STRLEN klen = strlen(message);
1051 svp = hv_fetch(ERRHV, message, klen, TRUE);
1054 static char prefix[] = "\t(in cleanup) ";
1056 sv_upgrade(*svp, SVt_IV);
1057 (void)SvIOK_only(*svp);
1060 SvGROW(err, SvCUR(err)+sizeof(prefix)+klen);
1061 sv_catpvn(err, prefix, sizeof(prefix)-1);
1062 sv_catpvn(err, message, klen);
1068 sv_setpv(ERRSV, message);
1070 cxix = dopoptoeval(cxstack_ix);
1074 if (cxix < cxstack_ix)
1078 if (cx->cx_type != CXt_EVAL) {
1079 PerlIO_printf(PerlIO_stderr(), "panic: die %s", message);
1084 if (gimme == G_SCALAR)
1085 *++newsp = &sv_undef;
1090 if (optype == OP_REQUIRE) {
1091 char* msg = SvPVx(ERRSV, na);
1092 DIE("%s", *msg ? msg : "Compilation failed in require");
1094 return pop_return();
1097 PerlIO_printf(PerlIO_stderr(), "%s",message);
1098 PerlIO_flush(PerlIO_stderr());
1107 if (SvTRUE(left) != SvTRUE(right))
1119 RETURNOP(cLOGOP->op_other);
1128 RETURNOP(cLOGOP->op_other);
1134 register I32 cxix = dopoptosub(cxstack_ix);
1135 register PERL_CONTEXT *cx;
1147 if (GIMME != G_ARRAY)
1151 if (DBsub && cxix >= 0 &&
1152 cxstack[cxix].blk_sub.cv == GvCV(DBsub))
1156 cxix = dopoptosub(cxix - 1);
1158 cx = &cxstack[cxix];
1159 if (cxstack[cxix].cx_type == CXt_SUB) {
1160 dbcxix = dopoptosub(cxix - 1);
1161 /* We expect that cxstack[dbcxix] is CXt_SUB, anyway, the
1162 field below is defined for any cx. */
1163 if (DBsub && dbcxix >= 0 && cxstack[dbcxix].blk_sub.cv == GvCV(DBsub))
1164 cx = &cxstack[dbcxix];
1167 if (GIMME != G_ARRAY) {
1168 hv = cx->blk_oldcop->cop_stash;
1173 sv_setpv(TARG, HvNAME(hv));
1179 hv = cx->blk_oldcop->cop_stash;
1183 PUSHs(sv_2mortal(newSVpv(HvNAME(hv), 0)));
1184 PUSHs(sv_2mortal(newSVpv(SvPVX(GvSV(cx->blk_oldcop->cop_filegv)), 0)));
1185 PUSHs(sv_2mortal(newSViv((I32)cx->blk_oldcop->cop_line)));
1188 if (cx->cx_type == CXt_SUB) { /* So is cxstack[dbcxix]. */
1190 gv_efullname3(sv, CvGV(cxstack[cxix].blk_sub.cv), Nullch);
1191 PUSHs(sv_2mortal(sv));
1192 PUSHs(sv_2mortal(newSViv((I32)cx->blk_sub.hasargs)));
1195 PUSHs(sv_2mortal(newSVpv("(eval)",0)));
1196 PUSHs(sv_2mortal(newSViv(0)));
1198 gimme = (I32)cx->blk_gimme;
1199 if (gimme == G_VOID)
1202 PUSHs(sv_2mortal(newSViv(gimme & G_ARRAY)));
1203 if (cx->cx_type == CXt_EVAL) {
1204 if (cx->blk_eval.old_op_type == OP_ENTEREVAL) {
1205 PUSHs(cx->blk_eval.cur_text);
1208 else if (cx->blk_eval.old_name) { /* Try blocks have old_name == 0. */
1209 /* Require, put the name. */
1210 PUSHs(sv_2mortal(newSVpv(cx->blk_eval.old_name, 0)));
1214 else if (cx->cx_type == CXt_SUB &&
1215 cx->blk_sub.hasargs &&
1216 curcop->cop_stash == debstash)
1218 AV *ary = cx->blk_sub.argarray;
1219 int off = AvARRAY(ary) - AvALLOC(ary);
1223 dbargs = GvAV(gv_AVadd(tmpgv = gv_fetchpv("DB::args", TRUE,
1226 AvREAL_off(dbargs); /* XXX Should be REIFY */
1229 if (AvMAX(dbargs) < AvFILLp(ary) + off)
1230 av_extend(dbargs, AvFILLp(ary) + off);
1231 Copy(AvALLOC(ary), AvARRAY(dbargs), AvFILLp(ary) + 1 + off, SV*);
1232 AvFILLp(dbargs) = AvFILLp(ary) + off;
1238 sortcv(SV *a, SV *b)
1241 I32 oldsaveix = savestack_ix;
1242 I32 oldscopeix = scopestack_ix;
1246 stack_sp = stack_base;
1249 if (stack_sp != stack_base + 1)
1250 croak("Sort subroutine didn't return single value");
1251 if (!SvNIOKp(*stack_sp))
1252 croak("Sort subroutine didn't return a numeric value");
1253 result = SvIV(*stack_sp);
1254 while (scopestack_ix > oldscopeix) {
1257 leave_scope(oldsaveix);
1270 sv_reset(tmps, curcop->cop_stash);
1283 TAINT_NOT; /* Each statement is presumed innocent */
1284 stack_sp = stack_base + cxstack[cxstack_ix].blk_oldsp;
1287 if (op->op_private || SvIV(DBsingle) || SvIV(DBsignal) || SvIV(DBtrace))
1291 register PERL_CONTEXT *cx;
1292 I32 gimme = G_ARRAY;
1299 DIE("No DB::DB routine defined");
1301 if (CvDEPTH(cv) >= 1 && !(debug & (1<<30))) /* don't do recursive DB::DB call */
1313 push_return(op->op_next);
1314 PUSHBLOCK(cx, CXt_SUB, sp);
1317 (void)SvREFCNT_inc(cv);
1319 curpad = AvARRAY((AV*)*av_fetch(CvPADLIST(cv),1,FALSE));
1320 RETURNOP(CvSTART(cv));
1334 register PERL_CONTEXT *cx;
1335 I32 gimme = GIMME_V;
1342 if (op->op_flags & OPf_SPECIAL)
1343 svp = save_threadsv(op->op_targ); /* per-thread variable */
1345 #endif /* USE_THREADS */
1347 svp = &curpad[op->op_targ]; /* "my" variable */
1351 svp = &GvSV((GV*)POPs); /* symbol table variable */
1357 PUSHBLOCK(cx, CXt_LOOP, SP);
1358 PUSHLOOP(cx, svp, MARK);
1359 if (op->op_flags & OPf_STACKED)
1360 cx->blk_loop.iterary = (AV*)SvREFCNT_inc(POPs);
1362 cx->blk_loop.iterary = curstack;
1363 AvFILLp(curstack) = sp - stack_base;
1364 cx->blk_loop.iterix = MARK - stack_base;
1373 register PERL_CONTEXT *cx;
1374 I32 gimme = GIMME_V;
1380 PUSHBLOCK(cx, CXt_LOOP, SP);
1381 PUSHLOOP(cx, 0, SP);
1389 register PERL_CONTEXT *cx;
1390 struct block_loop cxloop;
1398 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1401 if (gimme == G_VOID)
1403 else if (gimme == G_SCALAR) {
1405 *++newsp = sv_mortalcopy(*SP);
1407 *++newsp = &sv_undef;
1411 *++newsp = sv_mortalcopy(*++mark);
1412 TAINT_NOT; /* Each item is independent */
1418 POPLOOP2(); /* Stack values are safe: release loop vars ... */
1419 curpm = newpm; /* ... and pop $1 et al */
1431 register PERL_CONTEXT *cx;
1432 struct block_sub cxsub;
1433 bool popsub2 = FALSE;
1439 if (curstack == sortstack) {
1440 if (cxstack_ix == sortcxix || dopoptosub(cxstack_ix) <= sortcxix) {
1441 if (cxstack_ix > sortcxix)
1443 AvARRAY(curstack)[1] = *SP;
1444 stack_sp = stack_base + 1;
1449 cxix = dopoptosub(cxstack_ix);
1451 DIE("Can't return outside a subroutine");
1452 if (cxix < cxstack_ix)
1456 switch (cx->cx_type) {
1458 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1463 if (optype == OP_REQUIRE &&
1464 (MARK == SP || (gimme == G_SCALAR && !SvTRUE(*SP))) )
1466 /* Unassume the success we assumed earlier. */
1467 char *name = cx->blk_eval.old_name;
1468 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
1469 DIE("%s did not return a true value", name);
1473 DIE("panic: return");
1477 if (gimme == G_SCALAR) {
1479 *++newsp = (popsub2 && SvTEMP(*SP))
1480 ? *SP : sv_mortalcopy(*SP);
1482 *++newsp = &sv_undef;
1484 else if (gimme == G_ARRAY) {
1485 while (++MARK <= SP) {
1486 *++newsp = (popsub2 && SvTEMP(*MARK))
1487 ? *MARK : sv_mortalcopy(*MARK);
1488 TAINT_NOT; /* Each item is independent */
1493 /* Stack values are safe: */
1495 POPSUB2(); /* release CV and @_ ... */
1497 curpm = newpm; /* ... and pop $1 et al */
1500 return pop_return();
1507 register PERL_CONTEXT *cx;
1508 struct block_loop cxloop;
1509 struct block_sub cxsub;
1516 SV **mark = stack_base + cxstack[cxstack_ix].blk_oldsp;
1518 if (op->op_flags & OPf_SPECIAL) {
1519 cxix = dopoptoloop(cxstack_ix);
1521 DIE("Can't \"last\" outside a block");
1524 cxix = dopoptolabel(cPVOP->op_pv);
1526 DIE("Label not found for \"last %s\"", cPVOP->op_pv);
1528 if (cxix < cxstack_ix)
1532 switch (cx->cx_type) {
1534 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1536 nextop = cxloop.last_op->op_next;
1539 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1541 nextop = pop_return();
1545 nextop = pop_return();
1552 if (gimme == G_SCALAR) {
1554 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*SP))
1555 ? *SP : sv_mortalcopy(*SP);
1557 *++newsp = &sv_undef;
1559 else if (gimme == G_ARRAY) {
1560 while (++MARK <= SP) {
1561 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*MARK))
1562 ? *MARK : sv_mortalcopy(*MARK);
1563 TAINT_NOT; /* Each item is independent */
1569 /* Stack values are safe: */
1572 POPLOOP2(); /* release loop vars ... */
1576 POPSUB2(); /* release CV and @_ ... */
1579 curpm = newpm; /* ... and pop $1 et al */
1588 register PERL_CONTEXT *cx;
1591 if (op->op_flags & OPf_SPECIAL) {
1592 cxix = dopoptoloop(cxstack_ix);
1594 DIE("Can't \"next\" outside a block");
1597 cxix = dopoptolabel(cPVOP->op_pv);
1599 DIE("Label not found for \"next %s\"", cPVOP->op_pv);
1601 if (cxix < cxstack_ix)
1605 oldsave = scopestack[scopestack_ix - 1];
1606 LEAVE_SCOPE(oldsave);
1607 return cx->blk_loop.next_op;
1613 register PERL_CONTEXT *cx;
1616 if (op->op_flags & OPf_SPECIAL) {
1617 cxix = dopoptoloop(cxstack_ix);
1619 DIE("Can't \"redo\" outside a block");
1622 cxix = dopoptolabel(cPVOP->op_pv);
1624 DIE("Label not found for \"redo %s\"", cPVOP->op_pv);
1626 if (cxix < cxstack_ix)
1630 oldsave = scopestack[scopestack_ix - 1];
1631 LEAVE_SCOPE(oldsave);
1632 return cx->blk_loop.redo_op;
1636 dofindlabel(OP *o, char *label, OP **opstack, OP **oplimit)
1640 static char too_deep[] = "Target of goto is too deeply nested";
1644 if (o->op_type == OP_LEAVE ||
1645 o->op_type == OP_SCOPE ||
1646 o->op_type == OP_LEAVELOOP ||
1647 o->op_type == OP_LEAVETRY)
1649 *ops++ = cUNOPo->op_first;
1654 if (o->op_flags & OPf_KIDS) {
1655 /* First try all the kids at this level, since that's likeliest. */
1656 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1657 if ((kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) &&
1658 kCOP->cop_label && strEQ(kCOP->cop_label, label))
1661 for (kid = cUNOPo->op_first; kid; kid = kid->op_sibling) {
1662 if (kid == lastgotoprobe)
1664 if ((kid->op_type == OP_NEXTSTATE || kid->op_type == OP_DBSTATE) &&
1666 (ops[-1]->op_type != OP_NEXTSTATE &&
1667 ops[-1]->op_type != OP_DBSTATE)))
1669 if (o = dofindlabel(kid, label, ops, oplimit))
1679 return pp_goto(ARGS);
1688 register PERL_CONTEXT *cx;
1689 #define GOTO_DEPTH 64
1690 OP *enterops[GOTO_DEPTH];
1692 int do_dump = (op->op_type == OP_DUMP);
1695 if (op->op_flags & OPf_STACKED) {
1698 /* This egregious kludge implements goto &subroutine */
1699 if (SvROK(sv) && SvTYPE(SvRV(sv)) == SVt_PVCV) {
1701 register PERL_CONTEXT *cx;
1702 CV* cv = (CV*)SvRV(sv);
1707 if (!CvROOT(cv) && !CvXSUB(cv)) {
1709 SV *tmpstr = sv_newmortal();
1710 gv_efullname3(tmpstr, CvGV(cv), Nullch);
1711 DIE("Goto undefined subroutine &%s",SvPVX(tmpstr));
1713 DIE("Goto undefined subroutine");
1716 /* First do some returnish stuff. */
1717 cxix = dopoptosub(cxstack_ix);
1719 DIE("Can't goto subroutine outside a subroutine");
1720 if (cxix < cxstack_ix)
1724 if (cx->blk_sub.hasargs) { /* put @_ back onto stack */
1725 AV* av = cx->blk_sub.argarray;
1727 items = AvFILLp(av) + 1;
1729 EXTEND(stack_sp, items); /* @_ could have been extended. */
1730 Copy(AvARRAY(av), stack_sp, items, SV*);
1733 SvREFCNT_dec(GvAV(defgv));
1734 GvAV(defgv) = cx->blk_sub.savearray;
1735 #endif /* USE_THREADS */
1739 if (!(CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth))
1740 SvREFCNT_dec(cx->blk_sub.cv);
1741 oldsave = scopestack[scopestack_ix - 1];
1742 LEAVE_SCOPE(oldsave);
1744 /* Now do some callish stuff. */
1747 if (CvOLDSTYLE(cv)) {
1748 I32 (*fp3)_((int,int,int));
1753 fp3 = (I32(*)_((int,int,int)))CvXSUB(cv);
1754 items = (*fp3)(CvXSUBANY(cv).any_i32,
1755 mark - stack_base + 1,
1757 sp = stack_base + items;
1760 stack_sp--; /* There is no cv arg. */
1761 (void)(*CvXSUB(cv))(THIS_ cv);
1764 return pop_return();
1767 AV* padlist = CvPADLIST(cv);
1768 SV** svp = AvARRAY(padlist);
1769 cx->blk_sub.cv = cv;
1770 cx->blk_sub.olddepth = CvDEPTH(cv);
1772 if (CvDEPTH(cv) < 2)
1773 (void)SvREFCNT_inc(cv);
1774 else { /* save temporaries on recursion? */
1775 if (CvDEPTH(cv) == 100 && dowarn)
1776 sub_crush_depth(cv);
1777 if (CvDEPTH(cv) > AvFILLp(padlist)) {
1778 AV *newpad = newAV();
1779 SV **oldpad = AvARRAY(svp[CvDEPTH(cv)-1]);
1780 I32 ix = AvFILLp((AV*)svp[1]);
1781 svp = AvARRAY(svp[0]);
1782 for ( ;ix > 0; ix--) {
1783 if (svp[ix] != &sv_undef) {
1784 char *name = SvPVX(svp[ix]);
1785 if ((SvFLAGS(svp[ix]) & SVf_FAKE)
1788 /* outer lexical or anon code */
1789 av_store(newpad, ix,
1790 SvREFCNT_inc(oldpad[ix]) );
1792 else { /* our own lexical */
1794 av_store(newpad, ix, sv = (SV*)newAV());
1795 else if (*name == '%')
1796 av_store(newpad, ix, sv = (SV*)newHV());
1798 av_store(newpad, ix, sv = NEWSV(0,0));
1803 av_store(newpad, ix, sv = NEWSV(0,0));
1807 if (cx->blk_sub.hasargs) {
1810 av_store(newpad, 0, (SV*)av);
1811 AvFLAGS(av) = AVf_REIFY;
1813 av_store(padlist, CvDEPTH(cv), (SV*)newpad);
1814 AvFILLp(padlist) = CvDEPTH(cv);
1815 svp = AvARRAY(padlist);
1819 if (!cx->blk_sub.hasargs) {
1820 AV* av = (AV*)curpad[0];
1822 items = AvFILLp(av) + 1;
1824 /* Mark is at the end of the stack. */
1826 Copy(AvARRAY(av), sp + 1, items, SV*);
1831 #endif /* USE_THREADS */
1833 curpad = AvARRAY((AV*)svp[CvDEPTH(cv)]);
1835 if (cx->blk_sub.hasargs)
1836 #endif /* USE_THREADS */
1838 AV* av = (AV*)curpad[0];
1842 cx->blk_sub.savearray = GvAV(defgv);
1843 GvAV(defgv) = (AV*)SvREFCNT_inc(av);
1844 #endif /* USE_THREADS */
1845 cx->blk_sub.argarray = av;
1848 if (items >= AvMAX(av) + 1) {
1850 if (AvARRAY(av) != ary) {
1851 AvMAX(av) += AvARRAY(av) - AvALLOC(av);
1852 SvPVX(av) = (char*)ary;
1854 if (items >= AvMAX(av) + 1) {
1855 AvMAX(av) = items - 1;
1856 Renew(ary,items+1,SV*);
1858 SvPVX(av) = (char*)ary;
1861 Copy(mark,AvARRAY(av),items,SV*);
1862 AvFILLp(av) = items - 1;
1870 if (PERLDB_SUB && curstash != debstash) {
1872 * We do not care about using sv to call CV;
1873 * it's for informational purposes only.
1875 SV *sv = GvSV(DBsub);
1877 gv_efullname3(sv, CvGV(cv), Nullch);
1879 RETURNOP(CvSTART(cv));
1883 label = SvPV(sv,na);
1885 else if (op->op_flags & OPf_SPECIAL) {
1887 DIE("goto must have label");
1890 label = cPVOP->op_pv;
1892 if (label && *label) {
1899 for (ix = cxstack_ix; ix >= 0; ix--) {
1901 switch (cx->cx_type) {
1903 gotoprobe = eval_root; /* XXX not good for nested eval */
1906 gotoprobe = cx->blk_oldcop->op_sibling;
1912 gotoprobe = cx->blk_oldcop->op_sibling;
1914 gotoprobe = main_root;
1917 if (CvDEPTH(cx->blk_sub.cv)) {
1918 gotoprobe = CvROOT(cx->blk_sub.cv);
1923 DIE("Can't \"goto\" outside a block");
1927 gotoprobe = main_root;
1930 retop = dofindlabel(gotoprobe, label,
1931 enterops, enterops + GOTO_DEPTH);
1934 lastgotoprobe = gotoprobe;
1937 DIE("Can't find label %s", label);
1939 /* pop unwanted frames */
1941 if (ix < cxstack_ix) {
1948 oldsave = scopestack[scopestack_ix];
1949 LEAVE_SCOPE(oldsave);
1952 /* push wanted frames */
1954 if (*enterops && enterops[1]) {
1956 for (ix = 1; enterops[ix]; ix++) {
1958 /* Eventually we may want to stack the needed arguments
1959 * for each op. For now, we punt on the hard ones. */
1960 if (op->op_type == OP_ENTERITER)
1961 DIE("Can't \"goto\" into the middle of a foreach loop",
1963 (CALLOP->op_ppaddr)(ARGS);
1971 if (!retop) retop = main_start;
1978 restartop = 0; /* hmm, must be GNU unexec().. */
1982 if (curstack == signalstack) {
2000 if (anum == 1 && VMSISH_EXIT)
2013 double value = SvNVx(GvSV(cCOP->cop_gv));
2014 register I32 match = I_32(value);
2017 if (((double)match) > value)
2018 --match; /* was fractional--truncate other way */
2020 match -= cCOP->uop.scop.scop_offset;
2023 else if (match > cCOP->uop.scop.scop_max)
2024 match = cCOP->uop.scop.scop_max;
2025 op = cCOP->uop.scop.scop_next[match];
2035 op = op->op_next; /* can't assume anything */
2037 match = *(SvPVx(GvSV(cCOP->cop_gv), na)) & 255;
2038 match -= cCOP->uop.scop.scop_offset;
2041 else if (match > cCOP->uop.scop.scop_max)
2042 match = cCOP->uop.scop.scop_max;
2043 op = cCOP->uop.scop.scop_next[match];
2052 save_lines(AV *array, SV *sv)
2054 register char *s = SvPVX(sv);
2055 register char *send = SvPVX(sv) + SvCUR(sv);
2057 register I32 line = 1;
2059 while (s && s < send) {
2060 SV *tmpstr = NEWSV(85,0);
2062 sv_upgrade(tmpstr, SVt_PVMG);
2063 t = strchr(s, '\n');
2069 sv_setpvn(tmpstr, s, t - s);
2070 av_store(array, line++, tmpstr);
2085 assert(CATCH_GET == TRUE);
2086 DEBUG_l(deb("Setting up local jumplevel %p, was %p\n", &cur_env, top_env));
2090 default: /* topmost level handles it */
2097 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2113 sv_compile_2op(SV *sv, OP** startop, char *code, AV** avp)
2114 /* sv Text to convert to OP tree. */
2115 /* startop op_free() this to undo. */
2116 /* code Short string id of the caller. */
2118 dSP; /* Make POPBLOCK work. */
2121 I32 gimme = 0; /* SUSPECT - INITIALZE TO WHAT? NI-S */
2125 char tmpbuf[TYPE_DIGITS(long) + 12 + 10];
2131 /* switch to eval mode */
2133 SAVESPTR(compiling.cop_filegv);
2134 SAVEI16(compiling.cop_line);
2135 sprintf(tmpbuf, "_<(%.10s_eval %lu)", code, (unsigned long)++evalseq);
2136 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2137 compiling.cop_line = 1;
2138 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2139 deleting the eval's FILEGV from the stash before gv_check() runs
2140 (i.e. before run-time proper). To work around the coredump that
2141 ensues, we always turn GvMULTI_on for any globals that were
2142 introduced within evals. See force_ident(). GSAR 96-10-12 */
2143 safestr = savepv(tmpbuf);
2144 SAVEDELETE(defstash, safestr, strlen(safestr));
2150 op->op_type = 0; /* Avoid uninit warning. */
2151 op->op_flags = 0; /* Avoid uninit warning. */
2152 PUSHBLOCK(cx, CXt_EVAL, SP);
2153 PUSHEVAL(cx, 0, compiling.cop_filegv);
2154 rop = doeval(G_SCALAR, startop);
2158 (*startop)->op_type = OP_NULL;
2159 (*startop)->op_ppaddr = ppaddr[OP_NULL];
2161 *avp = (AV*)SvREFCNT_inc(comppad);
2166 /* With USE_THREADS, eval_owner must be held on entry to doeval */
2168 doeval(int gimme, OP** startop)
2181 /* set up a scratch pad */
2186 SAVESPTR(comppad_name);
2187 SAVEI32(comppad_name_fill);
2188 SAVEI32(min_intro_pending);
2189 SAVEI32(max_intro_pending);
2192 for (i = cxstack_ix - 1; i >= 0; i--) {
2193 PERL_CONTEXT *cx = &cxstack[i];
2194 if (cx->cx_type == CXt_EVAL)
2196 else if (cx->cx_type == CXt_SUB) {
2197 caller = cx->blk_sub.cv;
2203 compcv = (CV*)NEWSV(1104,0);
2204 sv_upgrade((SV *)compcv, SVt_PVCV);
2205 CvUNIQUE_on(compcv);
2207 CvOWNER(compcv) = 0;
2208 New(666, CvMUTEXP(compcv), 1, perl_mutex);
2209 MUTEX_INIT(CvMUTEXP(compcv));
2210 #endif /* USE_THREADS */
2213 av_push(comppad, Nullsv);
2214 curpad = AvARRAY(comppad);
2215 comppad_name = newAV();
2216 comppad_name_fill = 0;
2217 min_intro_pending = 0;
2220 av_store(comppad_name, 0, newSVpv("@_", 2));
2221 curpad[0] = (SV*)newAV();
2222 SvPADMY_on(curpad[0]); /* XXX Needed? */
2223 #endif /* USE_THREADS */
2225 comppadlist = newAV();
2226 AvREAL_off(comppadlist);
2227 av_store(comppadlist, 0, (SV*)comppad_name);
2228 av_store(comppadlist, 1, (SV*)comppad);
2229 CvPADLIST(compcv) = comppadlist;
2231 if (!saveop || saveop->op_type != OP_REQUIRE)
2232 CvOUTSIDE(compcv) = (CV*)SvREFCNT_inc(caller);
2236 /* make sure we compile in the right package */
2238 newstash = curcop->cop_stash;
2239 if (curstash != newstash) {
2241 curstash = newstash;
2245 SAVEFREESV(beginav);
2247 /* try to compile it */
2251 curcop = &compiling;
2252 curcop->cop_arybase = 0;
2254 rs = newSVpv("\n", 1);
2255 if (saveop && saveop->op_flags & OPf_SPECIAL)
2259 if (yyparse() || error_count || !eval_root) {
2263 I32 optype = 0; /* Might be reset by POPEVAL. */
2270 SP = stack_base + POPMARK; /* pop original mark */
2278 if (optype == OP_REQUIRE) {
2279 char* msg = SvPVx(ERRSV, na);
2280 DIE("%s", *msg ? msg : "Compilation failed in require");
2281 } else if (startop) {
2282 char* msg = SvPVx(ERRSV, na);
2286 croak("%sCompilation failed in regexp", (*msg ? msg : "Unknown error\n"));
2289 rs = SvREFCNT_inc(nrs);
2291 MUTEX_LOCK(&eval_mutex);
2293 COND_SIGNAL(&eval_cond);
2294 MUTEX_UNLOCK(&eval_mutex);
2295 #endif /* USE_THREADS */
2299 rs = SvREFCNT_inc(nrs);
2300 compiling.cop_line = 0;
2302 *startop = eval_root;
2303 SvREFCNT_dec(CvOUTSIDE(compcv));
2304 CvOUTSIDE(compcv) = Nullcv;
2306 SAVEFREEOP(eval_root);
2308 scalarvoid(eval_root);
2309 else if (gimme & G_ARRAY)
2314 DEBUG_x(dump_eval());
2316 /* Register with debugger: */
2317 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
2318 CV *cv = perl_get_cv("DB::postponed", FALSE);
2322 XPUSHs((SV*)compiling.cop_filegv);
2324 perl_call_sv((SV*)cv, G_DISCARD);
2328 /* compiled okay, so do it */
2330 CvDEPTH(compcv) = 1;
2331 SP = stack_base + POPMARK; /* pop original mark */
2332 op = saveop; /* The caller may need it. */
2334 MUTEX_LOCK(&eval_mutex);
2336 COND_SIGNAL(&eval_cond);
2337 MUTEX_UNLOCK(&eval_mutex);
2338 #endif /* USE_THREADS */
2340 RETURNOP(eval_start);
2346 register PERL_CONTEXT *cx;
2350 SV *namesv = Nullsv;
2352 I32 gimme = G_SCALAR;
2353 PerlIO *tryrsfp = 0;
2356 if (SvNIOKp(sv) && !SvPOKp(sv)) {
2357 SET_NUMERIC_STANDARD();
2358 if (atof(patchlevel) + 0.00000999 < SvNV(sv))
2359 DIE("Perl %s required--this is only version %s, stopped",
2360 SvPV(sv,na),patchlevel);
2363 name = SvPV(sv, na);
2365 DIE("Null filename used");
2366 TAINT_PROPER("require");
2367 if (op->op_type == OP_REQUIRE &&
2368 (svp = hv_fetch(GvHVn(incgv), name, SvCUR(sv), 0)) &&
2372 /* prepare to compile file */
2377 (name[1] == '.' && name[2] == '/')))
2379 || (name[0] && name[1] == ':')
2382 || (name[0] == '\\' && name[1] == '\\') /* UNC path */
2385 || (strchr(name,':') || ((*name == '[' || *name == '<') &&
2386 (isALNUM(name[1]) || strchr("$-_]>",name[1]))))
2391 tryrsfp = PerlIO_open(name,PERL_SCRIPT_MODE);
2394 AV *ar = GvAVn(incgv);
2398 if ((unixname = tounixspec(name, Nullch)) != Nullch)
2401 namesv = NEWSV(806, 0);
2402 for (i = 0; i <= AvFILL(ar); i++) {
2403 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2406 if ((unixdir = tounixpath(dir, Nullch)) == Nullch)
2408 sv_setpv(namesv, unixdir);
2409 sv_catpv(namesv, unixname);
2411 sv_setpvf(namesv, "%s/%s", dir, name);
2413 tryname = SvPVX(namesv);
2414 tryrsfp = PerlIO_open(tryname, PERL_SCRIPT_MODE);
2416 if (tryname[0] == '.' && tryname[1] == '/')
2423 SAVESPTR(compiling.cop_filegv);
2424 compiling.cop_filegv = gv_fetchfile(tryrsfp ? tryname : name);
2425 SvREFCNT_dec(namesv);
2427 if (op->op_type == OP_REQUIRE) {
2428 SV *msg = sv_2mortal(newSVpvf("Can't locate %s in @INC", name));
2429 SV *dirmsgsv = NEWSV(0, 0);
2430 AV *ar = GvAVn(incgv);
2432 if (instr(SvPVX(msg), ".h "))
2433 sv_catpv(msg, " (change .h to .ph maybe?)");
2434 if (instr(SvPVX(msg), ".ph "))
2435 sv_catpv(msg, " (did you run h2ph?)");
2436 sv_catpv(msg, " (@INC contains:");
2437 for (i = 0; i <= AvFILL(ar); i++) {
2438 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2439 sv_setpvf(dirmsgsv, " %s", dir);
2440 sv_catsv(msg, dirmsgsv);
2442 sv_catpvn(msg, ")", 1);
2443 SvREFCNT_dec(dirmsgsv);
2450 /* Assume success here to prevent recursive requirement. */
2451 (void)hv_store(GvHVn(incgv), name, strlen(name),
2452 newSVsv(GvSV(compiling.cop_filegv)), 0 );
2456 lex_start(sv_2mortal(newSVpv("",0)));
2458 save_aptr(&rsfp_filters);
2459 rsfp_filters = NULL;
2463 name = savepv(name);
2468 /* switch to eval mode */
2470 push_return(op->op_next);
2471 PUSHBLOCK(cx, CXt_EVAL, SP);
2472 PUSHEVAL(cx, name, compiling.cop_filegv);
2474 compiling.cop_line = 0;
2478 MUTEX_LOCK(&eval_mutex);
2479 if (eval_owner && eval_owner != thr)
2481 COND_WAIT(&eval_cond, &eval_mutex);
2483 MUTEX_UNLOCK(&eval_mutex);
2484 #endif /* USE_THREADS */
2485 return DOCATCH(doeval(G_SCALAR, NULL));
2490 return pp_require(ARGS);
2496 register PERL_CONTEXT *cx;
2498 I32 gimme = GIMME_V, was = sub_generation;
2499 char tmpbuf[TYPE_DIGITS(long) + 12];
2504 if (!SvPV(sv,len) || !len)
2506 TAINT_PROPER("eval");
2512 /* switch to eval mode */
2514 SAVESPTR(compiling.cop_filegv);
2515 sprintf(tmpbuf, "_<(eval %lu)", (unsigned long)++evalseq);
2516 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2517 compiling.cop_line = 1;
2518 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2519 deleting the eval's FILEGV from the stash before gv_check() runs
2520 (i.e. before run-time proper). To work around the coredump that
2521 ensues, we always turn GvMULTI_on for any globals that were
2522 introduced within evals. See force_ident(). GSAR 96-10-12 */
2523 safestr = savepv(tmpbuf);
2524 SAVEDELETE(defstash, safestr, strlen(safestr));
2526 hints = op->op_targ;
2528 push_return(op->op_next);
2529 PUSHBLOCK(cx, CXt_EVAL, SP);
2530 PUSHEVAL(cx, 0, compiling.cop_filegv);
2532 /* prepare to compile string */
2534 if (PERLDB_LINE && curstash != debstash)
2535 save_lines(GvAV(compiling.cop_filegv), linestr);
2538 MUTEX_LOCK(&eval_mutex);
2539 if (eval_owner && eval_owner != thr)
2541 COND_WAIT(&eval_cond, &eval_mutex);
2543 MUTEX_UNLOCK(&eval_mutex);
2544 #endif /* USE_THREADS */
2545 ret = doeval(gimme, NULL);
2546 if (PERLDB_INTER && was != sub_generation /* Some subs defined here. */
2547 && ret != op->op_next) { /* Successive compilation. */
2548 strcpy(safestr, "_<(eval )"); /* Anything fake and short. */
2550 return DOCATCH(ret);
2560 register PERL_CONTEXT *cx;
2562 U8 save_flags = op -> op_flags;
2567 retop = pop_return();
2570 if (gimme == G_VOID)
2572 else if (gimme == G_SCALAR) {
2575 if (SvFLAGS(TOPs) & SVs_TEMP)
2578 *MARK = sv_mortalcopy(TOPs);
2586 /* in case LEAVE wipes old return values */
2587 for (mark = newsp + 1; mark <= SP; mark++) {
2588 if (!(SvFLAGS(*mark) & SVs_TEMP)) {
2589 *mark = sv_mortalcopy(*mark);
2590 TAINT_NOT; /* Each item is independent */
2594 curpm = newpm; /* Don't pop $1 et al till now */
2597 * Closures mentioned at top level of eval cannot be referenced
2598 * again, and their presence indirectly causes a memory leak.
2599 * (Note that the fact that compcv and friends are still set here
2600 * is, AFAIK, an accident.) --Chip
2602 if (AvFILLp(comppad_name) >= 0) {
2603 SV **svp = AvARRAY(comppad_name);
2605 for (ix = AvFILLp(comppad_name); ix >= 0; ix--) {
2607 if (sv && sv != &sv_undef && *SvPVX(sv) == '&') {
2609 svp[ix] = &sv_undef;
2613 SvREFCNT_dec(CvOUTSIDE(sv));
2614 CvOUTSIDE(sv) = Nullcv;
2627 assert(CvDEPTH(compcv) == 1);
2629 CvDEPTH(compcv) = 0;
2631 if (optype == OP_REQUIRE &&
2632 !(gimme == G_SCALAR ? SvTRUE(*sp) : sp > newsp))
2634 /* Unassume the success we assumed earlier. */
2635 char *name = cx->blk_eval.old_name;
2636 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
2637 retop = die("%s did not return a true value", name);
2643 if (!(save_flags & OPf_SPECIAL))
2652 register PERL_CONTEXT *cx;
2653 I32 gimme = GIMME_V;
2658 push_return(cLOGOP->op_other->op_next);
2659 PUSHBLOCK(cx, CXt_EVAL, SP);
2661 eval_root = op; /* Only needed so that goto works right. */
2666 return DOCATCH(op->op_next);
2676 register PERL_CONTEXT *cx;
2684 if (gimme == G_VOID)
2686 else if (gimme == G_SCALAR) {
2689 if (SvFLAGS(TOPs) & (SVs_PADTMP|SVs_TEMP))
2692 *MARK = sv_mortalcopy(TOPs);
2701 /* in case LEAVE wipes old return values */
2702 for (mark = newsp + 1; mark <= SP; mark++) {
2703 if (!(SvFLAGS(*mark) & (SVs_PADTMP|SVs_TEMP))) {
2704 *mark = sv_mortalcopy(*mark);
2705 TAINT_NOT; /* Each item is independent */
2709 curpm = newpm; /* Don't pop $1 et al till now */
2720 register char *s = SvPV_force(sv, len);
2721 register char *send = s + len;
2722 register char *base;
2723 register I32 skipspaces = 0;
2726 bool postspace = FALSE;
2734 croak("Null picture in formline");
2736 New(804, fops, (send - s)*3+10, U16); /* Almost certainly too long... */
2741 *fpc++ = FF_LINEMARK;
2742 noblank = repeat = FALSE;
2760 case ' ': case '\t':
2771 *fpc++ = FF_LITERAL;
2779 *fpc++ = skipspaces;
2783 *fpc++ = FF_NEWLINE;
2787 arg = fpc - linepc + 1;
2794 *fpc++ = FF_LINEMARK;
2795 noblank = repeat = FALSE;
2804 ischop = s[-1] == '^';
2810 arg = (s - base) - 1;
2812 *fpc++ = FF_LITERAL;
2821 *fpc++ = FF_LINEGLOB;
2823 else if (*s == '#' || (*s == '.' && s[1] == '#')) {
2824 arg = ischop ? 512 : 0;
2834 arg |= 256 + (s - f);
2836 *fpc++ = s - base; /* fieldsize for FETCH */
2837 *fpc++ = FF_DECIMAL;
2842 bool ismore = FALSE;
2845 while (*++s == '>') ;
2846 prespace = FF_SPACE;
2848 else if (*s == '|') {
2849 while (*++s == '|') ;
2850 prespace = FF_HALFSPACE;
2855 while (*++s == '<') ;
2858 if (*s == '.' && s[1] == '.' && s[2] == '.') {
2862 *fpc++ = s - base; /* fieldsize for FETCH */
2864 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
2882 { /* need to jump to the next word */
2884 z = WORD_ALIGN - SvCUR(sv) % WORD_ALIGN;
2885 SvGROW(sv, SvCUR(sv) + z + arg * sizeof(U16) + 4);
2886 s = SvPVX(sv) + SvCUR(sv) + z;
2888 Copy(fops, s, arg, U16);
2890 sv_magic(sv, Nullsv, 'f', Nullch, 0);
2895 * The rest of this file was derived from source code contributed
2898 * NOTE: this code was derived from Tom Horsley's qsort replacement
2899 * and should not be confused with the original code.
2902 /* Copyright (C) Tom Horsley, 1997. All rights reserved.
2904 Permission granted to distribute under the same terms as perl which are
2907 This program is free software; you can redistribute it and/or modify
2908 it under the terms of either:
2910 a) the GNU General Public License as published by the Free
2911 Software Foundation; either version 1, or (at your option) any
2914 b) the "Artistic License" which comes with this Kit.
2916 Details on the perl license can be found in the perl source code which
2917 may be located via the www.perl.com web page.
2919 This is the most wonderfulest possible qsort I can come up with (and
2920 still be mostly portable) My (limited) tests indicate it consistently
2921 does about 20% fewer calls to compare than does the qsort in the Visual
2922 C++ library, other vendors may vary.
2924 Some of the ideas in here can be found in "Algorithms" by Sedgewick,
2925 others I invented myself (or more likely re-invented since they seemed
2926 pretty obvious once I watched the algorithm operate for a while).
2928 Most of this code was written while watching the Marlins sweep the Giants
2929 in the 1997 National League Playoffs - no Braves fans allowed to use this
2930 code (just kidding :-).
2932 I realize that if I wanted to be true to the perl tradition, the only
2933 comment in this file would be something like:
2935 ...they shuffled back towards the rear of the line. 'No, not at the
2936 rear!' the slave-driver shouted. 'Three files up. And stay there...
2938 However, I really needed to violate that tradition just so I could keep
2939 track of what happens myself, not to mention some poor fool trying to
2940 understand this years from now :-).
2943 /* ********************************************************** Configuration */
2945 #ifndef QSORT_ORDER_GUESS
2946 #define QSORT_ORDER_GUESS 2 /* Select doubling version of the netBSD trick */
2949 /* QSORT_MAX_STACK is the largest number of partitions that can be stacked up for
2950 future processing - a good max upper bound is log base 2 of memory size
2951 (32 on 32 bit machines, 64 on 64 bit machines, etc). In reality can
2952 safely be smaller than that since the program is taking up some space and
2953 most operating systems only let you grab some subset of contiguous
2954 memory (not to mention that you are normally sorting data larger than
2955 1 byte element size :-).
2957 #ifndef QSORT_MAX_STACK
2958 #define QSORT_MAX_STACK 32
2961 /* QSORT_BREAK_EVEN is the size of the largest partition we should insertion sort.
2962 Anything bigger and we use qsort. If you make this too small, the qsort
2963 will probably break (or become less efficient), because it doesn't expect
2964 the middle element of a partition to be the same as the right or left -
2965 you have been warned).
2967 #ifndef QSORT_BREAK_EVEN
2968 #define QSORT_BREAK_EVEN 6
2971 /* ************************************************************* Data Types */
2973 /* hold left and right index values of a partition waiting to be sorted (the
2974 partition includes both left and right - right is NOT one past the end or
2975 anything like that).
2977 struct partition_stack_entry {
2980 #ifdef QSORT_ORDER_GUESS
2981 int qsort_break_even;
2985 /* ******************************************************* Shorthand Macros */
2987 /* Note that these macros will be used from inside the qsort function where
2988 we happen to know that the variable 'elt_size' contains the size of an
2989 array element and the variable 'temp' points to enough space to hold a
2990 temp element and the variable 'array' points to the array being sorted
2991 and 'compare' is the pointer to the compare routine.
2993 Also note that there are very many highly architecture specific ways
2994 these might be sped up, but this is simply the most generally portable
2995 code I could think of.
2998 /* Return < 0 == 0 or > 0 as the value of elt1 is < elt2, == elt2, > elt2
3001 #define qsort_cmp(elt1, elt2) \
3002 ((this->*compare)(array[elt1], array[elt2]))
3004 #define qsort_cmp(elt1, elt2) \
3005 ((*compare)(array[elt1], array[elt2]))
3008 #ifdef QSORT_ORDER_GUESS
3009 #define QSORT_NOTICE_SWAP swapped++;
3011 #define QSORT_NOTICE_SWAP
3014 /* swaps contents of array elements elt1, elt2.
3016 #define qsort_swap(elt1, elt2) \
3019 temp = array[elt1]; \
3020 array[elt1] = array[elt2]; \
3021 array[elt2] = temp; \
3024 /* rotate contents of elt1, elt2, elt3 such that elt1 gets elt2, elt2 gets
3025 elt3 and elt3 gets elt1.
3027 #define qsort_rotate(elt1, elt2, elt3) \
3030 temp = array[elt1]; \
3031 array[elt1] = array[elt2]; \
3032 array[elt2] = array[elt3]; \
3033 array[elt3] = temp; \
3036 /* ************************************************************ Debug stuff */
3043 return; /* good place to set a breakpoint */
3046 #define qsort_assert(t) (void)( (t) || (break_here(), 0) )
3049 doqsort_all_asserts(
3053 int (*compare)(const void * elt1, const void * elt2),
3054 int pc_left, int pc_right, int u_left, int u_right)
3058 qsort_assert(pc_left <= pc_right);
3059 qsort_assert(u_right < pc_left);
3060 qsort_assert(pc_right < u_left);
3061 for (i = u_right + 1; i < pc_left; ++i) {
3062 qsort_assert(qsort_cmp(i, pc_left) < 0);
3064 for (i = pc_left; i < pc_right; ++i) {
3065 qsort_assert(qsort_cmp(i, pc_right) == 0);
3067 for (i = pc_right + 1; i < u_left; ++i) {
3068 qsort_assert(qsort_cmp(pc_right, i) < 0);
3072 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) \
3073 doqsort_all_asserts(array, num_elts, elt_size, compare, \
3074 PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT)
3078 #define qsort_assert(t) ((void)0)
3080 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) ((void)0)
3084 /* ****************************************************************** qsort */
3088 qsortsv(SV ** array, size_t num_elts, SVCOMPARE compare)
3093 I32 (*compare)(SV *a, SV *b))
3098 struct partition_stack_entry partition_stack[QSORT_MAX_STACK];
3099 int next_stack_entry = 0;
3103 #ifdef QSORT_ORDER_GUESS
3104 int qsort_break_even;
3108 /* Make sure we actually have work to do.
3110 if (num_elts <= 1) {
3114 /* Setup the initial partition definition and fall into the sorting loop
3117 part_right = (int)(num_elts - 1);
3118 #ifdef QSORT_ORDER_GUESS
3119 qsort_break_even = QSORT_BREAK_EVEN;
3121 #define qsort_break_even QSORT_BREAK_EVEN
3124 if ((part_right - part_left) >= qsort_break_even) {
3125 /* OK, this is gonna get hairy, so lets try to document all the
3126 concepts and abbreviations and variables and what they keep
3129 pc: pivot chunk - the set of array elements we accumulate in the
3130 middle of the partition, all equal in value to the original
3131 pivot element selected. The pc is defined by:
3133 pc_left - the leftmost array index of the pc
3134 pc_right - the rightmost array index of the pc
3136 we start with pc_left == pc_right and only one element
3137 in the pivot chunk (but it can grow during the scan).
3139 u: uncompared elements - the set of elements in the partition
3140 we have not yet compared to the pivot value. There are two
3141 uncompared sets during the scan - one to the left of the pc
3142 and one to the right.
3144 u_right - the rightmost index of the left side's uncompared set
3145 u_left - the leftmost index of the right side's uncompared set
3147 The leftmost index of the left sides's uncompared set
3148 doesn't need its own variable because it is always defined
3149 by the leftmost edge of the whole partition (part_left). The
3150 same goes for the rightmost edge of the right partition
3153 We know there are no uncompared elements on the left once we
3154 get u_right < part_left and no uncompared elements on the
3155 right once u_left > part_right. When both these conditions
3156 are met, we have completed the scan of the partition.
3158 Any elements which are between the pivot chunk and the
3159 uncompared elements should be less than the pivot value on
3160 the left side and greater than the pivot value on the right
3161 side (in fact, the goal of the whole algorithm is to arrange
3162 for that to be true and make the groups of less-than and
3163 greater-then elements into new partitions to sort again).
3165 As you marvel at the complexity of the code and wonder why it
3166 has to be so confusing. Consider some of the things this level
3167 of confusion brings:
3169 Once I do a compare, I squeeze every ounce of juice out of it. I
3170 never do compare calls I don't have to do, and I certainly never
3173 I also never swap any elements unless I can prove there is a
3174 good reason. Many sort algorithms will swap a known value with
3175 an uncompared value just to get things in the right place (or
3176 avoid complexity :-), but that uncompared value, once it gets
3177 compared, may then have to be swapped again. A lot of the
3178 complexity of this code is due to the fact that it never swaps
3179 anything except compared values, and it only swaps them when the
3180 compare shows they are out of position.
3182 int pc_left, pc_right;
3183 int u_right, u_left;
3187 pc_left = ((part_left + part_right) / 2);
3189 u_right = pc_left - 1;
3190 u_left = pc_right + 1;
3192 /* Qsort works best when the pivot value is also the median value
3193 in the partition (unfortunately you can't find the median value
3194 without first sorting :-), so to give the algorithm a helping
3195 hand, we pick 3 elements and sort them and use the median value
3196 of that tiny set as the pivot value.
3198 Some versions of qsort like to use the left middle and right as
3199 the 3 elements to sort so they can insure the ends of the
3200 partition will contain values which will stop the scan in the
3201 compare loop, but when you have to call an arbitrarily complex
3202 routine to do a compare, its really better to just keep track of
3203 array index values to know when you hit the edge of the
3204 partition and avoid the extra compare. An even better reason to
3205 avoid using a compare call is the fact that you can drop off the
3206 edge of the array if someone foolishly provides you with an
3207 unstable compare function that doesn't always provide consistent
3210 So, since it is simpler for us to compare the three adjacent
3211 elements in the middle of the partition, those are the ones we
3212 pick here (conveniently pointed at by u_right, pc_left, and
3213 u_left). The values of the left, center, and right elements
3214 are refered to as l c and r in the following comments.
3217 #ifdef QSORT_ORDER_GUESS
3220 s = qsort_cmp(u_right, pc_left);
3223 s = qsort_cmp(pc_left, u_left);
3224 /* if l < c, c < r - already in order - nothing to do */
3226 /* l < c, c == r - already in order, pc grows */
3228 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3230 /* l < c, c > r - need to know more */
3231 s = qsort_cmp(u_right, u_left);
3233 /* l < c, c > r, l < r - swap c & r to get ordered */
3234 qsort_swap(pc_left, u_left);
3235 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3236 } else if (s == 0) {
3237 /* l < c, c > r, l == r - swap c&r, grow pc */
3238 qsort_swap(pc_left, u_left);
3240 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3242 /* l < c, c > r, l > r - make lcr into rlc to get ordered */
3243 qsort_rotate(pc_left, u_right, u_left);
3244 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3247 } else if (s == 0) {
3249 s = qsort_cmp(pc_left, u_left);
3251 /* l == c, c < r - already in order, grow pc */
3253 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3254 } else if (s == 0) {
3255 /* l == c, c == r - already in order, grow pc both ways */
3258 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3260 /* l == c, c > r - swap l & r, grow pc */
3261 qsort_swap(u_right, u_left);
3263 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3267 s = qsort_cmp(pc_left, u_left);
3269 /* l > c, c < r - need to know more */
3270 s = qsort_cmp(u_right, u_left);
3272 /* l > c, c < r, l < r - swap l & c to get ordered */
3273 qsort_swap(u_right, pc_left);
3274 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3275 } else if (s == 0) {
3276 /* l > c, c < r, l == r - swap l & c, grow pc */
3277 qsort_swap(u_right, pc_left);
3279 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3281 /* l > c, c < r, l > r - rotate lcr into crl to order */
3282 qsort_rotate(u_right, pc_left, u_left);
3283 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3285 } else if (s == 0) {
3286 /* l > c, c == r - swap ends, grow pc */
3287 qsort_swap(u_right, u_left);
3289 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3291 /* l > c, c > r - swap ends to get in order */
3292 qsort_swap(u_right, u_left);
3293 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3296 /* We now know the 3 middle elements have been compared and
3297 arranged in the desired order, so we can shrink the uncompared
3302 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3304 /* The above massive nested if was the simple part :-). We now have
3305 the middle 3 elements ordered and we need to scan through the
3306 uncompared sets on either side, swapping elements that are on
3307 the wrong side or simply shuffling equal elements around to get
3308 all equal elements into the pivot chunk.
3312 int still_work_on_left;
3313 int still_work_on_right;
3315 /* Scan the uncompared values on the left. If I find a value
3316 equal to the pivot value, move it over so it is adjacent to
3317 the pivot chunk and expand the pivot chunk. If I find a value
3318 less than the pivot value, then just leave it - its already
3319 on the correct side of the partition. If I find a greater
3320 value, then stop the scan.
3322 while (still_work_on_left = (u_right >= part_left)) {
3323 s = qsort_cmp(u_right, pc_left);
3326 } else if (s == 0) {
3328 if (pc_left != u_right) {
3329 qsort_swap(u_right, pc_left);
3335 qsort_assert(u_right < pc_left);
3336 qsort_assert(pc_left <= pc_right);
3337 qsort_assert(qsort_cmp(u_right + 1, pc_left) <= 0);
3338 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3341 /* Do a mirror image scan of uncompared values on the right
3343 while (still_work_on_right = (u_left <= part_right)) {
3344 s = qsort_cmp(pc_right, u_left);
3347 } else if (s == 0) {
3349 if (pc_right != u_left) {
3350 qsort_swap(pc_right, u_left);
3356 qsort_assert(u_left > pc_right);
3357 qsort_assert(pc_left <= pc_right);
3358 qsort_assert(qsort_cmp(pc_right, u_left - 1) <= 0);
3359 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3362 if (still_work_on_left) {
3363 /* I know I have a value on the left side which needs to be
3364 on the right side, but I need to know more to decide
3365 exactly the best thing to do with it.
3367 if (still_work_on_right) {
3368 /* I know I have values on both side which are out of
3369 position. This is a big win because I kill two birds
3370 with one swap (so to speak). I can advance the
3371 uncompared pointers on both sides after swapping both
3372 of them into the right place.
3374 qsort_swap(u_right, u_left);
3377 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3379 /* I have an out of position value on the left, but the
3380 right is fully scanned, so I "slide" the pivot chunk
3381 and any less-than values left one to make room for the
3382 greater value over on the right. If the out of position
3383 value is immediately adjacent to the pivot chunk (there
3384 are no less-than values), I can do that with a swap,
3385 otherwise, I have to rotate one of the less than values
3386 into the former position of the out of position value
3387 and the right end of the pivot chunk into the left end
3391 if (pc_left == u_right) {
3392 qsort_swap(u_right, pc_right);
3393 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3395 qsort_rotate(u_right, pc_left, pc_right);
3396 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3401 } else if (still_work_on_right) {
3402 /* Mirror image of complex case above: I have an out of
3403 position value on the right, but the left is fully
3404 scanned, so I need to shuffle things around to make room
3405 for the right value on the left.
3408 if (pc_right == u_left) {
3409 qsort_swap(u_left, pc_left);
3410 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3412 qsort_rotate(pc_right, pc_left, u_left);
3413 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3418 /* No more scanning required on either side of partition,
3419 break out of loop and figure out next set of partitions
3425 /* The elements in the pivot chunk are now in the right place. They
3426 will never move or be compared again. All I have to do is decide
3427 what to do with the stuff to the left and right of the pivot
3430 Notes on the QSORT_ORDER_GUESS ifdef code:
3432 1. If I just built these partitions without swapping any (or
3433 very many) elements, there is a chance that the elements are
3434 already ordered properly (being properly ordered will
3435 certainly result in no swapping, but the converse can't be
3438 2. A (properly written) insertion sort will run faster on
3439 already ordered data than qsort will.
3441 3. Perhaps there is some way to make a good guess about
3442 switching to an insertion sort earlier than partition size 6
3443 (for instance - we could save the partition size on the stack
3444 and increase the size each time we find we didn't swap, thus
3445 switching to insertion sort earlier for partitions with a
3446 history of not swapping).
3448 4. Naturally, if I just switch right away, it will make
3449 artificial benchmarks with pure ascending (or descending)
3450 data look really good, but is that a good reason in general?
3454 #ifdef QSORT_ORDER_GUESS
3456 #if QSORT_ORDER_GUESS == 1
3457 qsort_break_even = (part_right - part_left) + 1;
3459 #if QSORT_ORDER_GUESS == 2
3460 qsort_break_even *= 2;
3462 #if QSORT_ORDER_GUESS == 3
3463 int prev_break = qsort_break_even;
3464 qsort_break_even *= qsort_break_even;
3465 if (qsort_break_even < prev_break) {
3466 qsort_break_even = (part_right - part_left) + 1;
3470 qsort_break_even = QSORT_BREAK_EVEN;
3474 if (part_left < pc_left) {
3475 /* There are elements on the left which need more processing.
3476 Check the right as well before deciding what to do.
3478 if (pc_right < part_right) {
3479 /* We have two partitions to be sorted. Stack the biggest one
3480 and process the smallest one on the next iteration. This
3481 minimizes the stack height by insuring that any additional
3482 stack entries must come from the smallest partition which
3483 (because it is smallest) will have the fewest
3484 opportunities to generate additional stack entries.
3486 if ((part_right - pc_right) > (pc_left - part_left)) {
3487 /* stack the right partition, process the left */
3488 partition_stack[next_stack_entry].left = pc_right + 1;
3489 partition_stack[next_stack_entry].right = part_right;
3490 #ifdef QSORT_ORDER_GUESS
3491 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3493 part_right = pc_left - 1;
3495 /* stack the left partition, process the right */
3496 partition_stack[next_stack_entry].left = part_left;
3497 partition_stack[next_stack_entry].right = pc_left - 1;
3498 #ifdef QSORT_ORDER_GUESS
3499 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3501 part_left = pc_right + 1;
3503 qsort_assert(next_stack_entry < QSORT_MAX_STACK);
3506 /* The elements on the left are the only remaining elements
3507 that need sorting, arrange for them to be processed as the
3510 part_right = pc_left - 1;
3512 } else if (pc_right < part_right) {
3513 /* There is only one chunk on the right to be sorted, make it
3514 the new partition and loop back around.
3516 part_left = pc_right + 1;
3518 /* This whole partition wound up in the pivot chunk, so
3519 we need to get a new partition off the stack.
3521 if (next_stack_entry == 0) {
3522 /* the stack is empty - we are done */
3526 part_left = partition_stack[next_stack_entry].left;
3527 part_right = partition_stack[next_stack_entry].right;
3528 #ifdef QSORT_ORDER_GUESS
3529 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3533 /* This partition is too small to fool with qsort complexity, just
3534 do an ordinary insertion sort to minimize overhead.
3537 /* Assume 1st element is in right place already, and start checking
3538 at 2nd element to see where it should be inserted.
3540 for (i = part_left + 1; i <= part_right; ++i) {
3542 /* Scan (backwards - just in case 'i' is already in right place)
3543 through the elements already sorted to see if the ith element
3544 belongs ahead of one of them.
3546 for (j = i - 1; j >= part_left; --j) {
3547 if (qsort_cmp(i, j) >= 0) {
3548 /* i belongs right after j
3555 /* Looks like we really need to move some things
3558 for (--i; i >= j; --i)
3559 array[i + 1] = array[i];
3564 /* That partition is now sorted, grab the next one, or get out
3565 of the loop if there aren't any more.
3568 if (next_stack_entry == 0) {
3569 /* the stack is empty - we are done */
3573 part_left = partition_stack[next_stack_entry].left;
3574 part_right = partition_stack[next_stack_entry].right;
3575 #ifdef QSORT_ORDER_GUESS
3576 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3581 /* Believe it or not, the array is sorted at this point! */