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