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