This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Revert "Revert "* Fixed typo in toke.c docs, identified by Zefram""
[perl5.git] / toke.c
1 /*    toke.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 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  *     [p.719 of _The Lord of the Rings_, IV/ix: "Shelob's Lair"]
15  */
16
17 /*
18  * This file is the lexer for Perl.  It's closely linked to the
19  * parser, perly.y.
20  *
21  * The main routine is yylex(), which returns the next token.
22  */
23
24 /*
25 =head1 Lexer interface
26
27 This is the lower layer of the Perl parser, managing characters and tokens.
28
29 =for apidoc AmU|yy_parser *|PL_parser
30
31 Pointer to a structure encapsulating the state of the parsing operation
32 currently in progress.  The pointer can be locally changed to perform
33 a nested parse without interfering with the state of an outer parse.
34 Individual members of C<PL_parser> have their own documentation.
35
36 =cut
37 */
38
39 #include "EXTERN.h"
40 #define PERL_IN_TOKE_C
41 #include "perl.h"
42
43 #define new_constant(a,b,c,d,e,f,g)     \
44         S_new_constant(aTHX_ a,b,STR_WITH_LEN(c),d,e,f, g)
45
46 #define pl_yylval       (PL_parser->yylval)
47
48 /* YYINITDEPTH -- initial size of the parser's stacks.  */
49 #define YYINITDEPTH 200
50
51 /* XXX temporary backwards compatibility */
52 #define PL_lex_brackets         (PL_parser->lex_brackets)
53 #define PL_lex_brackstack       (PL_parser->lex_brackstack)
54 #define PL_lex_casemods         (PL_parser->lex_casemods)
55 #define PL_lex_casestack        (PL_parser->lex_casestack)
56 #define PL_lex_defer            (PL_parser->lex_defer)
57 #define PL_lex_dojoin           (PL_parser->lex_dojoin)
58 #define PL_lex_expect           (PL_parser->lex_expect)
59 #define PL_lex_formbrack        (PL_parser->lex_formbrack)
60 #define PL_lex_inpat            (PL_parser->lex_inpat)
61 #define PL_lex_inwhat           (PL_parser->lex_inwhat)
62 #define PL_lex_op               (PL_parser->lex_op)
63 #define PL_lex_repl             (PL_parser->lex_repl)
64 #define PL_lex_starts           (PL_parser->lex_starts)
65 #define PL_lex_stuff            (PL_parser->lex_stuff)
66 #define PL_multi_start          (PL_parser->multi_start)
67 #define PL_multi_open           (PL_parser->multi_open)
68 #define PL_multi_close          (PL_parser->multi_close)
69 #define PL_pending_ident        (PL_parser->pending_ident)
70 #define PL_preambled            (PL_parser->preambled)
71 #define PL_sublex_info          (PL_parser->sublex_info)
72 #define PL_linestr              (PL_parser->linestr)
73 #define PL_expect               (PL_parser->expect)
74 #define PL_copline              (PL_parser->copline)
75 #define PL_bufptr               (PL_parser->bufptr)
76 #define PL_oldbufptr            (PL_parser->oldbufptr)
77 #define PL_oldoldbufptr         (PL_parser->oldoldbufptr)
78 #define PL_linestart            (PL_parser->linestart)
79 #define PL_bufend               (PL_parser->bufend)
80 #define PL_last_uni             (PL_parser->last_uni)
81 #define PL_last_lop             (PL_parser->last_lop)
82 #define PL_last_lop_op          (PL_parser->last_lop_op)
83 #define PL_lex_state            (PL_parser->lex_state)
84 #define PL_rsfp                 (PL_parser->rsfp)
85 #define PL_rsfp_filters         (PL_parser->rsfp_filters)
86 #define PL_in_my                (PL_parser->in_my)
87 #define PL_in_my_stash          (PL_parser->in_my_stash)
88 #define PL_tokenbuf             (PL_parser->tokenbuf)
89 #define PL_multi_end            (PL_parser->multi_end)
90 #define PL_error_count          (PL_parser->error_count)
91
92 #ifdef PERL_MAD
93 #  define PL_endwhite           (PL_parser->endwhite)
94 #  define PL_faketokens         (PL_parser->faketokens)
95 #  define PL_lasttoke           (PL_parser->lasttoke)
96 #  define PL_nextwhite          (PL_parser->nextwhite)
97 #  define PL_realtokenstart     (PL_parser->realtokenstart)
98 #  define PL_skipwhite          (PL_parser->skipwhite)
99 #  define PL_thisclose          (PL_parser->thisclose)
100 #  define PL_thismad            (PL_parser->thismad)
101 #  define PL_thisopen           (PL_parser->thisopen)
102 #  define PL_thisstuff          (PL_parser->thisstuff)
103 #  define PL_thistoken          (PL_parser->thistoken)
104 #  define PL_thiswhite          (PL_parser->thiswhite)
105 #  define PL_thiswhite          (PL_parser->thiswhite)
106 #  define PL_nexttoke           (PL_parser->nexttoke)
107 #  define PL_curforce           (PL_parser->curforce)
108 #else
109 #  define PL_nexttoke           (PL_parser->nexttoke)
110 #  define PL_nexttype           (PL_parser->nexttype)
111 #  define PL_nextval            (PL_parser->nextval)
112 #endif
113
114 /* This can't be done with embed.fnc, because struct yy_parser contains a
115    member named pending_ident, which clashes with the generated #define  */
116 static int
117 S_pending_ident(pTHX);
118
119 static const char ident_too_long[] = "Identifier too long";
120
121 #ifdef PERL_MAD
122 #  define CURMAD(slot,sv) if (PL_madskills) { curmad(slot,sv); sv = 0; }
123 #  define NEXTVAL_NEXTTOKE PL_nexttoke[PL_curforce].next_val
124 #else
125 #  define CURMAD(slot,sv)
126 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
127 #endif
128
129 #define XFAKEBRACK 128
130 #define XENUMMASK 127
131
132 #ifdef USE_UTF8_SCRIPTS
133 #   define UTF (!IN_BYTES)
134 #else
135 #   define UTF ((PL_linestr && DO_UTF8(PL_linestr)) || (PL_hints & HINT_UTF8))
136 #endif
137
138 /* The maximum number of characters preceding the unrecognized one to display */
139 #define UNRECOGNIZED_PRECEDE_COUNT 10
140
141 /* In variables named $^X, these are the legal values for X.
142  * 1999-02-27 mjd-perl-patch@plover.com */
143 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
144
145 #define SPACE_OR_TAB(c) ((c)==' '||(c)=='\t')
146
147 /* LEX_* are values for PL_lex_state, the state of the lexer.
148  * They are arranged oddly so that the guard on the switch statement
149  * can get by with a single comparison (if the compiler is smart enough).
150  */
151
152 /* #define LEX_NOTPARSING               11 is done in perl.h. */
153
154 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
155 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
156 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
157 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
158 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
159
160                                    /* at end of code, eg "$x" followed by:  */
161 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
162 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
163
164 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
165                                         string or after \E, $foo, etc       */
166 #define LEX_INTERPCONST          2 /* NOT USED */
167 #define LEX_FORMLINE             1 /* expecting a format line               */
168 #define LEX_KNOWNEXT             0 /* next token known; just return it      */
169
170
171 #ifdef DEBUGGING
172 static const char* const lex_state_names[] = {
173     "KNOWNEXT",
174     "FORMLINE",
175     "INTERPCONST",
176     "INTERPCONCAT",
177     "INTERPENDMAYBE",
178     "INTERPEND",
179     "INTERPSTART",
180     "INTERPPUSH",
181     "INTERPCASEMOD",
182     "INTERPNORMAL",
183     "NORMAL"
184 };
185 #endif
186
187 #ifdef ff_next
188 #undef ff_next
189 #endif
190
191 #include "keywords.h"
192
193 /* CLINE is a macro that ensures PL_copline has a sane value */
194
195 #ifdef CLINE
196 #undef CLINE
197 #endif
198 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
199
200 #ifdef PERL_MAD
201 #  define SKIPSPACE0(s) skipspace0(s)
202 #  define SKIPSPACE1(s) skipspace1(s)
203 #  define SKIPSPACE2(s,tsv) skipspace2(s,&tsv)
204 #  define PEEKSPACE(s) skipspace2(s,0)
205 #else
206 #  define SKIPSPACE0(s) skipspace(s)
207 #  define SKIPSPACE1(s) skipspace(s)
208 #  define SKIPSPACE2(s,tsv) skipspace(s)
209 #  define PEEKSPACE(s) skipspace(s)
210 #endif
211
212 /*
213  * Convenience functions to return different tokens and prime the
214  * lexer for the next token.  They all take an argument.
215  *
216  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
217  * OPERATOR     : generic operator
218  * AOPERATOR    : assignment operator
219  * PREBLOCK     : beginning the block after an if, while, foreach, ...
220  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
221  * PREREF       : *EXPR where EXPR is not a simple identifier
222  * TERM         : expression term
223  * LOOPX        : loop exiting command (goto, last, dump, etc)
224  * FTST         : file test operator
225  * FUN0         : zero-argument function
226  * FUN1         : not used, except for not, which isn't a UNIOP
227  * BOop         : bitwise or or xor
228  * BAop         : bitwise and
229  * SHop         : shift operator
230  * PWop         : power operator
231  * PMop         : pattern-matching operator
232  * Aop          : addition-level operator
233  * Mop          : multiplication-level operator
234  * Eop          : equality-testing operator
235  * Rop          : relational operator <= != gt
236  *
237  * Also see LOP and lop() below.
238  */
239
240 #ifdef DEBUGGING /* Serve -DT. */
241 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
242 #else
243 #   define REPORT(retval) (retval)
244 #endif
245
246 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
247 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
248 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, REPORT(retval)))
249 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
250 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
251 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
252 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
253 #define LOOPX(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)LOOPEX))
254 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
255 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
256 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
257 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)BITOROP)))
258 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)BITANDOP)))
259 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)SHIFTOP)))
260 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)POWOP)))
261 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
262 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)ADDOP)))
263 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MULOP)))
264 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
265 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
266
267 /* This bit of chicanery makes a unary function followed by
268  * a parenthesis into a function with one argument, highest precedence.
269  * The UNIDOR macro is for unary functions that can be followed by the //
270  * operator (such as C<shift // 0>).
271  */
272 #define UNI2(f,x) { \
273         pl_yylval.ival = f; \
274         PL_expect = x; \
275         PL_bufptr = s; \
276         PL_last_uni = PL_oldbufptr; \
277         PL_last_lop_op = f; \
278         if (*s == '(') \
279             return REPORT( (int)FUNC1 ); \
280         s = PEEKSPACE(s); \
281         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
282         }
283 #define UNI(f)    UNI2(f,XTERM)
284 #define UNIDOR(f) UNI2(f,XTERMORDORDOR)
285
286 #define UNIBRACK(f) { \
287         pl_yylval.ival = f; \
288         PL_bufptr = s; \
289         PL_last_uni = PL_oldbufptr; \
290         if (*s == '(') \
291             return REPORT( (int)FUNC1 ); \
292         s = PEEKSPACE(s); \
293         return REPORT( (*s == '(') ? (int)FUNC1 : (int)UNIOP ); \
294         }
295
296 /* grandfather return to old style */
297 #define OLDLOP(f) return(pl_yylval.ival=f,PL_expect = XTERM,PL_bufptr = s,(int)LSTOP)
298
299 #ifdef DEBUGGING
300
301 /* how to interpret the pl_yylval associated with the token */
302 enum token_type {
303     TOKENTYPE_NONE,
304     TOKENTYPE_IVAL,
305     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
306     TOKENTYPE_PVAL,
307     TOKENTYPE_OPVAL,
308     TOKENTYPE_GVVAL
309 };
310
311 static struct debug_tokens {
312     const int token;
313     enum token_type type;
314     const char *name;
315 } const debug_tokens[] =
316 {
317     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
318     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
319     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
320     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
321     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
322     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
323     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
324     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
325     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
326     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
327     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
328     { DO,               TOKENTYPE_NONE,         "DO" },
329     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
330     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
331     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
332     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
333     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
334     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
335     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
336     { FOR,              TOKENTYPE_IVAL,         "FOR" },
337     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
338     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
339     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
340     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
341     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
342     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
343     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
344     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
345     { IF,               TOKENTYPE_IVAL,         "IF" },
346     { LABEL,            TOKENTYPE_PVAL,         "LABEL" },
347     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
348     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
349     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
350     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
351     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
352     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
353     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
354     { MY,               TOKENTYPE_IVAL,         "MY" },
355     { MYSUB,            TOKENTYPE_NONE,         "MYSUB" },
356     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
357     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
358     { OROP,             TOKENTYPE_IVAL,         "OROP" },
359     { OROR,             TOKENTYPE_NONE,         "OROR" },
360     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
361     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
362     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
363     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
364     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
365     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
366     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
367     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
368     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
369     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
370     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
371     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
372     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
373     { SUB,              TOKENTYPE_NONE,         "SUB" },
374     { THING,            TOKENTYPE_OPVAL,        "THING" },
375     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
376     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
377     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
378     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
379     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
380     { USE,              TOKENTYPE_IVAL,         "USE" },
381     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
382     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
383     { WORD,             TOKENTYPE_OPVAL,        "WORD" },
384     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
385     { 0,                TOKENTYPE_NONE,         NULL }
386 };
387
388 /* dump the returned token in rv, plus any optional arg in pl_yylval */
389
390 STATIC int
391 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
392 {
393     dVAR;
394
395     PERL_ARGS_ASSERT_TOKEREPORT;
396
397     if (DEBUG_T_TEST) {
398         const char *name = NULL;
399         enum token_type type = TOKENTYPE_NONE;
400         const struct debug_tokens *p;
401         SV* const report = newSVpvs("<== ");
402
403         for (p = debug_tokens; p->token; p++) {
404             if (p->token == (int)rv) {
405                 name = p->name;
406                 type = p->type;
407                 break;
408             }
409         }
410         if (name)
411             Perl_sv_catpv(aTHX_ report, name);
412         else if ((char)rv > ' ' && (char)rv < '~')
413             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
414         else if (!rv)
415             sv_catpvs(report, "EOF");
416         else
417             Perl_sv_catpvf(aTHX_ report, "?? %"IVdf, (IV)rv);
418         switch (type) {
419         case TOKENTYPE_NONE:
420         case TOKENTYPE_GVVAL: /* doesn't appear to be used */
421             break;
422         case TOKENTYPE_IVAL:
423             Perl_sv_catpvf(aTHX_ report, "(ival=%"IVdf")", (IV)lvalp->ival);
424             break;
425         case TOKENTYPE_OPNUM:
426             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
427                                     PL_op_name[lvalp->ival]);
428             break;
429         case TOKENTYPE_PVAL:
430             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
431             break;
432         case TOKENTYPE_OPVAL:
433             if (lvalp->opval) {
434                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
435                                     PL_op_name[lvalp->opval->op_type]);
436                 if (lvalp->opval->op_type == OP_CONST) {
437                     Perl_sv_catpvf(aTHX_ report, " %s",
438                         SvPEEK(cSVOPx_sv(lvalp->opval)));
439                 }
440
441             }
442             else
443                 sv_catpvs(report, "(opval=null)");
444             break;
445         }
446         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
447     };
448     return (int)rv;
449 }
450
451
452 /* print the buffer with suitable escapes */
453
454 STATIC void
455 S_printbuf(pTHX_ const char *const fmt, const char *const s)
456 {
457     SV* const tmp = newSVpvs("");
458
459     PERL_ARGS_ASSERT_PRINTBUF;
460
461     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
462     SvREFCNT_dec(tmp);
463 }
464
465 #endif
466
467 static int
468 S_deprecate_commaless_var_list(pTHX) {
469     PL_expect = XTERM;
470     deprecate("comma-less variable list");
471     return REPORT(','); /* grandfather non-comma-format format */
472 }
473
474 /*
475  * S_ao
476  *
477  * This subroutine detects &&=, ||=, and //= and turns an ANDAND, OROR or DORDOR
478  * into an OP_ANDASSIGN, OP_ORASSIGN, or OP_DORASSIGN
479  */
480
481 STATIC int
482 S_ao(pTHX_ int toketype)
483 {
484     dVAR;
485     if (*PL_bufptr == '=') {
486         PL_bufptr++;
487         if (toketype == ANDAND)
488             pl_yylval.ival = OP_ANDASSIGN;
489         else if (toketype == OROR)
490             pl_yylval.ival = OP_ORASSIGN;
491         else if (toketype == DORDOR)
492             pl_yylval.ival = OP_DORASSIGN;
493         toketype = ASSIGNOP;
494     }
495     return toketype;
496 }
497
498 /*
499  * S_no_op
500  * When Perl expects an operator and finds something else, no_op
501  * prints the warning.  It always prints "<something> found where
502  * operator expected.  It prints "Missing semicolon on previous line?"
503  * if the surprise occurs at the start of the line.  "do you need to
504  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
505  * where the compiler doesn't know if foo is a method call or a function.
506  * It prints "Missing operator before end of line" if there's nothing
507  * after the missing operator, or "... before <...>" if there is something
508  * after the missing operator.
509  */
510
511 STATIC void
512 S_no_op(pTHX_ const char *const what, char *s)
513 {
514     dVAR;
515     char * const oldbp = PL_bufptr;
516     const bool is_first = (PL_oldbufptr == PL_linestart);
517
518     PERL_ARGS_ASSERT_NO_OP;
519
520     if (!s)
521         s = oldbp;
522     else
523         PL_bufptr = s;
524     yywarn(Perl_form(aTHX_ "%s found where operator expected", what));
525     if (ckWARN_d(WARN_SYNTAX)) {
526         if (is_first)
527             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
528                     "\t(Missing semicolon on previous line?)\n");
529         else if (PL_oldoldbufptr && isIDFIRST_lazy_if(PL_oldoldbufptr,UTF)) {
530             const char *t;
531             for (t = PL_oldoldbufptr; (isALNUM_lazy_if(t,UTF) || *t == ':'); t++)
532                 NOOP;
533             if (t < PL_bufptr && isSPACE(*t))
534                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
535                         "\t(Do you need to predeclare %.*s?)\n",
536                     (int)(t - PL_oldoldbufptr), PL_oldoldbufptr);
537         }
538         else {
539             assert(s >= oldbp);
540             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
541                     "\t(Missing operator before %.*s?)\n", (int)(s - oldbp), oldbp);
542         }
543     }
544     PL_bufptr = oldbp;
545 }
546
547 /*
548  * S_missingterm
549  * Complain about missing quote/regexp/heredoc terminator.
550  * If it's called with NULL then it cauterizes the line buffer.
551  * If we're in a delimited string and the delimiter is a control
552  * character, it's reformatted into a two-char sequence like ^C.
553  * This is fatal.
554  */
555
556 STATIC void
557 S_missingterm(pTHX_ char *s)
558 {
559     dVAR;
560     char tmpbuf[3];
561     char q;
562     if (s) {
563         char * const nl = strrchr(s,'\n');
564         if (nl)
565             *nl = '\0';
566     }
567     else if (isCNTRL(PL_multi_close)) {
568         *tmpbuf = '^';
569         tmpbuf[1] = (char)toCTRL(PL_multi_close);
570         tmpbuf[2] = '\0';
571         s = tmpbuf;
572     }
573     else {
574         *tmpbuf = (char)PL_multi_close;
575         tmpbuf[1] = '\0';
576         s = tmpbuf;
577     }
578     q = strchr(s,'"') ? '\'' : '"';
579     Perl_croak(aTHX_ "Can't find string terminator %c%s%c anywhere before EOF",q,s,q);
580 }
581
582 #define FEATURE_IS_ENABLED(name)                                        \
583         ((0 != (PL_hints & HINT_LOCALIZE_HH))                           \
584             && S_feature_is_enabled(aTHX_ STR_WITH_LEN(name)))
585 /* The longest string we pass in.  */
586 #define MAX_FEATURE_LEN (sizeof("unicode_strings")-1)
587
588 /*
589  * S_feature_is_enabled
590  * Check whether the named feature is enabled.
591  */
592 STATIC bool
593 S_feature_is_enabled(pTHX_ const char *const name, STRLEN namelen)
594 {
595     dVAR;
596     HV * const hinthv = GvHV(PL_hintgv);
597     char he_name[8 + MAX_FEATURE_LEN] = "feature_";
598
599     PERL_ARGS_ASSERT_FEATURE_IS_ENABLED;
600
601     assert(namelen <= MAX_FEATURE_LEN);
602     memcpy(&he_name[8], name, namelen);
603
604     return (hinthv && hv_exists(hinthv, he_name, 8 + namelen));
605 }
606
607 /*
608  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
609  * utf16-to-utf8-reversed.
610  */
611
612 #ifdef PERL_CR_FILTER
613 static void
614 strip_return(SV *sv)
615 {
616     register const char *s = SvPVX_const(sv);
617     register const char * const e = s + SvCUR(sv);
618
619     PERL_ARGS_ASSERT_STRIP_RETURN;
620
621     /* outer loop optimized to do nothing if there are no CR-LFs */
622     while (s < e) {
623         if (*s++ == '\r' && *s == '\n') {
624             /* hit a CR-LF, need to copy the rest */
625             register char *d = s - 1;
626             *d++ = *s++;
627             while (s < e) {
628                 if (*s == '\r' && s[1] == '\n')
629                     s++;
630                 *d++ = *s++;
631             }
632             SvCUR(sv) -= s - d;
633             return;
634         }
635     }
636 }
637
638 STATIC I32
639 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
640 {
641     const I32 count = FILTER_READ(idx+1, sv, maxlen);
642     if (count > 0 && !maxlen)
643         strip_return(sv);
644     return count;
645 }
646 #endif
647
648
649
650 /*
651  * Perl_lex_start
652  *
653  * Create a parser object and initialise its parser and lexer fields
654  *
655  * rsfp       is the opened file handle to read from (if any),
656  *
657  * line       holds any initial content already read from the file (or in
658  *            the case of no file, such as an eval, the whole contents);
659  *
660  * new_filter indicates that this is a new file and it shouldn't inherit
661  *            the filters from the current parser (ie require).
662  */
663
664 void
665 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, bool new_filter)
666 {
667     dVAR;
668     const char *s = NULL;
669     STRLEN len;
670     yy_parser *parser, *oparser;
671
672     /* create and initialise a parser */
673
674     Newxz(parser, 1, yy_parser);
675     parser->old_parser = oparser = PL_parser;
676     PL_parser = parser;
677
678     Newx(parser->stack, YYINITDEPTH, yy_stack_frame);
679     parser->ps = parser->stack;
680     parser->stack_size = YYINITDEPTH;
681
682     parser->stack->state = 0;
683     parser->yyerrstatus = 0;
684     parser->yychar = YYEMPTY;           /* Cause a token to be read.  */
685
686     /* on scope exit, free this parser and restore any outer one */
687     SAVEPARSER(parser);
688     parser->saved_curcop = PL_curcop;
689
690     /* initialise lexer state */
691
692 #ifdef PERL_MAD
693     parser->curforce = -1;
694 #else
695     parser->nexttoke = 0;
696 #endif
697     parser->error_count = oparser ? oparser->error_count : 0;
698     parser->copline = NOLINE;
699     parser->lex_state = LEX_NORMAL;
700     parser->expect = XSTATE;
701     parser->rsfp = rsfp;
702     parser->rsfp_filters = (new_filter || !oparser) ? newAV()
703                 : MUTABLE_AV(SvREFCNT_inc(oparser->rsfp_filters));
704
705     Newx(parser->lex_brackstack, 120, char);
706     Newx(parser->lex_casestack, 12, char);
707     *parser->lex_casestack = '\0';
708
709     if (line) {
710         s = SvPV_const(line, len);
711     } else {
712         len = 0;
713     }
714
715     if (!len) {
716         parser->linestr = newSVpvs("\n;");
717     } else if (SvREADONLY(line) || s[len-1] != ';') {
718         parser->linestr = newSVsv(line);
719         if (s[len-1] != ';')
720             sv_catpvs(parser->linestr, "\n;");
721     } else {
722         SvTEMP_off(line);
723         SvREFCNT_inc_simple_void_NN(line);
724         parser->linestr = line;
725     }
726     parser->oldoldbufptr =
727         parser->oldbufptr =
728         parser->bufptr =
729         parser->linestart = SvPVX(parser->linestr);
730     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
731     parser->last_lop = parser->last_uni = NULL;
732 }
733
734
735 /* delete a parser object */
736
737 void
738 Perl_parser_free(pTHX_  const yy_parser *parser)
739 {
740     PERL_ARGS_ASSERT_PARSER_FREE;
741
742     PL_curcop = parser->saved_curcop;
743     SvREFCNT_dec(parser->linestr);
744
745     if (parser->rsfp == PerlIO_stdin())
746         PerlIO_clearerr(parser->rsfp);
747     else if (parser->rsfp && (!parser->old_parser ||
748                 (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
749         PerlIO_close(parser->rsfp);
750     SvREFCNT_dec(parser->rsfp_filters);
751
752     Safefree(parser->stack);
753     Safefree(parser->lex_brackstack);
754     Safefree(parser->lex_casestack);
755     PL_parser = parser->old_parser;
756     Safefree(parser);
757 }
758
759
760 /*
761  * Perl_lex_end
762  * Finalizer for lexing operations.  Must be called when the parser is
763  * done with the lexer.
764  */
765
766 void
767 Perl_lex_end(pTHX)
768 {
769     dVAR;
770     PL_doextract = FALSE;
771 }
772
773 /*
774 =for apidoc AmxU|SV *|PL_parser-E<gt>linestr
775
776 Buffer scalar containing the chunk currently under consideration of the
777 text currently being lexed.  This is always a plain string scalar (for
778 which C<SvPOK> is true).  It is not intended to be used as a scalar by
779 normal scalar means; instead refer to the buffer directly by the pointer
780 variables described below.
781
782 The lexer maintains various C<char*> pointers to things in the
783 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
784 reallocated, all of these pointers must be updated.  Don't attempt to
785 do this manually, but rather use L</lex_grow_linestr> if you need to
786 reallocate the buffer.
787
788 The content of the text chunk in the buffer is commonly exactly one
789 complete line of input, up to and including a newline terminator,
790 but there are situations where it is otherwise.  The octets of the
791 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
792 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
793 flag on this scalar, which may disagree with it.
794
795 For direct examination of the buffer, the variable
796 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
797 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
798 of these pointers is usually preferable to examination of the scalar
799 through normal scalar means.
800
801 =for apidoc AmxU|char *|PL_parser-E<gt>bufend
802
803 Direct pointer to the end of the chunk of text currently being lexed, the
804 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
805 + SvCUR(PL_parser-E<gt>linestr)>.  A NUL character (zero octet) is
806 always located at the end of the buffer, and does not count as part of
807 the buffer's contents.
808
809 =for apidoc AmxU|char *|PL_parser-E<gt>bufptr
810
811 Points to the current position of lexing inside the lexer buffer.
812 Characters around this point may be freely examined, within
813 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
814 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
815 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
816
817 Lexing code (whether in the Perl core or not) moves this pointer past
818 the characters that it consumes.  It is also expected to perform some
819 bookkeeping whenever a newline character is consumed.  This movement
820 can be more conveniently performed by the function L</lex_read_to>,
821 which handles newlines appropriately.
822
823 Interpretation of the buffer's octets can be abstracted out by
824 using the slightly higher-level functions L</lex_peek_unichar> and
825 L</lex_read_unichar>.
826
827 =for apidoc AmxU|char *|PL_parser-E<gt>linestart
828
829 Points to the start of the current line inside the lexer buffer.
830 This is useful for indicating at which column an error occurred, and
831 not much else.  This must be updated by any lexing code that consumes
832 a newline; the function L</lex_read_to> handles this detail.
833
834 =cut
835 */
836
837 /*
838 =for apidoc Amx|bool|lex_bufutf8
839
840 Indicates whether the octets in the lexer buffer
841 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
842 of Unicode characters.  If not, they should be interpreted as Latin-1
843 characters.  This is analogous to the C<SvUTF8> flag for scalars.
844
845 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
846 contains valid UTF-8.  Lexing code must be robust in the face of invalid
847 encoding.
848
849 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
850 is significant, but not the whole story regarding the input character
851 encoding.  Normally, when a file is being read, the scalar contains octets
852 and its C<SvUTF8> flag is off, but the octets should be interpreted as
853 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
854 however, the scalar may have the C<SvUTF8> flag on, and in this case its
855 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
856 is in effect.  This logic may change in the future; use this function
857 instead of implementing the logic yourself.
858
859 =cut
860 */
861
862 bool
863 Perl_lex_bufutf8(pTHX)
864 {
865     return UTF;
866 }
867
868 /*
869 =for apidoc Amx|char *|lex_grow_linestr|STRLEN len
870
871 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
872 at least I<len> octets (including terminating NUL).  Returns a
873 pointer to the reallocated buffer.  This is necessary before making
874 any direct modification of the buffer that would increase its length.
875 L</lex_stuff_pvn> provides a more convenient way to insert text into
876 the buffer.
877
878 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
879 this function updates all of the lexer's variables that point directly
880 into the buffer.
881
882 =cut
883 */
884
885 char *
886 Perl_lex_grow_linestr(pTHX_ STRLEN len)
887 {
888     SV *linestr;
889     char *buf;
890     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
891     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
892     linestr = PL_parser->linestr;
893     buf = SvPVX(linestr);
894     if (len <= SvLEN(linestr))
895         return buf;
896     bufend_pos = PL_parser->bufend - buf;
897     bufptr_pos = PL_parser->bufptr - buf;
898     oldbufptr_pos = PL_parser->oldbufptr - buf;
899     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
900     linestart_pos = PL_parser->linestart - buf;
901     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
902     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
903     buf = sv_grow(linestr, len);
904     PL_parser->bufend = buf + bufend_pos;
905     PL_parser->bufptr = buf + bufptr_pos;
906     PL_parser->oldbufptr = buf + oldbufptr_pos;
907     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
908     PL_parser->linestart = buf + linestart_pos;
909     if (PL_parser->last_uni)
910         PL_parser->last_uni = buf + last_uni_pos;
911     if (PL_parser->last_lop)
912         PL_parser->last_lop = buf + last_lop_pos;
913     return buf;
914 }
915
916 /*
917 =for apidoc Amx|void|lex_stuff_pvn|char *pv|STRLEN len|U32 flags
918
919 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
920 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
921 reallocating the buffer if necessary.  This means that lexing code that
922 runs later will see the characters as if they had appeared in the input.
923 It is not recommended to do this as part of normal parsing, and most
924 uses of this facility run the risk of the inserted characters being
925 interpreted in an unintended manner.
926
927 The string to be inserted is represented by I<len> octets starting
928 at I<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
929 according to whether the C<LEX_STUFF_UTF8> flag is set in I<flags>.
930 The characters are recoded for the lexer buffer, according to how the
931 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
932 to be interpreted is available as a Perl scalar, the L</lex_stuff_sv>
933 function is more convenient.
934
935 =cut
936 */
937
938 void
939 Perl_lex_stuff_pvn(pTHX_ char *pv, STRLEN len, U32 flags)
940 {
941     dVAR;
942     char *bufptr;
943     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
944     if (flags & ~(LEX_STUFF_UTF8))
945         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
946     if (UTF) {
947         if (flags & LEX_STUFF_UTF8) {
948             goto plain_copy;
949         } else {
950             STRLEN highhalf = 0;
951             char *p, *e = pv+len;
952             for (p = pv; p != e; p++)
953                 highhalf += !!(((U8)*p) & 0x80);
954             if (!highhalf)
955                 goto plain_copy;
956             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
957             bufptr = PL_parser->bufptr;
958             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
959             PL_parser->bufend += len+highhalf;
960             for (p = pv; p != e; p++) {
961                 U8 c = (U8)*p;
962                 if (c & 0x80) {
963                     *bufptr++ = (char)(0xc0 | (c >> 6));
964                     *bufptr++ = (char)(0x80 | (c & 0x3f));
965                 } else {
966                     *bufptr++ = (char)c;
967                 }
968             }
969         }
970     } else {
971         if (flags & LEX_STUFF_UTF8) {
972             STRLEN highhalf = 0;
973             char *p, *e = pv+len;
974             for (p = pv; p != e; p++) {
975                 U8 c = (U8)*p;
976                 if (c >= 0xc4) {
977                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
978                                 "non-Latin-1 character into Latin-1 input");
979                 } else if (c >= 0xc2 && p+1 != e &&
980                             (((U8)p[1]) & 0xc0) == 0x80) {
981                     p++;
982                     highhalf++;
983                 } else if (c >= 0x80) {
984                     /* malformed UTF-8 */
985                     ENTER;
986                     SAVESPTR(PL_warnhook);
987                     PL_warnhook = PERL_WARNHOOK_FATAL;
988                     utf8n_to_uvuni((U8*)p, e-p, NULL, 0);
989                     LEAVE;
990                 }
991             }
992             if (!highhalf)
993                 goto plain_copy;
994             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
995             bufptr = PL_parser->bufptr;
996             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
997             PL_parser->bufend += len-highhalf;
998             for (p = pv; p != e; p++) {
999                 U8 c = (U8)*p;
1000                 if (c & 0x80) {
1001                     *bufptr++ = (char)(((c & 0x3) << 6) | (p[1] & 0x3f));
1002                     p++;
1003                 } else {
1004                     *bufptr++ = (char)c;
1005                 }
1006             }
1007         } else {
1008             plain_copy:
1009             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1010             bufptr = PL_parser->bufptr;
1011             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1012             PL_parser->bufend += len;
1013             Copy(pv, bufptr, len, char);
1014         }
1015     }
1016 }
1017
1018 /*
1019 =for apidoc Amx|void|lex_stuff_sv|SV *sv|U32 flags
1020
1021 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1022 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1023 reallocating the buffer if necessary.  This means that lexing code that
1024 runs later will see the characters as if they had appeared in the input.
1025 It is not recommended to do this as part of normal parsing, and most
1026 uses of this facility run the risk of the inserted characters being
1027 interpreted in an unintended manner.
1028
1029 The string to be inserted is the string value of I<sv>.  The characters
1030 are recoded for the lexer buffer, according to how the buffer is currently
1031 being interpreted (L</lex_bufutf8>).  If a string to be interpreted is
1032 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1033 need to construct a scalar.
1034
1035 =cut
1036 */
1037
1038 void
1039 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1040 {
1041     char *pv;
1042     STRLEN len;
1043     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1044     if (flags)
1045         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1046     pv = SvPV(sv, len);
1047     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1048 }
1049
1050 /*
1051 =for apidoc Amx|void|lex_unstuff|char *ptr
1052
1053 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1054 I<ptr>.  Text following I<ptr> will be moved, and the buffer shortened.
1055 This hides the discarded text from any lexing code that runs later,
1056 as if the text had never appeared.
1057
1058 This is not the normal way to consume lexed text.  For that, use
1059 L</lex_read_to>.
1060
1061 =cut
1062 */
1063
1064 void
1065 Perl_lex_unstuff(pTHX_ char *ptr)
1066 {
1067     char *buf, *bufend;
1068     STRLEN unstuff_len;
1069     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1070     buf = PL_parser->bufptr;
1071     if (ptr < buf)
1072         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1073     if (ptr == buf)
1074         return;
1075     bufend = PL_parser->bufend;
1076     if (ptr > bufend)
1077         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1078     unstuff_len = ptr - buf;
1079     Move(ptr, buf, bufend+1-ptr, char);
1080     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1081     PL_parser->bufend = bufend - unstuff_len;
1082 }
1083
1084 /*
1085 =for apidoc Amx|void|lex_read_to|char *ptr
1086
1087 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1088 to I<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match I<ptr>,
1089 performing the correct bookkeeping whenever a newline character is passed.
1090 This is the normal way to consume lexed text.
1091
1092 Interpretation of the buffer's octets can be abstracted out by
1093 using the slightly higher-level functions L</lex_peek_unichar> and
1094 L</lex_read_unichar>.
1095
1096 =cut
1097 */
1098
1099 void
1100 Perl_lex_read_to(pTHX_ char *ptr)
1101 {
1102     char *s;
1103     PERL_ARGS_ASSERT_LEX_READ_TO;
1104     s = PL_parser->bufptr;
1105     if (ptr < s || ptr > PL_parser->bufend)
1106         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1107     for (; s != ptr; s++)
1108         if (*s == '\n') {
1109             CopLINE_inc(PL_curcop);
1110             PL_parser->linestart = s+1;
1111         }
1112     PL_parser->bufptr = ptr;
1113 }
1114
1115 /*
1116 =for apidoc Amx|void|lex_discard_to|char *ptr
1117
1118 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1119 up to I<ptr>.  The remaining content of the buffer will be moved, and
1120 all pointers into the buffer updated appropriately.  I<ptr> must not
1121 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1122 it is not permitted to discard text that has yet to be lexed.
1123
1124 Normally it is not necessarily to do this directly, because it suffices to
1125 use the implicit discarding behaviour of L</lex_next_chunk> and things
1126 based on it.  However, if a token stretches across multiple lines,
1127 and the lexing code has kept multiple lines of text in the buffer for
1128 that purpose, then after completion of the token it would be wise to
1129 explicitly discard the now-unneeded earlier lines, to avoid future
1130 multi-line tokens growing the buffer without bound.
1131
1132 =cut
1133 */
1134
1135 void
1136 Perl_lex_discard_to(pTHX_ char *ptr)
1137 {
1138     char *buf;
1139     STRLEN discard_len;
1140     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1141     buf = SvPVX(PL_parser->linestr);
1142     if (ptr < buf)
1143         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1144     if (ptr == buf)
1145         return;
1146     if (ptr > PL_parser->bufptr)
1147         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1148     discard_len = ptr - buf;
1149     if (PL_parser->oldbufptr < ptr)
1150         PL_parser->oldbufptr = ptr;
1151     if (PL_parser->oldoldbufptr < ptr)
1152         PL_parser->oldoldbufptr = ptr;
1153     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1154         PL_parser->last_uni = NULL;
1155     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1156         PL_parser->last_lop = NULL;
1157     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1158     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1159     PL_parser->bufend -= discard_len;
1160     PL_parser->bufptr -= discard_len;
1161     PL_parser->oldbufptr -= discard_len;
1162     PL_parser->oldoldbufptr -= discard_len;
1163     if (PL_parser->last_uni)
1164         PL_parser->last_uni -= discard_len;
1165     if (PL_parser->last_lop)
1166         PL_parser->last_lop -= discard_len;
1167 }
1168
1169 /*
1170 =for apidoc Amx|bool|lex_next_chunk|U32 flags
1171
1172 Reads in the next chunk of text to be lexed, appending it to
1173 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1174 looked to the end of the current chunk and wants to know more.  It is
1175 usual, but not necessary, for lexing to have consumed the entirety of
1176 the current chunk at this time.
1177
1178 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1179 chunk (i.e., the current chunk has been entirely consumed), normally the
1180 current chunk will be discarded at the same time that the new chunk is
1181 read in.  If I<flags> includes C<LEX_KEEP_PREVIOUS>, the current chunk
1182 will not be discarded.  If the current chunk has not been entirely
1183 consumed, then it will not be discarded regardless of the flag.
1184
1185 Returns true if some new text was added to the buffer, or false if the
1186 buffer has reached the end of the input text.
1187
1188 =cut
1189 */
1190
1191 #define LEX_FAKE_EOF 0x80000000
1192
1193 bool
1194 Perl_lex_next_chunk(pTHX_ U32 flags)
1195 {
1196     SV *linestr;
1197     char *buf;
1198     STRLEN old_bufend_pos, new_bufend_pos;
1199     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1200     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1201     bool got_some_for_debugger = 0;
1202     bool got_some;
1203     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF))
1204         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1205     linestr = PL_parser->linestr;
1206     buf = SvPVX(linestr);
1207     if (!(flags & LEX_KEEP_PREVIOUS) &&
1208             PL_parser->bufptr == PL_parser->bufend) {
1209         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1210         linestart_pos = 0;
1211         if (PL_parser->last_uni != PL_parser->bufend)
1212             PL_parser->last_uni = NULL;
1213         if (PL_parser->last_lop != PL_parser->bufend)
1214             PL_parser->last_lop = NULL;
1215         last_uni_pos = last_lop_pos = 0;
1216         *buf = 0;
1217         SvCUR(linestr) = 0;
1218     } else {
1219         old_bufend_pos = PL_parser->bufend - buf;
1220         bufptr_pos = PL_parser->bufptr - buf;
1221         oldbufptr_pos = PL_parser->oldbufptr - buf;
1222         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1223         linestart_pos = PL_parser->linestart - buf;
1224         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1225         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1226     }
1227     if (flags & LEX_FAKE_EOF) {
1228         goto eof;
1229     } else if (!PL_parser->rsfp) {
1230         got_some = 0;
1231     } else if (filter_gets(linestr, old_bufend_pos)) {
1232         got_some = 1;
1233         got_some_for_debugger = 1;
1234     } else {
1235         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1236             sv_setpvs(linestr, "");
1237         eof:
1238         /* End of real input.  Close filehandle (unless it was STDIN),
1239          * then add implicit termination.
1240          */
1241         if ((PerlIO*)PL_parser->rsfp == PerlIO_stdin())
1242             PerlIO_clearerr(PL_parser->rsfp);
1243         else if (PL_parser->rsfp)
1244             (void)PerlIO_close(PL_parser->rsfp);
1245         PL_parser->rsfp = NULL;
1246         PL_doextract = FALSE;
1247 #ifdef PERL_MAD
1248         if (PL_madskills && !PL_in_eval && (PL_minus_p || PL_minus_n))
1249             PL_faketokens = 1;
1250 #endif
1251         if (!PL_in_eval && PL_minus_p) {
1252             sv_catpvs(linestr,
1253                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1254             PL_minus_n = PL_minus_p = 0;
1255         } else if (!PL_in_eval && PL_minus_n) {
1256             sv_catpvs(linestr, /*{*/";}");
1257             PL_minus_n = 0;
1258         } else
1259             sv_catpvs(linestr, ";");
1260         got_some = 1;
1261     }
1262     buf = SvPVX(linestr);
1263     new_bufend_pos = SvCUR(linestr);
1264     PL_parser->bufend = buf + new_bufend_pos;
1265     PL_parser->bufptr = buf + bufptr_pos;
1266     PL_parser->oldbufptr = buf + oldbufptr_pos;
1267     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1268     PL_parser->linestart = buf + linestart_pos;
1269     if (PL_parser->last_uni)
1270         PL_parser->last_uni = buf + last_uni_pos;
1271     if (PL_parser->last_lop)
1272         PL_parser->last_lop = buf + last_lop_pos;
1273     if (got_some_for_debugger && (PERLDB_LINE || PERLDB_SAVESRC) &&
1274             PL_curstash != PL_debstash) {
1275         /* debugger active and we're not compiling the debugger code,
1276          * so store the line into the debugger's array of lines
1277          */
1278         update_debugger_info(NULL, buf+old_bufend_pos,
1279             new_bufend_pos-old_bufend_pos);
1280     }
1281     return got_some;
1282 }
1283
1284 /*
1285 =for apidoc Amx|I32|lex_peek_unichar|U32 flags
1286
1287 Looks ahead one (Unicode) character in the text currently being lexed.
1288 Returns the codepoint (unsigned integer value) of the next character,
1289 or -1 if lexing has reached the end of the input text.  To consume the
1290 peeked character, use L</lex_read_unichar>.
1291
1292 If the next character is in (or extends into) the next chunk of input
1293 text, the next chunk will be read in.  Normally the current chunk will be
1294 discarded at the same time, but if I<flags> includes C<LEX_KEEP_PREVIOUS>
1295 then the current chunk will not be discarded.
1296
1297 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1298 is encountered, an exception is generated.
1299
1300 =cut
1301 */
1302
1303 I32
1304 Perl_lex_peek_unichar(pTHX_ U32 flags)
1305 {
1306     dVAR;
1307     char *s, *bufend;
1308     if (flags & ~(LEX_KEEP_PREVIOUS))
1309         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1310     s = PL_parser->bufptr;
1311     bufend = PL_parser->bufend;
1312     if (UTF) {
1313         U8 head;
1314         I32 unichar;
1315         STRLEN len, retlen;
1316         if (s == bufend) {
1317             if (!lex_next_chunk(flags))
1318                 return -1;
1319             s = PL_parser->bufptr;
1320             bufend = PL_parser->bufend;
1321         }
1322         head = (U8)*s;
1323         if (!(head & 0x80))
1324             return head;
1325         if (head & 0x40) {
1326             len = PL_utf8skip[head];
1327             while ((STRLEN)(bufend-s) < len) {
1328                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1329                     break;
1330                 s = PL_parser->bufptr;
1331                 bufend = PL_parser->bufend;
1332             }
1333         }
1334         unichar = utf8n_to_uvuni((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1335         if (retlen == (STRLEN)-1) {
1336             /* malformed UTF-8 */
1337             ENTER;
1338             SAVESPTR(PL_warnhook);
1339             PL_warnhook = PERL_WARNHOOK_FATAL;
1340             utf8n_to_uvuni((U8*)s, bufend-s, NULL, 0);
1341             LEAVE;
1342         }
1343         return unichar;
1344     } else {
1345         if (s == bufend) {
1346             if (!lex_next_chunk(flags))
1347                 return -1;
1348             s = PL_parser->bufptr;
1349         }
1350         return (U8)*s;
1351     }
1352 }
1353
1354 /*
1355 =for apidoc Amx|I32|lex_read_unichar|U32 flags
1356
1357 Reads the next (Unicode) character in the text currently being lexed.
1358 Returns the codepoint (unsigned integer value) of the character read,
1359 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1360 if lexing has reached the end of the input text.  To non-destructively
1361 examine the next character, use L</lex_peek_unichar> instead.
1362
1363 If the next character is in (or extends into) the next chunk of input
1364 text, the next chunk will be read in.  Normally the current chunk will be
1365 discarded at the same time, but if I<flags> includes C<LEX_KEEP_PREVIOUS>
1366 then the current chunk will not be discarded.
1367
1368 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1369 is encountered, an exception is generated.
1370
1371 =cut
1372 */
1373
1374 I32
1375 Perl_lex_read_unichar(pTHX_ U32 flags)
1376 {
1377     I32 c;
1378     if (flags & ~(LEX_KEEP_PREVIOUS))
1379         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1380     c = lex_peek_unichar(flags);
1381     if (c != -1) {
1382         if (c == '\n')
1383             CopLINE_inc(PL_curcop);
1384         PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1385     }
1386     return c;
1387 }
1388
1389 /*
1390 =for apidoc Amx|void|lex_read_space|U32 flags
1391
1392 Reads optional spaces, in Perl style, in the text currently being
1393 lexed.  The spaces may include ordinary whitespace characters and
1394 Perl-style comments.  C<#line> directives are processed if encountered.
1395 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1396 at a non-space character (or the end of the input text).
1397
1398 If spaces extend into the next chunk of input text, the next chunk will
1399 be read in.  Normally the current chunk will be discarded at the same
1400 time, but if I<flags> includes C<LEX_KEEP_PREVIOUS> then the current
1401 chunk will not be discarded.
1402
1403 =cut
1404 */
1405
1406 #define LEX_NO_NEXT_CHUNK 0x80000000
1407
1408 void
1409 Perl_lex_read_space(pTHX_ U32 flags)
1410 {
1411     char *s, *bufend;
1412     bool need_incline = 0;
1413     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK))
1414         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1415 #ifdef PERL_MAD
1416     if (PL_skipwhite) {
1417         sv_free(PL_skipwhite);
1418         PL_skipwhite = NULL;
1419     }
1420     if (PL_madskills)
1421         PL_skipwhite = newSVpvs("");
1422 #endif /* PERL_MAD */
1423     s = PL_parser->bufptr;
1424     bufend = PL_parser->bufend;
1425     while (1) {
1426         char c = *s;
1427         if (c == '#') {
1428             do {
1429                 c = *++s;
1430             } while (!(c == '\n' || (c == 0 && s == bufend)));
1431         } else if (c == '\n') {
1432             s++;
1433             PL_parser->linestart = s;
1434             if (s == bufend)
1435                 need_incline = 1;
1436             else
1437                 incline(s);
1438         } else if (isSPACE(c)) {
1439             s++;
1440         } else if (c == 0 && s == bufend) {
1441             bool got_more;
1442 #ifdef PERL_MAD
1443             if (PL_madskills)
1444                 sv_catpvn(PL_skipwhite, PL_parser->bufptr, s-PL_parser->bufptr);
1445 #endif /* PERL_MAD */
1446             if (flags & LEX_NO_NEXT_CHUNK)
1447                 break;
1448             PL_parser->bufptr = s;
1449             CopLINE_inc(PL_curcop);
1450             got_more = lex_next_chunk(flags);
1451             CopLINE_dec(PL_curcop);
1452             s = PL_parser->bufptr;
1453             bufend = PL_parser->bufend;
1454             if (!got_more)
1455                 break;
1456             if (need_incline && PL_parser->rsfp) {
1457                 incline(s);
1458                 need_incline = 0;
1459             }
1460         } else {
1461             break;
1462         }
1463     }
1464 #ifdef PERL_MAD
1465     if (PL_madskills)
1466         sv_catpvn(PL_skipwhite, PL_parser->bufptr, s-PL_parser->bufptr);
1467 #endif /* PERL_MAD */
1468     PL_parser->bufptr = s;
1469 }
1470
1471 /*
1472  * S_incline
1473  * This subroutine has nothing to do with tilting, whether at windmills
1474  * or pinball tables.  Its name is short for "increment line".  It
1475  * increments the current line number in CopLINE(PL_curcop) and checks
1476  * to see whether the line starts with a comment of the form
1477  *    # line 500 "foo.pm"
1478  * If so, it sets the current line number and file to the values in the comment.
1479  */
1480
1481 STATIC void
1482 S_incline(pTHX_ const char *s)
1483 {
1484     dVAR;
1485     const char *t;
1486     const char *n;
1487     const char *e;
1488
1489     PERL_ARGS_ASSERT_INCLINE;
1490
1491     CopLINE_inc(PL_curcop);
1492     if (*s++ != '#')
1493         return;
1494     while (SPACE_OR_TAB(*s))
1495         s++;
1496     if (strnEQ(s, "line", 4))
1497         s += 4;
1498     else
1499         return;
1500     if (SPACE_OR_TAB(*s))
1501         s++;
1502     else
1503         return;
1504     while (SPACE_OR_TAB(*s))
1505         s++;
1506     if (!isDIGIT(*s))
1507         return;
1508
1509     n = s;
1510     while (isDIGIT(*s))
1511         s++;
1512     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1513         return;
1514     while (SPACE_OR_TAB(*s))
1515         s++;
1516     if (*s == '"' && (t = strchr(s+1, '"'))) {
1517         s++;
1518         e = t + 1;
1519     }
1520     else {
1521         t = s;
1522         while (!isSPACE(*t))
1523             t++;
1524         e = t;
1525     }
1526     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1527         e++;
1528     if (*e != '\n' && *e != '\0')
1529         return;         /* false alarm */
1530
1531     if (t - s > 0) {
1532         const STRLEN len = t - s;
1533 #ifndef USE_ITHREADS
1534         SV *const temp_sv = CopFILESV(PL_curcop);
1535         const char *cf;
1536         STRLEN tmplen;
1537
1538         if (temp_sv) {
1539             cf = SvPVX(temp_sv);
1540             tmplen = SvCUR(temp_sv);
1541         } else {
1542             cf = NULL;
1543             tmplen = 0;
1544         }
1545
1546         if (tmplen > 7 && strnEQ(cf, "(eval ", 6)) {
1547             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1548              * to *{"::_<newfilename"} */
1549             /* However, the long form of evals is only turned on by the
1550                debugger - usually they're "(eval %lu)" */
1551             char smallbuf[128];
1552             char *tmpbuf;
1553             GV **gvp;
1554             STRLEN tmplen2 = len;
1555             if (tmplen + 2 <= sizeof smallbuf)
1556                 tmpbuf = smallbuf;
1557             else
1558                 Newx(tmpbuf, tmplen + 2, char);
1559             tmpbuf[0] = '_';
1560             tmpbuf[1] = '<';
1561             memcpy(tmpbuf + 2, cf, tmplen);
1562             tmplen += 2;
1563             gvp = (GV**)hv_fetch(PL_defstash, tmpbuf, tmplen, FALSE);
1564             if (gvp) {
1565                 char *tmpbuf2;
1566                 GV *gv2;
1567
1568                 if (tmplen2 + 2 <= sizeof smallbuf)
1569                     tmpbuf2 = smallbuf;
1570                 else
1571                     Newx(tmpbuf2, tmplen2 + 2, char);
1572
1573                 if (tmpbuf2 != smallbuf || tmpbuf != smallbuf) {
1574                     /* Either they malloc'd it, or we malloc'd it,
1575                        so no prefix is present in ours.  */
1576                     tmpbuf2[0] = '_';
1577                     tmpbuf2[1] = '<';
1578                 }
1579
1580                 memcpy(tmpbuf2 + 2, s, tmplen2);
1581                 tmplen2 += 2;
1582
1583                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1584                 if (!isGV(gv2)) {
1585                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1586                     /* adjust ${"::_<newfilename"} to store the new file name */
1587                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1588                     GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(*gvp)));
1589                     GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(*gvp)));
1590                 }
1591
1592                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1593             }
1594             if (tmpbuf != smallbuf) Safefree(tmpbuf);
1595         }
1596 #endif
1597         CopFILE_free(PL_curcop);
1598         CopFILE_setn(PL_curcop, s, len);
1599     }
1600     CopLINE_set(PL_curcop, atoi(n)-1);
1601 }
1602
1603 #ifdef PERL_MAD
1604 /* skip space before PL_thistoken */
1605
1606 STATIC char *
1607 S_skipspace0(pTHX_ register char *s)
1608 {
1609     PERL_ARGS_ASSERT_SKIPSPACE0;
1610
1611     s = skipspace(s);
1612     if (!PL_madskills)
1613         return s;
1614     if (PL_skipwhite) {
1615         if (!PL_thiswhite)
1616             PL_thiswhite = newSVpvs("");
1617         sv_catsv(PL_thiswhite, PL_skipwhite);
1618         sv_free(PL_skipwhite);
1619         PL_skipwhite = 0;
1620     }
1621     PL_realtokenstart = s - SvPVX(PL_linestr);
1622     return s;
1623 }
1624
1625 /* skip space after PL_thistoken */
1626
1627 STATIC char *
1628 S_skipspace1(pTHX_ register char *s)
1629 {
1630     const char *start = s;
1631     I32 startoff = start - SvPVX(PL_linestr);
1632
1633     PERL_ARGS_ASSERT_SKIPSPACE1;
1634
1635     s = skipspace(s);
1636     if (!PL_madskills)
1637         return s;
1638     start = SvPVX(PL_linestr) + startoff;
1639     if (!PL_thistoken && PL_realtokenstart >= 0) {
1640         const char * const tstart = SvPVX(PL_linestr) + PL_realtokenstart;
1641         PL_thistoken = newSVpvn(tstart, start - tstart);
1642     }
1643     PL_realtokenstart = -1;
1644     if (PL_skipwhite) {
1645         if (!PL_nextwhite)
1646             PL_nextwhite = newSVpvs("");
1647         sv_catsv(PL_nextwhite, PL_skipwhite);
1648         sv_free(PL_skipwhite);
1649         PL_skipwhite = 0;
1650     }
1651     return s;
1652 }
1653
1654 STATIC char *
1655 S_skipspace2(pTHX_ register char *s, SV **svp)
1656 {
1657     char *start;
1658     const I32 bufptroff = PL_bufptr - SvPVX(PL_linestr);
1659     const I32 startoff = s - SvPVX(PL_linestr);
1660
1661     PERL_ARGS_ASSERT_SKIPSPACE2;
1662
1663     s = skipspace(s);
1664     PL_bufptr = SvPVX(PL_linestr) + bufptroff;
1665     if (!PL_madskills || !svp)
1666         return s;
1667     start = SvPVX(PL_linestr) + startoff;
1668     if (!PL_thistoken && PL_realtokenstart >= 0) {
1669         char * const tstart = SvPVX(PL_linestr) + PL_realtokenstart;
1670         PL_thistoken = newSVpvn(tstart, start - tstart);
1671         PL_realtokenstart = -1;
1672     }
1673     if (PL_skipwhite) {
1674         if (!*svp)
1675             *svp = newSVpvs("");
1676         sv_setsv(*svp, PL_skipwhite);
1677         sv_free(PL_skipwhite);
1678         PL_skipwhite = 0;
1679     }
1680     
1681     return s;
1682 }
1683 #endif
1684
1685 STATIC void
1686 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1687 {
1688     AV *av = CopFILEAVx(PL_curcop);
1689     if (av) {
1690         SV * const sv = newSV_type(SVt_PVMG);
1691         if (orig_sv)
1692             sv_setsv(sv, orig_sv);
1693         else
1694             sv_setpvn(sv, buf, len);
1695         (void)SvIOK_on(sv);
1696         SvIV_set(sv, 0);
1697         av_store(av, (I32)CopLINE(PL_curcop), sv);
1698     }
1699 }
1700
1701 /*
1702  * S_skipspace
1703  * Called to gobble the appropriate amount and type of whitespace.
1704  * Skips comments as well.
1705  */
1706
1707 STATIC char *
1708 S_skipspace(pTHX_ register char *s)
1709 {
1710 #ifdef PERL_MAD
1711     char *start = s;
1712 #endif /* PERL_MAD */
1713     PERL_ARGS_ASSERT_SKIPSPACE;
1714 #ifdef PERL_MAD
1715     if (PL_skipwhite) {
1716         sv_free(PL_skipwhite);
1717         PL_skipwhite = NULL;
1718     }
1719 #endif /* PERL_MAD */
1720     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1721         while (s < PL_bufend && SPACE_OR_TAB(*s))
1722             s++;
1723     } else {
1724         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1725         PL_bufptr = s;
1726         lex_read_space(LEX_KEEP_PREVIOUS |
1727                 (PL_sublex_info.sub_inwhat || PL_lex_state == LEX_FORMLINE ?
1728                     LEX_NO_NEXT_CHUNK : 0));
1729         s = PL_bufptr;
1730         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1731         if (PL_linestart > PL_bufptr)
1732             PL_bufptr = PL_linestart;
1733         return s;
1734     }
1735 #ifdef PERL_MAD
1736     if (PL_madskills)
1737         PL_skipwhite = newSVpvn(start, s-start);
1738 #endif /* PERL_MAD */
1739     return s;
1740 }
1741
1742 /*
1743  * S_check_uni
1744  * Check the unary operators to ensure there's no ambiguity in how they're
1745  * used.  An ambiguous piece of code would be:
1746  *     rand + 5
1747  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1748  * the +5 is its argument.
1749  */
1750
1751 STATIC void
1752 S_check_uni(pTHX)
1753 {
1754     dVAR;
1755     const char *s;
1756     const char *t;
1757
1758     if (PL_oldoldbufptr != PL_last_uni)
1759         return;
1760     while (isSPACE(*PL_last_uni))
1761         PL_last_uni++;
1762     s = PL_last_uni;
1763     while (isALNUM_lazy_if(s,UTF) || *s == '-')
1764         s++;
1765     if ((t = strchr(s, '(')) && t < PL_bufptr)
1766         return;
1767
1768     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1769                      "Warning: Use of \"%.*s\" without parentheses is ambiguous",
1770                      (int)(s - PL_last_uni), PL_last_uni);
1771 }
1772
1773 /*
1774  * LOP : macro to build a list operator.  Its behaviour has been replaced
1775  * with a subroutine, S_lop() for which LOP is just another name.
1776  */
1777
1778 #define LOP(f,x) return lop(f,x,s)
1779
1780 /*
1781  * S_lop
1782  * Build a list operator (or something that might be one).  The rules:
1783  *  - if we have a next token, then it's a list operator [why?]
1784  *  - if the next thing is an opening paren, then it's a function
1785  *  - else it's a list operator
1786  */
1787
1788 STATIC I32
1789 S_lop(pTHX_ I32 f, int x, char *s)
1790 {
1791     dVAR;
1792
1793     PERL_ARGS_ASSERT_LOP;
1794
1795     pl_yylval.ival = f;
1796     CLINE;
1797     PL_expect = x;
1798     PL_bufptr = s;
1799     PL_last_lop = PL_oldbufptr;
1800     PL_last_lop_op = (OPCODE)f;
1801 #ifdef PERL_MAD
1802     if (PL_lasttoke)
1803         return REPORT(LSTOP);
1804 #else
1805     if (PL_nexttoke)
1806         return REPORT(LSTOP);
1807 #endif
1808     if (*s == '(')
1809         return REPORT(FUNC);
1810     s = PEEKSPACE(s);
1811     if (*s == '(')
1812         return REPORT(FUNC);
1813     else
1814         return REPORT(LSTOP);
1815 }
1816
1817 #ifdef PERL_MAD
1818  /*
1819  * S_start_force
1820  * Sets up for an eventual force_next().  start_force(0) basically does
1821  * an unshift, while start_force(-1) does a push.  yylex removes items
1822  * on the "pop" end.
1823  */
1824
1825 STATIC void
1826 S_start_force(pTHX_ int where)
1827 {
1828     int i;
1829
1830     if (where < 0)      /* so people can duplicate start_force(PL_curforce) */
1831         where = PL_lasttoke;
1832     assert(PL_curforce < 0 || PL_curforce == where);
1833     if (PL_curforce != where) {
1834         for (i = PL_lasttoke; i > where; --i) {
1835             PL_nexttoke[i] = PL_nexttoke[i-1];
1836         }
1837         PL_lasttoke++;
1838     }
1839     if (PL_curforce < 0)        /* in case of duplicate start_force() */
1840         Zero(&PL_nexttoke[where], 1, NEXTTOKE);
1841     PL_curforce = where;
1842     if (PL_nextwhite) {
1843         if (PL_madskills)
1844             curmad('^', newSVpvs(""));
1845         CURMAD('_', PL_nextwhite);
1846     }
1847 }
1848
1849 STATIC void
1850 S_curmad(pTHX_ char slot, SV *sv)
1851 {
1852     MADPROP **where;
1853
1854     if (!sv)
1855         return;
1856     if (PL_curforce < 0)
1857         where = &PL_thismad;
1858     else
1859         where = &PL_nexttoke[PL_curforce].next_mad;
1860
1861     if (PL_faketokens)
1862         sv_setpvs(sv, "");
1863     else {
1864         if (!IN_BYTES) {
1865             if (UTF && is_utf8_string((U8*)SvPVX(sv), SvCUR(sv)))
1866                 SvUTF8_on(sv);
1867             else if (PL_encoding) {
1868                 sv_recode_to_utf8(sv, PL_encoding);
1869             }
1870         }
1871     }
1872
1873     /* keep a slot open for the head of the list? */
1874     if (slot != '_' && *where && (*where)->mad_key == '^') {
1875         (*where)->mad_key = slot;
1876         sv_free(MUTABLE_SV(((*where)->mad_val)));
1877         (*where)->mad_val = (void*)sv;
1878     }
1879     else
1880         addmad(newMADsv(slot, sv), where, 0);
1881 }
1882 #else
1883 #  define start_force(where)    NOOP
1884 #  define curmad(slot, sv)      NOOP
1885 #endif
1886
1887 /*
1888  * S_force_next
1889  * When the lexer realizes it knows the next token (for instance,
1890  * it is reordering tokens for the parser) then it can call S_force_next
1891  * to know what token to return the next time the lexer is called.  Caller
1892  * will need to set PL_nextval[] (or PL_nexttoke[].next_val with PERL_MAD),
1893  * and possibly PL_expect to ensure the lexer handles the token correctly.
1894  */
1895
1896 STATIC void
1897 S_force_next(pTHX_ I32 type)
1898 {
1899     dVAR;
1900 #ifdef DEBUGGING
1901     if (DEBUG_T_TEST) {
1902         PerlIO_printf(Perl_debug_log, "### forced token:\n");
1903         tokereport(type, &NEXTVAL_NEXTTOKE);
1904     }
1905 #endif
1906 #ifdef PERL_MAD
1907     if (PL_curforce < 0)
1908         start_force(PL_lasttoke);
1909     PL_nexttoke[PL_curforce].next_type = type;
1910     if (PL_lex_state != LEX_KNOWNEXT)
1911         PL_lex_defer = PL_lex_state;
1912     PL_lex_state = LEX_KNOWNEXT;
1913     PL_lex_expect = PL_expect;
1914     PL_curforce = -1;
1915 #else
1916     PL_nexttype[PL_nexttoke] = type;
1917     PL_nexttoke++;
1918     if (PL_lex_state != LEX_KNOWNEXT) {
1919         PL_lex_defer = PL_lex_state;
1920         PL_lex_expect = PL_expect;
1921         PL_lex_state = LEX_KNOWNEXT;
1922     }
1923 #endif
1924 }
1925
1926 STATIC SV *
1927 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
1928 {
1929     dVAR;
1930     SV * const sv = newSVpvn_utf8(start, len,
1931                                   !IN_BYTES
1932                                   && UTF
1933                                   && !is_ascii_string((const U8*)start, len)
1934                                   && is_utf8_string((const U8*)start, len));
1935     return sv;
1936 }
1937
1938 /*
1939  * S_force_word
1940  * When the lexer knows the next thing is a word (for instance, it has
1941  * just seen -> and it knows that the next char is a word char, then
1942  * it calls S_force_word to stick the next word into the PL_nexttoke/val
1943  * lookahead.
1944  *
1945  * Arguments:
1946  *   char *start : buffer position (must be within PL_linestr)
1947  *   int token   : PL_next* will be this type of bare word (e.g., METHOD,WORD)
1948  *   int check_keyword : if true, Perl checks to make sure the word isn't
1949  *       a keyword (do this if the word is a label, e.g. goto FOO)
1950  *   int allow_pack : if true, : characters will also be allowed (require,
1951  *       use, etc. do this)
1952  *   int allow_initial_tick : used by the "sub" lexer only.
1953  */
1954
1955 STATIC char *
1956 S_force_word(pTHX_ register char *start, int token, int check_keyword, int allow_pack, int allow_initial_tick)
1957 {
1958     dVAR;
1959     register char *s;
1960     STRLEN len;
1961
1962     PERL_ARGS_ASSERT_FORCE_WORD;
1963
1964     start = SKIPSPACE1(start);
1965     s = start;
1966     if (isIDFIRST_lazy_if(s,UTF) ||
1967         (allow_pack && *s == ':') ||
1968         (allow_initial_tick && *s == '\'') )
1969     {
1970         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
1971         if (check_keyword && keyword(PL_tokenbuf, len, 0))
1972             return start;
1973         start_force(PL_curforce);
1974         if (PL_madskills)
1975             curmad('X', newSVpvn(start,s-start));
1976         if (token == METHOD) {
1977             s = SKIPSPACE1(s);
1978             if (*s == '(')
1979                 PL_expect = XTERM;
1980             else {
1981                 PL_expect = XOPERATOR;
1982             }
1983         }
1984         if (PL_madskills)
1985             curmad('g', newSVpvs( "forced" ));
1986         NEXTVAL_NEXTTOKE.opval
1987             = (OP*)newSVOP(OP_CONST,0,
1988                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
1989         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
1990         force_next(token);
1991     }
1992     return s;
1993 }
1994
1995 /*
1996  * S_force_ident
1997  * Called when the lexer wants $foo *foo &foo etc, but the program
1998  * text only contains the "foo" portion.  The first argument is a pointer
1999  * to the "foo", and the second argument is the type symbol to prefix.
2000  * Forces the next token to be a "WORD".
2001  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2002  */
2003
2004 STATIC void
2005 S_force_ident(pTHX_ register const char *s, int kind)
2006 {
2007     dVAR;
2008
2009     PERL_ARGS_ASSERT_FORCE_IDENT;
2010
2011     if (*s) {
2012         const STRLEN len = strlen(s);
2013         OP* const o = (OP*)newSVOP(OP_CONST, 0, newSVpvn(s, len));
2014         start_force(PL_curforce);
2015         NEXTVAL_NEXTTOKE.opval = o;
2016         force_next(WORD);
2017         if (kind) {
2018             o->op_private = OPpCONST_ENTERED;
2019             /* XXX see note in pp_entereval() for why we forgo typo
2020                warnings if the symbol must be introduced in an eval.
2021                GSAR 96-10-12 */
2022             gv_fetchpvn_flags(s, len,
2023                               PL_in_eval ? (GV_ADDMULTI | GV_ADDINEVAL)
2024                               : GV_ADD,
2025                               kind == '$' ? SVt_PV :
2026                               kind == '@' ? SVt_PVAV :
2027                               kind == '%' ? SVt_PVHV :
2028                               SVt_PVGV
2029                               );
2030         }
2031     }
2032 }
2033
2034 NV
2035 Perl_str_to_version(pTHX_ SV *sv)
2036 {
2037     NV retval = 0.0;
2038     NV nshift = 1.0;
2039     STRLEN len;
2040     const char *start = SvPV_const(sv,len);
2041     const char * const end = start + len;
2042     const bool utf = SvUTF8(sv) ? TRUE : FALSE;
2043
2044     PERL_ARGS_ASSERT_STR_TO_VERSION;
2045
2046     while (start < end) {
2047         STRLEN skip;
2048         UV n;
2049         if (utf)
2050             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2051         else {
2052             n = *(U8*)start;
2053             skip = 1;
2054         }
2055         retval += ((NV)n)/nshift;
2056         start += skip;
2057         nshift *= 1000;
2058     }
2059     return retval;
2060 }
2061
2062 /*
2063  * S_force_version
2064  * Forces the next token to be a version number.
2065  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2066  * and if "guessing" is TRUE, then no new token is created (and the caller
2067  * must use an alternative parsing method).
2068  */
2069
2070 STATIC char *
2071 S_force_version(pTHX_ char *s, int guessing)
2072 {
2073     dVAR;
2074     OP *version = NULL;
2075     char *d;
2076 #ifdef PERL_MAD
2077     I32 startoff = s - SvPVX(PL_linestr);
2078 #endif
2079
2080     PERL_ARGS_ASSERT_FORCE_VERSION;
2081
2082     s = SKIPSPACE1(s);
2083
2084     d = s;
2085     if (*d == 'v')
2086         d++;
2087     if (isDIGIT(*d)) {
2088         while (isDIGIT(*d) || *d == '_' || *d == '.')
2089             d++;
2090 #ifdef PERL_MAD
2091         if (PL_madskills) {
2092             start_force(PL_curforce);
2093             curmad('X', newSVpvn(s,d-s));
2094         }
2095 #endif
2096         if (*d == ';' || isSPACE(*d) || *d == '}' || !*d) {
2097             SV *ver;
2098 #ifdef USE_LOCALE_NUMERIC
2099             char *loc = setlocale(LC_NUMERIC, "C");
2100 #endif
2101             s = scan_num(s, &pl_yylval);
2102 #ifdef USE_LOCALE_NUMERIC
2103             setlocale(LC_NUMERIC, loc);
2104 #endif
2105             version = pl_yylval.opval;
2106             ver = cSVOPx(version)->op_sv;
2107             if (SvPOK(ver) && !SvNIOK(ver)) {
2108                 SvUPGRADE(ver, SVt_PVNV);
2109                 SvNV_set(ver, str_to_version(ver));
2110                 SvNOK_on(ver);          /* hint that it is a version */
2111             }
2112         }
2113         else if (guessing) {
2114 #ifdef PERL_MAD
2115             if (PL_madskills) {
2116                 sv_free(PL_nextwhite);  /* let next token collect whitespace */
2117                 PL_nextwhite = 0;
2118                 s = SvPVX(PL_linestr) + startoff;
2119             }
2120 #endif
2121             return s;
2122         }
2123     }
2124
2125 #ifdef PERL_MAD
2126     if (PL_madskills && !version) {
2127         sv_free(PL_nextwhite);  /* let next token collect whitespace */
2128         PL_nextwhite = 0;
2129         s = SvPVX(PL_linestr) + startoff;
2130     }
2131 #endif
2132     /* NOTE: The parser sees the package name and the VERSION swapped */
2133     start_force(PL_curforce);
2134     NEXTVAL_NEXTTOKE.opval = version;
2135     force_next(WORD);
2136
2137     return s;
2138 }
2139
2140 /*
2141  * S_force_strict_version
2142  * Forces the next token to be a version number using strict syntax rules.
2143  */
2144
2145 STATIC char *
2146 S_force_strict_version(pTHX_ char *s)
2147 {
2148     dVAR;
2149     OP *version = NULL;
2150 #ifdef PERL_MAD
2151     I32 startoff = s - SvPVX(PL_linestr);
2152 #endif
2153     const char *errstr = NULL;
2154
2155     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2156
2157     while (isSPACE(*s)) /* leading whitespace */
2158         s++;
2159
2160     if (is_STRICT_VERSION(s,&errstr)) {
2161         SV *ver = newSV(0);
2162         s = (char *)scan_version(s, ver, 0);
2163         version = newSVOP(OP_CONST, 0, ver);
2164     }
2165     else if ( (*s != ';' && *s != '}' ) && (s = SKIPSPACE1(s), (*s != ';' && *s !='}' ))) {
2166         PL_bufptr = s;
2167         if (errstr)
2168             yyerror(errstr); /* version required */
2169         return s;
2170     }
2171
2172 #ifdef PERL_MAD
2173     if (PL_madskills && !version) {
2174         sv_free(PL_nextwhite);  /* let next token collect whitespace */
2175         PL_nextwhite = 0;
2176         s = SvPVX(PL_linestr) + startoff;
2177     }
2178 #endif
2179     /* NOTE: The parser sees the package name and the VERSION swapped */
2180     start_force(PL_curforce);
2181     NEXTVAL_NEXTTOKE.opval = version;
2182     force_next(WORD);
2183
2184     return s;
2185 }
2186
2187 /*
2188  * S_tokeq
2189  * Tokenize a quoted string passed in as an SV.  It finds the next
2190  * chunk, up to end of string or a backslash.  It may make a new
2191  * SV containing that chunk (if HINT_NEW_STRING is on).  It also
2192  * turns \\ into \.
2193  */
2194
2195 STATIC SV *
2196 S_tokeq(pTHX_ SV *sv)
2197 {
2198     dVAR;
2199     register char *s;
2200     register char *send;
2201     register char *d;
2202     STRLEN len = 0;
2203     SV *pv = sv;
2204
2205     PERL_ARGS_ASSERT_TOKEQ;
2206
2207     if (!SvLEN(sv))
2208         goto finish;
2209
2210     s = SvPV_force(sv, len);
2211     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1)
2212         goto finish;
2213     send = s + len;
2214     while (s < send && *s != '\\')
2215         s++;
2216     if (s == send)
2217         goto finish;
2218     d = s;
2219     if ( PL_hints & HINT_NEW_STRING ) {
2220         pv = newSVpvn_flags(SvPVX_const(pv), len, SVs_TEMP | SvUTF8(sv));
2221     }
2222     while (s < send) {
2223         if (*s == '\\') {
2224             if (s + 1 < send && (s[1] == '\\'))
2225                 s++;            /* all that, just for this */
2226         }
2227         *d++ = *s++;
2228     }
2229     *d = '\0';
2230     SvCUR_set(sv, d - SvPVX_const(sv));
2231   finish:
2232     if ( PL_hints & HINT_NEW_STRING )
2233        return new_constant(NULL, 0, "q", sv, pv, "q", 1);
2234     return sv;
2235 }
2236
2237 /*
2238  * Now come three functions related to double-quote context,
2239  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2240  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2241  * interact with PL_lex_state, and create fake ( ... ) argument lists
2242  * to handle functions and concatenation.
2243  * They assume that whoever calls them will be setting up a fake
2244  * join call, because each subthing puts a ',' after it.  This lets
2245  *   "lower \luPpEr"
2246  * become
2247  *  join($, , 'lower ', lcfirst( 'uPpEr', ) ,)
2248  *
2249  * (I'm not sure whether the spurious commas at the end of lcfirst's
2250  * arguments and join's arguments are created or not).
2251  */
2252
2253 /*
2254  * S_sublex_start
2255  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2256  *
2257  * Pattern matching will set PL_lex_op to the pattern-matching op to
2258  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2259  *
2260  * OP_CONST and OP_READLINE are easy--just make the new op and return.
2261  *
2262  * Everything else becomes a FUNC.
2263  *
2264  * Sets PL_lex_state to LEX_INTERPPUSH unless (ival was OP_NULL or we
2265  * had an OP_CONST or OP_READLINE).  This just sets us up for a
2266  * call to S_sublex_push().
2267  */
2268
2269 STATIC I32
2270 S_sublex_start(pTHX)
2271 {
2272     dVAR;
2273     register const I32 op_type = pl_yylval.ival;
2274
2275     if (op_type == OP_NULL) {
2276         pl_yylval.opval = PL_lex_op;
2277         PL_lex_op = NULL;
2278         return THING;
2279     }
2280     if (op_type == OP_CONST || op_type == OP_READLINE) {
2281         SV *sv = tokeq(PL_lex_stuff);
2282
2283         if (SvTYPE(sv) == SVt_PVIV) {
2284             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2285             STRLEN len;
2286             const char * const p = SvPV_const(sv, len);
2287             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2288             SvREFCNT_dec(sv);
2289             sv = nsv;
2290         }
2291         pl_yylval.opval = (OP*)newSVOP(op_type, 0, sv);
2292         PL_lex_stuff = NULL;
2293         /* Allow <FH> // "foo" */
2294         if (op_type == OP_READLINE)
2295             PL_expect = XTERMORDORDOR;
2296         return THING;
2297     }
2298     else if (op_type == OP_BACKTICK && PL_lex_op) {
2299         /* readpipe() vas overriden */
2300         cSVOPx(cLISTOPx(cUNOPx(PL_lex_op)->op_first)->op_first->op_sibling)->op_sv = tokeq(PL_lex_stuff);
2301         pl_yylval.opval = PL_lex_op;
2302         PL_lex_op = NULL;
2303         PL_lex_stuff = NULL;
2304         return THING;
2305     }
2306
2307     PL_sublex_info.super_state = PL_lex_state;
2308     PL_sublex_info.sub_inwhat = (U16)op_type;
2309     PL_sublex_info.sub_op = PL_lex_op;
2310     PL_lex_state = LEX_INTERPPUSH;
2311
2312     PL_expect = XTERM;
2313     if (PL_lex_op) {
2314         pl_yylval.opval = PL_lex_op;
2315         PL_lex_op = NULL;
2316         return PMFUNC;
2317     }
2318     else
2319         return FUNC;
2320 }
2321
2322 /*
2323  * S_sublex_push
2324  * Create a new scope to save the lexing state.  The scope will be
2325  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2326  * to the uc, lc, etc. found before.
2327  * Sets PL_lex_state to LEX_INTERPCONCAT.
2328  */
2329
2330 STATIC I32
2331 S_sublex_push(pTHX)
2332 {
2333     dVAR;
2334     ENTER;
2335
2336     PL_lex_state = PL_sublex_info.super_state;
2337     SAVEBOOL(PL_lex_dojoin);
2338     SAVEI32(PL_lex_brackets);
2339     SAVEI32(PL_lex_casemods);
2340     SAVEI32(PL_lex_starts);
2341     SAVEI8(PL_lex_state);
2342     SAVEVPTR(PL_lex_inpat);
2343     SAVEI16(PL_lex_inwhat);
2344     SAVECOPLINE(PL_curcop);
2345     SAVEPPTR(PL_bufptr);
2346     SAVEPPTR(PL_bufend);
2347     SAVEPPTR(PL_oldbufptr);
2348     SAVEPPTR(PL_oldoldbufptr);
2349     SAVEPPTR(PL_last_lop);
2350     SAVEPPTR(PL_last_uni);
2351     SAVEPPTR(PL_linestart);
2352     SAVESPTR(PL_linestr);
2353     SAVEGENERICPV(PL_lex_brackstack);
2354     SAVEGENERICPV(PL_lex_casestack);
2355
2356     PL_linestr = PL_lex_stuff;
2357     PL_lex_stuff = NULL;
2358
2359     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2360         = SvPVX(PL_linestr);
2361     PL_bufend += SvCUR(PL_linestr);
2362     PL_last_lop = PL_last_uni = NULL;
2363     SAVEFREESV(PL_linestr);
2364
2365     PL_lex_dojoin = FALSE;
2366     PL_lex_brackets = 0;
2367     Newx(PL_lex_brackstack, 120, char);
2368     Newx(PL_lex_casestack, 12, char);
2369     PL_lex_casemods = 0;
2370     *PL_lex_casestack = '\0';
2371     PL_lex_starts = 0;
2372     PL_lex_state = LEX_INTERPCONCAT;
2373     CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2374
2375     PL_lex_inwhat = PL_sublex_info.sub_inwhat;
2376     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2377         PL_lex_inpat = PL_sublex_info.sub_op;
2378     else
2379         PL_lex_inpat = NULL;
2380
2381     return '(';
2382 }
2383
2384 /*
2385  * S_sublex_done
2386  * Restores lexer state after a S_sublex_push.
2387  */
2388
2389 STATIC I32
2390 S_sublex_done(pTHX)
2391 {
2392     dVAR;
2393     if (!PL_lex_starts++) {
2394         SV * const sv = newSVpvs("");
2395         if (SvUTF8(PL_linestr))
2396             SvUTF8_on(sv);
2397         PL_expect = XOPERATOR;
2398         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
2399         return THING;
2400     }
2401
2402     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2403         PL_lex_state = LEX_INTERPCASEMOD;
2404         return yylex();
2405     }
2406
2407     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2408     if (PL_lex_repl && (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS)) {
2409         PL_linestr = PL_lex_repl;
2410         PL_lex_inpat = 0;
2411         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2412         PL_bufend += SvCUR(PL_linestr);
2413         PL_last_lop = PL_last_uni = NULL;
2414         SAVEFREESV(PL_linestr);
2415         PL_lex_dojoin = FALSE;
2416         PL_lex_brackets = 0;
2417         PL_lex_casemods = 0;
2418         *PL_lex_casestack = '\0';
2419         PL_lex_starts = 0;
2420         if (SvEVALED(PL_lex_repl)) {
2421             PL_lex_state = LEX_INTERPNORMAL;
2422             PL_lex_starts++;
2423             /*  we don't clear PL_lex_repl here, so that we can check later
2424                 whether this is an evalled subst; that means we rely on the
2425                 logic to ensure sublex_done() is called again only via the
2426                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2427         }
2428         else {
2429             PL_lex_state = LEX_INTERPCONCAT;
2430             PL_lex_repl = NULL;
2431         }
2432         return ',';
2433     }
2434     else {
2435 #ifdef PERL_MAD
2436         if (PL_madskills) {
2437             if (PL_thiswhite) {
2438                 if (!PL_endwhite)
2439                     PL_endwhite = newSVpvs("");
2440                 sv_catsv(PL_endwhite, PL_thiswhite);
2441                 PL_thiswhite = 0;
2442             }
2443             if (PL_thistoken)
2444                 sv_setpvs(PL_thistoken,"");
2445             else
2446                 PL_realtokenstart = -1;
2447         }
2448 #endif
2449         LEAVE;
2450         PL_bufend = SvPVX(PL_linestr);
2451         PL_bufend += SvCUR(PL_linestr);
2452         PL_expect = XOPERATOR;
2453         PL_sublex_info.sub_inwhat = 0;
2454         return ')';
2455     }
2456 }
2457
2458 /*
2459   scan_const
2460
2461   Extracts a pattern, double-quoted string, or transliteration.  This
2462   is terrifying code.
2463
2464   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2465   processing a pattern (PL_lex_inpat is true), a transliteration
2466   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2467
2468   Returns a pointer to the character scanned up to. If this is
2469   advanced from the start pointer supplied (i.e. if anything was
2470   successfully parsed), will leave an OP for the substring scanned
2471   in pl_yylval. Caller must intuit reason for not parsing further
2472   by looking at the next characters herself.
2473
2474   In patterns:
2475     backslashes:
2476       constants: \N{NAME} only
2477       case and quoting: \U \Q \E
2478     stops on @ and $, but not for $ as tail anchor
2479
2480   In transliterations:
2481     characters are VERY literal, except for - not at the start or end
2482     of the string, which indicates a range. If the range is in bytes,
2483     scan_const expands the range to the full set of intermediate
2484     characters. If the range is in utf8, the hyphen is replaced with
2485     a certain range mark which will be handled by pmtrans() in op.c.
2486
2487   In double-quoted strings:
2488     backslashes:
2489       double-quoted style: \r and \n
2490       constants: \x31, etc.
2491       deprecated backrefs: \1 (in substitution replacements)
2492       case and quoting: \U \Q \E
2493     stops on @ and $
2494
2495   scan_const does *not* construct ops to handle interpolated strings.
2496   It stops processing as soon as it finds an embedded $ or @ variable
2497   and leaves it to the caller to work out what's going on.
2498
2499   embedded arrays (whether in pattern or not) could be:
2500       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2501
2502   $ in double-quoted strings must be the symbol of an embedded scalar.
2503
2504   $ in pattern could be $foo or could be tail anchor.  Assumption:
2505   it's a tail anchor if $ is the last thing in the string, or if it's
2506   followed by one of "()| \r\n\t"
2507
2508   \1 (backreferences) are turned into $1
2509
2510   The structure of the code is
2511       while (there's a character to process) {
2512           handle transliteration ranges
2513           skip regexp comments /(?#comment)/ and codes /(?{code})/
2514           skip #-initiated comments in //x patterns
2515           check for embedded arrays
2516           check for embedded scalars
2517           if (backslash) {
2518               deprecate \1 in substitution replacements
2519               handle string-changing backslashes \l \U \Q \E, etc.
2520               switch (what was escaped) {
2521                   handle \- in a transliteration (becomes a literal -)
2522                   if a pattern and not \N{, go treat as regular character
2523                   handle \132 (octal characters)
2524                   handle \x15 and \x{1234} (hex characters)
2525                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2526                   handle \cV (control characters)
2527                   handle printf-style backslashes (\f, \r, \n, etc)
2528               } (end switch)
2529               continue
2530           } (end if backslash)
2531           handle regular character
2532     } (end while character to read)
2533                 
2534 */
2535
2536 STATIC char *
2537 S_scan_const(pTHX_ char *start)
2538 {
2539     dVAR;
2540     register char *send = PL_bufend;            /* end of the constant */
2541     SV *sv = newSV(send - start);               /* sv for the constant.  See
2542                                                    note below on sizing. */
2543     register char *s = start;                   /* start of the constant */
2544     register char *d = SvPVX(sv);               /* destination for copies */
2545     bool dorange = FALSE;                       /* are we in a translit range? */
2546     bool didrange = FALSE;                      /* did we just finish a range? */
2547     I32  has_utf8 = FALSE;                      /* Output constant is UTF8 */
2548     I32  this_utf8 = UTF;                       /* Is the source string assumed
2549                                                    to be UTF8?  But, this can
2550                                                    show as true when the source
2551                                                    isn't utf8, as for example
2552                                                    when it is entirely composed
2553                                                    of hex constants */
2554
2555     /* Note on sizing:  The scanned constant is placed into sv, which is
2556      * initialized by newSV() assuming one byte of output for every byte of
2557      * input.  This routine expects newSV() to allocate an extra byte for a
2558      * trailing NUL, which this routine will append if it gets to the end of
2559      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2560      * CAPITAL LETTER A}), or more output than input if the constant ends up
2561      * recoded to utf8, but each time a construct is found that might increase
2562      * the needed size, SvGROW() is called.  Its size parameter each time is
2563      * based on the best guess estimate at the time, namely the length used so
2564      * far, plus the length the current construct will occupy, plus room for
2565      * the trailing NUL, plus one byte for every input byte still unscanned */ 
2566
2567     UV uv;
2568 #ifdef EBCDIC
2569     UV literal_endpoint = 0;
2570     bool native_range = TRUE; /* turned to FALSE if the first endpoint is Unicode. */
2571 #endif
2572
2573     PERL_ARGS_ASSERT_SCAN_CONST;
2574
2575     if (PL_lex_inwhat == OP_TRANS && PL_sublex_info.sub_op) {
2576         /* If we are doing a trans and we know we want UTF8 set expectation */
2577         has_utf8   = PL_sublex_info.sub_op->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF);
2578         this_utf8  = PL_sublex_info.sub_op->op_private & (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
2579     }
2580
2581
2582     while (s < send || dorange) {
2583
2584         /* get transliterations out of the way (they're most literal) */
2585         if (PL_lex_inwhat == OP_TRANS) {
2586             /* expand a range A-Z to the full set of characters.  AIE! */
2587             if (dorange) {
2588                 I32 i;                          /* current expanded character */
2589                 I32 min;                        /* first character in range */
2590                 I32 max;                        /* last character in range */
2591
2592 #ifdef EBCDIC
2593                 UV uvmax = 0;
2594 #endif
2595
2596                 if (has_utf8
2597 #ifdef EBCDIC
2598                     && !native_range
2599 #endif
2600                     ) {
2601                     char * const c = (char*)utf8_hop((U8*)d, -1);
2602                     char *e = d++;
2603                     while (e-- > c)
2604                         *(e + 1) = *e;
2605                     *c = (char)UTF_TO_NATIVE(0xff);
2606                     /* mark the range as done, and continue */
2607                     dorange = FALSE;
2608                     didrange = TRUE;
2609                     continue;
2610                 }
2611
2612                 i = d - SvPVX_const(sv);                /* remember current offset */
2613 #ifdef EBCDIC
2614                 SvGROW(sv,
2615                        SvLEN(sv) + (has_utf8 ?
2616                                     (512 - UTF_CONTINUATION_MARK +
2617                                      UNISKIP(0x100))
2618                                     : 256));
2619                 /* How many two-byte within 0..255: 128 in UTF-8,
2620                  * 96 in UTF-8-mod. */
2621 #else
2622                 SvGROW(sv, SvLEN(sv) + 256);    /* never more than 256 chars in a range */
2623 #endif
2624                 d = SvPVX(sv) + i;              /* refresh d after realloc */
2625 #ifdef EBCDIC
2626                 if (has_utf8) {
2627                     int j;
2628                     for (j = 0; j <= 1; j++) {
2629                         char * const c = (char*)utf8_hop((U8*)d, -1);
2630                         const UV uv    = utf8n_to_uvchr((U8*)c, d - c, NULL, 0);
2631                         if (j)
2632                             min = (U8)uv;
2633                         else if (uv < 256)
2634                             max = (U8)uv;
2635                         else {
2636                             max = (U8)0xff; /* only to \xff */
2637                             uvmax = uv; /* \x{100} to uvmax */
2638                         }
2639                         d = c; /* eat endpoint chars */
2640                      }
2641                 }
2642                else {
2643 #endif
2644                    d -= 2;              /* eat the first char and the - */
2645                    min = (U8)*d;        /* first char in range */
2646                    max = (U8)d[1];      /* last char in range  */
2647 #ifdef EBCDIC
2648                }
2649 #endif
2650
2651                 if (min > max) {
2652                     Perl_croak(aTHX_
2653                                "Invalid range \"%c-%c\" in transliteration operator",
2654                                (char)min, (char)max);
2655                 }
2656
2657 #ifdef EBCDIC
2658                 if (literal_endpoint == 2 &&
2659                     ((isLOWER(min) && isLOWER(max)) ||
2660                      (isUPPER(min) && isUPPER(max)))) {
2661                     if (isLOWER(min)) {
2662                         for (i = min; i <= max; i++)
2663                             if (isLOWER(i))
2664                                 *d++ = NATIVE_TO_NEED(has_utf8,i);
2665                     } else {
2666                         for (i = min; i <= max; i++)
2667                             if (isUPPER(i))
2668                                 *d++ = NATIVE_TO_NEED(has_utf8,i);
2669                     }
2670                 }
2671                 else
2672 #endif
2673                     for (i = min; i <= max; i++)
2674 #ifdef EBCDIC
2675                         if (has_utf8) {
2676                             const U8 ch = (U8)NATIVE_TO_UTF(i);
2677                             if (UNI_IS_INVARIANT(ch))
2678                                 *d++ = (U8)i;
2679                             else {
2680                                 *d++ = (U8)UTF8_EIGHT_BIT_HI(ch);
2681                                 *d++ = (U8)UTF8_EIGHT_BIT_LO(ch);
2682                             }
2683                         }
2684                         else
2685 #endif
2686                             *d++ = (char)i;
2687  
2688 #ifdef EBCDIC
2689                 if (uvmax) {
2690                     d = (char*)uvchr_to_utf8((U8*)d, 0x100);
2691                     if (uvmax > 0x101)
2692                         *d++ = (char)UTF_TO_NATIVE(0xff);
2693                     if (uvmax > 0x100)
2694                         d = (char*)uvchr_to_utf8((U8*)d, uvmax);
2695                 }
2696 #endif
2697
2698                 /* mark the range as done, and continue */
2699                 dorange = FALSE;
2700                 didrange = TRUE;
2701 #ifdef EBCDIC
2702                 literal_endpoint = 0;
2703 #endif
2704                 continue;
2705             }
2706
2707             /* range begins (ignore - as first or last char) */
2708             else if (*s == '-' && s+1 < send  && s != start) {
2709                 if (didrange) {
2710                     Perl_croak(aTHX_ "Ambiguous range in transliteration operator");
2711                 }
2712                 if (has_utf8
2713 #ifdef EBCDIC
2714                     && !native_range
2715 #endif
2716                     ) {
2717                     *d++ = (char)UTF_TO_NATIVE(0xff);   /* use illegal utf8 byte--see pmtrans */
2718                     s++;
2719                     continue;
2720                 }
2721                 dorange = TRUE;
2722                 s++;
2723             }
2724             else {
2725                 didrange = FALSE;
2726 #ifdef EBCDIC
2727                 literal_endpoint = 0;
2728                 native_range = TRUE;
2729 #endif
2730             }
2731         }
2732
2733         /* if we get here, we're not doing a transliteration */
2734
2735         /* skip for regexp comments /(?#comment)/ and code /(?{code})/,
2736            except for the last char, which will be done separately. */
2737         else if (*s == '(' && PL_lex_inpat && s[1] == '?') {
2738             if (s[2] == '#') {
2739                 while (s+1 < send && *s != ')')
2740                     *d++ = NATIVE_TO_NEED(has_utf8,*s++);
2741             }
2742             else if (s[2] == '{' /* This should match regcomp.c */
2743                     || (s[2] == '?' && s[3] == '{'))
2744             {
2745                 I32 count = 1;
2746                 char *regparse = s + (s[2] == '{' ? 3 : 4);
2747                 char c;
2748
2749                 while (count && (c = *regparse)) {
2750                     if (c == '\\' && regparse[1])
2751                         regparse++;
2752                     else if (c == '{')
2753                         count++;
2754                     else if (c == '}')
2755                         count--;
2756                     regparse++;
2757                 }
2758                 if (*regparse != ')')
2759                     regparse--;         /* Leave one char for continuation. */
2760                 while (s < regparse)
2761                     *d++ = NATIVE_TO_NEED(has_utf8,*s++);
2762             }
2763         }
2764
2765         /* likewise skip #-initiated comments in //x patterns */
2766         else if (*s == '#' && PL_lex_inpat &&
2767           ((PMOP*)PL_lex_inpat)->op_pmflags & PMf_EXTENDED) {
2768             while (s+1 < send && *s != '\n')
2769                 *d++ = NATIVE_TO_NEED(has_utf8,*s++);
2770         }
2771
2772         /* check for embedded arrays
2773            (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
2774            */
2775         else if (*s == '@' && s[1]) {
2776             if (isALNUM_lazy_if(s+1,UTF))
2777                 break;
2778             if (strchr(":'{$", s[1]))
2779                 break;
2780             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
2781                 break; /* in regexp, neither @+ nor @- are interpolated */
2782         }
2783
2784         /* check for embedded scalars.  only stop if we're sure it's a
2785            variable.
2786         */
2787         else if (*s == '$') {
2788             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
2789                 break;
2790             if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
2791                 if (s[1] == '\\') {
2792                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
2793                                    "Possible unintended interpolation of $\\ in regex");
2794                 }
2795                 break;          /* in regexp, $ might be tail anchor */
2796             }
2797         }
2798
2799         /* End of else if chain - OP_TRANS rejoin rest */
2800
2801         /* backslashes */
2802         if (*s == '\\' && s+1 < send) {
2803             char* e;    /* Can be used for ending '}', etc. */
2804
2805             s++;
2806
2807             /* deprecate \1 in strings and substitution replacements */
2808             if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat &&
2809                 isDIGIT(*s) && *s != '0' && !isDIGIT(s[1]))
2810             {
2811                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
2812                 *--s = '$';
2813                 break;
2814             }
2815
2816             /* string-change backslash escapes */
2817             if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQ", *s)) {
2818                 --s;
2819                 break;
2820             }
2821             /* In a pattern, process \N, but skip any other backslash escapes.
2822              * This is because we don't want to translate an escape sequence
2823              * into a meta symbol and have the regex compiler use the meta
2824              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
2825              * in spite of this, we do have to process \N here while the proper
2826              * charnames handler is in scope.  See bugs #56444 and #62056.
2827              * There is a complication because \N in a pattern may also stand
2828              * for 'match a non-nl', and not mean a charname, in which case its
2829              * processing should be deferred to the regex compiler.  To be a
2830              * charname it must be followed immediately by a '{', and not look
2831              * like \N followed by a curly quantifier, i.e., not something like
2832              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
2833              * quantifier */
2834             else if (PL_lex_inpat
2835                     && (*s != 'N'
2836                         || s[1] != '{'
2837                         || regcurly(s + 1)))
2838             {
2839                 *d++ = NATIVE_TO_NEED(has_utf8,'\\');
2840                 goto default_action;
2841             }
2842
2843             switch (*s) {
2844
2845             /* quoted - in transliterations */
2846             case '-':
2847                 if (PL_lex_inwhat == OP_TRANS) {
2848                     *d++ = *s++;
2849                     continue;
2850                 }
2851                 /* FALL THROUGH */
2852             default:
2853                 {
2854                     if ((isALPHA(*s) || isDIGIT(*s)))
2855                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
2856                                        "Unrecognized escape \\%c passed through",
2857                                        *s);
2858                     /* default action is to copy the quoted character */
2859                     goto default_action;
2860                 }
2861
2862             /* eg. \132 indicates the octal constant 0x132 */
2863             case '0': case '1': case '2': case '3':
2864             case '4': case '5': case '6': case '7':
2865                 {
2866                     I32 flags = 0;
2867                     STRLEN len = 3;
2868                     uv = NATIVE_TO_UNI(grok_oct(s, &len, &flags, NULL));
2869                     s += len;
2870                 }
2871                 goto NUM_ESCAPE_INSERT;
2872
2873             /* eg. \x24 indicates the hex constant 0x24 */
2874             case 'x':
2875                 ++s;
2876                 if (*s == '{') {
2877                     char* const e = strchr(s, '}');
2878                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES |
2879                       PERL_SCAN_DISALLOW_PREFIX;
2880                     STRLEN len;
2881
2882                     ++s;
2883                     if (!e) {
2884                         yyerror("Missing right brace on \\x{}");
2885                         continue;
2886                     }
2887                     len = e - s;
2888                     uv = NATIVE_TO_UNI(grok_hex(s, &len, &flags, NULL));
2889                     s = e + 1;
2890                 }
2891                 else {
2892                     {
2893                         STRLEN len = 2;
2894                         I32 flags = PERL_SCAN_DISALLOW_PREFIX;
2895                         uv = NATIVE_TO_UNI(grok_hex(s, &len, &flags, NULL));
2896                         s += len;
2897                     }
2898                 }
2899
2900               NUM_ESCAPE_INSERT:
2901                 /* Insert oct or hex escaped character.  There will always be
2902                  * enough room in sv since such escapes will be longer than any
2903                  * UTF-8 sequence they can end up as, except if they force us
2904                  * to recode the rest of the string into utf8 */
2905                 
2906                 /* Here uv is the ordinal of the next character being added in
2907                  * unicode (converted from native). */
2908                 if (!UNI_IS_INVARIANT(uv)) {
2909                     if (!has_utf8 && uv > 255) {
2910                         /* Might need to recode whatever we have accumulated so
2911                          * far if it contains any chars variant in utf8 or
2912                          * utf-ebcdic. */
2913                           
2914                         SvCUR_set(sv, d - SvPVX_const(sv));
2915                         SvPOK_on(sv);
2916                         *d = '\0';
2917                         /* See Note on sizing above.  */
2918                         sv_utf8_upgrade_flags_grow(sv,
2919                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
2920                                         UNISKIP(uv) + (STRLEN)(send - s) + 1);
2921                         d = SvPVX(sv) + SvCUR(sv);
2922                         has_utf8 = TRUE;
2923                     }
2924
2925                     if (has_utf8) {
2926                         d = (char*)uvuni_to_utf8((U8*)d, uv);
2927                         if (PL_lex_inwhat == OP_TRANS &&
2928                             PL_sublex_info.sub_op) {
2929                             PL_sublex_info.sub_op->op_private |=
2930                                 (PL_lex_repl ? OPpTRANS_FROM_UTF
2931                                              : OPpTRANS_TO_UTF);
2932                         }
2933 #ifdef EBCDIC
2934                         if (uv > 255 && !dorange)
2935                             native_range = FALSE;
2936 #endif
2937                     }
2938                     else {
2939                         *d++ = (char)uv;
2940                     }
2941                 }
2942                 else {
2943                     *d++ = (char) uv;
2944                 }
2945                 continue;
2946
2947             case 'N':
2948                 /* In a non-pattern \N must be a named character, like \N{LATIN
2949                  * SMALL LETTER A} or \N{U+0041}.  For patterns, it also can
2950                  * mean to match a non-newline.  For non-patterns, named
2951                  * characters are converted to their string equivalents. In
2952                  * patterns, named characters are not converted to their
2953                  * ultimate forms for the same reasons that other escapes
2954                  * aren't.  Instead, they are converted to the \N{U+...} form
2955                  * to get the value from the charnames that is in effect right
2956                  * now, while preserving the fact that it was a named character
2957                  * so that the regex compiler knows this */
2958
2959                 /* This section of code doesn't generally use the
2960                  * NATIVE_TO_NEED() macro to transform the input.  I (khw) did
2961                  * a close examination of this macro and determined it is a
2962                  * no-op except on utfebcdic variant characters.  Every
2963                  * character generated by this that would normally need to be
2964                  * enclosed by this macro is invariant, so the macro is not
2965                  * needed, and would complicate use of copy(). There are other
2966                  * parts of this file where the macro is used inconsistently,
2967                  * but are saved by it being a no-op */
2968
2969                 /* The structure of this section of code (besides checking for
2970                  * errors and upgrading to utf8) is:
2971                  *  Further disambiguate between the two meanings of \N, and if
2972                  *      not a charname, go process it elsewhere
2973                  *  If of form \N{U+...}, pass it through if a pattern;
2974                  *      otherwise convert to utf8
2975                  *  Otherwise must be \N{NAME}: convert to \N{U+c1.c2...} if a
2976                  *  pattern; otherwise convert to utf8 */
2977
2978                 /* Here, s points to the 'N'; the test below is guaranteed to
2979                  * succeed if we are being called on a pattern as we already
2980                  * know from a test above that the next character is a '{'.
2981                  * On a non-pattern \N must mean 'named sequence, which
2982                  * requires braces */
2983                 s++;
2984                 if (*s != '{') {
2985                     yyerror("Missing braces on \\N{}"); 
2986                     continue;
2987                 }
2988                 s++;
2989
2990                 /* If there is no matching '}', it is an error. */
2991                 if (! (e = strchr(s, '}'))) {
2992                     if (! PL_lex_inpat) {
2993                         yyerror("Missing right brace on \\N{}");
2994                     } else {
2995                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N.");
2996                     }
2997                     continue;
2998                 }
2999
3000                 /* Here it looks like a named character */
3001
3002                 if (PL_lex_inpat) {
3003
3004                     /* XXX This block is temporary code.  \N{} implies that the
3005                      * pattern is to have Unicode semantics, and therefore
3006                      * currently has to be encoded in utf8.  By putting it in
3007                      * utf8 now, we save a whole pass in the regular expression
3008                      * compiler.  Once that code is changed so Unicode
3009                      * semantics doesn't necessarily have to be in utf8, this
3010                      * block should be removed */
3011                     if (!has_utf8) {
3012                         SvCUR_set(sv, d - SvPVX_const(sv));
3013                         SvPOK_on(sv);
3014                         *d = '\0';
3015                         /* See Note on sizing above.  */
3016                         sv_utf8_upgrade_flags_grow(sv,
3017                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3018                                         /* 5 = '\N{' + cur char + NUL */
3019                                         (STRLEN)(send - s) + 5);
3020                         d = SvPVX(sv) + SvCUR(sv);
3021                         has_utf8 = TRUE;
3022                     }
3023                 }
3024
3025                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3026                     I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3027                                 | PERL_SCAN_DISALLOW_PREFIX;
3028                     STRLEN len;
3029
3030                     /* For \N{U+...}, the '...' is a unicode value even on
3031                      * EBCDIC machines */
3032                     s += 2;         /* Skip to next char after the 'U+' */
3033                     len = e - s;
3034                     uv = grok_hex(s, &len, &flags, NULL);
3035                     if (len == 0 || len != (STRLEN)(e - s)) {
3036                         yyerror("Invalid hexadecimal number in \\N{U+...}");
3037                         s = e + 1;
3038                         continue;
3039                     }
3040
3041                     if (PL_lex_inpat) {
3042
3043                         /* Pass through to the regex compiler unchanged.  The
3044                          * reason we evaluated the number above is to make sure
3045                          * there wasn't a syntax error. */
3046                         s -= 5;     /* Include the '\N{U+' */
3047                         Copy(s, d, e - s + 1, char);    /* 1 = include the } */
3048                         d += e - s + 1;
3049                     }
3050                     else {  /* Not a pattern: convert the hex to string */
3051
3052                          /* If destination is not in utf8, unconditionally
3053                           * recode it to be so.  This is because \N{} implies
3054                           * Unicode semantics, and scalars have to be in utf8
3055                           * to guarantee those semantics */
3056                         if (! has_utf8) {
3057                             SvCUR_set(sv, d - SvPVX_const(sv));
3058                             SvPOK_on(sv);
3059                             *d = '\0';
3060                             /* See Note on sizing above.  */
3061                             sv_utf8_upgrade_flags_grow(
3062                                         sv,
3063                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3064                                         UNISKIP(uv) + (STRLEN)(send - e) + 1);
3065                             d = SvPVX(sv) + SvCUR(sv);
3066                             has_utf8 = TRUE;
3067                         }
3068
3069                         /* Add the string to the output */
3070                         if (UNI_IS_INVARIANT(uv)) {
3071                             *d++ = (char) uv;
3072                         }
3073                         else d = (char*)uvuni_to_utf8((U8*)d, uv);
3074                     }
3075                 }
3076                 else { /* Here is \N{NAME} but not \N{U+...}. */
3077
3078                     SV *res;            /* result from charnames */
3079                     const char *str;    /* the string in 'res' */
3080                     STRLEN len;         /* its length */
3081
3082                     /* Get the value for NAME */
3083                     res = newSVpvn(s, e - s);
3084                     res = new_constant( NULL, 0, "charnames",
3085                                         /* includes all of: \N{...} */
3086                                         res, NULL, s - 3, e - s + 4 );
3087
3088                     /* Most likely res will be in utf8 already since the
3089                      * standard charnames uses pack U, but a custom translator
3090                      * can leave it otherwise, so make sure.  XXX This can be
3091                      * revisited to not have charnames use utf8 for characters
3092                      * that don't need it when regexes don't have to be in utf8
3093                      * for Unicode semantics.  If doing so, remember EBCDIC */
3094                     sv_utf8_upgrade(res);
3095                     str = SvPV_const(res, len);
3096
3097                     /* Don't accept malformed input */
3098                     if (! is_utf8_string((U8 *) str, len)) {
3099                         yyerror("Malformed UTF-8 returned by \\N");
3100                     }
3101                     else if (PL_lex_inpat) {
3102
3103                         if (! len) { /* The name resolved to an empty string */
3104                             Copy("\\N{}", d, 4, char);
3105                             d += 4;
3106                         }
3107                         else {
3108                             /* In order to not lose information for the regex
3109                             * compiler, pass the result in the specially made
3110                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3111                             * the code points in hex of each character
3112                             * returned by charnames */
3113
3114                             const char *str_end = str + len;
3115                             STRLEN char_length;     /* cur char's byte length */
3116                             STRLEN output_length;   /* and the number of bytes
3117                                                        after this is translated
3118                                                        into hex digits */
3119                             const STRLEN off = d - SvPVX_const(sv);
3120
3121                             /* 2 hex per byte; 2 chars for '\N'; 2 chars for
3122                              * max('U+', '.'); and 1 for NUL */
3123                             char hex_string[2 * UTF8_MAXBYTES + 5];
3124
3125                             /* Get the first character of the result. */
3126                             U32 uv = utf8n_to_uvuni((U8 *) str,
3127                                                     len,
3128                                                     &char_length,
3129                                                     UTF8_ALLOW_ANYUV);
3130
3131                             /* The call to is_utf8_string() above hopefully
3132                              * guarantees that there won't be an error.  But
3133                              * it's easy here to make sure.  The function just
3134                              * above warns and returns 0 if invalid utf8, but
3135                              * it can also return 0 if the input is validly a
3136                              * NUL. Disambiguate */
3137                             if (uv == 0 && NATIVE_TO_ASCII(*str) != '\0') {
3138                                 uv = UNICODE_REPLACEMENT;
3139                             }
3140
3141                             /* Convert first code point to hex, including the
3142                              * boiler plate before it */
3143                             sprintf(hex_string, "\\N{U+%X", (unsigned int) uv);
3144                             output_length = strlen(hex_string);
3145
3146                             /* Make sure there is enough space to hold it */
3147                             d = off + SvGROW(sv, off
3148                                                  + output_length
3149                                                  + (STRLEN)(send - e)
3150                                                  + 2);  /* '}' + NUL */
3151                             /* And output it */
3152                             Copy(hex_string, d, output_length, char);
3153                             d += output_length;
3154
3155                             /* For each subsequent character, append dot and
3156                              * its ordinal in hex */
3157                             while ((str += char_length) < str_end) {
3158                                 const STRLEN off = d - SvPVX_const(sv);
3159                                 U32 uv = utf8n_to_uvuni((U8 *) str,
3160                                                         str_end - str,
3161                                                         &char_length,
3162                                                         UTF8_ALLOW_ANYUV);
3163                                 if (uv == 0 && NATIVE_TO_ASCII(*str) != '\0') {
3164                                     uv = UNICODE_REPLACEMENT;
3165                                 }
3166
3167                                 sprintf(hex_string, ".%X", (unsigned int) uv);
3168                                 output_length = strlen(hex_string);
3169
3170                                 d = off + SvGROW(sv, off
3171                                                      + output_length
3172                                                      + (STRLEN)(send - e)
3173                                                      + 2);      /* '}' +  NUL */
3174                                 Copy(hex_string, d, output_length, char);
3175                                 d += output_length;
3176                             }
3177
3178                             *d++ = '}'; /* Done.  Add the trailing brace */
3179                         }
3180                     }
3181                     else { /* Here, not in a pattern.  Convert the name to a
3182                             * string. */
3183
3184                          /* If destination is not in utf8, unconditionally
3185                           * recode it to be so.  This is because \N{} implies
3186                           * Unicode semantics, and scalars have to be in utf8
3187                           * to guarantee those semantics */
3188                         if (! has_utf8) {
3189                             SvCUR_set(sv, d - SvPVX_const(sv));
3190                             SvPOK_on(sv);
3191                             *d = '\0';
3192                             /* See Note on sizing above.  */
3193                             sv_utf8_upgrade_flags_grow(sv,
3194                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3195                                                 len + (STRLEN)(send - s) + 1);
3196                             d = SvPVX(sv) + SvCUR(sv);
3197                             has_utf8 = TRUE;
3198                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3199
3200                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3201                              * set correctly here). */
3202                             const STRLEN off = d - SvPVX_const(sv);
3203                             d = off + SvGROW(sv, off + len + (STRLEN)(send - s) + 1);
3204                         }
3205                         Copy(str, d, len, char);
3206                         d += len;
3207                     }
3208                     SvREFCNT_dec(res);
3209
3210                     /* Deprecate non-approved name syntax */
3211                     if (ckWARN_d(WARN_DEPRECATED)) {
3212                         bool problematic = FALSE;
3213                         char* i = s;
3214
3215                         /* For non-ut8 input, look to see that the first
3216                          * character is an alpha, then loop through the rest
3217                          * checking that each is a continuation */
3218                         if (! this_utf8) {
3219                             if (! isALPHAU(*i)) problematic = TRUE;
3220                             else for (i = s + 1; i < e; i++) {
3221                                 if (isCHARNAME_CONT(*i)) continue;
3222                                 problematic = TRUE;
3223                                 break;
3224                             }
3225                         }
3226                         else {
3227                             /* Similarly for utf8.  For invariants can check
3228                              * directly.  We accept anything above the latin1
3229                              * range because it is immaterial to Perl if it is
3230                              * correct or not, and is expensive to check.  But
3231                              * it is fairly easy in the latin1 range to convert
3232                              * the variants into a single character and check
3233                              * those */
3234                             if (UTF8_IS_INVARIANT(*i)) {
3235                                 if (! isALPHAU(*i)) problematic = TRUE;
3236                             } else if (UTF8_IS_DOWNGRADEABLE_START(*i)) {
3237                                 if (! isALPHAU(UNI_TO_NATIVE(UTF8_ACCUMULATE(*i,
3238                                                                             *(i+1)))))
3239                                 {
3240                                     problematic = TRUE;
3241                                 }
3242                             }
3243                             if (! problematic) for (i = s + UTF8SKIP(s);
3244                                                     i < e;
3245                                                     i+= UTF8SKIP(i))
3246                             {
3247                                 if (UTF8_IS_INVARIANT(*i)) {
3248                                     if (isCHARNAME_CONT(*i)) continue;
3249                                 } else if (! UTF8_IS_DOWNGRADEABLE_START(*i)) {
3250                                     continue;
3251                                 } else if (isCHARNAME_CONT(
3252                                             UNI_TO_NATIVE(
3253                                             UTF8_ACCUMULATE(*i, *(i+1)))))
3254                                 {
3255                                     continue;
3256                                 }
3257                                 problematic = TRUE;
3258                                 break;
3259                             }
3260                         }
3261                         if (problematic) {
3262                             char *string;
3263                             Newx(string, e - i + 1, char);
3264                             Copy(i, string, e - i, char);
3265                             string[e - i] = '\0';
3266                             Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
3267                                 "Deprecated character(s) in \\N{...} starting at '%s'",
3268                                 string);
3269                             Safefree(string);
3270                         }
3271                     }
3272                 } /* End \N{NAME} */
3273 #ifdef EBCDIC
3274                 if (!dorange) 
3275                     native_range = FALSE; /* \N{} is defined to be Unicode */
3276 #endif
3277                 s = e + 1;  /* Point to just after the '}' */
3278                 continue;
3279
3280             /* \c is a control character */
3281             case 'c':
3282                 s++;
3283                 if (s < send) {
3284                     U8 c = *s++;
3285 #ifdef EBCDIC
3286                     if (isLOWER(c))
3287                         c = toUPPER(c);
3288 #endif
3289                     *d++ = NATIVE_TO_NEED(has_utf8,toCTRL(c));
3290                 }
3291                 else {
3292                     yyerror("Missing control char name in \\c");
3293                 }
3294                 continue;
3295
3296             /* printf-style backslashes, formfeeds, newlines, etc */
3297             case 'b':
3298                 *d++ = NATIVE_TO_NEED(has_utf8,'\b');
3299                 break;
3300             case 'n':
3301                 *d++ = NATIVE_TO_NEED(has_utf8,'\n');
3302                 break;
3303             case 'r':
3304                 *d++ = NATIVE_TO_NEED(has_utf8,'\r');
3305                 break;
3306             case 'f':
3307                 *d++ = NATIVE_TO_NEED(has_utf8,'\f');
3308                 break;
3309             case 't':
3310                 *d++ = NATIVE_TO_NEED(has_utf8,'\t');
3311                 break;
3312             case 'e':
3313                 *d++ = ASCII_TO_NEED(has_utf8,'\033');
3314                 break;
3315             case 'a':
3316                 *d++ = ASCII_TO_NEED(has_utf8,'\007');
3317                 break;
3318             } /* end switch */
3319
3320             s++;
3321             continue;
3322         } /* end if (backslash) */
3323 #ifdef EBCDIC
3324         else
3325             literal_endpoint++;
3326 #endif
3327
3328     default_action:
3329         /* If we started with encoded form, or already know we want it,
3330            then encode the next character */
3331         if (! NATIVE_IS_INVARIANT((U8)(*s)) && (this_utf8 || has_utf8)) {
3332             STRLEN len  = 1;
3333
3334
3335             /* One might think that it is wasted effort in the case of the
3336              * source being utf8 (this_utf8 == TRUE) to take the next character
3337              * in the source, convert it to an unsigned value, and then convert
3338              * it back again.  But the source has not been validated here.  The
3339              * routine that does the conversion checks for errors like
3340              * malformed utf8 */
3341
3342             const UV nextuv   = (this_utf8) ? utf8n_to_uvchr((U8*)s, send - s, &len, 0) : (UV) ((U8) *s);
3343             const STRLEN need = UNISKIP(NATIVE_TO_UNI(nextuv));
3344             if (!has_utf8) {
3345                 SvCUR_set(sv, d - SvPVX_const(sv));
3346                 SvPOK_on(sv);
3347                 *d = '\0';
3348                 /* See Note on sizing above.  */
3349                 sv_utf8_upgrade_flags_grow(sv,
3350                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3351                                         need + (STRLEN)(send - s) + 1);
3352                 d = SvPVX(sv) + SvCUR(sv);
3353                 has_utf8 = TRUE;
3354             } else if (need > len) {
3355                 /* encoded value larger than old, may need extra space (NOTE:
3356                  * SvCUR() is not set correctly here).   See Note on sizing
3357                  * above.  */
3358                 const STRLEN off = d - SvPVX_const(sv);
3359                 d = SvGROW(sv, off + need + (STRLEN)(send - s) + 1) + off;
3360             }
3361             s += len;
3362
3363             d = (char*)uvchr_to_utf8((U8*)d, nextuv);
3364 #ifdef EBCDIC
3365             if (uv > 255 && !dorange)
3366                 native_range = FALSE;
3367 #endif
3368         }
3369         else {
3370             *d++ = NATIVE_TO_NEED(has_utf8,*s++);
3371         }
3372     } /* while loop to process each character */
3373
3374     /* terminate the string and set up the sv */
3375     *d = '\0';
3376     SvCUR_set(sv, d - SvPVX_const(sv));
3377     if (SvCUR(sv) >= SvLEN(sv))
3378         Perl_croak(aTHX_ "panic: constant overflowed allocated space");
3379
3380     SvPOK_on(sv);
3381     if (PL_encoding && !has_utf8) {
3382         sv_recode_to_utf8(sv, PL_encoding);
3383         if (SvUTF8(sv))
3384             has_utf8 = TRUE;
3385     }
3386     if (has_utf8) {
3387         SvUTF8_on(sv);
3388         if (PL_lex_inwhat == OP_TRANS && PL_sublex_info.sub_op) {
3389             PL_sublex_info.sub_op->op_private |=
3390                     (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
3391         }
3392     }
3393
3394     /* shrink the sv if we allocated more than we used */
3395     if (SvCUR(sv) + 5 < SvLEN(sv)) {
3396         SvPV_shrink_to_cur(sv);
3397     }
3398
3399     /* return the substring (via pl_yylval) only if we parsed anything */
3400     if (s > PL_bufptr) {
3401         if ( PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ) ) {
3402             const char *const key = PL_lex_inpat ? "qr" : "q";
3403             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
3404             const char *type;
3405             STRLEN typelen;
3406
3407             if (PL_lex_inwhat == OP_TRANS) {
3408                 type = "tr";
3409                 typelen = 2;
3410             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
3411                 type = "s";
3412                 typelen = 1;
3413             } else  {
3414                 type = "qq";
3415                 typelen = 2;
3416             }
3417
3418             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
3419                                 type, typelen);
3420         }
3421         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
3422     } else
3423         SvREFCNT_dec(sv);
3424     return s;
3425 }
3426
3427 /* S_intuit_more
3428  * Returns TRUE if there's more to the expression (e.g., a subscript),
3429  * FALSE otherwise.
3430  *
3431  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
3432  *
3433  * ->[ and ->{ return TRUE
3434  * { and [ outside a pattern are always subscripts, so return TRUE
3435  * if we're outside a pattern and it's not { or [, then return FALSE
3436  * if we're in a pattern and the first char is a {
3437  *   {4,5} (any digits around the comma) returns FALSE
3438  * if we're in a pattern and the first char is a [
3439  *   [] returns FALSE
3440  *   [SOMETHING] has a funky algorithm to decide whether it's a
3441  *      character class or not.  It has to deal with things like
3442  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
3443  * anything else returns TRUE
3444  */
3445
3446 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
3447
3448 STATIC int
3449 S_intuit_more(pTHX_ register char *s)
3450 {
3451     dVAR;
3452
3453     PERL_ARGS_ASSERT_INTUIT_MORE;
3454
3455     if (PL_lex_brackets)
3456         return TRUE;
3457     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
3458         return TRUE;
3459     if (*s != '{' && *s != '[')
3460         return FALSE;
3461     if (!PL_lex_inpat)
3462         return TRUE;
3463
3464     /* In a pattern, so maybe we have {n,m}. */
3465     if (*s == '{') {
3466         s++;
3467         if (!isDIGIT(*s))
3468             return TRUE;
3469         while (isDIGIT(*s))
3470             s++;
3471         if (*s == ',')
3472             s++;
3473         while (isDIGIT(*s))
3474             s++;
3475         if (*s == '}')
3476             return FALSE;
3477         return TRUE;
3478         
3479     }
3480
3481     /* On the other hand, maybe we have a character class */
3482
3483     s++;
3484     if (*s == ']' || *s == '^')
3485         return FALSE;
3486     else {
3487         /* this is terrifying, and it works */
3488         int weight = 2;         /* let's weigh the evidence */
3489         char seen[256];
3490         unsigned char un_char = 255, last_un_char;
3491         const char * const send = strchr(s,']');
3492         char tmpbuf[sizeof PL_tokenbuf * 4];
3493
3494         if (!send)              /* has to be an expression */
3495             return TRUE;
3496
3497         Zero(seen,256,char);
3498         if (*s == '$')
3499             weight -= 3;
3500         else if (isDIGIT(*s)) {
3501             if (s[1] != ']') {
3502                 if (isDIGIT(s[1]) && s[2] == ']')
3503                     weight -= 10;
3504             }
3505             else
3506                 weight -= 100;
3507         }
3508         for (; s < send; s++) {
3509             last_un_char = un_char;
3510             un_char = (unsigned char)*s;
3511             switch (*s) {
3512             case '@':
3513             case '&':
3514             case '$':
3515                 weight -= seen[un_char] * 10;
3516                 if (isALNUM_lazy_if(s+1,UTF)) {
3517                     int len;
3518                     scan_ident(s, send, tmpbuf, sizeof tmpbuf, FALSE);
3519                     len = (int)strlen(tmpbuf);
3520                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len, 0, SVt_PV))
3521                         weight -= 100;
3522                     else
3523                         weight -= 10;
3524                 }
3525                 else if (*s == '$' && s[1] &&
3526                   strchr("[#!%*<>()-=",s[1])) {
3527                     if (/*{*/ strchr("])} =",s[2]))
3528                         weight -= 10;
3529                     else
3530                         weight -= 1;
3531                 }
3532                 break;
3533             case '\\':
3534                 un_char = 254;
3535                 if (s[1]) {
3536                     if (strchr("wds]",s[1]))
3537                         weight += 100;
3538                     else if (seen[(U8)'\''] || seen[(U8)'"'])
3539                         weight += 1;
3540                     else if (strchr("rnftbxcav",s[1]))
3541                         weight += 40;
3542                     else if (isDIGIT(s[1])) {
3543                         weight += 40;
3544                         while (s[1] && isDIGIT(s[1]))
3545                             s++;
3546                     }
3547                 }
3548                 else
3549                     weight += 100;
3550                 break;
3551             case '-':
3552                 if (s[1] == '\\')
3553                     weight += 50;
3554                 if (strchr("aA01! ",last_un_char))
3555                     weight += 30;
3556                 if (strchr("zZ79~",s[1]))
3557                     weight += 30;
3558                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
3559                     weight -= 5;        /* cope with negative subscript */
3560                 break;
3561             default:
3562                 if (!isALNUM(last_un_char)
3563                     && !(last_un_char == '$' || last_un_char == '@'
3564                          || last_un_char == '&')
3565                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
3566                     char *d = tmpbuf;
3567                     while (isALPHA(*s))
3568                         *d++ = *s++;
3569                     *d = '\0';
3570                     if (keyword(tmpbuf, d - tmpbuf, 0))
3571                         weight -= 150;
3572                 }
3573                 if (un_char == last_un_char + 1)
3574                     weight += 5;
3575                 weight -= seen[un_char];
3576                 break;
3577             }
3578             seen[un_char]++;
3579         }
3580         if (weight >= 0)        /* probably a character class */
3581             return FALSE;
3582     }
3583
3584     return TRUE;
3585 }
3586
3587 /*
3588  * S_intuit_method
3589  *
3590  * Does all the checking to disambiguate
3591  *   foo bar
3592  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
3593  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
3594  *
3595  * First argument is the stuff after the first token, e.g. "bar".
3596  *
3597  * Not a method if bar is a filehandle.
3598  * Not a method if foo is a subroutine prototyped to take a filehandle.
3599  * Not a method if it's really "Foo $bar"
3600  * Method if it's "foo $bar"
3601  * Not a method if it's really "print foo $bar"
3602  * Method if it's really "foo package::" (interpreted as package->foo)
3603  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
3604  * Not a method if bar is a filehandle or package, but is quoted with
3605  *   =>
3606  */
3607
3608 STATIC int
3609 S_intuit_method(pTHX_ char *start, GV *gv, CV *cv)
3610 {
3611     dVAR;
3612     char *s = start + (*start == '$');
3613     char tmpbuf[sizeof PL_tokenbuf];
3614     STRLEN len;
3615     GV* indirgv;
3616 #ifdef PERL_MAD
3617     int soff;
3618 #endif
3619
3620     PERL_ARGS_ASSERT_INTUIT_METHOD;
3621
3622     if (gv) {
3623         if (SvTYPE(gv) == SVt_PVGV && GvIO(gv))
3624             return 0;
3625         if (cv) {
3626             if (SvPOK(cv)) {
3627                 const char *proto = SvPVX_const(cv);
3628                 if (proto) {
3629                     if (*proto == ';')
3630                         proto++;
3631                     if (*proto == '*')
3632                         return 0;
3633                 }
3634             }
3635         } else
3636             gv = NULL;
3637     }
3638     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
3639     /* start is the beginning of the possible filehandle/object,
3640      * and s is the end of it
3641      * tmpbuf is a copy of it
3642      */
3643
3644     if (*start == '$') {
3645         if (gv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY ||
3646                 isUPPER(*PL_tokenbuf))
3647             return 0;
3648 #ifdef PERL_MAD
3649         len = start - SvPVX(PL_linestr);
3650 #endif
3651         s = PEEKSPACE(s);
3652 #ifdef PERL_MAD
3653         start = SvPVX(PL_linestr) + len;
3654 #endif
3655         PL_bufptr = start;
3656         PL_expect = XREF;
3657         return *s == '(' ? FUNCMETH : METHOD;
3658     }
3659     if (!keyword(tmpbuf, len, 0)) {
3660         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
3661             len -= 2;
3662             tmpbuf[len] = '\0';
3663 #ifdef PERL_MAD
3664             soff = s - SvPVX(PL_linestr);
3665 #endif
3666             goto bare_package;
3667         }
3668         indirgv = gv_fetchpvn_flags(tmpbuf, len, 0, SVt_PVCV);
3669         if (indirgv && GvCVu(indirgv))
3670             return 0;
3671         /* filehandle or package name makes it a method */
3672         if (!gv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, 0)) {
3673 #ifdef PERL_MAD
3674             soff = s - SvPVX(PL_linestr);
3675 #endif
3676             s = PEEKSPACE(s);
3677             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
3678                 return 0;       /* no assumptions -- "=>" quotes bearword */
3679       bare_package:
3680             start_force(PL_curforce);
3681             NEXTVAL_NEXTTOKE.opval = (OP*)newSVOP(OP_CONST, 0,
3682                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
3683             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
3684             if (PL_madskills)
3685                 curmad('X', newSVpvn(start,SvPVX(PL_linestr) + soff - start));
3686             PL_expect = XTERM;
3687             force_next(WORD);
3688             PL_bufptr = s;
3689 #ifdef PERL_MAD
3690             PL_bufptr = SvPVX(PL_linestr) + soff; /* restart before space */
3691 #endif
3692             return *s == '(' ? FUNCMETH : METHOD;
3693         }
3694     }
3695     return 0;
3696 }
3697
3698 /* Encoded script support. filter_add() effectively inserts a
3699  * 'pre-processing' function into the current source input stream.
3700  * Note that the filter function only applies to the current source file
3701  * (e.g., it will not affect files 'require'd or 'use'd by this one).
3702  *
3703  * The datasv parameter (which may be NULL) can be used to pass
3704  * private data to this instance of the filter. The filter function
3705  * can recover the SV using the FILTER_DATA macro and use it to
3706  * store private buffers and state information.
3707  *
3708  * The supplied datasv parameter is upgraded to a PVIO type
3709  * and the IoDIRP/IoANY field is used to store the function pointer,
3710  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
3711  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
3712  * private use must be set using malloc'd pointers.
3713  */
3714
3715 SV *
3716 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
3717 {
3718     dVAR;
3719     if (!funcp)
3720         return NULL;
3721
3722     if (!PL_parser)
3723         return NULL;
3724
3725     if (!PL_rsfp_filters)
3726         PL_rsfp_filters = newAV();
3727     if (!datasv)
3728         datasv = newSV(0);
3729     SvUPGRADE(datasv, SVt_PVIO);
3730     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
3731     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
3732     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
3733                           FPTR2DPTR(void *, IoANY(datasv)),
3734                           SvPV_nolen(datasv)));
3735     av_unshift(PL_rsfp_filters, 1);
3736     av_store(PL_rsfp_filters, 0, datasv) ;
3737     return(datasv);
3738 }
3739
3740
3741 /* Delete most recently added instance of this filter function. */
3742 void
3743 Perl_filter_del(pTHX_ filter_t funcp)
3744 {
3745     dVAR;
3746     SV *datasv;
3747
3748     PERL_ARGS_ASSERT_FILTER_DEL;
3749
3750 #ifdef DEBUGGING
3751     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
3752                           FPTR2DPTR(void*, funcp)));
3753 #endif
3754     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
3755         return;
3756     /* if filter is on top of stack (usual case) just pop it off */
3757     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
3758     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
3759         IoFLAGS(datasv) &= ~IOf_FAKE_DIRP;
3760         IoANY(datasv) = (void *)NULL;
3761         sv_free(av_pop(PL_rsfp_filters));
3762
3763         return;
3764     }
3765     /* we need to search for the correct entry and clear it     */
3766     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
3767 }
3768
3769
3770 /* Invoke the idxth filter function for the current rsfp.        */
3771 /* maxlen 0 = read one text line */
3772 I32
3773 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
3774 {
3775     dVAR;
3776     filter_t funcp;
3777     SV *datasv = NULL;
3778     /* This API is bad. It should have been using unsigned int for maxlen.
3779        Not sure if we want to change the API, but if not we should sanity
3780        check the value here.  */
3781     const unsigned int correct_length
3782         = maxlen < 0 ?
3783 #ifdef PERL_MICRO
3784         0x7FFFFFFF
3785 #else
3786         INT_MAX
3787 #endif
3788         : maxlen;
3789
3790     PERL_ARGS_ASSERT_FILTER_READ;
3791
3792     if (!PL_parser || !PL_rsfp_filters)
3793         return -1;
3794     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
3795         /* Provide a default input filter to make life easy.    */
3796         /* Note that we append to the line. This is handy.      */
3797         DEBUG_P(PerlIO_printf(Perl_debug_log,
3798                               "filter_read %d: from rsfp\n", idx));
3799         if (correct_length) {
3800             /* Want a block */
3801             int len ;
3802             const int old_len = SvCUR(buf_sv);
3803
3804             /* ensure buf_sv is large enough */
3805             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
3806             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
3807                                    correct_length)) <= 0) {
3808                 if (PerlIO_error(PL_rsfp))
3809                     return -1;          /* error */
3810                 else
3811                     return 0 ;          /* end of file */
3812             }
3813             SvCUR_set(buf_sv, old_len + len) ;
3814             SvPVX(buf_sv)[old_len + len] = '\0';
3815         } else {
3816             /* Want a line */
3817             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
3818                 if (PerlIO_error(PL_rsfp))
3819                     return -1;          /* error */
3820                 else
3821                     return 0 ;          /* end of file */
3822             }
3823         }
3824         return SvCUR(buf_sv);
3825     }
3826     /* Skip this filter slot if filter has been deleted */
3827     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
3828         DEBUG_P(PerlIO_printf(Perl_debug_log,
3829                               "filter_read %d: skipped (filter deleted)\n",
3830                               idx));
3831         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
3832     }
3833     /* Get function pointer hidden within datasv        */
3834     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
3835     DEBUG_P(PerlIO_printf(Perl_debug_log,
3836                           "filter_read %d: via function %p (%s)\n",
3837                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
3838     /* Call function. The function is expected to       */
3839     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
3840     /* Return: <0:error, =0:eof, >0:not eof             */
3841     return (*funcp)(aTHX_ idx, buf_sv, correct_length);
3842 }
3843
3844 STATIC char *
3845 S_filter_gets(pTHX_ register SV *sv, STRLEN append)
3846 {
3847     dVAR;
3848
3849     PERL_ARGS_ASSERT_FILTER_GETS;
3850
3851 #ifdef PERL_CR_FILTER
3852     if (!PL_rsfp_filters) {
3853         filter_add(S_cr_textfilter,NULL);
3854     }
3855 #endif
3856     if (PL_rsfp_filters) {
3857         if (!append)
3858             SvCUR_set(sv, 0);   /* start with empty line        */
3859         if (FILTER_READ(0, sv, 0) > 0)
3860             return ( SvPVX(sv) ) ;
3861         else
3862             return NULL ;
3863     }
3864     else
3865         return (sv_gets(sv, PL_rsfp, append));
3866 }
3867
3868 STATIC HV *
3869 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
3870 {
3871     dVAR;
3872     GV *gv;
3873
3874     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
3875
3876     if (len == 11 && *pkgname == '_' && strEQ(pkgname, "__PACKAGE__"))
3877         return PL_curstash;
3878
3879     if (len > 2 &&
3880         (pkgname[len - 2] == ':' && pkgname[len - 1] == ':') &&
3881         (gv = gv_fetchpvn_flags(pkgname, len, 0, SVt_PVHV)))
3882     {
3883         return GvHV(gv);                        /* Foo:: */
3884     }
3885
3886     /* use constant CLASS => 'MyClass' */
3887     gv = gv_fetchpvn_flags(pkgname, len, 0, SVt_PVCV);
3888     if (gv && GvCV(gv)) {
3889         SV * const sv = cv_const_sv(GvCV(gv));
3890         if (sv)
3891             pkgname = SvPV_const(sv, len);
3892     }
3893
3894     return gv_stashpvn(pkgname, len, 0);
3895 }
3896
3897 /*
3898  * S_readpipe_override
3899  * Check whether readpipe() is overriden, and generates the appropriate
3900  * optree, provided sublex_start() is called afterwards.
3901  */
3902 STATIC void
3903 S_readpipe_override(pTHX)
3904 {
3905     GV **gvp;
3906     GV *gv_readpipe = gv_fetchpvs("readpipe", GV_NOTQUAL, SVt_PVCV);
3907     pl_yylval.ival = OP_BACKTICK;
3908     if ((gv_readpipe
3909                 && GvCVu(gv_readpipe) && GvIMPORTED_CV(gv_readpipe))
3910             ||
3911             ((gvp = (GV**)hv_fetchs(PL_globalstash, "readpipe", FALSE))
3912              && (gv_readpipe = *gvp) && isGV_with_GP(gv_readpipe)
3913              && GvCVu(gv_readpipe) && GvIMPORTED_CV(gv_readpipe)))
3914     {
3915         PL_lex_op = (OP*)newUNOP(OP_ENTERSUB, OPf_STACKED,
3916             append_elem(OP_LIST,
3917                 newSVOP(OP_CONST, 0, &PL_sv_undef), /* value will be read later */
3918                 newCVREF(0, newGVOP(OP_GV, 0, gv_readpipe))));
3919     }
3920 }
3921
3922 #ifdef PERL_MAD 
3923  /*
3924  * Perl_madlex
3925  * The intent of this yylex wrapper is to minimize the changes to the
3926  * tokener when we aren't interested in collecting madprops.  It remains
3927  * to be seen how successful this strategy will be...
3928  */
3929
3930 int
3931 Perl_madlex(pTHX)
3932 {
3933     int optype;
3934     char *s = PL_bufptr;
3935
3936     /* make sure PL_thiswhite is initialized */
3937     PL_thiswhite = 0;
3938     PL_thismad = 0;
3939
3940     /* just do what yylex would do on pending identifier; leave PL_thiswhite alone */
3941     if (PL_pending_ident)
3942         return S_pending_ident(aTHX);
3943
3944     /* previous token ate up our whitespace? */
3945     if (!PL_lasttoke && PL_nextwhite) {
3946         PL_thiswhite = PL_nextwhite;
3947         PL_nextwhite = 0;
3948     }
3949
3950     /* isolate the token, and figure out where it is without whitespace */
3951     PL_realtokenstart = -1;
3952     PL_thistoken = 0;
3953     optype = yylex();
3954     s = PL_bufptr;
3955     assert(PL_curforce < 0);
3956
3957     if (!PL_thismad || PL_thismad->mad_key == '^') {    /* not forced already? */
3958         if (!PL_thistoken) {
3959             if (PL_realtokenstart < 0 || !CopLINE(PL_curcop))
3960                 PL_thistoken = newSVpvs("");
3961             else {
3962                 char * const tstart = SvPVX(PL_linestr) + PL_realtokenstart;
3963                 PL_thistoken = newSVpvn(tstart, s - tstart);
3964             }
3965         }
3966         if (PL_thismad) /* install head */
3967             CURMAD('X', PL_thistoken);
3968     }
3969
3970     /* last whitespace of a sublex? */
3971     if (optype == ')' && PL_endwhite) {
3972         CURMAD('X', PL_endwhite);
3973     }
3974
3975     if (!PL_thismad) {
3976
3977         /* if no whitespace and we're at EOF, bail.  Otherwise fake EOF below. */
3978         if (!PL_thiswhite && !PL_endwhite && !optype) {
3979             sv_free(PL_thistoken);
3980             PL_thistoken = 0;
3981             return 0;
3982         }
3983
3984         /* put off final whitespace till peg */
3985         if (optype == ';' && !PL_rsfp) {
3986             PL_nextwhite = PL_thiswhite;
3987             PL_thiswhite = 0;
3988         }
3989         else if (PL_thisopen) {
3990             CURMAD('q', PL_thisopen);
3991             if (PL_thistoken)
3992                 sv_free(PL_thistoken);
3993             PL_thistoken = 0;
3994         }
3995         else {
3996             /* Store actual token text as madprop X */
3997             CURMAD('X', PL_thistoken);
3998         }
3999
4000         if (PL_thiswhite) {
4001             /* add preceding whitespace as madprop _ */
4002             CURMAD('_', PL_thiswhite);
4003         }
4004
4005         if (PL_thisstuff) {
4006             /* add quoted material as madprop = */
4007             CURMAD('=', PL_thisstuff);
4008         }
4009
4010         if (PL_thisclose) {
4011             /* add terminating quote as madprop Q */
4012             CURMAD('Q', PL_thisclose);
4013         }
4014     }
4015
4016     /* special processing based on optype */
4017
4018     switch (optype) {
4019
4020     /* opval doesn't need a TOKEN since it can already store mp */
4021     case WORD:
4022     case METHOD:
4023     case FUNCMETH:
4024     case THING:
4025     case PMFUNC:
4026     case PRIVATEREF:
4027     case FUNC0SUB:
4028     case UNIOPSUB:
4029     case LSTOPSUB:
4030         if (pl_yylval.opval)
4031             append_madprops(PL_thismad, pl_yylval.opval, 0);
4032         PL_thismad = 0;
4033         return optype;
4034
4035     /* fake EOF */
4036     case 0:
4037         optype = PEG;
4038         if (PL_endwhite) {
4039             addmad(newMADsv('p', PL_endwhite), &PL_thismad, 0);
4040             PL_endwhite = 0;
4041         }
4042         break;
4043
4044     case ']':
4045     case '}':
4046         if (PL_faketokens)
4047             break;
4048         /* remember any fake bracket that lexer is about to discard */ 
4049         if (PL_lex_brackets == 1 &&
4050             ((expectation)PL_lex_brackstack[0] & XFAKEBRACK))
4051         {
4052             s = PL_bufptr;
4053             while (s < PL_bufend && (*s == ' ' || *s == '\t'))
4054                 s++;
4055             if (*s == '}') {
4056                 PL_thiswhite = newSVpvn(PL_bufptr, ++s - PL_bufptr);
4057                 addmad(newMADsv('#', PL_thiswhite), &PL_thismad, 0);
4058                 PL_thiswhite = 0;
4059                 PL_bufptr = s - 1;
4060                 break;  /* don't bother looking for trailing comment */
4061             }
4062             else
4063                 s = PL_bufptr;
4064         }
4065         if (optype == ']')
4066             break;
4067         /* FALLTHROUGH */
4068
4069     /* attach a trailing comment to its statement instead of next token */
4070     case ';':
4071         if (PL_faketokens)
4072             break;
4073         if (PL_bufptr > PL_oldbufptr && PL_bufptr[-1] == optype) {
4074             s = PL_bufptr;
4075             while (s < PL_bufend && (*s == ' ' || *s == '\t'))
4076                 s++;
4077             if (*s == '\n' || *s == '#') {
4078                 while (s < PL_bufend && *s != '\n')
4079                     s++;
4080                 if (s < PL_bufend)
4081                     s++;
4082                 PL_thiswhite = newSVpvn(PL_bufptr, s - PL_bufptr);
4083                 addmad(newMADsv('#', PL_thiswhite), &PL_thismad, 0);
4084                 PL_thiswhite = 0;
4085                 PL_bufptr = s;
4086             }
4087         }
4088         break;
4089
4090     /* pval */
4091     case LABEL:
4092         break;
4093
4094     /* ival */
4095     default:
4096         break;
4097
4098     }
4099
4100     /* Create new token struct.  Note: opvals return early above. */
4101     pl_yylval.tkval = newTOKEN(optype, pl_yylval, PL_thismad);
4102     PL_thismad = 0;
4103     return optype;
4104 }
4105 #endif
4106
4107 STATIC char *
4108 S_tokenize_use(pTHX_ int is_use, char *s) {
4109     dVAR;
4110
4111     PERL_ARGS_ASSERT_TOKENIZE_USE;
4112
4113     if (PL_expect != XSTATE)
4114         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4115                     is_use ? "use" : "no"));
4116     s = SKIPSPACE1(s);
4117     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4118         s = force_version(s, TRUE);
4119         if (*s == ';' || *s == '}'
4120                 || (s = SKIPSPACE1(s), (*s == ';' || *s == '}'))) {
4121             start_force(PL_curforce);
4122             NEXTVAL_NEXTTOKE.opval = NULL;
4123             force_next(WORD);
4124         }
4125         else if (*s == 'v') {
4126             s = force_word(s,WORD,FALSE,TRUE,FALSE);
4127             s = force_version(s, FALSE);
4128         }
4129     }
4130     else {
4131         s = force_word(s,WORD,FALSE,TRUE,FALSE);
4132         s = force_version(s, FALSE);
4133     }
4134     pl_yylval.ival = is_use;
4135     return s;
4136 }
4137 #ifdef DEBUGGING
4138     static const char* const exp_name[] =
4139         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4140           "ATTRTERM", "TERMBLOCK", "TERMORDORDOR"
4141         };
4142 #endif
4143
4144 /*
4145   yylex
4146
4147   Works out what to call the token just pulled out of the input
4148   stream.  The yacc parser takes care of taking the ops we return and
4149   stitching them into a tree.
4150
4151   Returns:
4152     PRIVATEREF
4153
4154   Structure:
4155       if read an identifier
4156           if we're in a my declaration
4157               croak if they tried to say my($foo::bar)
4158               build the ops for a my() declaration
4159           if it's an access to a my() variable
4160               are we in a sort block?
4161                   croak if my($a); $a <=> $b
4162               build ops for access to a my() variable
4163           if in a dq string, and they've said @foo and we can't find @foo
4164               croak
4165           build ops for a bareword
4166       if we already built the token before, use it.
4167 */
4168
4169
4170 #ifdef __SC__
4171 #pragma segment Perl_yylex
4172 #endif
4173 int
4174 Perl_yylex(pTHX)
4175 {
4176     dVAR;
4177     register char *s = PL_bufptr;
4178     register char *d;
4179     STRLEN len;
4180     bool bof = FALSE;
4181     U32 fake_eof = 0;
4182
4183     /* orig_keyword, gvp, and gv are initialized here because
4184      * jump to the label just_a_word_zero can bypass their
4185      * initialization later. */
4186     I32 orig_keyword = 0;
4187     GV *gv = NULL;
4188     GV **gvp = NULL;
4189
4190     DEBUG_T( {
4191         SV* tmp = newSVpvs("");
4192         PerlIO_printf(Perl_debug_log, "### %"IVdf":LEX_%s/X%s %s\n",
4193             (IV)CopLINE(PL_curcop),
4194             lex_state_names[PL_lex_state],
4195             exp_name[PL_expect],
4196             pv_display(tmp, s, strlen(s), 0, 60));
4197         SvREFCNT_dec(tmp);
4198     } );
4199     /* check if there's an identifier for us to look at */
4200     if (PL_pending_ident)
4201         return REPORT(S_pending_ident(aTHX));
4202
4203     /* no identifier pending identification */
4204
4205     switch (PL_lex_state) {
4206 #ifdef COMMENTARY
4207     case LEX_NORMAL:            /* Some compilers will produce faster */
4208     case LEX_INTERPNORMAL:      /* code if we comment these out. */
4209         break;
4210 #endif
4211
4212     /* when we've already built the next token, just pull it out of the queue */
4213     case LEX_KNOWNEXT:
4214 #ifdef PERL_MAD
4215         PL_lasttoke--;
4216         pl_yylval = PL_nexttoke[PL_lasttoke].next_val;
4217         if (PL_madskills) {
4218             PL_thismad = PL_nexttoke[PL_lasttoke].next_mad;
4219             PL_nexttoke[PL_lasttoke].next_mad = 0;
4220             if (PL_thismad && PL_thismad->mad_key == '_') {
4221                 PL_thiswhite = MUTABLE_SV(PL_thismad->mad_val);
4222                 PL_thismad->mad_val = 0;
4223                 mad_free(PL_thismad);
4224                 PL_thismad = 0;
4225             }
4226         }
4227         if (!PL_lasttoke) {
4228             PL_lex_state = PL_lex_defer;
4229             PL_expect = PL_lex_expect;
4230             PL_lex_defer = LEX_NORMAL;
4231             if (!PL_nexttoke[PL_lasttoke].next_type)
4232                 return yylex();
4233         }
4234 #else
4235         PL_nexttoke--;
4236         pl_yylval = PL_nextval[PL_nexttoke];
4237         if (!PL_nexttoke) {
4238             PL_lex_state = PL_lex_defer;
4239             PL_expect = PL_lex_expect;
4240             PL_lex_defer = LEX_NORMAL;
4241         }
4242 #endif
4243 #ifdef PERL_MAD
4244         /* FIXME - can these be merged?  */
4245         return(PL_nexttoke[PL_lasttoke].next_type);
4246 #else
4247         return REPORT(PL_nexttype[PL_nexttoke]);
4248 #endif
4249
4250     /* interpolated case modifiers like \L \U, including \Q and \E.
4251        when we get here, PL_bufptr is at the \
4252     */
4253     case LEX_INTERPCASEMOD:
4254 #ifdef DEBUGGING
4255         if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
4256             Perl_croak(aTHX_ "panic: INTERPCASEMOD");
4257 #endif
4258         /* handle \E or end of string */
4259         if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
4260             /* if at a \E */
4261             if (PL_lex_casemods) {
4262                 const char oldmod = PL_lex_casestack[--PL_lex_casemods];
4263                 PL_lex_casestack[PL_lex_casemods] = '\0';
4264
4265                 if (PL_bufptr != PL_bufend
4266                     && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q')) {
4267                     PL_bufptr += 2;
4268                     PL_lex_state = LEX_INTERPCONCAT;
4269 #ifdef PERL_MAD
4270                     if (PL_madskills)
4271                         PL_thistoken = newSVpvs("\\E");
4272 #endif
4273                 }
4274                 return REPORT(')');
4275             }
4276 #ifdef PERL_MAD
4277             while (PL_bufptr != PL_bufend &&
4278               PL_bufptr[0] == '\\' && PL_bufptr[1] == 'E') {
4279                 if (!PL_thiswhite)
4280                     PL_thiswhite = newSVpvs("");
4281                 sv_catpvn(PL_thiswhite, PL_bufptr, 2);
4282                 PL_bufptr += 2;
4283             }
4284 #else
4285             if (PL_bufptr != PL_bufend)
4286                 PL_bufptr += 2;
4287 #endif
4288             PL_lex_state = LEX_INTERPCONCAT;
4289             return yylex();
4290         }
4291         else {
4292             DEBUG_T({ PerlIO_printf(Perl_debug_log,
4293               "### Saw case modifier\n"); });
4294             s = PL_bufptr + 1;
4295             if (s[1] == '\\' && s[2] == 'E') {
4296 #ifdef PERL_MAD
4297                 if (!PL_thiswhite)
4298                     PL_thiswhite = newSVpvs("");
4299                 sv_catpvn(PL_thiswhite, PL_bufptr, 4);
4300 #endif
4301                 PL_bufptr = s + 3;
4302                 PL_lex_state = LEX_INTERPCONCAT;
4303                 return yylex();
4304             }
4305             else {
4306                 I32 tmp;
4307                 if (!PL_madskills) /* when just compiling don't need correct */
4308                     if (strnEQ(s, "L\\u", 3) || strnEQ(s, "U\\l", 3))
4309                         tmp = *s, *s = s[2], s[2] = (char)tmp;  /* misordered... */
4310                 if ((*s == 'L' || *s == 'U') &&
4311                     (strchr(PL_lex_casestack, 'L') || strchr(PL_lex_casestack, 'U'))) {
4312                     PL_lex_casestack[--PL_lex_casemods] = '\0';
4313                     return REPORT(')');
4314                 }
4315                 if (PL_lex_casemods > 10)
4316                     Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
4317                 PL_lex_casestack[PL_lex_casemods++] = *s;
4318                 PL_lex_casestack[PL_lex_casemods] = '\0';
4319                 PL_lex_state = LEX_INTERPCONCAT;
4320                 start_force(PL_curforce);
4321                 NEXTVAL_NEXTTOKE.ival = 0;
4322                 force_next('(');
4323                 start_force(PL_curforce);
4324                 if (*s == 'l')
4325                     NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
4326                 else if (*s == 'u')
4327                     NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
4328                 else if (*s == 'L')
4329                     NEXTVAL_NEXTTOKE.ival = OP_LC;
4330                 else if (*s == 'U')
4331                     NEXTVAL_NEXTTOKE.ival = OP_UC;
4332                 else if (*s == 'Q')
4333                     NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
4334                 else
4335                     Perl_croak(aTHX_ "panic: yylex");
4336                 if (PL_madskills) {
4337                     SV* const tmpsv = newSVpvs("\\ ");
4338                     /* replace the space with the character we want to escape
4339                      */
4340                     SvPVX(tmpsv)[1] = *s;
4341                     curmad('_', tmpsv);
4342                 }
4343                 PL_bufptr = s + 1;
4344             }
4345             force_next(FUNC);
4346             if (PL_lex_starts) {
4347                 s = PL_bufptr;
4348                 PL_lex_starts = 0;
4349 #ifdef PERL_MAD
4350                 if (PL_madskills) {
4351                     if (PL_thistoken)
4352                         sv_free(PL_thistoken);
4353                     PL_thistoken = newSVpvs("");
4354                 }
4355 #endif
4356                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4357                 if (PL_lex_casemods == 1 && PL_lex_inpat)
4358                     OPERATOR(',');
4359                 else
4360                     Aop(OP_CONCAT);
4361             }
4362             else
4363                 return yylex();
4364         }
4365
4366     case LEX_INTERPPUSH:
4367         return REPORT(sublex_push());
4368
4369     case LEX_INTERPSTART:
4370         if (PL_bufptr == PL_bufend)
4371             return REPORT(sublex_done());
4372         DEBUG_T({ PerlIO_printf(Perl_debug_log,
4373               "### Interpolated variable\n"); });
4374         PL_expect = XTERM;
4375         PL_lex_dojoin = (*PL_bufptr == '@');
4376         PL_lex_state = LEX_INTERPNORMAL;
4377         if (PL_lex_dojoin) {
4378             start_force(PL_curforce);
4379             NEXTVAL_NEXTTOKE.ival = 0;
4380             force_next(',');
4381             start_force(PL_curforce);
4382             force_ident("\"", '$');
4383             start_force(PL_curforce);
4384             NEXTVAL_NEXTTOKE.ival = 0;
4385             force_next('$');
4386             start_force(PL_curforce);
4387             NEXTVAL_NEXTTOKE.ival = 0;
4388             force_next('(');
4389             start_force(PL_curforce);
4390             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
4391             force_next(FUNC);
4392         }
4393         if (PL_lex_starts++) {
4394             s = PL_bufptr;
4395 #ifdef PERL_MAD
4396             if (PL_madskills) {
4397                 if (PL_thistoken)
4398                     sv_free(PL_thistoken);
4399                 PL_thistoken = newSVpvs("");
4400             }
4401 #endif
4402             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4403             if (!PL_lex_casemods && PL_lex_inpat)
4404                 OPERATOR(',');
4405             else
4406                 Aop(OP_CONCAT);
4407         }
4408         return yylex();
4409
4410     case LEX_INTERPENDMAYBE:
4411         if (intuit_more(PL_bufptr)) {
4412             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
4413             break;
4414         }
4415         /* FALL THROUGH */
4416
4417     case LEX_INTERPEND:
4418         if (PL_lex_dojoin) {
4419             PL_lex_dojoin = FALSE;
4420             PL_lex_state = LEX_INTERPCONCAT;
4421 #ifdef PERL_MAD
4422             if (PL_madskills) {
4423                 if (PL_thistoken)
4424                     sv_free(PL_thistoken);
4425                 PL_thistoken = newSVpvs("");
4426             }
4427 #endif
4428             return REPORT(')');
4429         }
4430         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
4431             && SvEVALED(PL_lex_repl))
4432         {
4433             if (PL_bufptr != PL_bufend)
4434                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
4435             PL_lex_repl = NULL;
4436         }
4437         /* FALLTHROUGH */
4438     case LEX_INTERPCONCAT:
4439 #ifdef DEBUGGING
4440         if (PL_lex_brackets)
4441             Perl_croak(aTHX_ "panic: INTERPCONCAT");
4442 #endif
4443         if (PL_bufptr == PL_bufend)
4444             return REPORT(sublex_done());
4445
4446         if (SvIVX(PL_linestr) == '\'') {
4447             SV *sv = newSVsv(PL_linestr);
4448             if (!PL_lex_inpat)
4449                 sv = tokeq(sv);
4450             else if ( PL_hints & HINT_NEW_RE )
4451                 sv = new_constant(NULL, 0, "qr", sv, sv, "q", 1);
4452             pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
4453             s = PL_bufend;
4454         }
4455         else {
4456             s = scan_const(PL_bufptr);
4457             if (*s == '\\')
4458                 PL_lex_state = LEX_INTERPCASEMOD;
4459             else
4460                 PL_lex_state = LEX_INTERPSTART;
4461         }
4462
4463         if (s != PL_bufptr) {
4464             start_force(PL_curforce);
4465             if (PL_madskills) {
4466                 curmad('X', newSVpvn(PL_bufptr,s-PL_bufptr));
4467             }
4468             NEXTVAL_NEXTTOKE = pl_yylval;
4469             PL_expect = XTERM;
4470             force_next(THING);
4471             if (PL_lex_starts++) {
4472 #ifdef PERL_MAD
4473                 if (PL_madskills) {
4474                     if (PL_thistoken)
4475                         sv_free(PL_thistoken);
4476                     PL_thistoken = newSVpvs("");
4477                 }
4478 #endif
4479                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4480                 if (!PL_lex_casemods && PL_lex_inpat)
4481                     OPERATOR(',');
4482                 else
4483                     Aop(OP_CONCAT);
4484             }
4485             else {
4486                 PL_bufptr = s;
4487                 return yylex();
4488             }
4489         }
4490
4491         return yylex();
4492     case LEX_FORMLINE:
4493         PL_lex_state = LEX_NORMAL;