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))
28 static OP *docatch _((OP *o));
29 static OP *dofindlabel _((OP *o, char *label, OP **opstack, OP **oplimit));
30 static void doparseform _((SV *sv));
31 static I32 dopoptoeval _((I32 startingblock));
32 static I32 dopoptolabel _((char *label));
33 static I32 dopoptoloop _((I32 startingblock));
34 static I32 dopoptosub _((I32 startingblock));
35 static void save_lines _((AV *array, SV *sv));
36 static I32 sortcv _((SV *a, SV *b));
37 static void qsortsv _((SV **array, size_t num_elts, I32 (*fun)(SV *a, SV *b)));
38 static OP *doeval _((int gimme, OP** startop));
48 cxix = dopoptosub(cxstack_ix);
52 switch (cxstack[cxix].blk_gimme) {
69 register PMOP *pm = (PMOP*)cLOGOP->op_other;
73 MAGIC *mg = Null(MAGIC*);
77 SV *sv = SvRV(tmpstr);
79 mg = mg_find(sv, 'r');
82 regexp *re = (regexp *)mg->mg_obj;
83 ReREFCNT_dec(pm->op_pmregexp);
84 pm->op_pmregexp = ReREFCNT_inc(re);
87 t = SvPV(tmpstr, len);
89 /* JMR: Check against the last compiled regexp
90 To know for sure, we'd need the length of precomp.
91 But we don't have it, so we must ... take a guess. */
92 if (!pm->op_pmregexp || !pm->op_pmregexp->precomp ||
93 memNE(pm->op_pmregexp->precomp, t, len + 1))
95 if (pm->op_pmregexp) {
96 ReREFCNT_dec(pm->op_pmregexp);
97 pm->op_pmregexp = Null(REGEXP*); /* crucial if regcomp aborts */
100 pm->op_pmflags = pm->op_pmpermflags; /* reset case sensitivity */
101 pm->op_pmregexp = pregcomp(t, t + len, pm);
105 if (!pm->op_pmregexp->prelen && curpm)
107 else if (strEQ("\\s+", pm->op_pmregexp->precomp))
108 pm->op_pmflags |= PMf_WHITE;
110 if (pm->op_pmflags & PMf_KEEP) {
111 pm->op_private &= ~OPpRUNTIME; /* no point compiling again */
112 cLOGOP->op_first->op_next = op->op_next;
120 register PMOP *pm = (PMOP*) cLOGOP->op_other;
121 register PERL_CONTEXT *cx = &cxstack[cxstack_ix];
122 register SV *dstr = cx->sb_dstr;
123 register char *s = cx->sb_s;
124 register char *m = cx->sb_m;
125 char *orig = cx->sb_orig;
126 register REGEXP *rx = cx->sb_rx;
128 rxres_restore(&cx->sb_rxres, rx);
130 if (cx->sb_iters++) {
131 if (cx->sb_iters > cx->sb_maxiters)
132 DIE("Substitution loop");
134 if (!cx->sb_rxtainted)
135 cx->sb_rxtainted = SvTAINTED(TOPs);
136 sv_catsv(dstr, POPs);
139 if (cx->sb_once || !regexec_flags(rx, s, cx->sb_strend, orig,
140 s == m, Nullsv, NULL,
141 cx->sb_safebase ? 0 : REXEC_COPY_STR))
143 SV *targ = cx->sb_targ;
144 sv_catpvn(dstr, s, cx->sb_strend - s);
146 TAINT_IF(cx->sb_rxtainted || RX_MATCH_TAINTED(rx));
148 (void)SvOOK_off(targ);
149 Safefree(SvPVX(targ));
150 SvPVX(targ) = SvPVX(dstr);
151 SvCUR_set(targ, SvCUR(dstr));
152 SvLEN_set(targ, SvLEN(dstr));
155 (void)SvPOK_only(targ);
159 PUSHs(sv_2mortal(newSViv((I32)cx->sb_iters - 1)));
160 LEAVE_SCOPE(cx->sb_oldsave);
162 RETURNOP(pm->op_next);
165 if (rx->subbase && rx->subbase != orig) {
168 cx->sb_orig = orig = rx->subbase;
170 cx->sb_strend = s + (cx->sb_strend - m);
172 cx->sb_m = m = rx->startp[0];
173 sv_catpvn(dstr, s, m-s);
174 cx->sb_s = rx->endp[0];
175 cx->sb_rxtainted |= RX_MATCH_TAINTED(rx);
176 rxres_save(&cx->sb_rxres, rx);
177 RETURNOP(pm->op_pmreplstart);
181 rxres_save(void **rsp, REGEXP *rx)
186 if (!p || p[1] < rx->nparens) {
187 i = 6 + rx->nparens * 2;
195 *p++ = (UV)rx->subbase;
196 rx->subbase = Nullch;
200 *p++ = (UV)rx->subbeg;
201 *p++ = (UV)rx->subend;
202 for (i = 0; i <= rx->nparens; ++i) {
203 *p++ = (UV)rx->startp[i];
204 *p++ = (UV)rx->endp[i];
209 rxres_restore(void **rsp, REGEXP *rx)
214 Safefree(rx->subbase);
215 rx->subbase = (char*)(*p);
220 rx->subbeg = (char*)(*p++);
221 rx->subend = (char*)(*p++);
222 for (i = 0; i <= rx->nparens; ++i) {
223 rx->startp[i] = (char*)(*p++);
224 rx->endp[i] = (char*)(*p++);
229 rxres_free(void **rsp)
234 Safefree((char*)(*p));
242 djSP; dMARK; dORIGMARK;
243 register SV *form = *++MARK;
255 bool chopspace = (strchr(chopset, ' ') != Nullch);
262 if (!SvMAGICAL(form) || !SvCOMPILED(form)) {
263 SvREADONLY_off(form);
267 SvPV_force(formtarget, len);
268 t = SvGROW(formtarget, len + SvCUR(form) + 1); /* XXX SvCUR bad */
271 /* need to jump to the next word */
272 s = f + len + WORD_ALIGN - SvCUR(form) % WORD_ALIGN;
281 case FF_LITERAL: arg = fpc[1]; name = "LITERAL"; break;
282 case FF_BLANK: arg = fpc[1]; name = "BLANK"; break;
283 case FF_SKIP: arg = fpc[1]; name = "SKIP"; break;
284 case FF_FETCH: arg = fpc[1]; name = "FETCH"; break;
285 case FF_DECIMAL: arg = fpc[1]; name = "DECIMAL"; break;
287 case FF_CHECKNL: name = "CHECKNL"; break;
288 case FF_CHECKCHOP: name = "CHECKCHOP"; break;
289 case FF_SPACE: name = "SPACE"; break;
290 case FF_HALFSPACE: name = "HALFSPACE"; break;
291 case FF_ITEM: name = "ITEM"; break;
292 case FF_CHOP: name = "CHOP"; break;
293 case FF_LINEGLOB: name = "LINEGLOB"; break;
294 case FF_NEWLINE: name = "NEWLINE"; break;
295 case FF_MORE: name = "MORE"; break;
296 case FF_LINEMARK: name = "LINEMARK"; break;
297 case FF_END: name = "END"; break;
300 PerlIO_printf(PerlIO_stderr(), "%-16s%ld\n", name, (long) arg);
302 PerlIO_printf(PerlIO_stderr(), "%-16s\n", name);
331 warn("Not enough format arguments");
336 item = s = SvPV(sv, len);
338 if (itemsize > fieldsize)
339 itemsize = fieldsize;
340 send = chophere = s + itemsize;
352 item = s = SvPV(sv, len);
354 if (itemsize <= fieldsize) {
355 send = chophere = s + itemsize;
366 itemsize = fieldsize;
367 send = chophere = s + itemsize;
368 while (s < send || (s == send && isSPACE(*s))) {
378 if (strchr(chopset, *s))
383 itemsize = chophere - item;
388 arg = fieldsize - itemsize;
397 arg = fieldsize - itemsize;
411 int ch = *t++ = *s++;
415 if ( !((*t++ = *s++) & ~31) )
425 while (*s && isSPACE(*s))
432 item = s = SvPV(sv, len);
445 SvCUR_set(formtarget, t - SvPVX(formtarget));
446 sv_catpvn(formtarget, item, itemsize);
447 SvGROW(formtarget, SvCUR(formtarget) + SvCUR(form) + 1);
448 t = SvPVX(formtarget) + SvCUR(formtarget);
453 /* If the field is marked with ^ and the value is undefined,
456 if ((arg & 512) && !SvOK(sv)) {
464 /* Formats aren't yet marked for locales, so assume "yes". */
467 sprintf(t, "%#*.*f", (int) fieldsize, (int) arg & 255, value);
469 sprintf(t, "%*.0f", (int) fieldsize, value);
476 while (t-- > linemark && *t == ' ') ;
484 if (arg) { /* repeat until fields exhausted? */
486 SvCUR_set(formtarget, t - SvPVX(formtarget));
487 lines += FmLINES(formtarget);
490 if (strnEQ(linemark, linemark - arg, arg))
491 DIE("Runaway format");
493 FmLINES(formtarget) = lines;
495 RETURNOP(cLISTOP->op_first);
506 arg = fieldsize - itemsize;
513 if (strnEQ(s," ",3)) {
514 while (s > SvPVX(formtarget) && isSPACE(s[-1]))
525 SvCUR_set(formtarget, t - SvPVX(formtarget));
526 FmLINES(formtarget) += lines;
538 if (stack_base + *markstack_ptr == SP) {
540 if (GIMME_V == G_SCALAR)
542 RETURNOP(op->op_next->op_next);
544 stack_sp = stack_base + *markstack_ptr + 1;
545 pp_pushmark(ARGS); /* push dst */
546 pp_pushmark(ARGS); /* push src */
547 ENTER; /* enter outer scope */
551 /* SAVE_DEFSV does *not* suffice here */
552 save_sptr(&THREADSV(0));
554 SAVESPTR(GvSV(defgv));
555 #endif /* USE_THREADS */
556 ENTER; /* enter inner scope */
559 src = stack_base[*markstack_ptr];
564 if (op->op_type == OP_MAPSTART)
565 pp_pushmark(ARGS); /* push top */
566 return ((LOGOP*)op->op_next)->op_other;
571 DIE("panic: mapstart"); /* uses grepstart */
577 I32 diff = (SP - stack_base) - *markstack_ptr;
585 if (diff > markstack_ptr[-1] - markstack_ptr[-2]) {
586 shift = diff - (markstack_ptr[-1] - markstack_ptr[-2]);
587 count = (SP - stack_base) - markstack_ptr[-1] + 2;
592 markstack_ptr[-1] += shift;
593 *markstack_ptr += shift;
597 dst = stack_base + (markstack_ptr[-2] += diff) - 1;
600 *dst-- = SvTEMP(TOPs) ? POPs : sv_mortalcopy(POPs);
602 LEAVE; /* exit inner scope */
605 if (markstack_ptr[-1] > *markstack_ptr) {
609 (void)POPMARK; /* pop top */
610 LEAVE; /* exit outer scope */
611 (void)POPMARK; /* pop src */
612 items = --*markstack_ptr - markstack_ptr[-1];
613 (void)POPMARK; /* pop dst */
614 SP = stack_base + POPMARK; /* pop original mark */
615 if (gimme == G_SCALAR) {
619 else if (gimme == G_ARRAY)
626 ENTER; /* enter inner scope */
629 src = stack_base[markstack_ptr[-1]];
633 RETURNOP(cLOGOP->op_other);
640 djSP; dMARK; dORIGMARK;
642 SV **myorigmark = ORIGMARK;
648 OP* nextop = op->op_next;
650 if (gimme != G_ARRAY) {
657 if (op->op_flags & OPf_STACKED) {
658 if (op->op_flags & OPf_SPECIAL) {
659 OP *kid = cLISTOP->op_first->op_sibling; /* pass pushmark */
660 kid = kUNOP->op_first; /* pass rv2gv */
661 kid = kUNOP->op_first; /* pass leave */
662 sortcop = kid->op_next;
663 stash = curcop->cop_stash;
666 cv = sv_2cv(*++MARK, &stash, &gv, 0);
667 if (!(cv && CvROOT(cv))) {
669 SV *tmpstr = sv_newmortal();
670 gv_efullname3(tmpstr, gv, Nullch);
671 if (cv && CvXSUB(cv))
672 DIE("Xsub \"%s\" called in sort", SvPVX(tmpstr));
673 DIE("Undefined sort subroutine \"%s\" called",
678 DIE("Xsub called in sort");
679 DIE("Undefined subroutine in sort");
681 DIE("Not a CODE reference in sort");
683 sortcop = CvSTART(cv);
684 SAVESPTR(CvROOT(cv)->op_ppaddr);
685 CvROOT(cv)->op_ppaddr = ppaddr[OP_NULL];
688 curpad = AvARRAY((AV*)AvARRAY(CvPADLIST(cv))[1]);
693 stash = curcop->cop_stash;
697 while (MARK < SP) { /* This may or may not shift down one here. */
699 if (*up = *++MARK) { /* Weed out nulls. */
701 if (!sortcop && !SvPOK(*up))
702 (void)sv_2pv(*up, &na);
706 max = --up - myorigmark;
711 bool oldcatch = CATCH_GET;
718 if (sortstash != stash) {
719 firstgv = gv_fetchpv("a", TRUE, SVt_PV);
720 secondgv = gv_fetchpv("b", TRUE, SVt_PV);
724 SAVESPTR(GvSV(firstgv));
725 SAVESPTR(GvSV(secondgv));
727 PUSHBLOCK(cx, CXt_NULL, stack_base);
728 if (!(op->op_flags & OPf_SPECIAL)) {
729 bool hasargs = FALSE;
730 cx->cx_type = CXt_SUB;
731 cx->blk_gimme = G_SCALAR;
734 (void)SvREFCNT_inc(cv); /* in preparation for POPSUB */
736 sortcxix = cxstack_ix;
738 qsortsv(myorigmark+1, max, sortcv);
747 MEXTEND(SP, 20); /* Can't afford stack realloc on signal. */
748 qsortsv(ORIGMARK+1, max,
749 (op->op_private & OPpLOCALE) ? sv_cmp_locale : sv_cmp);
753 stack_sp = ORIGMARK + max;
761 if (GIMME == G_ARRAY)
762 return cCONDOP->op_true;
763 return SvTRUEx(PAD_SV(op->op_targ)) ? cCONDOP->op_false : cCONDOP->op_true;
770 if (GIMME == G_ARRAY) {
771 RETURNOP(((CONDOP*)cUNOP->op_first)->op_false);
775 SV *targ = PAD_SV(op->op_targ);
777 if ((op->op_private & OPpFLIP_LINENUM)
778 ? last_in_gv && SvIV(sv) == IoLINES(GvIOp(last_in_gv))
780 sv_setiv(PAD_SV(cUNOP->op_first->op_targ), 1);
781 if (op->op_flags & OPf_SPECIAL) {
789 RETURNOP(((CONDOP*)cUNOP->op_first)->op_false);
802 if (GIMME == G_ARRAY) {
808 if (SvNIOKp(left) || !SvPOKp(left) ||
809 (looks_like_number(left) && *SvPVX(left) != '0') )
814 EXTEND_MORTAL(max - i + 1);
815 EXTEND(SP, max - i + 1);
818 sv = sv_2mortal(newSViv(i++));
823 SV *final = sv_mortalcopy(right);
825 char *tmps = SvPV(final, len);
827 sv = sv_mortalcopy(left);
828 while (!SvNIOKp(sv) && SvCUR(sv) <= len &&
829 strNE(SvPVX(sv),tmps) ) {
831 sv = sv_2mortal(newSVsv(sv));
834 if (strEQ(SvPVX(sv),tmps))
840 SV *targ = PAD_SV(cUNOP->op_first->op_targ);
842 if ((op->op_private & OPpFLIP_LINENUM)
843 ? last_in_gv && SvIV(sv) == IoLINES(GvIOp(last_in_gv))
845 sv_setiv(PAD_SV(((UNOP*)cUNOP->op_first)->op_first->op_targ), 0);
846 sv_catpv(targ, "E0");
857 dopoptolabel(char *label)
861 register PERL_CONTEXT *cx;
863 for (i = cxstack_ix; i >= 0; i--) {
865 switch (cx->cx_type) {
868 warn("Exiting substitution via %s", op_name[op->op_type]);
872 warn("Exiting subroutine via %s", op_name[op->op_type]);
876 warn("Exiting eval via %s", op_name[op->op_type]);
880 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
883 if (!cx->blk_loop.label ||
884 strNE(label, cx->blk_loop.label) ) {
885 DEBUG_l(deb("(Skipping label #%ld %s)\n",
886 (long)i, cx->blk_loop.label));
889 DEBUG_l( deb("(Found label #%ld %s)\n", (long)i, label));
899 I32 gimme = block_gimme();
900 return (gimme == G_VOID) ? G_SCALAR : gimme;
909 cxix = dopoptosub(cxstack_ix);
913 switch (cxstack[cxix].blk_gimme) {
919 croak("panic: bad gimme: %d\n", cxstack[cxix].blk_gimme);
926 dopoptosub(I32 startingblock)
930 register PERL_CONTEXT *cx;
931 for (i = startingblock; i >= 0; i--) {
933 switch (cx->cx_type) {
938 DEBUG_l( deb("(Found sub #%ld)\n", (long)i));
946 dopoptoeval(I32 startingblock)
950 register PERL_CONTEXT *cx;
951 for (i = startingblock; i >= 0; i--) {
953 switch (cx->cx_type) {
957 DEBUG_l( deb("(Found eval #%ld)\n", (long)i));
965 dopoptoloop(I32 startingblock)
969 register PERL_CONTEXT *cx;
970 for (i = startingblock; i >= 0; i--) {
972 switch (cx->cx_type) {
975 warn("Exiting substitution via %s", op_name[op->op_type]);
979 warn("Exiting subroutine via %s", op_name[op->op_type]);
983 warn("Exiting eval via %s", op_name[op->op_type]);
987 warn("Exiting pseudo-block via %s", op_name[op->op_type]);
990 DEBUG_l( deb("(Found loop #%ld)\n", (long)i));
1001 register PERL_CONTEXT *cx;
1005 while (cxstack_ix > cxix) {
1006 cx = &cxstack[cxstack_ix];
1007 DEBUG_l(PerlIO_printf(Perl_debug_log, "Unwinding block %ld, type %s\n",
1008 (long) cxstack_ix, block_type[cx->cx_type]));
1009 /* Note: we don't need to restore the base context info till the end. */
1010 switch (cx->cx_type) {
1013 continue; /* not break */
1031 die_where(char *message)
1036 register PERL_CONTEXT *cx;
1042 STRLEN klen = strlen(message);
1044 svp = hv_fetch(ERRHV, message, klen, TRUE);
1047 static char prefix[] = "\t(in cleanup) ";
1049 sv_upgrade(*svp, SVt_IV);
1050 (void)SvIOK_only(*svp);
1053 SvGROW(err, SvCUR(err)+sizeof(prefix)+klen);
1054 sv_catpvn(err, prefix, sizeof(prefix)-1);
1055 sv_catpvn(err, message, klen);
1061 sv_setpv(ERRSV, message);
1063 while ((cxix = dopoptoeval(cxstack_ix)) < 0 && curstackinfo->si_prev) {
1071 if (cxix < cxstack_ix)
1075 if (cx->cx_type != CXt_EVAL) {
1076 PerlIO_printf(PerlIO_stderr(), "panic: die %s", message);
1081 if (gimme == G_SCALAR)
1082 *++newsp = &sv_undef;
1087 if (optype == OP_REQUIRE) {
1088 char* msg = SvPVx(ERRSV, na);
1089 DIE("%s", *msg ? msg : "Compilation failed in require");
1091 return pop_return();
1094 PerlIO_printf(PerlIO_stderr(), "%s",message);
1095 PerlIO_flush(PerlIO_stderr());
1104 if (SvTRUE(left) != SvTRUE(right))
1116 RETURNOP(cLOGOP->op_other);
1125 RETURNOP(cLOGOP->op_other);
1131 register I32 cxix = dopoptosub(cxstack_ix);
1132 register PERL_CONTEXT *cx;
1144 if (GIMME != G_ARRAY)
1148 if (DBsub && cxix >= 0 &&
1149 cxstack[cxix].blk_sub.cv == GvCV(DBsub))
1153 cxix = dopoptosub(cxix - 1);
1155 cx = &cxstack[cxix];
1156 if (cxstack[cxix].cx_type == CXt_SUB) {
1157 dbcxix = dopoptosub(cxix - 1);
1158 /* We expect that cxstack[dbcxix] is CXt_SUB, anyway, the
1159 field below is defined for any cx. */
1160 if (DBsub && dbcxix >= 0 && cxstack[dbcxix].blk_sub.cv == GvCV(DBsub))
1161 cx = &cxstack[dbcxix];
1164 if (GIMME != G_ARRAY) {
1165 hv = cx->blk_oldcop->cop_stash;
1170 sv_setpv(TARG, HvNAME(hv));
1176 hv = cx->blk_oldcop->cop_stash;
1180 PUSHs(sv_2mortal(newSVpv(HvNAME(hv), 0)));
1181 PUSHs(sv_2mortal(newSVpv(SvPVX(GvSV(cx->blk_oldcop->cop_filegv)), 0)));
1182 PUSHs(sv_2mortal(newSViv((I32)cx->blk_oldcop->cop_line)));
1185 if (cx->cx_type == CXt_SUB) { /* So is cxstack[dbcxix]. */
1187 gv_efullname3(sv, CvGV(cxstack[cxix].blk_sub.cv), Nullch);
1188 PUSHs(sv_2mortal(sv));
1189 PUSHs(sv_2mortal(newSViv((I32)cx->blk_sub.hasargs)));
1192 PUSHs(sv_2mortal(newSVpv("(eval)",0)));
1193 PUSHs(sv_2mortal(newSViv(0)));
1195 gimme = (I32)cx->blk_gimme;
1196 if (gimme == G_VOID)
1199 PUSHs(sv_2mortal(newSViv(gimme & G_ARRAY)));
1200 if (cx->cx_type == CXt_EVAL) {
1201 if (cx->blk_eval.old_op_type == OP_ENTEREVAL) {
1202 PUSHs(cx->blk_eval.cur_text);
1205 else if (cx->blk_eval.old_name) { /* Try blocks have old_name == 0. */
1206 /* Require, put the name. */
1207 PUSHs(sv_2mortal(newSVpv(cx->blk_eval.old_name, 0)));
1211 else if (cx->cx_type == CXt_SUB &&
1212 cx->blk_sub.hasargs &&
1213 curcop->cop_stash == debstash)
1215 AV *ary = cx->blk_sub.argarray;
1216 int off = AvARRAY(ary) - AvALLOC(ary);
1220 dbargs = GvAV(gv_AVadd(tmpgv = gv_fetchpv("DB::args", TRUE,
1223 AvREAL_off(dbargs); /* XXX Should be REIFY */
1226 if (AvMAX(dbargs) < AvFILLp(ary) + off)
1227 av_extend(dbargs, AvFILLp(ary) + off);
1228 Copy(AvALLOC(ary), AvARRAY(dbargs), AvFILLp(ary) + 1 + off, SV*);
1229 AvFILLp(dbargs) = AvFILLp(ary) + off;
1235 sortcv(SV *a, SV *b)
1238 I32 oldsaveix = savestack_ix;
1239 I32 oldscopeix = scopestack_ix;
1243 stack_sp = stack_base;
1246 if (stack_sp != stack_base + 1)
1247 croak("Sort subroutine didn't return single value");
1248 if (!SvNIOKp(*stack_sp))
1249 croak("Sort subroutine didn't return a numeric value");
1250 result = SvIV(*stack_sp);
1251 while (scopestack_ix > oldscopeix) {
1254 leave_scope(oldsaveix);
1267 sv_reset(tmps, curcop->cop_stash);
1280 TAINT_NOT; /* Each statement is presumed innocent */
1281 stack_sp = stack_base + cxstack[cxstack_ix].blk_oldsp;
1284 if (op->op_private || SvIV(DBsingle) || SvIV(DBsignal) || SvIV(DBtrace))
1288 register PERL_CONTEXT *cx;
1289 I32 gimme = G_ARRAY;
1296 DIE("No DB::DB routine defined");
1298 if (CvDEPTH(cv) >= 1 && !(debug & (1<<30))) /* don't do recursive DB::DB call */
1310 push_return(op->op_next);
1311 PUSHBLOCK(cx, CXt_SUB, SP);
1314 (void)SvREFCNT_inc(cv);
1316 curpad = AvARRAY((AV*)*av_fetch(CvPADLIST(cv),1,FALSE));
1317 RETURNOP(CvSTART(cv));
1331 register PERL_CONTEXT *cx;
1332 I32 gimme = GIMME_V;
1339 if (op->op_flags & OPf_SPECIAL)
1340 svp = save_threadsv(op->op_targ); /* per-thread variable */
1342 #endif /* USE_THREADS */
1344 svp = &curpad[op->op_targ]; /* "my" variable */
1349 (void)save_scalar(gv);
1350 svp = &GvSV(gv); /* symbol table variable */
1355 PUSHBLOCK(cx, CXt_LOOP, SP);
1356 PUSHLOOP(cx, svp, MARK);
1357 if (op->op_flags & OPf_STACKED)
1358 cx->blk_loop.iterary = (AV*)SvREFCNT_inc(POPs);
1360 cx->blk_loop.iterary = curstack;
1361 AvFILLp(curstack) = SP - stack_base;
1362 cx->blk_loop.iterix = MARK - stack_base;
1371 register PERL_CONTEXT *cx;
1372 I32 gimme = GIMME_V;
1378 PUSHBLOCK(cx, CXt_LOOP, SP);
1379 PUSHLOOP(cx, 0, SP);
1387 register PERL_CONTEXT *cx;
1388 struct block_loop cxloop;
1396 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1399 if (gimme == G_VOID)
1401 else if (gimme == G_SCALAR) {
1403 *++newsp = sv_mortalcopy(*SP);
1405 *++newsp = &sv_undef;
1409 *++newsp = sv_mortalcopy(*++mark);
1410 TAINT_NOT; /* Each item is independent */
1416 POPLOOP2(); /* Stack values are safe: release loop vars ... */
1417 curpm = newpm; /* ... and pop $1 et al */
1429 register PERL_CONTEXT *cx;
1430 struct block_sub cxsub;
1431 bool popsub2 = FALSE;
1437 if (curstackinfo->si_type == SI_SORT) {
1438 if (cxstack_ix == sortcxix || dopoptosub(cxstack_ix) <= sortcxix) {
1439 if (cxstack_ix > sortcxix)
1441 AvARRAY(curstack)[1] = *SP;
1442 stack_sp = stack_base + 1;
1447 cxix = dopoptosub(cxstack_ix);
1449 DIE("Can't return outside a subroutine");
1450 if (cxix < cxstack_ix)
1454 switch (cx->cx_type) {
1456 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1461 if (optype == OP_REQUIRE &&
1462 (MARK == SP || (gimme == G_SCALAR && !SvTRUE(*SP))) )
1464 /* Unassume the success we assumed earlier. */
1465 char *name = cx->blk_eval.old_name;
1466 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
1467 DIE("%s did not return a true value", name);
1471 DIE("panic: return");
1475 if (gimme == G_SCALAR) {
1477 *++newsp = (popsub2 && SvTEMP(*SP))
1478 ? *SP : sv_mortalcopy(*SP);
1480 *++newsp = &sv_undef;
1482 else if (gimme == G_ARRAY) {
1483 while (++MARK <= SP) {
1484 *++newsp = (popsub2 && SvTEMP(*MARK))
1485 ? *MARK : sv_mortalcopy(*MARK);
1486 TAINT_NOT; /* Each item is independent */
1491 /* Stack values are safe: */
1493 POPSUB2(); /* release CV and @_ ... */
1495 curpm = newpm; /* ... and pop $1 et al */
1498 return pop_return();
1505 register PERL_CONTEXT *cx;
1506 struct block_loop cxloop;
1507 struct block_sub cxsub;
1514 SV **mark = stack_base + cxstack[cxstack_ix].blk_oldsp;
1516 if (op->op_flags & OPf_SPECIAL) {
1517 cxix = dopoptoloop(cxstack_ix);
1519 DIE("Can't \"last\" outside a block");
1522 cxix = dopoptolabel(cPVOP->op_pv);
1524 DIE("Label not found for \"last %s\"", cPVOP->op_pv);
1526 if (cxix < cxstack_ix)
1530 switch (cx->cx_type) {
1532 POPLOOP1(cx); /* Delay POPLOOP2 until stack values are safe */
1534 nextop = cxloop.last_op->op_next;
1537 POPSUB1(cx); /* Delay POPSUB2 until stack values are safe */
1539 nextop = pop_return();
1543 nextop = pop_return();
1550 if (gimme == G_SCALAR) {
1552 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*SP))
1553 ? *SP : sv_mortalcopy(*SP);
1555 *++newsp = &sv_undef;
1557 else if (gimme == G_ARRAY) {
1558 while (++MARK <= SP) {
1559 *++newsp = ((pop2 == CXt_SUB) && SvTEMP(*MARK))
1560 ? *MARK : sv_mortalcopy(*MARK);
1561 TAINT_NOT; /* Each item is independent */
1567 /* Stack values are safe: */
1570 POPLOOP2(); /* release loop vars ... */
1574 POPSUB2(); /* release CV and @_ ... */
1577 curpm = newpm; /* ... and pop $1 et al */
1586 register PERL_CONTEXT *cx;
1589 if (op->op_flags & OPf_SPECIAL) {
1590 cxix = dopoptoloop(cxstack_ix);
1592 DIE("Can't \"next\" outside a block");
1595 cxix = dopoptolabel(cPVOP->op_pv);
1597 DIE("Label not found for \"next %s\"", cPVOP->op_pv);
1599 if (cxix < cxstack_ix)
1603 oldsave = scopestack[scopestack_ix - 1];
1604 LEAVE_SCOPE(oldsave);
1605 return cx->blk_loop.next_op;
1611 register PERL_CONTEXT *cx;
1614 if (op->op_flags & OPf_SPECIAL) {
1615 cxix = dopoptoloop(cxstack_ix);
1617 DIE("Can't \"redo\" outside a block");
1620 cxix = dopoptolabel(cPVOP->op_pv);
1622 DIE("Label not found for \"redo %s\"", cPVOP->op_pv);
1624 if (cxix < cxstack_ix)
1628 oldsave = scopestack[scopestack_ix - 1];
1629 LEAVE_SCOPE(oldsave);
1630 return cx->blk_loop.redo_op;
1633 static OP* lastgotoprobe;
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)
1723 if (cx->cx_type == CXt_EVAL && cx->blk_eval.old_op_type == OP_ENTEREVAL)
1724 DIE("Can't goto subroutine from an eval-string");
1726 if (cx->cx_type == CXt_SUB &&
1727 cx->blk_sub.hasargs) { /* put @_ back onto stack */
1728 AV* av = cx->blk_sub.argarray;
1730 items = AvFILLp(av) + 1;
1732 EXTEND(stack_sp, items); /* @_ could have been extended. */
1733 Copy(AvARRAY(av), stack_sp, items, SV*);
1736 SvREFCNT_dec(GvAV(defgv));
1737 GvAV(defgv) = cx->blk_sub.savearray;
1738 #endif /* USE_THREADS */
1742 if (cx->cx_type == CXt_SUB &&
1743 !(CvDEPTH(cx->blk_sub.cv) = cx->blk_sub.olddepth))
1744 SvREFCNT_dec(cx->blk_sub.cv);
1745 oldsave = scopestack[scopestack_ix - 1];
1746 LEAVE_SCOPE(oldsave);
1748 /* Now do some callish stuff. */
1751 if (CvOLDSTYLE(cv)) {
1752 I32 (*fp3)_((int,int,int));
1757 fp3 = (I32(*)_((int,int,int)))CvXSUB(cv);
1758 items = (*fp3)(CvXSUBANY(cv).any_i32,
1759 mark - stack_base + 1,
1761 SP = stack_base + items;
1764 stack_sp--; /* There is no cv arg. */
1765 (void)(*CvXSUB(cv))(cv);
1768 return pop_return();
1771 AV* padlist = CvPADLIST(cv);
1772 SV** svp = AvARRAY(padlist);
1773 if (cx->cx_type == CXt_EVAL) {
1774 in_eval = cx->blk_eval.old_in_eval;
1775 eval_root = cx->blk_eval.old_eval_root;
1776 cx->cx_type = CXt_SUB;
1777 cx->blk_sub.hasargs = 0;
1779 cx->blk_sub.cv = cv;
1780 cx->blk_sub.olddepth = CvDEPTH(cv);
1782 if (CvDEPTH(cv) < 2)
1783 (void)SvREFCNT_inc(cv);
1784 else { /* save temporaries on recursion? */
1785 if (CvDEPTH(cv) == 100 && dowarn)
1786 sub_crush_depth(cv);
1787 if (CvDEPTH(cv) > AvFILLp(padlist)) {
1788 AV *newpad = newAV();
1789 SV **oldpad = AvARRAY(svp[CvDEPTH(cv)-1]);
1790 I32 ix = AvFILLp((AV*)svp[1]);
1791 svp = AvARRAY(svp[0]);
1792 for ( ;ix > 0; ix--) {
1793 if (svp[ix] != &sv_undef) {
1794 char *name = SvPVX(svp[ix]);
1795 if ((SvFLAGS(svp[ix]) & SVf_FAKE)
1798 /* outer lexical or anon code */
1799 av_store(newpad, ix,
1800 SvREFCNT_inc(oldpad[ix]) );
1802 else { /* our own lexical */
1804 av_store(newpad, ix, sv = (SV*)newAV());
1805 else if (*name == '%')
1806 av_store(newpad, ix, sv = (SV*)newHV());
1808 av_store(newpad, ix, sv = NEWSV(0,0));
1813 av_store(newpad, ix, sv = NEWSV(0,0));
1817 if (cx->blk_sub.hasargs) {
1820 av_store(newpad, 0, (SV*)av);
1821 AvFLAGS(av) = AVf_REIFY;
1823 av_store(padlist, CvDEPTH(cv), (SV*)newpad);
1824 AvFILLp(padlist) = CvDEPTH(cv);
1825 svp = AvARRAY(padlist);
1829 if (!cx->blk_sub.hasargs) {
1830 AV* av = (AV*)curpad[0];
1832 items = AvFILLp(av) + 1;
1834 /* Mark is at the end of the stack. */
1836 Copy(AvARRAY(av), SP + 1, items, SV*);
1841 #endif /* USE_THREADS */
1843 curpad = AvARRAY((AV*)svp[CvDEPTH(cv)]);
1845 if (cx->blk_sub.hasargs)
1846 #endif /* USE_THREADS */
1848 AV* av = (AV*)curpad[0];
1852 cx->blk_sub.savearray = GvAV(defgv);
1853 GvAV(defgv) = (AV*)SvREFCNT_inc(av);
1854 #endif /* USE_THREADS */
1855 cx->blk_sub.argarray = av;
1858 if (items >= AvMAX(av) + 1) {
1860 if (AvARRAY(av) != ary) {
1861 AvMAX(av) += AvARRAY(av) - AvALLOC(av);
1862 SvPVX(av) = (char*)ary;
1864 if (items >= AvMAX(av) + 1) {
1865 AvMAX(av) = items - 1;
1866 Renew(ary,items+1,SV*);
1868 SvPVX(av) = (char*)ary;
1871 Copy(mark,AvARRAY(av),items,SV*);
1872 AvFILLp(av) = items - 1;
1880 if (PERLDB_SUB && curstash != debstash) {
1882 * We do not care about using sv to call CV;
1883 * it's for informational purposes only.
1885 SV *sv = GvSV(DBsub);
1887 gv_efullname3(sv, CvGV(cv), Nullch);
1889 RETURNOP(CvSTART(cv));
1893 label = SvPV(sv,na);
1895 else if (op->op_flags & OPf_SPECIAL) {
1897 DIE("goto must have label");
1900 label = cPVOP->op_pv;
1902 if (label && *label) {
1909 for (ix = cxstack_ix; ix >= 0; ix--) {
1911 switch (cx->cx_type) {
1913 gotoprobe = eval_root; /* XXX not good for nested eval */
1916 gotoprobe = cx->blk_oldcop->op_sibling;
1922 gotoprobe = cx->blk_oldcop->op_sibling;
1924 gotoprobe = main_root;
1927 if (CvDEPTH(cx->blk_sub.cv)) {
1928 gotoprobe = CvROOT(cx->blk_sub.cv);
1933 DIE("Can't \"goto\" outside a block");
1937 gotoprobe = main_root;
1940 retop = dofindlabel(gotoprobe, label,
1941 enterops, enterops + GOTO_DEPTH);
1944 lastgotoprobe = gotoprobe;
1947 DIE("Can't find label %s", label);
1949 /* pop unwanted frames */
1951 if (ix < cxstack_ix) {
1958 oldsave = scopestack[scopestack_ix];
1959 LEAVE_SCOPE(oldsave);
1962 /* push wanted frames */
1964 if (*enterops && enterops[1]) {
1966 for (ix = 1; enterops[ix]; ix++) {
1968 /* Eventually we may want to stack the needed arguments
1969 * for each op. For now, we punt on the hard ones. */
1970 if (op->op_type == OP_ENTERITER)
1971 DIE("Can't \"goto\" into the middle of a foreach loop",
1973 (*op->op_ppaddr)(ARGS);
1981 if (!retop) retop = main_start;
1988 restartop = 0; /* hmm, must be GNU unexec().. */
1992 if (top_env->je_prev) {
2010 if (anum == 1 && VMSISH_EXIT)
2023 double value = SvNVx(GvSV(cCOP->cop_gv));
2024 register I32 match = I_32(value);
2027 if (((double)match) > value)
2028 --match; /* was fractional--truncate other way */
2030 match -= cCOP->uop.scop.scop_offset;
2033 else if (match > cCOP->uop.scop.scop_max)
2034 match = cCOP->uop.scop.scop_max;
2035 op = cCOP->uop.scop.scop_next[match];
2045 op = op->op_next; /* can't assume anything */
2047 match = *(SvPVx(GvSV(cCOP->cop_gv), na)) & 255;
2048 match -= cCOP->uop.scop.scop_offset;
2051 else if (match > cCOP->uop.scop.scop_max)
2052 match = cCOP->uop.scop.scop_max;
2053 op = cCOP->uop.scop.scop_next[match];
2062 save_lines(AV *array, SV *sv)
2064 register char *s = SvPVX(sv);
2065 register char *send = SvPVX(sv) + SvCUR(sv);
2067 register I32 line = 1;
2069 while (s && s < send) {
2070 SV *tmpstr = NEWSV(85,0);
2072 sv_upgrade(tmpstr, SVt_PVMG);
2073 t = strchr(s, '\n');
2079 sv_setpvn(tmpstr, s, t - s);
2080 av_store(array, line++, tmpstr);
2095 assert(CATCH_GET == TRUE);
2096 DEBUG_l(deb("Setting up local jumplevel %p, was %p\n", &cur_env, top_env));
2100 default: /* topmost level handles it */
2107 PerlIO_printf(PerlIO_stderr(), "panic: restartop\n");
2123 sv_compile_2op(SV *sv, OP** startop, char *code, AV** avp)
2124 /* sv Text to convert to OP tree. */
2125 /* startop op_free() this to undo. */
2126 /* code Short string id of the caller. */
2128 dSP; /* Make POPBLOCK work. */
2131 I32 gimme = 0; /* SUSPECT - INITIALZE TO WHAT? NI-S */
2135 char tmpbuf[TYPE_DIGITS(long) + 12 + 10];
2141 /* switch to eval mode */
2143 SAVESPTR(compiling.cop_filegv);
2144 SAVEI16(compiling.cop_line);
2145 sprintf(tmpbuf, "_<(%.10s_eval %lu)", code, (unsigned long)++evalseq);
2146 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2147 compiling.cop_line = 1;
2148 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2149 deleting the eval's FILEGV from the stash before gv_check() runs
2150 (i.e. before run-time proper). To work around the coredump that
2151 ensues, we always turn GvMULTI_on for any globals that were
2152 introduced within evals. See force_ident(). GSAR 96-10-12 */
2153 safestr = savepv(tmpbuf);
2154 SAVEDELETE(defstash, safestr, strlen(safestr));
2156 #ifdef OP_IN_REGISTER
2164 op->op_type = 0; /* Avoid uninit warning. */
2165 op->op_flags = 0; /* Avoid uninit warning. */
2166 PUSHBLOCK(cx, CXt_EVAL, SP);
2167 PUSHEVAL(cx, 0, compiling.cop_filegv);
2168 rop = doeval(G_SCALAR, startop);
2172 (*startop)->op_type = OP_NULL;
2173 (*startop)->op_ppaddr = ppaddr[OP_NULL];
2175 *avp = (AV*)SvREFCNT_inc(comppad);
2177 #ifdef OP_IN_REGISTER
2183 /* With USE_THREADS, eval_owner must be held on entry to doeval */
2185 doeval(int gimme, OP** startop)
2198 /* set up a scratch pad */
2203 SAVESPTR(comppad_name);
2204 SAVEI32(comppad_name_fill);
2205 SAVEI32(min_intro_pending);
2206 SAVEI32(max_intro_pending);
2209 for (i = cxstack_ix - 1; i >= 0; i--) {
2210 PERL_CONTEXT *cx = &cxstack[i];
2211 if (cx->cx_type == CXt_EVAL)
2213 else if (cx->cx_type == CXt_SUB) {
2214 caller = cx->blk_sub.cv;
2220 compcv = (CV*)NEWSV(1104,0);
2221 sv_upgrade((SV *)compcv, SVt_PVCV);
2222 CvUNIQUE_on(compcv);
2224 CvOWNER(compcv) = 0;
2225 New(666, CvMUTEXP(compcv), 1, perl_mutex);
2226 MUTEX_INIT(CvMUTEXP(compcv));
2227 #endif /* USE_THREADS */
2230 av_push(comppad, Nullsv);
2231 curpad = AvARRAY(comppad);
2232 comppad_name = newAV();
2233 comppad_name_fill = 0;
2234 min_intro_pending = 0;
2237 av_store(comppad_name, 0, newSVpv("@_", 2));
2238 curpad[0] = (SV*)newAV();
2239 SvPADMY_on(curpad[0]); /* XXX Needed? */
2240 #endif /* USE_THREADS */
2242 comppadlist = newAV();
2243 AvREAL_off(comppadlist);
2244 av_store(comppadlist, 0, (SV*)comppad_name);
2245 av_store(comppadlist, 1, (SV*)comppad);
2246 CvPADLIST(compcv) = comppadlist;
2248 if (!saveop || saveop->op_type != OP_REQUIRE)
2249 CvOUTSIDE(compcv) = (CV*)SvREFCNT_inc(caller);
2253 /* make sure we compile in the right package */
2255 newstash = curcop->cop_stash;
2256 if (curstash != newstash) {
2258 curstash = newstash;
2262 SAVEFREESV(beginav);
2264 /* try to compile it */
2268 curcop = &compiling;
2269 curcop->cop_arybase = 0;
2271 rs = newSVpv("\n", 1);
2272 if (saveop && saveop->op_flags & OPf_SPECIAL)
2276 if (yyparse() || error_count || !eval_root) {
2280 I32 optype = 0; /* Might be reset by POPEVAL. */
2287 SP = stack_base + POPMARK; /* pop original mark */
2295 if (optype == OP_REQUIRE) {
2296 char* msg = SvPVx(ERRSV, na);
2297 DIE("%s", *msg ? msg : "Compilation failed in require");
2298 } else if (startop) {
2299 char* msg = SvPVx(ERRSV, na);
2303 croak("%sCompilation failed in regexp", (*msg ? msg : "Unknown error\n"));
2306 rs = SvREFCNT_inc(nrs);
2308 MUTEX_LOCK(&eval_mutex);
2310 COND_SIGNAL(&eval_cond);
2311 MUTEX_UNLOCK(&eval_mutex);
2312 #endif /* USE_THREADS */
2316 rs = SvREFCNT_inc(nrs);
2317 compiling.cop_line = 0;
2319 *startop = eval_root;
2320 SvREFCNT_dec(CvOUTSIDE(compcv));
2321 CvOUTSIDE(compcv) = Nullcv;
2323 SAVEFREEOP(eval_root);
2325 scalarvoid(eval_root);
2326 else if (gimme & G_ARRAY)
2331 DEBUG_x(dump_eval());
2333 /* Register with debugger: */
2334 if (PERLDB_INTER && saveop->op_type == OP_REQUIRE) {
2335 CV *cv = perl_get_cv("DB::postponed", FALSE);
2339 XPUSHs((SV*)compiling.cop_filegv);
2341 perl_call_sv((SV*)cv, G_DISCARD);
2345 /* compiled okay, so do it */
2347 CvDEPTH(compcv) = 1;
2348 SP = stack_base + POPMARK; /* pop original mark */
2349 op = saveop; /* The caller may need it. */
2351 MUTEX_LOCK(&eval_mutex);
2353 COND_SIGNAL(&eval_cond);
2354 MUTEX_UNLOCK(&eval_mutex);
2355 #endif /* USE_THREADS */
2357 RETURNOP(eval_start);
2363 register PERL_CONTEXT *cx;
2368 SV *namesv = Nullsv;
2370 I32 gimme = G_SCALAR;
2371 PerlIO *tryrsfp = 0;
2374 if (SvNIOKp(sv) && !SvPOKp(sv)) {
2375 SET_NUMERIC_STANDARD();
2376 if (atof(patchlevel) + 0.00000999 < SvNV(sv))
2377 DIE("Perl %s required--this is only version %s, stopped",
2378 SvPV(sv,na),patchlevel);
2381 name = SvPV(sv, len);
2382 if (!(name && len > 0 && *name))
2383 DIE("Null filename used");
2384 TAINT_PROPER("require");
2385 if (op->op_type == OP_REQUIRE &&
2386 (svp = hv_fetch(GvHVn(incgv), name, len, 0)) &&
2390 /* prepare to compile file */
2395 (name[1] == '.' && name[2] == '/')))
2397 || (name[0] && name[1] == ':')
2400 || (name[0] == '\\' && name[1] == '\\') /* UNC path */
2403 || (strchr(name,':') || ((*name == '[' || *name == '<') &&
2404 (isALNUM(name[1]) || strchr("$-_]>",name[1]))))
2409 tryrsfp = PerlIO_open(name,PERL_SCRIPT_MODE);
2412 AV *ar = GvAVn(incgv);
2416 if ((unixname = tounixspec(name, Nullch)) != Nullch)
2419 namesv = NEWSV(806, 0);
2420 for (i = 0; i <= AvFILL(ar); i++) {
2421 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2424 if ((unixdir = tounixpath(dir, Nullch)) == Nullch)
2426 sv_setpv(namesv, unixdir);
2427 sv_catpv(namesv, unixname);
2429 sv_setpvf(namesv, "%s/%s", dir, name);
2431 tryname = SvPVX(namesv);
2432 tryrsfp = PerlIO_open(tryname, PERL_SCRIPT_MODE);
2434 if (tryname[0] == '.' && tryname[1] == '/')
2441 SAVESPTR(compiling.cop_filegv);
2442 compiling.cop_filegv = gv_fetchfile(tryrsfp ? tryname : name);
2443 SvREFCNT_dec(namesv);
2445 if (op->op_type == OP_REQUIRE) {
2446 SV *msg = sv_2mortal(newSVpvf("Can't locate %s in @INC", name));
2447 SV *dirmsgsv = NEWSV(0, 0);
2448 AV *ar = GvAVn(incgv);
2450 if (instr(SvPVX(msg), ".h "))
2451 sv_catpv(msg, " (change .h to .ph maybe?)");
2452 if (instr(SvPVX(msg), ".ph "))
2453 sv_catpv(msg, " (did you run h2ph?)");
2454 sv_catpv(msg, " (@INC contains:");
2455 for (i = 0; i <= AvFILL(ar); i++) {
2456 char *dir = SvPVx(*av_fetch(ar, i, TRUE), na);
2457 sv_setpvf(dirmsgsv, " %s", dir);
2458 sv_catsv(msg, dirmsgsv);
2460 sv_catpvn(msg, ")", 1);
2461 SvREFCNT_dec(dirmsgsv);
2468 /* Assume success here to prevent recursive requirement. */
2469 (void)hv_store(GvHVn(incgv), name, strlen(name),
2470 newSVsv(GvSV(compiling.cop_filegv)), 0 );
2474 lex_start(sv_2mortal(newSVpv("",0)));
2476 save_aptr(&rsfp_filters);
2477 rsfp_filters = NULL;
2481 name = savepv(name);
2486 /* switch to eval mode */
2488 push_return(op->op_next);
2489 PUSHBLOCK(cx, CXt_EVAL, SP);
2490 PUSHEVAL(cx, name, compiling.cop_filegv);
2492 compiling.cop_line = 0;
2496 MUTEX_LOCK(&eval_mutex);
2497 if (eval_owner && eval_owner != thr)
2499 COND_WAIT(&eval_cond, &eval_mutex);
2501 MUTEX_UNLOCK(&eval_mutex);
2502 #endif /* USE_THREADS */
2503 return DOCATCH(doeval(G_SCALAR, NULL));
2508 return pp_require(ARGS);
2514 register PERL_CONTEXT *cx;
2516 I32 gimme = GIMME_V, was = sub_generation;
2517 char tmpbuf[TYPE_DIGITS(long) + 12];
2522 if (!SvPV(sv,len) || !len)
2524 TAINT_PROPER("eval");
2530 /* switch to eval mode */
2532 SAVESPTR(compiling.cop_filegv);
2533 sprintf(tmpbuf, "_<(eval %lu)", (unsigned long)++evalseq);
2534 compiling.cop_filegv = gv_fetchfile(tmpbuf+2);
2535 compiling.cop_line = 1;
2536 /* XXX For C<eval "...">s within BEGIN {} blocks, this ends up
2537 deleting the eval's FILEGV from the stash before gv_check() runs
2538 (i.e. before run-time proper). To work around the coredump that
2539 ensues, we always turn GvMULTI_on for any globals that were
2540 introduced within evals. See force_ident(). GSAR 96-10-12 */
2541 safestr = savepv(tmpbuf);
2542 SAVEDELETE(defstash, safestr, strlen(safestr));
2544 hints = op->op_targ;
2546 push_return(op->op_next);
2547 PUSHBLOCK(cx, CXt_EVAL, SP);
2548 PUSHEVAL(cx, 0, compiling.cop_filegv);
2550 /* prepare to compile string */
2552 if (PERLDB_LINE && curstash != debstash)
2553 save_lines(GvAV(compiling.cop_filegv), linestr);
2556 MUTEX_LOCK(&eval_mutex);
2557 if (eval_owner && eval_owner != thr)
2559 COND_WAIT(&eval_cond, &eval_mutex);
2561 MUTEX_UNLOCK(&eval_mutex);
2562 #endif /* USE_THREADS */
2563 ret = doeval(gimme, NULL);
2564 if (PERLDB_INTER && was != sub_generation /* Some subs defined here. */
2565 && ret != op->op_next) { /* Successive compilation. */
2566 strcpy(safestr, "_<(eval )"); /* Anything fake and short. */
2568 return DOCATCH(ret);
2578 register PERL_CONTEXT *cx;
2580 U8 save_flags = op -> op_flags;
2585 retop = pop_return();
2588 if (gimme == G_VOID)
2590 else if (gimme == G_SCALAR) {
2593 if (SvFLAGS(TOPs) & SVs_TEMP)
2596 *MARK = sv_mortalcopy(TOPs);
2604 /* in case LEAVE wipes old return values */
2605 for (mark = newsp + 1; mark <= SP; mark++) {
2606 if (!(SvFLAGS(*mark) & SVs_TEMP)) {
2607 *mark = sv_mortalcopy(*mark);
2608 TAINT_NOT; /* Each item is independent */
2612 curpm = newpm; /* Don't pop $1 et al till now */
2615 * Closures mentioned at top level of eval cannot be referenced
2616 * again, and their presence indirectly causes a memory leak.
2617 * (Note that the fact that compcv and friends are still set here
2618 * is, AFAIK, an accident.) --Chip
2620 if (AvFILLp(comppad_name) >= 0) {
2621 SV **svp = AvARRAY(comppad_name);
2623 for (ix = AvFILLp(comppad_name); ix >= 0; ix--) {
2625 if (sv && sv != &sv_undef && *SvPVX(sv) == '&') {
2627 svp[ix] = &sv_undef;
2631 SvREFCNT_dec(CvOUTSIDE(sv));
2632 CvOUTSIDE(sv) = Nullcv;
2645 assert(CvDEPTH(compcv) == 1);
2647 CvDEPTH(compcv) = 0;
2650 if (optype == OP_REQUIRE &&
2651 !(gimme == G_SCALAR ? SvTRUE(*SP) : SP > newsp))
2653 /* Unassume the success we assumed earlier. */
2654 char *name = cx->blk_eval.old_name;
2655 (void)hv_delete(GvHVn(incgv), name, strlen(name), G_DISCARD);
2656 retop = die("%s did not return a true value", name);
2657 /* die_where() did LEAVE, or we won't be here */
2661 if (!(save_flags & OPf_SPECIAL))
2671 register PERL_CONTEXT *cx;
2672 I32 gimme = GIMME_V;
2677 push_return(cLOGOP->op_other->op_next);
2678 PUSHBLOCK(cx, CXt_EVAL, SP);
2680 eval_root = op; /* Only needed so that goto works right. */
2685 return DOCATCH(op->op_next);
2695 register PERL_CONTEXT *cx;
2703 if (gimme == G_VOID)
2705 else if (gimme == G_SCALAR) {
2708 if (SvFLAGS(TOPs) & (SVs_PADTMP|SVs_TEMP))
2711 *MARK = sv_mortalcopy(TOPs);
2720 /* in case LEAVE wipes old return values */
2721 for (mark = newsp + 1; mark <= SP; mark++) {
2722 if (!(SvFLAGS(*mark) & (SVs_PADTMP|SVs_TEMP))) {
2723 *mark = sv_mortalcopy(*mark);
2724 TAINT_NOT; /* Each item is independent */
2728 curpm = newpm; /* Don't pop $1 et al till now */
2739 register char *s = SvPV_force(sv, len);
2740 register char *send = s + len;
2741 register char *base;
2742 register I32 skipspaces = 0;
2745 bool postspace = FALSE;
2753 croak("Null picture in formline");
2755 New(804, fops, (send - s)*3+10, U16); /* Almost certainly too long... */
2760 *fpc++ = FF_LINEMARK;
2761 noblank = repeat = FALSE;
2779 case ' ': case '\t':
2790 *fpc++ = FF_LITERAL;
2798 *fpc++ = skipspaces;
2802 *fpc++ = FF_NEWLINE;
2806 arg = fpc - linepc + 1;
2813 *fpc++ = FF_LINEMARK;
2814 noblank = repeat = FALSE;
2823 ischop = s[-1] == '^';
2829 arg = (s - base) - 1;
2831 *fpc++ = FF_LITERAL;
2840 *fpc++ = FF_LINEGLOB;
2842 else if (*s == '#' || (*s == '.' && s[1] == '#')) {
2843 arg = ischop ? 512 : 0;
2853 arg |= 256 + (s - f);
2855 *fpc++ = s - base; /* fieldsize for FETCH */
2856 *fpc++ = FF_DECIMAL;
2861 bool ismore = FALSE;
2864 while (*++s == '>') ;
2865 prespace = FF_SPACE;
2867 else if (*s == '|') {
2868 while (*++s == '|') ;
2869 prespace = FF_HALFSPACE;
2874 while (*++s == '<') ;
2877 if (*s == '.' && s[1] == '.' && s[2] == '.') {
2881 *fpc++ = s - base; /* fieldsize for FETCH */
2883 *fpc++ = ischop ? FF_CHECKCHOP : FF_CHECKNL;
2901 { /* need to jump to the next word */
2903 z = WORD_ALIGN - SvCUR(sv) % WORD_ALIGN;
2904 SvGROW(sv, SvCUR(sv) + z + arg * sizeof(U16) + 4);
2905 s = SvPVX(sv) + SvCUR(sv) + z;
2907 Copy(fops, s, arg, U16);
2909 sv_magic(sv, Nullsv, 'f', Nullch, 0);
2914 * The rest of this file was derived from source code contributed
2917 * NOTE: this code was derived from Tom Horsley's qsort replacement
2918 * and should not be confused with the original code.
2921 /* Copyright (C) Tom Horsley, 1997. All rights reserved.
2923 Permission granted to distribute under the same terms as perl which are
2926 This program is free software; you can redistribute it and/or modify
2927 it under the terms of either:
2929 a) the GNU General Public License as published by the Free
2930 Software Foundation; either version 1, or (at your option) any
2933 b) the "Artistic License" which comes with this Kit.
2935 Details on the perl license can be found in the perl source code which
2936 may be located via the www.perl.com web page.
2938 This is the most wonderfulest possible qsort I can come up with (and
2939 still be mostly portable) My (limited) tests indicate it consistently
2940 does about 20% fewer calls to compare than does the qsort in the Visual
2941 C++ library, other vendors may vary.
2943 Some of the ideas in here can be found in "Algorithms" by Sedgewick,
2944 others I invented myself (or more likely re-invented since they seemed
2945 pretty obvious once I watched the algorithm operate for a while).
2947 Most of this code was written while watching the Marlins sweep the Giants
2948 in the 1997 National League Playoffs - no Braves fans allowed to use this
2949 code (just kidding :-).
2951 I realize that if I wanted to be true to the perl tradition, the only
2952 comment in this file would be something like:
2954 ...they shuffled back towards the rear of the line. 'No, not at the
2955 rear!' the slave-driver shouted. 'Three files up. And stay there...
2957 However, I really needed to violate that tradition just so I could keep
2958 track of what happens myself, not to mention some poor fool trying to
2959 understand this years from now :-).
2962 /* ********************************************************** Configuration */
2964 #ifndef QSORT_ORDER_GUESS
2965 #define QSORT_ORDER_GUESS 2 /* Select doubling version of the netBSD trick */
2968 /* QSORT_MAX_STACK is the largest number of partitions that can be stacked up for
2969 future processing - a good max upper bound is log base 2 of memory size
2970 (32 on 32 bit machines, 64 on 64 bit machines, etc). In reality can
2971 safely be smaller than that since the program is taking up some space and
2972 most operating systems only let you grab some subset of contiguous
2973 memory (not to mention that you are normally sorting data larger than
2974 1 byte element size :-).
2976 #ifndef QSORT_MAX_STACK
2977 #define QSORT_MAX_STACK 32
2980 /* QSORT_BREAK_EVEN is the size of the largest partition we should insertion sort.
2981 Anything bigger and we use qsort. If you make this too small, the qsort
2982 will probably break (or become less efficient), because it doesn't expect
2983 the middle element of a partition to be the same as the right or left -
2984 you have been warned).
2986 #ifndef QSORT_BREAK_EVEN
2987 #define QSORT_BREAK_EVEN 6
2990 /* ************************************************************* Data Types */
2992 /* hold left and right index values of a partition waiting to be sorted (the
2993 partition includes both left and right - right is NOT one past the end or
2994 anything like that).
2996 struct partition_stack_entry {
2999 #ifdef QSORT_ORDER_GUESS
3000 int qsort_break_even;
3004 /* ******************************************************* Shorthand Macros */
3006 /* Note that these macros will be used from inside the qsort function where
3007 we happen to know that the variable 'elt_size' contains the size of an
3008 array element and the variable 'temp' points to enough space to hold a
3009 temp element and the variable 'array' points to the array being sorted
3010 and 'compare' is the pointer to the compare routine.
3012 Also note that there are very many highly architecture specific ways
3013 these might be sped up, but this is simply the most generally portable
3014 code I could think of.
3017 /* Return < 0 == 0 or > 0 as the value of elt1 is < elt2, == elt2, > elt2
3019 #define qsort_cmp(elt1, elt2) \
3020 ((*compare)(array[elt1], array[elt2]))
3022 #ifdef QSORT_ORDER_GUESS
3023 #define QSORT_NOTICE_SWAP swapped++;
3025 #define QSORT_NOTICE_SWAP
3028 /* swaps contents of array elements elt1, elt2.
3030 #define qsort_swap(elt1, elt2) \
3033 temp = array[elt1]; \
3034 array[elt1] = array[elt2]; \
3035 array[elt2] = temp; \
3038 /* rotate contents of elt1, elt2, elt3 such that elt1 gets elt2, elt2 gets
3039 elt3 and elt3 gets elt1.
3041 #define qsort_rotate(elt1, elt2, elt3) \
3044 temp = array[elt1]; \
3045 array[elt1] = array[elt2]; \
3046 array[elt2] = array[elt3]; \
3047 array[elt3] = temp; \
3050 /* ************************************************************ Debug stuff */
3057 return; /* good place to set a breakpoint */
3060 #define qsort_assert(t) (void)( (t) || (break_here(), 0) )
3063 doqsort_all_asserts(
3067 int (*compare)(const void * elt1, const void * elt2),
3068 int pc_left, int pc_right, int u_left, int u_right)
3072 qsort_assert(pc_left <= pc_right);
3073 qsort_assert(u_right < pc_left);
3074 qsort_assert(pc_right < u_left);
3075 for (i = u_right + 1; i < pc_left; ++i) {
3076 qsort_assert(qsort_cmp(i, pc_left) < 0);
3078 for (i = pc_left; i < pc_right; ++i) {
3079 qsort_assert(qsort_cmp(i, pc_right) == 0);
3081 for (i = pc_right + 1; i < u_left; ++i) {
3082 qsort_assert(qsort_cmp(pc_right, i) < 0);
3086 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) \
3087 doqsort_all_asserts(array, num_elts, elt_size, compare, \
3088 PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT)
3092 #define qsort_assert(t) ((void)0)
3094 #define qsort_all_asserts(PC_LEFT, PC_RIGHT, U_LEFT, U_RIGHT) ((void)0)
3098 /* ****************************************************************** qsort */
3104 I32 (*compare)(SV *a, SV *b))
3108 struct partition_stack_entry partition_stack[QSORT_MAX_STACK];
3109 int next_stack_entry = 0;
3113 #ifdef QSORT_ORDER_GUESS
3114 int qsort_break_even;
3118 /* Make sure we actually have work to do.
3120 if (num_elts <= 1) {
3124 /* Setup the initial partition definition and fall into the sorting loop
3127 part_right = (int)(num_elts - 1);
3128 #ifdef QSORT_ORDER_GUESS
3129 qsort_break_even = QSORT_BREAK_EVEN;
3131 #define qsort_break_even QSORT_BREAK_EVEN
3134 if ((part_right - part_left) >= qsort_break_even) {
3135 /* OK, this is gonna get hairy, so lets try to document all the
3136 concepts and abbreviations and variables and what they keep
3139 pc: pivot chunk - the set of array elements we accumulate in the
3140 middle of the partition, all equal in value to the original
3141 pivot element selected. The pc is defined by:
3143 pc_left - the leftmost array index of the pc
3144 pc_right - the rightmost array index of the pc
3146 we start with pc_left == pc_right and only one element
3147 in the pivot chunk (but it can grow during the scan).
3149 u: uncompared elements - the set of elements in the partition
3150 we have not yet compared to the pivot value. There are two
3151 uncompared sets during the scan - one to the left of the pc
3152 and one to the right.
3154 u_right - the rightmost index of the left side's uncompared set
3155 u_left - the leftmost index of the right side's uncompared set
3157 The leftmost index of the left sides's uncompared set
3158 doesn't need its own variable because it is always defined
3159 by the leftmost edge of the whole partition (part_left). The
3160 same goes for the rightmost edge of the right partition
3163 We know there are no uncompared elements on the left once we
3164 get u_right < part_left and no uncompared elements on the
3165 right once u_left > part_right. When both these conditions
3166 are met, we have completed the scan of the partition.
3168 Any elements which are between the pivot chunk and the
3169 uncompared elements should be less than the pivot value on
3170 the left side and greater than the pivot value on the right
3171 side (in fact, the goal of the whole algorithm is to arrange
3172 for that to be true and make the groups of less-than and
3173 greater-then elements into new partitions to sort again).
3175 As you marvel at the complexity of the code and wonder why it
3176 has to be so confusing. Consider some of the things this level
3177 of confusion brings:
3179 Once I do a compare, I squeeze every ounce of juice out of it. I
3180 never do compare calls I don't have to do, and I certainly never
3183 I also never swap any elements unless I can prove there is a
3184 good reason. Many sort algorithms will swap a known value with
3185 an uncompared value just to get things in the right place (or
3186 avoid complexity :-), but that uncompared value, once it gets
3187 compared, may then have to be swapped again. A lot of the
3188 complexity of this code is due to the fact that it never swaps
3189 anything except compared values, and it only swaps them when the
3190 compare shows they are out of position.
3192 int pc_left, pc_right;
3193 int u_right, u_left;
3197 pc_left = ((part_left + part_right) / 2);
3199 u_right = pc_left - 1;
3200 u_left = pc_right + 1;
3202 /* Qsort works best when the pivot value is also the median value
3203 in the partition (unfortunately you can't find the median value
3204 without first sorting :-), so to give the algorithm a helping
3205 hand, we pick 3 elements and sort them and use the median value
3206 of that tiny set as the pivot value.
3208 Some versions of qsort like to use the left middle and right as
3209 the 3 elements to sort so they can insure the ends of the
3210 partition will contain values which will stop the scan in the
3211 compare loop, but when you have to call an arbitrarily complex
3212 routine to do a compare, its really better to just keep track of
3213 array index values to know when you hit the edge of the
3214 partition and avoid the extra compare. An even better reason to
3215 avoid using a compare call is the fact that you can drop off the
3216 edge of the array if someone foolishly provides you with an
3217 unstable compare function that doesn't always provide consistent
3220 So, since it is simpler for us to compare the three adjacent
3221 elements in the middle of the partition, those are the ones we
3222 pick here (conveniently pointed at by u_right, pc_left, and
3223 u_left). The values of the left, center, and right elements
3224 are refered to as l c and r in the following comments.
3227 #ifdef QSORT_ORDER_GUESS
3230 s = qsort_cmp(u_right, pc_left);
3233 s = qsort_cmp(pc_left, u_left);
3234 /* if l < c, c < r - already in order - nothing to do */
3236 /* l < c, c == r - already in order, pc grows */
3238 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3240 /* l < c, c > r - need to know more */
3241 s = qsort_cmp(u_right, u_left);
3243 /* l < c, c > r, l < r - swap c & r to get ordered */
3244 qsort_swap(pc_left, u_left);
3245 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3246 } else if (s == 0) {
3247 /* l < c, c > r, l == r - swap c&r, grow pc */
3248 qsort_swap(pc_left, u_left);
3250 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3252 /* l < c, c > r, l > r - make lcr into rlc to get ordered */
3253 qsort_rotate(pc_left, u_right, u_left);
3254 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3257 } else if (s == 0) {
3259 s = qsort_cmp(pc_left, u_left);
3261 /* l == c, c < r - already in order, grow pc */
3263 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3264 } else if (s == 0) {
3265 /* l == c, c == r - already in order, grow pc both ways */
3268 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3270 /* l == c, c > r - swap l & r, grow pc */
3271 qsort_swap(u_right, u_left);
3273 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3277 s = qsort_cmp(pc_left, u_left);
3279 /* l > c, c < r - need to know more */
3280 s = qsort_cmp(u_right, u_left);
3282 /* l > c, c < r, l < r - swap l & c to get ordered */
3283 qsort_swap(u_right, pc_left);
3284 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3285 } else if (s == 0) {
3286 /* l > c, c < r, l == r - swap l & c, grow pc */
3287 qsort_swap(u_right, pc_left);
3289 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3291 /* l > c, c < r, l > r - rotate lcr into crl to order */
3292 qsort_rotate(u_right, pc_left, u_left);
3293 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3295 } else if (s == 0) {
3296 /* l > c, c == r - swap ends, grow pc */
3297 qsort_swap(u_right, u_left);
3299 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3301 /* l > c, c > r - swap ends to get in order */
3302 qsort_swap(u_right, u_left);
3303 qsort_all_asserts(pc_left, pc_right, u_left + 1, u_right - 1);
3306 /* We now know the 3 middle elements have been compared and
3307 arranged in the desired order, so we can shrink the uncompared
3312 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3314 /* The above massive nested if was the simple part :-). We now have
3315 the middle 3 elements ordered and we need to scan through the
3316 uncompared sets on either side, swapping elements that are on
3317 the wrong side or simply shuffling equal elements around to get
3318 all equal elements into the pivot chunk.
3322 int still_work_on_left;
3323 int still_work_on_right;
3325 /* Scan the uncompared values on the left. If I find a value
3326 equal to the pivot value, move it over so it is adjacent to
3327 the pivot chunk and expand the pivot chunk. If I find a value
3328 less than the pivot value, then just leave it - its already
3329 on the correct side of the partition. If I find a greater
3330 value, then stop the scan.
3332 while (still_work_on_left = (u_right >= part_left)) {
3333 s = qsort_cmp(u_right, pc_left);
3336 } else if (s == 0) {
3338 if (pc_left != u_right) {
3339 qsort_swap(u_right, pc_left);
3345 qsort_assert(u_right < pc_left);
3346 qsort_assert(pc_left <= pc_right);
3347 qsort_assert(qsort_cmp(u_right + 1, pc_left) <= 0);
3348 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3351 /* Do a mirror image scan of uncompared values on the right
3353 while (still_work_on_right = (u_left <= part_right)) {
3354 s = qsort_cmp(pc_right, u_left);
3357 } else if (s == 0) {
3359 if (pc_right != u_left) {
3360 qsort_swap(pc_right, u_left);
3366 qsort_assert(u_left > pc_right);
3367 qsort_assert(pc_left <= pc_right);
3368 qsort_assert(qsort_cmp(pc_right, u_left - 1) <= 0);
3369 qsort_assert(qsort_cmp(pc_left, pc_right) == 0);
3372 if (still_work_on_left) {
3373 /* I know I have a value on the left side which needs to be
3374 on the right side, but I need to know more to decide
3375 exactly the best thing to do with it.
3377 if (still_work_on_right) {
3378 /* I know I have values on both side which are out of
3379 position. This is a big win because I kill two birds
3380 with one swap (so to speak). I can advance the
3381 uncompared pointers on both sides after swapping both
3382 of them into the right place.
3384 qsort_swap(u_right, u_left);
3387 qsort_all_asserts(pc_left, pc_right, u_left, u_right);
3389 /* I have an out of position value on the left, but the
3390 right is fully scanned, so I "slide" the pivot chunk
3391 and any less-than values left one to make room for the
3392 greater value over on the right. If the out of position
3393 value is immediately adjacent to the pivot chunk (there
3394 are no less-than values), I can do that with a swap,
3395 otherwise, I have to rotate one of the less than values
3396 into the former position of the out of position value
3397 and the right end of the pivot chunk into the left end
3401 if (pc_left == u_right) {
3402 qsort_swap(u_right, pc_right);
3403 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3405 qsort_rotate(u_right, pc_left, pc_right);
3406 qsort_all_asserts(pc_left, pc_right-1, u_left, u_right-1);
3411 } else if (still_work_on_right) {
3412 /* Mirror image of complex case above: I have an out of
3413 position value on the right, but the left is fully
3414 scanned, so I need to shuffle things around to make room
3415 for the right value on the left.
3418 if (pc_right == u_left) {
3419 qsort_swap(u_left, pc_left);
3420 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3422 qsort_rotate(pc_right, pc_left, u_left);
3423 qsort_all_asserts(pc_left+1, pc_right, u_left+1, u_right);
3428 /* No more scanning required on either side of partition,
3429 break out of loop and figure out next set of partitions
3435 /* The elements in the pivot chunk are now in the right place. They
3436 will never move or be compared again. All I have to do is decide
3437 what to do with the stuff to the left and right of the pivot
3440 Notes on the QSORT_ORDER_GUESS ifdef code:
3442 1. If I just built these partitions without swapping any (or
3443 very many) elements, there is a chance that the elements are
3444 already ordered properly (being properly ordered will
3445 certainly result in no swapping, but the converse can't be
3448 2. A (properly written) insertion sort will run faster on
3449 already ordered data than qsort will.
3451 3. Perhaps there is some way to make a good guess about
3452 switching to an insertion sort earlier than partition size 6
3453 (for instance - we could save the partition size on the stack
3454 and increase the size each time we find we didn't swap, thus
3455 switching to insertion sort earlier for partitions with a
3456 history of not swapping).
3458 4. Naturally, if I just switch right away, it will make
3459 artificial benchmarks with pure ascending (or descending)
3460 data look really good, but is that a good reason in general?
3464 #ifdef QSORT_ORDER_GUESS
3466 #if QSORT_ORDER_GUESS == 1
3467 qsort_break_even = (part_right - part_left) + 1;
3469 #if QSORT_ORDER_GUESS == 2
3470 qsort_break_even *= 2;
3472 #if QSORT_ORDER_GUESS == 3
3473 int prev_break = qsort_break_even;
3474 qsort_break_even *= qsort_break_even;
3475 if (qsort_break_even < prev_break) {
3476 qsort_break_even = (part_right - part_left) + 1;
3480 qsort_break_even = QSORT_BREAK_EVEN;
3484 if (part_left < pc_left) {
3485 /* There are elements on the left which need more processing.
3486 Check the right as well before deciding what to do.
3488 if (pc_right < part_right) {
3489 /* We have two partitions to be sorted. Stack the biggest one
3490 and process the smallest one on the next iteration. This
3491 minimizes the stack height by insuring that any additional
3492 stack entries must come from the smallest partition which
3493 (because it is smallest) will have the fewest
3494 opportunities to generate additional stack entries.
3496 if ((part_right - pc_right) > (pc_left - part_left)) {
3497 /* stack the right partition, process the left */
3498 partition_stack[next_stack_entry].left = pc_right + 1;
3499 partition_stack[next_stack_entry].right = part_right;
3500 #ifdef QSORT_ORDER_GUESS
3501 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3503 part_right = pc_left - 1;
3505 /* stack the left partition, process the right */
3506 partition_stack[next_stack_entry].left = part_left;
3507 partition_stack[next_stack_entry].right = pc_left - 1;
3508 #ifdef QSORT_ORDER_GUESS
3509 partition_stack[next_stack_entry].qsort_break_even = qsort_break_even;
3511 part_left = pc_right + 1;
3513 qsort_assert(next_stack_entry < QSORT_MAX_STACK);
3516 /* The elements on the left are the only remaining elements
3517 that need sorting, arrange for them to be processed as the
3520 part_right = pc_left - 1;
3522 } else if (pc_right < part_right) {
3523 /* There is only one chunk on the right to be sorted, make it
3524 the new partition and loop back around.
3526 part_left = pc_right + 1;
3528 /* This whole partition wound up in the pivot chunk, so
3529 we need to get a new partition off the stack.
3531 if (next_stack_entry == 0) {
3532 /* the stack is empty - we are done */
3536 part_left = partition_stack[next_stack_entry].left;
3537 part_right = partition_stack[next_stack_entry].right;
3538 #ifdef QSORT_ORDER_GUESS
3539 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3543 /* This partition is too small to fool with qsort complexity, just
3544 do an ordinary insertion sort to minimize overhead.
3547 /* Assume 1st element is in right place already, and start checking
3548 at 2nd element to see where it should be inserted.
3550 for (i = part_left + 1; i <= part_right; ++i) {
3552 /* Scan (backwards - just in case 'i' is already in right place)
3553 through the elements already sorted to see if the ith element
3554 belongs ahead of one of them.
3556 for (j = i - 1; j >= part_left; --j) {
3557 if (qsort_cmp(i, j) >= 0) {
3558 /* i belongs right after j
3565 /* Looks like we really need to move some things
3569 for (k = i - 1; k >= j; --k)
3570 array[k + 1] = array[k];
3575 /* That partition is now sorted, grab the next one, or get out
3576 of the loop if there aren't any more.
3579 if (next_stack_entry == 0) {
3580 /* the stack is empty - we are done */
3584 part_left = partition_stack[next_stack_entry].left;
3585 part_right = partition_stack[next_stack_entry].right;
3586 #ifdef QSORT_ORDER_GUESS
3587 qsort_break_even = partition_stack[next_stack_entry].qsort_break_even;
3592 /* Believe it or not, the array is sorted at this point! */