1 /* stolen_chunk_of_toke.c - from perl 5.8.8 toke.c
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
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.
12 * "It all comes from here, the stench and the peril." --Frodo
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
20 /* the following #defines are stolen from assorted headers, not toke.c */
22 #define DPTR2FPTR(t,p) ((t)PTR2nat(p)) /* data pointer to function pointer */
23 #define FPTR2DPTR(t,p) ((t)PTR2nat(p)) /* function pointer to data pointer */
24 #define PTR2nat(p) (PTRV)(p) /* pointer to integer of PTRSIZE */
25 #define MEM_WRAP_CHECK_(n,t) MEM_WRAP_CHECK(n,t),
26 #define Newx(v,n,t) (v = (MEM_WRAP_CHECK_(n,t) (t*)safemalloc((MEM_SIZE)((n)*sizeof(t)))))
27 #define SvPVX_const(sv) ((const char*) (0 + SvPVX(sv)))
28 #define SvPV_renew(sv,n) \
29 STMT_START { SvLEN_set(sv, n); \
30 SvPV_set((sv), (MEM_WRAP_CHECK_(n,char) \
31 (char*)saferealloc((Malloc_t)SvPVX(sv), \
35 /* On MacOS, respect nonbreaking spaces */
36 #ifdef MACOS_TRADITIONAL
37 #define SPACE_OR_TAB(c) ((c)==' '||(c)=='\312'||(c)=='\t')
39 #define SPACE_OR_TAB(c) ((c)==' '||(c)=='\t')
42 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
44 #define LEX_NORMAL 10 /* normal code (ie not within "...") */
45 #define LEX_INTERPNORMAL 9 /* code within a string, eg "$foo[$x+1]" */
46 #define LEX_INTERPCASEMOD 8 /* expecting a \U, \Q or \E etc */
47 #define LEX_INTERPPUSH 7 /* starting a new sublex parse level */
48 #define LEX_INTERPSTART 6 /* expecting the start of a $var */
50 /* at end of code, eg "$x" followed by: */
51 #define LEX_INTERPEND 5 /* ... eg not one of [, { or -> */
52 #define LEX_INTERPENDMAYBE 4 /* ... eg one of [, { or -> */
54 #define LEX_INTERPCONCAT 3 /* expecting anything, eg at start of
55 string or after \E, $foo, etc */
56 #define LEX_INTERPCONST 2 /* NOT USED */
57 #define LEX_FORMLINE 1 /* expecting a format line */
58 #define LEX_KNOWNEXT 0 /* next token known; just return it */
60 static const char ident_too_long[] =
61 "Identifier too long";
62 static const char c_without_g[] =
63 "Use of /c modifier is meaningless without /g";
64 static const char c_in_subst[] =
65 "Use of /c modifier is meaningless in s///";
67 #ifdef USE_UTF8_SCRIPTS
68 # define UTF (!IN_BYTES)
70 # define UTF ((PL_linestr && DO_UTF8(PL_linestr)) || (PL_hints & HINT_UTF8))
73 /* Invoke the idxth filter function for the current rsfp. */
74 /* maxlen 0 = read one text line */
76 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
83 if (idx > AvFILLp(PL_rsfp_filters)) { /* Any more filters? */
84 /* Provide a default input filter to make life easy. */
85 /* Note that we append to the line. This is handy. */
86 DEBUG_P(PerlIO_printf(Perl_debug_log,
87 "filter_read %d: from rsfp\n", idx));
91 const int old_len = SvCUR(buf_sv);
93 /* ensure buf_sv is large enough */
94 SvGROW(buf_sv, (STRLEN)(old_len + maxlen)) ;
95 if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len, maxlen)) <= 0){
96 if (PerlIO_error(PL_rsfp))
97 return -1; /* error */
99 return 0 ; /* end of file */
101 SvCUR_set(buf_sv, old_len + len) ;
104 if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
105 if (PerlIO_error(PL_rsfp))
106 return -1; /* error */
108 return 0 ; /* end of file */
111 return SvCUR(buf_sv);
113 /* Skip this filter slot if filter has been deleted */
114 if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
115 DEBUG_P(PerlIO_printf(Perl_debug_log,
116 "filter_read %d: skipped (filter deleted)\n",
118 return FILTER_READ(idx+1, buf_sv, maxlen); /* recurse */
120 /* Get function pointer hidden within datasv */
121 funcp = DPTR2FPTR(filter_t, IoANY(datasv));
122 DEBUG_P(PerlIO_printf(Perl_debug_log,
123 "filter_read %d: via function %p (%s)\n",
124 idx, datasv, SvPV_nolen_const(datasv)));
125 /* Call function. The function is expected to */
126 /* call "FILTER_READ(idx+1, buf_sv)" first. */
127 /* Return: <0:error, =0:eof, >0:not eof */
128 return (*funcp)(aTHX_ idx, buf_sv, maxlen);
132 S_filter_gets(pTHX_ register SV *sv, register PerlIO *fp, STRLEN append)
134 #ifdef PERL_CR_FILTER
135 if (!PL_rsfp_filters) {
136 filter_add(S_cr_textfilter,NULL);
139 if (PL_rsfp_filters) {
141 SvCUR_set(sv, 0); /* start with empty line */
142 if (FILTER_READ(0, sv, 0) > 0)
143 return ( SvPVX(sv) ) ;
148 return (sv_gets(sv, fp, append));
153 * Called to gobble the appropriate amount and type of whitespace.
154 * Skips comments as well.
158 S_skipspace(pTHX_ register char *s)
160 if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
161 while (s < PL_bufend && SPACE_OR_TAB(*s))
167 SSize_t oldprevlen, oldoldprevlen;
168 SSize_t oldloplen = 0, oldunilen = 0;
169 while (s < PL_bufend && isSPACE(*s)) {
170 if (*s++ == '\n' && PL_in_eval && !PL_rsfp)
175 if (s < PL_bufend && *s == '#') {
176 while (s < PL_bufend && *s != '\n')
180 if (PL_in_eval && !PL_rsfp) {
187 /* only continue to recharge the buffer if we're at the end
188 * of the buffer, we're not reading from a source filter, and
189 * we're in normal lexing mode
191 if (s < PL_bufend || !PL_rsfp || PL_sublex_info.sub_inwhat ||
192 PL_lex_state == LEX_FORMLINE)
195 /* try to recharge the buffer */
196 if ((s = filter_gets(PL_linestr, PL_rsfp,
197 (prevlen = SvCUR(PL_linestr)))) == Nullch)
199 /* end of file. Add on the -p or -n magic */
202 ";}continue{print or die qq(-p destination: $!\\n);}");
203 PL_minus_n = PL_minus_p = 0;
205 else if (PL_minus_n) {
206 sv_setpvn(PL_linestr, ";}", 2);
210 sv_setpvn(PL_linestr,";", 1);
212 /* reset variables for next time we lex */
213 PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = s = PL_linestart
215 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
216 PL_last_lop = PL_last_uni = Nullch;
218 /* Close the filehandle. Could be from -P preprocessor,
219 * STDIN, or a regular file. If we were reading code from
220 * STDIN (because the commandline held no -e or filename)
221 * then we don't close it, we reset it so the code can
222 * read from STDIN too.
225 if (PL_preprocess && !PL_in_eval)
226 (void)PerlProc_pclose(PL_rsfp);
227 else if ((PerlIO*)PL_rsfp == PerlIO_stdin())
228 PerlIO_clearerr(PL_rsfp);
230 (void)PerlIO_close(PL_rsfp);
235 /* not at end of file, so we only read another line */
236 /* make corresponding updates to old pointers, for yyerror() */
237 oldprevlen = PL_oldbufptr - PL_bufend;
238 oldoldprevlen = PL_oldoldbufptr - PL_bufend;
240 oldunilen = PL_last_uni - PL_bufend;
242 oldloplen = PL_last_lop - PL_bufend;
243 PL_linestart = PL_bufptr = s + prevlen;
244 PL_bufend = s + SvCUR(PL_linestr);
246 PL_oldbufptr = s + oldprevlen;
247 PL_oldoldbufptr = s + oldoldprevlen;
249 PL_last_uni = s + oldunilen;
251 PL_last_lop = s + oldloplen;
254 /* debugger active and we're not compiling the debugger code,
255 * so store the line into the debugger's array of lines
257 if (PERLDB_LINE && PL_curstash != PL_debstash) {
258 SV * const sv = NEWSV(85,0);
260 sv_upgrade(sv, SVt_PVMG);
261 sv_setpvn(sv,PL_bufptr,PL_bufend-PL_bufptr);
264 av_store(CopFILEAV(PL_curcop),(I32)CopLINE(PL_curcop),sv);
270 S_scan_word(pTHX_ register char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
272 register char *d = dest;
273 register char * const e = d + destlen - 3; /* two-character token, ending NUL */
276 Perl_croak(aTHX_ ident_too_long);
277 if (isALNUM(*s)) /* UTF handled below */
279 else if (*s == '\'' && allow_package && isIDFIRST_lazy_if(s+1,UTF)) {
284 else if (*s == ':' && s[1] == ':' && allow_package && s[2] != '$') {
288 else if (UTF && UTF8_IS_START(*s) && isALNUM_utf8((U8*)s)) {
289 char *t = s + UTF8SKIP(s);
290 while (UTF8_IS_CONTINUED(*t) && is_utf8_mark((U8*)t))
293 Perl_croak(aTHX_ ident_too_long);
294 Copy(s, d, t - s, char);
308 * This subroutine has nothing to do with tilting, whether at windmills
309 * or pinball tables. Its name is short for "increment line". It
310 * increments the current line number in CopLINE(PL_curcop) and checks
311 * to see whether the line starts with a comment of the form
312 * # line 500 "foo.pm"
313 * If so, it sets the current line number and file to the values in the comment.
317 S_incline(pTHX_ char *s)
324 CopLINE_inc(PL_curcop);
327 while (SPACE_OR_TAB(*s)) s++;
328 if (strnEQ(s, "line", 4))
332 if (SPACE_OR_TAB(*s))
336 while (SPACE_OR_TAB(*s)) s++;
342 while (SPACE_OR_TAB(*s))
344 if (*s == '"' && (t = strchr(s+1, '"'))) {
349 for (t = s; !isSPACE(*t); t++) ;
352 while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
354 if (*e != '\n' && *e != '\0')
355 return; /* false alarm */
361 const char *cf = CopFILE(PL_curcop);
362 if (cf && strlen(cf) > 7 && strnEQ(cf, "(eval ", 6)) {
363 /* must copy *{"::_<(eval N)[oldfilename:L]"}
364 * to *{"::_<newfilename"} */
365 char smallbuf[256], smallbuf2[256];
366 char *tmpbuf, *tmpbuf2;
368 STRLEN tmplen = strlen(cf);
369 STRLEN tmplen2 = strlen(s);
370 if (tmplen + 3 < sizeof smallbuf)
373 Newx(tmpbuf, tmplen + 3, char);
374 if (tmplen2 + 3 < sizeof smallbuf2)
377 Newx(tmpbuf2, tmplen2 + 3, char);
378 tmpbuf[0] = tmpbuf2[0] = '_';
379 tmpbuf[1] = tmpbuf2[1] = '<';
380 memcpy(tmpbuf + 2, cf, ++tmplen);
381 memcpy(tmpbuf2 + 2, s, ++tmplen2);
383 gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, FALSE);
385 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
387 gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
388 /* adjust ${"::_<newfilename"} to store the new file name */
389 GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
390 GvHV(gv2) = (HV*)SvREFCNT_inc(GvHV(*gvp));
391 GvAV(gv2) = (AV*)SvREFCNT_inc(GvAV(*gvp));
393 if (tmpbuf != smallbuf) Safefree(tmpbuf);
394 if (tmpbuf2 != smallbuf2) Safefree(tmpbuf2);
397 CopFILE_free(PL_curcop);
398 CopFILE_set(PL_curcop, s);
401 CopLINE_set(PL_curcop, atoi(n)-1);
405 takes: start position in buffer
406 keep_quoted preserve \ on the embedded delimiter(s)
407 keep_delims preserve the delimiters around the string
408 returns: position to continue reading from buffer
409 side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
410 updates the read buffer.
412 This subroutine pulls a string out of the input. It is called for:
413 q single quotes q(literal text)
414 ' single quotes 'literal text'
415 qq double quotes qq(interpolate $here please)
416 " double quotes "interpolate $here please"
417 qx backticks qx(/bin/ls -l)
418 ` backticks `/bin/ls -l`
419 qw quote words @EXPORT_OK = qw( func() $spam )
420 m// regexp match m/this/
421 s/// regexp substitute s/this/that/
422 tr/// string transliterate tr/this/that/
423 y/// string transliterate y/this/that/
424 ($*@) sub prototypes sub foo ($)
425 (stuff) sub attr parameters sub foo : attr(stuff)
426 <> readline or globs <FOO>, <>, <$fh>, or <*.c>
428 In most of these cases (all but <>, patterns and transliterate)
429 yylex() calls scan_str(). m// makes yylex() call scan_pat() which
430 calls scan_str(). s/// makes yylex() call scan_subst() which calls
431 scan_str(). tr/// and y/// make yylex() call scan_trans() which
434 It skips whitespace before the string starts, and treats the first
435 character as the delimiter. If the delimiter is one of ([{< then
436 the corresponding "close" character )]}> is used as the closing
437 delimiter. It allows quoting of delimiters, and if the string has
438 balanced delimiters ([{<>}]) it allows nesting.
440 On success, the SV with the resulting string is put into lex_stuff or,
441 if that is already non-NULL, into lex_repl. The second case occurs only
442 when parsing the RHS of the special constructs s/// and tr/// (y///).
443 For convenience, the terminating delimiter character is stuffed into
448 S_scan_str(pTHX_ char *start, int keep_quoted, int keep_delims)
450 SV *sv; /* scalar value: string */
451 char *tmps; /* temp string, used for delimiter matching */
452 register char *s = start; /* current position in the buffer */
453 register char term; /* terminating character */
454 register char *to; /* current position in the sv's data */
455 I32 brackets = 1; /* bracket nesting level */
456 bool has_utf8 = FALSE; /* is there any utf8 content? */
457 I32 termcode; /* terminating char. code */
458 U8 termstr[UTF8_MAXBYTES]; /* terminating string */
459 STRLEN termlen; /* length of terminating string */
460 char *last = NULL; /* last position for nesting bracket */
462 /* skip space before the delimiter */
466 /* mark where we are, in case we need to report errors */
469 /* after skipping whitespace, the next character is the terminator */
472 termcode = termstr[0] = term;
476 termcode = utf8_to_uvchr((U8*)s, &termlen);
477 Copy(s, termstr, termlen, U8);
478 if (!UTF8_IS_INVARIANT(term))
482 /* mark where we are */
483 PL_multi_start = CopLINE(PL_curcop);
484 PL_multi_open = term;
486 /* find corresponding closing delimiter */
487 if (term && (tmps = strchr("([{< )]}> )]}>",term)))
488 termcode = termstr[0] = term = tmps[5];
490 PL_multi_close = term;
492 /* create a new SV to hold the contents. 87 is leak category, I'm
493 assuming. 79 is the SV's initial length. What a random number. */
495 sv_upgrade(sv, SVt_PVIV);
496 SvIV_set(sv, termcode);
497 (void)SvPOK_only(sv); /* validate pointer */
499 /* move past delimiter and try to read a complete string */
501 sv_catpvn(sv, s, termlen);
504 if (PL_encoding && !UTF) {
508 int offset = s - SvPVX_const(PL_linestr);
509 const bool found = sv_cat_decode(sv, PL_encoding, PL_linestr,
510 &offset, (char*)termstr, termlen);
511 const char *ns = SvPVX_const(PL_linestr) + offset;
512 char *svlast = SvEND(sv) - 1;
514 for (; s < ns; s++) {
515 if (*s == '\n' && !PL_rsfp)
516 CopLINE_inc(PL_curcop);
521 /* handle quoted delimiters */
522 if (SvCUR(sv) > 1 && *(svlast-1) == '\\') {
524 for (t = svlast-2; t >= SvPVX_const(sv) && *t == '\\';)
526 if ((svlast-1 - t) % 2) {
530 SvCUR_set(sv, SvCUR(sv) - 1);
535 if (PL_multi_open == PL_multi_close) {
543 for (t = w = last; t < svlast; w++, t++) {
544 /* At here, all closes are "was quoted" one,
545 so we don't check PL_multi_close. */
547 if (!keep_quoted && *(t+1) == PL_multi_open)
552 else if (*t == PL_multi_open)
560 SvCUR_set(sv, w - SvPVX_const(sv));
569 SvCUR_set(sv, SvCUR(sv) - 1);
575 /* extend sv if need be */
576 SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
577 /* set 'to' to the next character in the sv's string */
578 to = SvPVX(sv)+SvCUR(sv);
580 /* if open delimiter is the close delimiter read unbridle */
581 if (PL_multi_open == PL_multi_close) {
582 for (; s < PL_bufend; s++,to++) {
583 /* embedded newlines increment the current line number */
584 if (*s == '\n' && !PL_rsfp)
585 CopLINE_inc(PL_curcop);
586 /* handle quoted delimiters */
587 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
588 if (!keep_quoted && s[1] == term)
590 /* any other quotes are simply copied straight through */
594 /* terminate when run out of buffer (the for() condition), or
595 have found the terminator */
596 else if (*s == term) {
599 if (s+termlen <= PL_bufend && memEQ(s, (char*)termstr, termlen))
602 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
608 /* if the terminator isn't the same as the start character (e.g.,
609 matched brackets), we have to allow more in the quoting, and
610 be prepared for nested brackets.
613 /* read until we run out of string, or we find the terminator */
614 for (; s < PL_bufend; s++,to++) {
615 /* embedded newlines increment the line count */
616 if (*s == '\n' && !PL_rsfp)
617 CopLINE_inc(PL_curcop);
618 /* backslashes can escape the open or closing characters */
619 if (*s == '\\' && s+1 < PL_bufend) {
621 ((s[1] == PL_multi_open) || (s[1] == PL_multi_close)))
626 /* allow nested opens and closes */
627 else if (*s == PL_multi_close && --brackets <= 0)
629 else if (*s == PL_multi_open)
631 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
636 /* terminate the copied string and update the sv's end-of-string */
638 SvCUR_set(sv, to - SvPVX_const(sv));
641 * this next chunk reads more into the buffer if we're not done yet
645 break; /* handle case where we are done yet :-) */
647 #ifndef PERL_STRICT_CR
648 if (to - SvPVX_const(sv) >= 2) {
649 if ((to[-2] == '\r' && to[-1] == '\n') ||
650 (to[-2] == '\n' && to[-1] == '\r'))
654 SvCUR_set(sv, to - SvPVX_const(sv));
656 else if (to[-1] == '\r')
659 else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
664 /* if we're out of file, or a read fails, bail and reset the current
665 line marker so we can report where the unterminated string began
668 !(PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = filter_gets(PL_linestr, PL_rsfp, 0))) {
670 CopLINE_set(PL_curcop, (line_t)PL_multi_start);
673 /* we read a line, so increment our line counter */
674 CopLINE_inc(PL_curcop);
676 /* update debugger info */
677 if (PERLDB_LINE && PL_curstash != PL_debstash) {
678 SV *sv = NEWSV(88,0);
680 sv_upgrade(sv, SVt_PVMG);
681 sv_setsv(sv,PL_linestr);
684 av_store(CopFILEAV(PL_curcop), (I32)CopLINE(PL_curcop), sv);
687 /* having changed the buffer, we must update PL_bufend */
688 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
689 PL_last_lop = PL_last_uni = Nullch;
692 /* at this point, we have successfully read the delimited string */
694 if (!PL_encoding || UTF) {
696 sv_catpvn(sv, s, termlen);
699 if (has_utf8 || PL_encoding)
702 PL_multi_end = CopLINE(PL_curcop);
704 /* if we allocated too much space, give some back */
705 if (SvCUR(sv) + 5 < SvLEN(sv)) {
706 SvLEN_set(sv, SvCUR(sv) + 1);
707 SvPV_renew(sv, SvLEN(sv));
710 /* decide whether this is the first or second quoted string we've read
723 * When the lexer realizes it knows the next token (for instance,
724 * it is reordering tokens for the parser) then it can call S_force_next
725 * to know what token to return the next time the lexer is called. Caller
726 * will need to set PL_nextval[], and possibly PL_expect to ensure the lexer
727 * handles the token correctly.
731 S_force_next(pTHX_ I32 type)
733 PL_nexttype[PL_nexttoke] = type;
735 if (PL_lex_state != LEX_KNOWNEXT) {
736 PL_lex_defer = PL_lex_state;
737 PL_lex_expect = PL_expect;
738 PL_lex_state = LEX_KNOWNEXT;