compiles against 5.8.1 (no threads, no multiplicity)
[p5sagit/Devel-Declare.git] / stolen_chunk_of_toke.c
1 /*    stolen_chunk_of_toke.c - from perl 5.8.8 toke.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999,
4  *    2000, 2001, 2002, 2003, 2004, 2005, 2006, by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *   "It all comes from here, the stench and the peril."  --Frodo
13  */
14
15 /*
16  *   this is all blatantly stolen. I sincerely hopes it doesn't fuck anything
17  *   up but if it does blame me (Matt S Trout), not the poor original authors
18  */
19
20 /* the following #defines are stolen from assorted headers, not toke.c (mst) */
21
22 #define DPTR2FPTR(t,p) ((t)PTR2nat(p))  /* data pointer to function pointer */
23 #define FPTR2DPTR(t,p) ((t)PTR2nat(p))  /* function pointer to data pointer */
24 #define PTR2nat(p)       (PTRV)(p)       /* pointer to integer of PTRSIZE */
25 #define MEM_WRAP_CHECK_(n,t) MEM_WRAP_CHECK(n,t),
26 #define Newx(v,n,t) (v = (MEM_WRAP_CHECK_(n,t) (t*)safemalloc((MEM_SIZE)((n)*sizeof(t)))))
27 #define SvPVX_const(sv) ((const char*) (0 + SvPVX(sv)))
28 #define SvPV_renew(sv,n) \
29   STMT_START { SvLEN_set(sv, n); \
30     SvPV_set((sv), (MEM_WRAP_CHECK_(n,char)     \
31         (char*)saferealloc((Malloc_t)SvPVX(sv), \
32                (MEM_SIZE)((n)))));  \
33      } STMT_END
34
35 /* On MacOS, respect nonbreaking spaces */
36 #ifdef MACOS_TRADITIONAL
37 #define SPACE_OR_TAB(c) ((c)==' '||(c)=='\312'||(c)=='\t')
38 #else
39 #define SPACE_OR_TAB(c) ((c)==' '||(c)=='\t')
40 #endif
41
42 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
43
44 #define LEX_NORMAL    10 /* normal code (ie not within "...")     */
45 #define LEX_INTERPNORMAL   9 /* code within a string, eg "$foo[$x+1]" */
46 #define LEX_INTERPCASEMOD  8 /* expecting a \U, \Q or \E etc          */
47 #define LEX_INTERPPUSH     7 /* starting a new sublex parse level     */
48 #define LEX_INTERPSTART    6 /* expecting the start of a $var         */
49
50            /* at end of code, eg "$x" followed by:  */
51 #define LEX_INTERPEND    5 /* ... eg not one of [, { or ->          */
52 #define LEX_INTERPENDMAYBE   4 /* ... eg one of [, { or ->              */
53
54 #define LEX_INTERPCONCAT   3 /* expecting anything, eg at start of
55                 string or after \E, $foo, etc       */
56 #define LEX_INTERPCONST    2 /* NOT USED */
57 #define LEX_FORMLINE     1 /* expecting a format line               */
58 #define LEX_KNOWNEXT     0 /* next token known; just return it      */
59
60 /* and this one is my own madness (mst) */
61
62 #if PERL_REVISION == 5 && PERL_VERSION == 8 && PERL_SUBVERSION >= 8
63 #define PERL_5_8_8_PLUS
64 #endif
65
66 /* and now we're back to the toke.c stuff again (mst) */
67
68 static const char ident_too_long[] =
69   "Identifier too long";
70 static const char c_without_g[] =
71   "Use of /c modifier is meaningless without /g";
72 static const char c_in_subst[] =
73   "Use of /c modifier is meaningless in s///";
74
75 #ifdef USE_UTF8_SCRIPTS
76 #   define UTF (!IN_BYTES)
77 #else
78 #   define UTF ((PL_linestr && DO_UTF8(PL_linestr)) || (PL_hints & HINT_UTF8))
79 #endif
80
81 /* Invoke the idxth filter function for the current rsfp.        */
82 /* maxlen 0 = read one text line */
83 I32
84 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
85 {
86     filter_t funcp;
87     SV *datasv = NULL;
88
89     if (!PL_rsfp_filters)
90         return -1;
91     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
92         /* Provide a default input filter to make life easy.    */
93         /* Note that we append to the line. This is handy.      */
94         DEBUG_P(PerlIO_printf(Perl_debug_log,
95                               "filter_read %d: from rsfp\n", idx));
96         if (maxlen) {
97             /* Want a block */
98             int len ;
99             const int old_len = SvCUR(buf_sv);
100
101             /* ensure buf_sv is large enough */
102             SvGROW(buf_sv, (STRLEN)(old_len + maxlen)) ;
103             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len, maxlen)) <= 0){
104                 if (PerlIO_error(PL_rsfp))
105                     return -1;          /* error */
106                 else
107                     return 0 ;          /* end of file */
108             }
109             SvCUR_set(buf_sv, old_len + len) ;
110         } else {
111             /* Want a line */
112             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
113                 if (PerlIO_error(PL_rsfp))
114                     return -1;          /* error */
115                 else
116                     return 0 ;          /* end of file */
117             }
118         }
119         return SvCUR(buf_sv);
120     }
121     /* Skip this filter slot if filter has been deleted */
122     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
123         DEBUG_P(PerlIO_printf(Perl_debug_log,
124                               "filter_read %d: skipped (filter deleted)\n",
125                               idx));
126         return FILTER_READ(idx+1, buf_sv, maxlen); /* recurse */
127     }
128     /* Get function pointer hidden within datasv        */
129     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
130     DEBUG_P(PerlIO_printf(Perl_debug_log,
131                           "filter_read %d: via function %p (%s)\n",
132                           idx, datasv, SvPV_nolen_const(datasv)));
133     /* Call function. The function is expected to       */
134     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
135     /* Return: <0:error, =0:eof, >0:not eof             */
136     return (*funcp)(aTHX_ idx, buf_sv, maxlen);
137 }
138
139 STATIC char *
140 S_filter_gets(pTHX_ register SV *sv, register PerlIO *fp, STRLEN append)
141 {
142 #ifdef PERL_CR_FILTER
143     if (!PL_rsfp_filters) {
144         filter_add(S_cr_textfilter,NULL);
145     }
146 #endif
147     if (PL_rsfp_filters) {
148         if (!append)
149             SvCUR_set(sv, 0);   /* start with empty line        */
150         if (FILTER_READ(0, sv, 0) > 0)
151             return ( SvPVX(sv) ) ;
152         else
153             return Nullch ;
154     }
155     else
156         return (sv_gets(sv, fp, append));
157 }
158
159 /*
160  * S_skipspace
161  * Called to gobble the appropriate amount and type of whitespace.
162  * Skips comments as well.
163  */
164
165 STATIC char *
166 S_skipspace(pTHX_ register char *s)
167 {
168     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
169         while (s < PL_bufend && SPACE_OR_TAB(*s))
170             s++;
171         return s;
172     }
173     for (;;) {
174         STRLEN prevlen;
175         SSize_t oldprevlen, oldoldprevlen;
176         SSize_t oldloplen = 0, oldunilen = 0;
177         while (s < PL_bufend && isSPACE(*s)) {
178             if (*s++ == '\n' && PL_in_eval && !PL_rsfp)
179                 incline(s);
180         }
181
182         /* comment */
183         if (s < PL_bufend && *s == '#') {
184             while (s < PL_bufend && *s != '\n')
185                 s++;
186             if (s < PL_bufend) {
187                 s++;
188                 if (PL_in_eval && !PL_rsfp) {
189                     incline(s);
190                     continue;
191                 }
192             }
193         }
194
195         /* only continue to recharge the buffer if we're at the end
196          * of the buffer, we're not reading from a source filter, and
197          * we're in normal lexing mode
198          */
199         if (s < PL_bufend || !PL_rsfp || PL_sublex_info.sub_inwhat ||
200                 PL_lex_state == LEX_FORMLINE)
201             return s;
202
203         /* try to recharge the buffer */
204         if ((s = filter_gets(PL_linestr, PL_rsfp,
205                              (prevlen = SvCUR(PL_linestr)))) == Nullch)
206         {
207             /* end of file.  Add on the -p or -n magic */
208             if (PL_minus_p) {
209                 sv_setpv(PL_linestr,
210                          ";}continue{print or die qq(-p destination: $!\\n);}");
211                 PL_minus_n = PL_minus_p = 0;
212             }
213             else if (PL_minus_n) {
214                 sv_setpvn(PL_linestr, ";}", 2);
215                 PL_minus_n = 0;
216             }
217             else
218                 sv_setpvn(PL_linestr,";", 1);
219
220             /* reset variables for next time we lex */
221             PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = s = PL_linestart
222                 = SvPVX(PL_linestr);
223             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
224             PL_last_lop = PL_last_uni = Nullch;
225
226             /* Close the filehandle.  Could be from -P preprocessor,
227              * STDIN, or a regular file.  If we were reading code from
228              * STDIN (because the commandline held no -e or filename)
229              * then we don't close it, we reset it so the code can
230              * read from STDIN too.
231              */
232
233             if (PL_preprocess && !PL_in_eval)
234                 (void)PerlProc_pclose(PL_rsfp);
235             else if ((PerlIO*)PL_rsfp == PerlIO_stdin())
236                 PerlIO_clearerr(PL_rsfp);
237             else
238                 (void)PerlIO_close(PL_rsfp);
239             PL_rsfp = Nullfp;
240             return s;
241         }
242
243         /* not at end of file, so we only read another line */
244         /* make corresponding updates to old pointers, for yyerror() */
245         oldprevlen = PL_oldbufptr - PL_bufend;
246         oldoldprevlen = PL_oldoldbufptr - PL_bufend;
247         if (PL_last_uni)
248             oldunilen = PL_last_uni - PL_bufend;
249         if (PL_last_lop)
250             oldloplen = PL_last_lop - PL_bufend;
251         PL_linestart = PL_bufptr = s + prevlen;
252         PL_bufend = s + SvCUR(PL_linestr);
253         s = PL_bufptr;
254         PL_oldbufptr = s + oldprevlen;
255         PL_oldoldbufptr = s + oldoldprevlen;
256         if (PL_last_uni)
257             PL_last_uni = s + oldunilen;
258         if (PL_last_lop)
259             PL_last_lop = s + oldloplen;
260         incline(s);
261
262         /* debugger active and we're not compiling the debugger code,
263          * so store the line into the debugger's array of lines
264          */
265         if (PERLDB_LINE && PL_curstash != PL_debstash) {
266             SV * const sv = NEWSV(85,0);
267
268             sv_upgrade(sv, SVt_PVMG);
269             sv_setpvn(sv,PL_bufptr,PL_bufend-PL_bufptr);
270             (void)SvIOK_on(sv);
271             SvIV_set(sv, 0);
272             av_store(CopFILEAV(PL_curcop),(I32)CopLINE(PL_curcop),sv);
273         }
274     }
275 }
276
277 STATIC char *
278 S_scan_word(pTHX_ register char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
279 {
280     register char *d = dest;
281     register char * const e = d + destlen - 3;  /* two-character token, ending NUL */
282     for (;;) {
283         if (d >= e)
284             Perl_croak(aTHX_ ident_too_long);
285         if (isALNUM(*s))        /* UTF handled below */
286             *d++ = *s++;
287         else if (*s == '\'' && allow_package && isIDFIRST_lazy_if(s+1,UTF)) {
288             *d++ = ':';
289             *d++ = ':';
290             s++;
291         }
292         else if (*s == ':' && s[1] == ':' && allow_package && s[2] != '$') {
293             *d++ = *s++;
294             *d++ = *s++;
295         }
296         else if (UTF && UTF8_IS_START(*s) && isALNUM_utf8((U8*)s)) {
297             char *t = s + UTF8SKIP(s);
298             while (UTF8_IS_CONTINUED(*t) && is_utf8_mark((U8*)t))
299                 t += UTF8SKIP(t);
300             if (d + (t - s) > e)
301                 Perl_croak(aTHX_ ident_too_long);
302             Copy(s, d, t - s, char);
303             d += t - s;
304             s = t;
305         }
306         else {
307             *d = '\0';
308             *slp = d - dest;
309             return s;
310         }
311     }
312 }
313
314 /*
315  * S_incline
316  * This subroutine has nothing to do with tilting, whether at windmills
317  * or pinball tables.  Its name is short for "increment line".  It
318  * increments the current line number in CopLINE(PL_curcop) and checks
319  * to see whether the line starts with a comment of the form
320  *    # line 500 "foo.pm"
321  * If so, it sets the current line number and file to the values in the comment.
322  */
323
324 STATIC void
325 S_incline(pTHX_ char *s)
326 {
327     char *t;
328     char *n;
329     char *e;
330     char ch;
331
332     CopLINE_inc(PL_curcop);
333     if (*s++ != '#')
334         return;
335     while (SPACE_OR_TAB(*s)) s++;
336     if (strnEQ(s, "line", 4))
337         s += 4;
338     else
339         return;
340     if (SPACE_OR_TAB(*s))
341         s++;
342     else
343         return;
344     while (SPACE_OR_TAB(*s)) s++;
345     if (!isDIGIT(*s))
346         return;
347     n = s;
348     while (isDIGIT(*s))
349         s++;
350     while (SPACE_OR_TAB(*s))
351         s++;
352     if (*s == '"' && (t = strchr(s+1, '"'))) {
353         s++;
354         e = t + 1;
355     }
356     else {
357         for (t = s; !isSPACE(*t); t++) ;
358         e = t;
359     }
360     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
361         e++;
362     if (*e != '\n' && *e != '\0')
363         return;         /* false alarm */
364
365     ch = *t;
366     *t = '\0';
367     if (t - s > 0) {
368 /* this chunk was added to S_incline during 5.8.8. I don't know why but I don't
369    honestly care since I probably want to be bug-compatible anyway (mst) */
370
371 /* ... my kingdom for a perl parser in perl ... (mst) */
372
373 #ifdef PERL_5_8_8_PLUS
374 #ifndef USE_ITHREADS
375         const char *cf = CopFILE(PL_curcop);
376         if (cf && strlen(cf) > 7 && strnEQ(cf, "(eval ", 6)) {
377             /* must copy *{"::_<(eval N)[oldfilename:L]"}
378              * to *{"::_<newfilename"} */
379             char smallbuf[256], smallbuf2[256];
380             char *tmpbuf, *tmpbuf2;
381             GV **gvp, *gv2;
382             STRLEN tmplen = strlen(cf);
383             STRLEN tmplen2 = strlen(s);
384             if (tmplen + 3 < sizeof smallbuf)
385                 tmpbuf = smallbuf;
386             else
387                 Newx(tmpbuf, tmplen + 3, char);
388             if (tmplen2 + 3 < sizeof smallbuf2)
389                 tmpbuf2 = smallbuf2;
390             else
391                 Newx(tmpbuf2, tmplen2 + 3, char);
392             tmpbuf[0] = tmpbuf2[0] = '_';
393             tmpbuf[1] = tmpbuf2[1] = '<';
394             memcpy(tmpbuf + 2, cf, ++tmplen);
395             memcpy(tmpbuf2 + 2, s, ++tmplen2);
396             ++tmplen; ++tmplen2;
397             gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, FALSE);
398             if (gvp) {
399                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
400                 if (!isGV(gv2))
401                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
402                 /* adjust ${"::_<newfilename"} to store the new file name */
403                 GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
404                 GvHV(gv2) = (HV*)SvREFCNT_inc(GvHV(*gvp));
405                 GvAV(gv2) = (AV*)SvREFCNT_inc(GvAV(*gvp));
406             }
407             if (tmpbuf != smallbuf) Safefree(tmpbuf);
408             if (tmpbuf2 != smallbuf2) Safefree(tmpbuf2);
409         }
410 #endif
411 #endif
412 /* second endif closes out the "are we 5.8.(8+)" conditional */
413         CopFILE_free(PL_curcop);
414         CopFILE_set(PL_curcop, s);
415     }
416     *t = ch;
417     CopLINE_set(PL_curcop, atoi(n)-1);
418 }
419
420 /* scan_str
421    takes: start position in buffer
422           keep_quoted preserve \ on the embedded delimiter(s)
423           keep_delims preserve the delimiters around the string
424    returns: position to continue reading from buffer
425    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
426         updates the read buffer.
427
428    This subroutine pulls a string out of the input.  It is called for:
429         q               single quotes           q(literal text)
430         '               single quotes           'literal text'
431         qq              double quotes           qq(interpolate $here please)
432         "               double quotes           "interpolate $here please"
433         qx              backticks               qx(/bin/ls -l)
434         `               backticks               `/bin/ls -l`
435         qw              quote words             @EXPORT_OK = qw( func() $spam )
436         m//             regexp match            m/this/
437         s///            regexp substitute       s/this/that/
438         tr///           string transliterate    tr/this/that/
439         y///            string transliterate    y/this/that/
440         ($*@)           sub prototypes          sub foo ($)
441         (stuff)         sub attr parameters     sub foo : attr(stuff)
442         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
443         
444    In most of these cases (all but <>, patterns and transliterate)
445    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
446    calls scan_str().  s/// makes yylex() call scan_subst() which calls
447    scan_str().  tr/// and y/// make yylex() call scan_trans() which
448    calls scan_str().
449
450    It skips whitespace before the string starts, and treats the first
451    character as the delimiter.  If the delimiter is one of ([{< then
452    the corresponding "close" character )]}> is used as the closing
453    delimiter.  It allows quoting of delimiters, and if the string has
454    balanced delimiters ([{<>}]) it allows nesting.
455
456    On success, the SV with the resulting string is put into lex_stuff or,
457    if that is already non-NULL, into lex_repl. The second case occurs only
458    when parsing the RHS of the special constructs s/// and tr/// (y///).
459    For convenience, the terminating delimiter character is stuffed into
460    SvIVX of the SV.
461 */
462
463 STATIC char *
464 S_scan_str(pTHX_ char *start, int keep_quoted, int keep_delims)
465 {
466     SV *sv;                             /* scalar value: string */
467     char *tmps;                         /* temp string, used for delimiter matching */
468     register char *s = start;           /* current position in the buffer */
469     register char term;                 /* terminating character */
470     register char *to;                  /* current position in the sv's data */
471     I32 brackets = 1;                   /* bracket nesting level */
472     bool has_utf8 = FALSE;              /* is there any utf8 content? */
473     I32 termcode;                       /* terminating char. code */
474     /* 5.8.7+ uses UTF8_MAXBYTES but also its utf8.h defs _MAXLEN to it so
475        I'm reasonably hopeful this won't destroy anything (mst) */
476     U8 termstr[UTF8_MAXLEN];            /* terminating string */
477     STRLEN termlen;                     /* length of terminating string */
478     char *last = NULL;                  /* last position for nesting bracket */
479
480     /* skip space before the delimiter */
481     if (isSPACE(*s))
482         s = skipspace(s);
483
484     /* mark where we are, in case we need to report errors */
485     CLINE;
486
487     /* after skipping whitespace, the next character is the terminator */
488     term = *s;
489     if (!UTF) {
490         termcode = termstr[0] = term;
491         termlen = 1;
492     }
493     else {
494         termcode = utf8_to_uvchr((U8*)s, &termlen);
495         Copy(s, termstr, termlen, U8);
496         if (!UTF8_IS_INVARIANT(term))
497             has_utf8 = TRUE;
498     }
499
500     /* mark where we are */
501     PL_multi_start = CopLINE(PL_curcop);
502     PL_multi_open = term;
503
504     /* find corresponding closing delimiter */
505     if (term && (tmps = strchr("([{< )]}> )]}>",term)))
506         termcode = termstr[0] = term = tmps[5];
507
508     PL_multi_close = term;
509
510     /* create a new SV to hold the contents.  87 is leak category, I'm
511        assuming.  79 is the SV's initial length.  What a random number. */
512     sv = NEWSV(87,79);
513     sv_upgrade(sv, SVt_PVIV);
514     SvIV_set(sv, termcode);
515     (void)SvPOK_only(sv);               /* validate pointer */
516
517     /* move past delimiter and try to read a complete string */
518     if (keep_delims)
519         sv_catpvn(sv, s, termlen);
520     s += termlen;
521     for (;;) {
522         if (PL_encoding && !UTF) {
523             bool cont = TRUE;
524
525             while (cont) {
526                 int offset = s - SvPVX_const(PL_linestr);
527                 const bool found = sv_cat_decode(sv, PL_encoding, PL_linestr,
528                                            &offset, (char*)termstr, termlen);
529                 const char *ns = SvPVX_const(PL_linestr) + offset;
530                 char *svlast = SvEND(sv) - 1;
531
532                 for (; s < ns; s++) {
533                     if (*s == '\n' && !PL_rsfp)
534                         CopLINE_inc(PL_curcop);
535                 }
536                 if (!found)
537                     goto read_more_line;
538                 else {
539                     /* handle quoted delimiters */
540                     if (SvCUR(sv) > 1 && *(svlast-1) == '\\') {
541                         const char *t;
542                         for (t = svlast-2; t >= SvPVX_const(sv) && *t == '\\';)
543                             t--;
544                         if ((svlast-1 - t) % 2) {
545                             if (!keep_quoted) {
546                                 *(svlast-1) = term;
547                                 *svlast = '\0';
548                                 SvCUR_set(sv, SvCUR(sv) - 1);
549                             }
550                             continue;
551                         }
552                     }
553                     if (PL_multi_open == PL_multi_close) {
554                         cont = FALSE;
555                     }
556                     else {
557                         const char *t;
558                         char *w;
559                         if (!last)
560                             last = SvPVX(sv);
561                         for (t = w = last; t < svlast; w++, t++) {
562                             /* At here, all closes are "was quoted" one,
563                                so we don't check PL_multi_close. */
564                             if (*t == '\\') {
565                                 if (!keep_quoted && *(t+1) == PL_multi_open)
566                                     t++;
567                                 else
568                                     *w++ = *t++;
569                             }
570                             else if (*t == PL_multi_open)
571                                 brackets++;
572
573                             *w = *t;
574                         }
575                         if (w < t) {
576                             *w++ = term;
577                             *w = '\0';
578                             SvCUR_set(sv, w - SvPVX_const(sv));
579                         }
580                         last = w;
581                         if (--brackets <= 0)
582                             cont = FALSE;
583                     }
584                 }
585             }
586             if (!keep_delims) {
587                 SvCUR_set(sv, SvCUR(sv) - 1);
588                 *SvEND(sv) = '\0';
589             }
590             break;
591         }
592
593         /* extend sv if need be */
594         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
595         /* set 'to' to the next character in the sv's string */
596         to = SvPVX(sv)+SvCUR(sv);
597
598         /* if open delimiter is the close delimiter read unbridle */
599         if (PL_multi_open == PL_multi_close) {
600             for (; s < PL_bufend; s++,to++) {
601                 /* embedded newlines increment the current line number */
602                 if (*s == '\n' && !PL_rsfp)
603                     CopLINE_inc(PL_curcop);
604                 /* handle quoted delimiters */
605                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
606                     if (!keep_quoted && s[1] == term)
607                         s++;
608                 /* any other quotes are simply copied straight through */
609                     else
610                         *to++ = *s++;
611                 }
612                 /* terminate when run out of buffer (the for() condition), or
613                    have found the terminator */
614                 else if (*s == term) {
615                     if (termlen == 1)
616                         break;
617                     if (s+termlen <= PL_bufend && memEQ(s, (char*)termstr, termlen))
618                         break;
619                 }
620                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
621                     has_utf8 = TRUE;
622                 *to = *s;
623             }
624         }
625         
626         /* if the terminator isn't the same as the start character (e.g.,
627            matched brackets), we have to allow more in the quoting, and
628            be prepared for nested brackets.
629         */
630         else {
631             /* read until we run out of string, or we find the terminator */
632             for (; s < PL_bufend; s++,to++) {
633                 /* embedded newlines increment the line count */
634                 if (*s == '\n' && !PL_rsfp)
635                     CopLINE_inc(PL_curcop);
636                 /* backslashes can escape the open or closing characters */
637                 if (*s == '\\' && s+1 < PL_bufend) {
638                     if (!keep_quoted &&
639                         ((s[1] == PL_multi_open) || (s[1] == PL_multi_close)))
640                         s++;
641                     else
642                         *to++ = *s++;
643                 }
644                 /* allow nested opens and closes */
645                 else if (*s == PL_multi_close && --brackets <= 0)
646                     break;
647                 else if (*s == PL_multi_open)
648                     brackets++;
649                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
650                     has_utf8 = TRUE;
651                 *to = *s;
652             }
653         }
654         /* terminate the copied string and update the sv's end-of-string */
655         *to = '\0';
656         SvCUR_set(sv, to - SvPVX_const(sv));
657
658         /*
659          * this next chunk reads more into the buffer if we're not done yet
660          */
661
662         if (s < PL_bufend)
663             break;              /* handle case where we are done yet :-) */
664
665 #ifndef PERL_STRICT_CR
666         if (to - SvPVX_const(sv) >= 2) {
667             if ((to[-2] == '\r' && to[-1] == '\n') ||
668                 (to[-2] == '\n' && to[-1] == '\r'))
669             {
670                 to[-2] = '\n';
671                 to--;
672                 SvCUR_set(sv, to - SvPVX_const(sv));
673             }
674             else if (to[-1] == '\r')
675                 to[-1] = '\n';
676         }
677         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
678             to[-1] = '\n';
679 #endif
680         
681      read_more_line:
682         /* if we're out of file, or a read fails, bail and reset the current
683            line marker so we can report where the unterminated string began
684         */
685         if (!PL_rsfp ||
686          !(PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = filter_gets(PL_linestr, PL_rsfp, 0))) {
687             sv_free(sv);
688             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
689             return Nullch;
690         }
691         /* we read a line, so increment our line counter */
692         CopLINE_inc(PL_curcop);
693
694         /* update debugger info */
695         if (PERLDB_LINE && PL_curstash != PL_debstash) {
696             SV *sv = NEWSV(88,0);
697
698             sv_upgrade(sv, SVt_PVMG);
699             sv_setsv(sv,PL_linestr);
700             (void)SvIOK_on(sv);
701             SvIV_set(sv, 0);
702             av_store(CopFILEAV(PL_curcop), (I32)CopLINE(PL_curcop), sv);
703         }
704
705         /* having changed the buffer, we must update PL_bufend */
706         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
707         PL_last_lop = PL_last_uni = Nullch;
708     }
709
710     /* at this point, we have successfully read the delimited string */
711
712     if (!PL_encoding || UTF) {
713         if (keep_delims)
714             sv_catpvn(sv, s, termlen);
715         s += termlen;
716     }
717     if (has_utf8 || PL_encoding)
718         SvUTF8_on(sv);
719
720     PL_multi_end = CopLINE(PL_curcop);
721
722     /* if we allocated too much space, give some back */
723     if (SvCUR(sv) + 5 < SvLEN(sv)) {
724         SvLEN_set(sv, SvCUR(sv) + 1);
725 /* 5.8.8 uses SvPV_renew, no prior version actually has the damn thing (mst) */
726 #ifdef PERL_5_8_8_PLUS
727         SvPV_renew(sv, SvLEN(sv));
728 #else
729         Renew(SvPVX(sv), SvLEN(sv), char);
730 #endif
731     }
732
733     /* decide whether this is the first or second quoted string we've read
734        for this op
735     */
736
737     if (PL_lex_stuff)
738         PL_lex_repl = sv;
739     else
740         PL_lex_stuff = sv;
741     return s;
742 }
743
744 /*
745  * S_force_next
746  * When the lexer realizes it knows the next token (for instance,
747  * it is reordering tokens for the parser) then it can call S_force_next
748  * to know what token to return the next time the lexer is called.  Caller
749  * will need to set PL_nextval[], and possibly PL_expect to ensure the lexer
750  * handles the token correctly.
751  */
752
753 STATIC void
754 S_force_next(pTHX_ I32 type)
755 {
756     PL_nexttype[PL_nexttoke] = type;
757     PL_nexttoke++;
758     if (PL_lex_state != LEX_KNOWNEXT) {
759   PL_lex_defer = PL_lex_state;
760   PL_lex_expect = PL_expect;
761   PL_lex_state = LEX_KNOWNEXT;
762     }
763 }