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