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