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