This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
utf8.c: use new SvPVCLEAR and constant string friendly macros
[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 This is the lower layer of the Perl parser, managing characters and tokens.
27
28 =for apidoc AmU|yy_parser *|PL_parser
29
30 Pointer to a structure encapsulating the state of the parsing operation
31 currently in progress.  The pointer can be locally changed to perform
32 a nested parse without interfering with the state of an outer parse.
33 Individual members of C<PL_parser> have their own documentation.
34
35 =cut
36 */
37
38 #include "EXTERN.h"
39 #define PERL_IN_TOKE_C
40 #include "perl.h"
41 #include "dquote_inline.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 /* XXX temporary backwards compatibility */
49 #define PL_lex_brackets         (PL_parser->lex_brackets)
50 #define PL_lex_allbrackets      (PL_parser->lex_allbrackets)
51 #define PL_lex_fakeeof          (PL_parser->lex_fakeeof)
52 #define PL_lex_brackstack       (PL_parser->lex_brackstack)
53 #define PL_lex_casemods         (PL_parser->lex_casemods)
54 #define PL_lex_casestack        (PL_parser->lex_casestack)
55 #define PL_lex_dojoin           (PL_parser->lex_dojoin)
56 #define PL_lex_formbrack        (PL_parser->lex_formbrack)
57 #define PL_lex_inpat            (PL_parser->lex_inpat)
58 #define PL_lex_inwhat           (PL_parser->lex_inwhat)
59 #define PL_lex_op               (PL_parser->lex_op)
60 #define PL_lex_repl             (PL_parser->lex_repl)
61 #define PL_lex_starts           (PL_parser->lex_starts)
62 #define PL_lex_stuff            (PL_parser->lex_stuff)
63 #define PL_multi_start          (PL_parser->multi_start)
64 #define PL_multi_open           (PL_parser->multi_open)
65 #define PL_multi_close          (PL_parser->multi_close)
66 #define PL_preambled            (PL_parser->preambled)
67 #define PL_linestr              (PL_parser->linestr)
68 #define PL_expect               (PL_parser->expect)
69 #define PL_copline              (PL_parser->copline)
70 #define PL_bufptr               (PL_parser->bufptr)
71 #define PL_oldbufptr            (PL_parser->oldbufptr)
72 #define PL_oldoldbufptr         (PL_parser->oldoldbufptr)
73 #define PL_linestart            (PL_parser->linestart)
74 #define PL_bufend               (PL_parser->bufend)
75 #define PL_last_uni             (PL_parser->last_uni)
76 #define PL_last_lop             (PL_parser->last_lop)
77 #define PL_last_lop_op          (PL_parser->last_lop_op)
78 #define PL_lex_state            (PL_parser->lex_state)
79 #define PL_rsfp                 (PL_parser->rsfp)
80 #define PL_rsfp_filters         (PL_parser->rsfp_filters)
81 #define PL_in_my                (PL_parser->in_my)
82 #define PL_in_my_stash          (PL_parser->in_my_stash)
83 #define PL_tokenbuf             (PL_parser->tokenbuf)
84 #define PL_multi_end            (PL_parser->multi_end)
85 #define PL_error_count          (PL_parser->error_count)
86
87 #  define PL_nexttoke           (PL_parser->nexttoke)
88 #  define PL_nexttype           (PL_parser->nexttype)
89 #  define PL_nextval            (PL_parser->nextval)
90
91 static const char* const ident_too_long = "Identifier too long";
92
93 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
94
95 #define XENUMMASK  0x3f
96 #define XFAKEEOF   0x40
97 #define XFAKEBRACK 0x80
98
99 #ifdef USE_UTF8_SCRIPTS
100 #   define UTF cBOOL(!IN_BYTES)
101 #else
102 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
103 #endif
104
105 /* The maximum number of characters preceding the unrecognized one to display */
106 #define UNRECOGNIZED_PRECEDE_COUNT 10
107
108 /* In variables named $^X, these are the legal values for X.
109  * 1999-02-27 mjd-perl-patch@plover.com */
110 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
111
112 #define SPACE_OR_TAB(c) isBLANK_A(c)
113
114 #define HEXFP_PEEK(s)     \
115     (((s[0] == '.') && \
116       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
117      isALPHA_FOLD_EQ(s[0], 'p'))
118
119 /* LEX_* are values for PL_lex_state, the state of the lexer.
120  * They are arranged oddly so that the guard on the switch statement
121  * can get by with a single comparison (if the compiler is smart enough).
122  *
123  * These values refer to the various states within a sublex parse,
124  * i.e. within a double quotish string
125  */
126
127 /* #define LEX_NOTPARSING               11 is done in perl.h. */
128
129 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
130 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
131 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
132 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
133 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
134
135                                    /* at end of code, eg "$x" followed by:  */
136 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
137 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
138
139 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
140                                         string or after \E, $foo, etc       */
141 #define LEX_INTERPCONST          2 /* NOT USED */
142 #define LEX_FORMLINE             1 /* expecting a format line               */
143
144
145 #ifdef DEBUGGING
146 static const char* const lex_state_names[] = {
147     "KNOWNEXT",
148     "FORMLINE",
149     "INTERPCONST",
150     "INTERPCONCAT",
151     "INTERPENDMAYBE",
152     "INTERPEND",
153     "INTERPSTART",
154     "INTERPPUSH",
155     "INTERPCASEMOD",
156     "INTERPNORMAL",
157     "NORMAL"
158 };
159 #endif
160
161 #include "keywords.h"
162
163 /* CLINE is a macro that ensures PL_copline has a sane value */
164
165 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
166
167 /*
168  * Convenience functions to return different tokens and prime the
169  * lexer for the next token.  They all take an argument.
170  *
171  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
172  * OPERATOR     : generic operator
173  * AOPERATOR    : assignment operator
174  * PREBLOCK     : beginning the block after an if, while, foreach, ...
175  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
176  * PREREF       : *EXPR where EXPR is not a simple identifier
177  * TERM         : expression term
178  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
179  * LOOPX        : loop exiting command (goto, last, dump, etc)
180  * FTST         : file test operator
181  * FUN0         : zero-argument function
182  * FUN0OP       : zero-argument function, with its op created in this file
183  * FUN1         : not used, except for not, which isn't a UNIOP
184  * BOop         : bitwise or or xor
185  * BAop         : bitwise and
186  * BCop         : bitwise complement
187  * SHop         : shift operator
188  * PWop         : power operator
189  * PMop         : pattern-matching operator
190  * Aop          : addition-level operator
191  * AopNOASSIGN  : addition-level operator that is never part of .=
192  * Mop          : multiplication-level operator
193  * Eop          : equality-testing operator
194  * Rop          : relational operator <= != gt
195  *
196  * Also see LOP and lop() below.
197  */
198
199 #ifdef DEBUGGING /* Serve -DT. */
200 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
201 #else
202 #   define REPORT(retval) (retval)
203 #endif
204
205 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
206 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
207 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
208 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
209 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
210 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
211 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
212 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
213 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
214                          pl_yylval.ival=f, \
215                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
216                          REPORT((int)LOOPEX))
217 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
218 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
219 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
220 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
221 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
222 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
223 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
224                        REPORT('~')
225 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
226 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
227 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
228 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
229 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
230 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
231 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
232 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
233
234 /* This bit of chicanery makes a unary function followed by
235  * a parenthesis into a function with one argument, highest precedence.
236  * The UNIDOR macro is for unary functions that can be followed by the //
237  * operator (such as C<shift // 0>).
238  */
239 #define UNI3(f,x,have_x) { \
240         pl_yylval.ival = f; \
241         if (have_x) PL_expect = x; \
242         PL_bufptr = s; \
243         PL_last_uni = PL_oldbufptr; \
244         PL_last_lop_op = (f) < 0 ? -(f) : (f); \
245         if (*s == '(') \
246             return REPORT( (int)FUNC1 ); \
247         s = skipspace(s); \
248         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
249         }
250 #define UNI(f)    UNI3(f,XTERM,1)
251 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
252 #define UNIPROTO(f,optional) { \
253         if (optional) PL_last_uni = PL_oldbufptr; \
254         OPERATOR(f); \
255         }
256
257 #define UNIBRACK(f) UNI3(f,0,0)
258
259 /* grandfather return to old style */
260 #define OLDLOP(f) \
261         do { \
262             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
263                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
264             pl_yylval.ival = (f); \
265             PL_expect = XTERM; \
266             PL_bufptr = s; \
267             return (int)LSTOP; \
268         } while(0)
269
270 #define COPLINE_INC_WITH_HERELINES                  \
271     STMT_START {                                     \
272         CopLINE_inc(PL_curcop);                       \
273         if (PL_parser->herelines)                      \
274             CopLINE(PL_curcop) += PL_parser->herelines, \
275             PL_parser->herelines = 0;                    \
276     } STMT_END
277 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
278  * is no sublex_push to follow. */
279 #define COPLINE_SET_FROM_MULTI_END            \
280     STMT_START {                               \
281         CopLINE_set(PL_curcop, PL_multi_end);   \
282         if (PL_multi_end != PL_multi_start)      \
283             PL_parser->herelines = 0;             \
284     } STMT_END
285
286
287 #ifdef DEBUGGING
288
289 /* how to interpret the pl_yylval associated with the token */
290 enum token_type {
291     TOKENTYPE_NONE,
292     TOKENTYPE_IVAL,
293     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
294     TOKENTYPE_PVAL,
295     TOKENTYPE_OPVAL
296 };
297
298 static struct debug_tokens {
299     const int token;
300     enum token_type type;
301     const char *name;
302 } const debug_tokens[] =
303 {
304     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
305     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
306     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
307     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
308     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
309     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
310     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
311     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
312     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
313     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
314     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
315     { DO,               TOKENTYPE_NONE,         "DO" },
316     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
317     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
318     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
319     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
320     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
321     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
322     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
323     { FOR,              TOKENTYPE_IVAL,         "FOR" },
324     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
325     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
326     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
327     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
328     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
329     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
330     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
331     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
332     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
333     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
334     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
335     { IF,               TOKENTYPE_IVAL,         "IF" },
336     { LABEL,            TOKENTYPE_PVAL,         "LABEL" },
337     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
338     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
339     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
340     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
341     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
342     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
343     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
344     { MY,               TOKENTYPE_IVAL,         "MY" },
345     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
346     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
347     { OROP,             TOKENTYPE_IVAL,         "OROP" },
348     { OROR,             TOKENTYPE_NONE,         "OROR" },
349     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
350     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
351     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
352     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
353     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
354     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
355     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
356     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
357     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
358     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
359     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
360     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
361     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
362     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
363     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
364     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
365     { SUB,              TOKENTYPE_NONE,         "SUB" },
366     { THING,            TOKENTYPE_OPVAL,        "THING" },
367     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
368     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
369     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
370     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
371     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
372     { USE,              TOKENTYPE_IVAL,         "USE" },
373     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
374     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
375     { BAREWORD,         TOKENTYPE_OPVAL,        "BAREWORD" },
376     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
377     { 0,                TOKENTYPE_NONE,         NULL }
378 };
379
380 /* dump the returned token in rv, plus any optional arg in pl_yylval */
381
382 STATIC int
383 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
384 {
385     PERL_ARGS_ASSERT_TOKEREPORT;
386
387     if (DEBUG_T_TEST) {
388         const char *name = NULL;
389         enum token_type type = TOKENTYPE_NONE;
390         const struct debug_tokens *p;
391         SV* const report = newSVpvs("<== ");
392
393         for (p = debug_tokens; p->token; p++) {
394             if (p->token == (int)rv) {
395                 name = p->name;
396                 type = p->type;
397                 break;
398             }
399         }
400         if (name)
401             Perl_sv_catpv(aTHX_ report, name);
402         else if (isGRAPH(rv))
403         {
404             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
405             if ((char)rv == 'p')
406                 sv_catpvs(report, " (pending identifier)");
407         }
408         else if (!rv)
409             sv_catpvs(report, "EOF");
410         else
411             Perl_sv_catpvf(aTHX_ report, "?? %"IVdf, (IV)rv);
412         switch (type) {
413         case TOKENTYPE_NONE:
414             break;
415         case TOKENTYPE_IVAL:
416             Perl_sv_catpvf(aTHX_ report, "(ival=%"IVdf")", (IV)lvalp->ival);
417             break;
418         case TOKENTYPE_OPNUM:
419             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
420                                     PL_op_name[lvalp->ival]);
421             break;
422         case TOKENTYPE_PVAL:
423             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
424             break;
425         case TOKENTYPE_OPVAL:
426             if (lvalp->opval) {
427                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
428                                     PL_op_name[lvalp->opval->op_type]);
429                 if (lvalp->opval->op_type == OP_CONST) {
430                     Perl_sv_catpvf(aTHX_ report, " %s",
431                         SvPEEK(cSVOPx_sv(lvalp->opval)));
432                 }
433
434             }
435             else
436                 sv_catpvs(report, "(opval=null)");
437             break;
438         }
439         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
440     };
441     return (int)rv;
442 }
443
444
445 /* print the buffer with suitable escapes */
446
447 STATIC void
448 S_printbuf(pTHX_ const char *const fmt, const char *const s)
449 {
450     SV* const tmp = newSVpvs("");
451
452     PERL_ARGS_ASSERT_PRINTBUF;
453
454     GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
455     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
456     GCC_DIAG_RESTORE;
457     SvREFCNT_dec(tmp);
458 }
459
460 #endif
461
462 static int
463 S_deprecate_commaless_var_list(pTHX) {
464     PL_expect = XTERM;
465     deprecate("comma-less variable list");
466     return REPORT(','); /* grandfather non-comma-format format */
467 }
468
469 /*
470  * S_ao
471  *
472  * This subroutine looks for an '=' next to the operator that has just been
473  * parsed and turns it into an ASSIGNOP if it finds one.
474  */
475
476 STATIC int
477 S_ao(pTHX_ int toketype)
478 {
479     if (*PL_bufptr == '=') {
480         PL_bufptr++;
481         if (toketype == ANDAND)
482             pl_yylval.ival = OP_ANDASSIGN;
483         else if (toketype == OROR)
484             pl_yylval.ival = OP_ORASSIGN;
485         else if (toketype == DORDOR)
486             pl_yylval.ival = OP_DORASSIGN;
487         toketype = ASSIGNOP;
488     }
489     return REPORT(toketype);
490 }
491
492 /*
493  * S_no_op
494  * When Perl expects an operator and finds something else, no_op
495  * prints the warning.  It always prints "<something> found where
496  * operator expected.  It prints "Missing semicolon on previous line?"
497  * if the surprise occurs at the start of the line.  "do you need to
498  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
499  * where the compiler doesn't know if foo is a method call or a function.
500  * It prints "Missing operator before end of line" if there's nothing
501  * after the missing operator, or "... before <...>" if there is something
502  * after the missing operator.
503  *
504  * PL_bufptr is expected to point to the start of the thing that was found,
505  * and s after the next token or partial token.
506  */
507
508 STATIC void
509 S_no_op(pTHX_ const char *const what, char *s)
510 {
511     char * const oldbp = PL_bufptr;
512     const bool is_first = (PL_oldbufptr == PL_linestart);
513
514     PERL_ARGS_ASSERT_NO_OP;
515
516     if (!s)
517         s = oldbp;
518     else
519         PL_bufptr = s;
520     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
521     if (ckWARN_d(WARN_SYNTAX)) {
522         if (is_first)
523             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
524                     "\t(Missing semicolon on previous line?)\n");
525         else if (PL_oldoldbufptr && isIDFIRST_lazy_if(PL_oldoldbufptr,UTF)) {
526             const char *t;
527             for (t = PL_oldoldbufptr; (isWORDCHAR_lazy_if(t,UTF) || *t == ':');
528                                                             t += UTF ? UTF8SKIP(t) : 1)
529                 NOOP;
530             if (t < PL_bufptr && isSPACE(*t))
531                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
532                         "\t(Do you need to predeclare %"UTF8f"?)\n",
533                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
534         }
535         else {
536             assert(s >= oldbp);
537             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
538                     "\t(Missing operator before %"UTF8f"?)\n",
539                      UTF8fARG(UTF, s - oldbp, oldbp));
540         }
541     }
542     PL_bufptr = oldbp;
543 }
544
545 /*
546  * S_missingterm
547  * Complain about missing quote/regexp/heredoc terminator.
548  * If it's called with NULL then it cauterizes the line buffer.
549  * If we're in a delimited string and the delimiter is a control
550  * character, it's reformatted into a two-char sequence like ^C.
551  * This is fatal.
552  */
553
554 STATIC void
555 S_missingterm(pTHX_ char *s)
556 {
557     char tmpbuf[UTF8_MAXBYTES + 1];
558     char q;
559     bool uni = FALSE;
560     SV *sv;
561     if (s) {
562         char * const nl = strrchr(s,'\n');
563         if (nl)
564             *nl = '\0';
565         uni = UTF;
566     }
567     else if (PL_multi_close < 32) {
568         *tmpbuf = '^';
569         tmpbuf[1] = (char)toCTRL(PL_multi_close);
570         tmpbuf[2] = '\0';
571         s = tmpbuf;
572     }
573     else {
574         if (LIKELY(PL_multi_close < 256)) {
575             *tmpbuf = (char)PL_multi_close;
576             tmpbuf[1] = '\0';
577         }
578         else {
579             uni = TRUE;
580             *uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close) = 0;
581         }
582         s = tmpbuf;
583     }
584     q = strchr(s,'"') ? '\'' : '"';
585     sv = sv_2mortal(newSVpv(s,0));
586     if (uni)
587         SvUTF8_on(sv);
588     Perl_croak(aTHX_ "Can't find string terminator %c%"SVf
589                      "%c anywhere before EOF",q,SVfARG(sv),q);
590 }
591
592 #include "feature.h"
593
594 /*
595  * Check whether the named feature is enabled.
596  */
597 bool
598 Perl_feature_is_enabled(pTHX_ const char *const name, STRLEN namelen)
599 {
600     char he_name[8 + MAX_FEATURE_LEN] = "feature_";
601
602     PERL_ARGS_ASSERT_FEATURE_IS_ENABLED;
603
604     assert(CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM);
605
606     if (namelen > MAX_FEATURE_LEN)
607         return FALSE;
608     memcpy(&he_name[8], name, namelen);
609
610     return cBOOL(cop_hints_fetch_pvn(PL_curcop, he_name, 8 + namelen, 0,
611                                      REFCOUNTED_HE_EXISTS));
612 }
613
614 /*
615  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
616  * utf16-to-utf8-reversed.
617  */
618
619 #ifdef PERL_CR_FILTER
620 static void
621 strip_return(SV *sv)
622 {
623     const char *s = SvPVX_const(sv);
624     const char * const e = s + SvCUR(sv);
625
626     PERL_ARGS_ASSERT_STRIP_RETURN;
627
628     /* outer loop optimized to do nothing if there are no CR-LFs */
629     while (s < e) {
630         if (*s++ == '\r' && *s == '\n') {
631             /* hit a CR-LF, need to copy the rest */
632             char *d = s - 1;
633             *d++ = *s++;
634             while (s < e) {
635                 if (*s == '\r' && s[1] == '\n')
636                     s++;
637                 *d++ = *s++;
638             }
639             SvCUR(sv) -= s - d;
640             return;
641         }
642     }
643 }
644
645 STATIC I32
646 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
647 {
648     const I32 count = FILTER_READ(idx+1, sv, maxlen);
649     if (count > 0 && !maxlen)
650         strip_return(sv);
651     return count;
652 }
653 #endif
654
655 /*
656 =for apidoc Amx|void|lex_start|SV *line|PerlIO *rsfp|U32 flags
657
658 Creates and initialises a new lexer/parser state object, supplying
659 a context in which to lex and parse from a new source of Perl code.
660 A pointer to the new state object is placed in L</PL_parser>.  An entry
661 is made on the save stack so that upon unwinding the new state object
662 will be destroyed and the former value of L</PL_parser> will be restored.
663 Nothing else need be done to clean up the parsing context.
664
665 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
666 non-null, provides a string (in SV form) containing code to be parsed.
667 A copy of the string is made, so subsequent modification of C<line>
668 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
669 from which code will be read to be parsed.  If both are non-null, the
670 code in C<line> comes first and must consist of complete lines of input,
671 and C<rsfp> supplies the remainder of the source.
672
673 The C<flags> parameter is reserved for future use.  Currently it is only
674 used by perl internally, so extensions should always pass zero.
675
676 =cut
677 */
678
679 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
680    can share filters with the current parser.
681    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
682    caller, hence isn't owned by the parser, so shouldn't be closed on parser
683    destruction. This is used to handle the case of defaulting to reading the
684    script from the standard input because no filename was given on the command
685    line (without getting confused by situation where STDIN has been closed, so
686    the script handle is opened on fd 0)  */
687
688 void
689 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
690 {
691     const char *s = NULL;
692     yy_parser *parser, *oparser;
693     if (flags && flags & ~LEX_START_FLAGS)
694         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
695
696     /* create and initialise a parser */
697
698     Newxz(parser, 1, yy_parser);
699     parser->old_parser = oparser = PL_parser;
700     PL_parser = parser;
701
702     parser->stack = NULL;
703     parser->ps = NULL;
704     parser->stack_size = 0;
705
706     /* on scope exit, free this parser and restore any outer one */
707     SAVEPARSER(parser);
708     parser->saved_curcop = PL_curcop;
709
710     /* initialise lexer state */
711
712     parser->nexttoke = 0;
713     parser->error_count = oparser ? oparser->error_count : 0;
714     parser->copline = parser->preambling = NOLINE;
715     parser->lex_state = LEX_NORMAL;
716     parser->expect = XSTATE;
717     parser->rsfp = rsfp;
718     parser->rsfp_filters =
719       !(flags & LEX_START_SAME_FILTER) || !oparser
720         ? NULL
721         : MUTABLE_AV(SvREFCNT_inc(
722             oparser->rsfp_filters
723              ? oparser->rsfp_filters
724              : (oparser->rsfp_filters = newAV())
725           ));
726
727     Newx(parser->lex_brackstack, 120, char);
728     Newx(parser->lex_casestack, 12, char);
729     *parser->lex_casestack = '\0';
730     Newxz(parser->lex_shared, 1, LEXSHARED);
731
732     if (line) {
733         STRLEN len;
734         s = SvPV_const(line, len);
735         parser->linestr = flags & LEX_START_COPIED
736                             ? SvREFCNT_inc_simple_NN(line)
737                             : newSVpvn_flags(s, len, SvUTF8(line));
738         if (!rsfp)
739             sv_catpvs(parser->linestr, "\n;");
740     } else {
741         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
742     }
743     parser->oldoldbufptr =
744         parser->oldbufptr =
745         parser->bufptr =
746         parser->linestart = SvPVX(parser->linestr);
747     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
748     parser->last_lop = parser->last_uni = NULL;
749
750     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
751                                                         |LEX_DONT_CLOSE_RSFP));
752     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
753                                                         |LEX_DONT_CLOSE_RSFP));
754
755     parser->in_pod = parser->filtered = 0;
756 }
757
758
759 /* delete a parser object */
760
761 void
762 Perl_parser_free(pTHX_  const yy_parser *parser)
763 {
764     PERL_ARGS_ASSERT_PARSER_FREE;
765
766     PL_curcop = parser->saved_curcop;
767     SvREFCNT_dec(parser->linestr);
768
769     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
770         PerlIO_clearerr(parser->rsfp);
771     else if (parser->rsfp && (!parser->old_parser
772           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
773         PerlIO_close(parser->rsfp);
774     SvREFCNT_dec(parser->rsfp_filters);
775     SvREFCNT_dec(parser->lex_stuff);
776     SvREFCNT_dec(parser->lex_sub_repl);
777
778     Safefree(parser->lex_brackstack);
779     Safefree(parser->lex_casestack);
780     Safefree(parser->lex_shared);
781     PL_parser = parser->old_parser;
782     Safefree(parser);
783 }
784
785 void
786 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
787 {
788     I32 nexttoke = parser->nexttoke;
789     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
790     while (nexttoke--) {
791         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
792          && parser->nextval[nexttoke].opval
793          && parser->nextval[nexttoke].opval->op_slabbed
794          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
795             op_free(parser->nextval[nexttoke].opval);
796             parser->nextval[nexttoke].opval = NULL;
797         }
798     }
799 }
800
801
802 /*
803 =for apidoc AmxU|SV *|PL_parser-E<gt>linestr
804
805 Buffer scalar containing the chunk currently under consideration of the
806 text currently being lexed.  This is always a plain string scalar (for
807 which C<SvPOK> is true).  It is not intended to be used as a scalar by
808 normal scalar means; instead refer to the buffer directly by the pointer
809 variables described below.
810
811 The lexer maintains various C<char*> pointers to things in the
812 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
813 reallocated, all of these pointers must be updated.  Don't attempt to
814 do this manually, but rather use L</lex_grow_linestr> if you need to
815 reallocate the buffer.
816
817 The content of the text chunk in the buffer is commonly exactly one
818 complete line of input, up to and including a newline terminator,
819 but there are situations where it is otherwise.  The octets of the
820 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
821 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
822 flag on this scalar, which may disagree with it.
823
824 For direct examination of the buffer, the variable
825 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
826 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
827 of these pointers is usually preferable to examination of the scalar
828 through normal scalar means.
829
830 =for apidoc AmxU|char *|PL_parser-E<gt>bufend
831
832 Direct pointer to the end of the chunk of text currently being lexed, the
833 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
834 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
835 always located at the end of the buffer, and does not count as part of
836 the buffer's contents.
837
838 =for apidoc AmxU|char *|PL_parser-E<gt>bufptr
839
840 Points to the current position of lexing inside the lexer buffer.
841 Characters around this point may be freely examined, within
842 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
843 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
844 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
845
846 Lexing code (whether in the Perl core or not) moves this pointer past
847 the characters that it consumes.  It is also expected to perform some
848 bookkeeping whenever a newline character is consumed.  This movement
849 can be more conveniently performed by the function L</lex_read_to>,
850 which handles newlines appropriately.
851
852 Interpretation of the buffer's octets can be abstracted out by
853 using the slightly higher-level functions L</lex_peek_unichar> and
854 L</lex_read_unichar>.
855
856 =for apidoc AmxU|char *|PL_parser-E<gt>linestart
857
858 Points to the start of the current line inside the lexer buffer.
859 This is useful for indicating at which column an error occurred, and
860 not much else.  This must be updated by any lexing code that consumes
861 a newline; the function L</lex_read_to> handles this detail.
862
863 =cut
864 */
865
866 /*
867 =for apidoc Amx|bool|lex_bufutf8
868
869 Indicates whether the octets in the lexer buffer
870 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
871 of Unicode characters.  If not, they should be interpreted as Latin-1
872 characters.  This is analogous to the C<SvUTF8> flag for scalars.
873
874 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
875 contains valid UTF-8.  Lexing code must be robust in the face of invalid
876 encoding.
877
878 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
879 is significant, but not the whole story regarding the input character
880 encoding.  Normally, when a file is being read, the scalar contains octets
881 and its C<SvUTF8> flag is off, but the octets should be interpreted as
882 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
883 however, the scalar may have the C<SvUTF8> flag on, and in this case its
884 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
885 is in effect.  This logic may change in the future; use this function
886 instead of implementing the logic yourself.
887
888 =cut
889 */
890
891 bool
892 Perl_lex_bufutf8(pTHX)
893 {
894     return UTF;
895 }
896
897 /*
898 =for apidoc Amx|char *|lex_grow_linestr|STRLEN len
899
900 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
901 at least C<len> octets (including terminating C<NUL>).  Returns a
902 pointer to the reallocated buffer.  This is necessary before making
903 any direct modification of the buffer that would increase its length.
904 L</lex_stuff_pvn> provides a more convenient way to insert text into
905 the buffer.
906
907 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
908 this function updates all of the lexer's variables that point directly
909 into the buffer.
910
911 =cut
912 */
913
914 char *
915 Perl_lex_grow_linestr(pTHX_ STRLEN len)
916 {
917     SV *linestr;
918     char *buf;
919     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
920     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
921     linestr = PL_parser->linestr;
922     buf = SvPVX(linestr);
923     if (len <= SvLEN(linestr))
924         return buf;
925     bufend_pos = PL_parser->bufend - buf;
926     bufptr_pos = PL_parser->bufptr - buf;
927     oldbufptr_pos = PL_parser->oldbufptr - buf;
928     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
929     linestart_pos = PL_parser->linestart - buf;
930     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
931     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
932     re_eval_start_pos = PL_parser->lex_shared->re_eval_start ?
933                             PL_parser->lex_shared->re_eval_start - buf : 0;
934
935     buf = sv_grow(linestr, len);
936
937     PL_parser->bufend = buf + bufend_pos;
938     PL_parser->bufptr = buf + bufptr_pos;
939     PL_parser->oldbufptr = buf + oldbufptr_pos;
940     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
941     PL_parser->linestart = buf + linestart_pos;
942     if (PL_parser->last_uni)
943         PL_parser->last_uni = buf + last_uni_pos;
944     if (PL_parser->last_lop)
945         PL_parser->last_lop = buf + last_lop_pos;
946     if (PL_parser->lex_shared->re_eval_start)
947         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
948     return buf;
949 }
950
951 /*
952 =for apidoc Amx|void|lex_stuff_pvn|const char *pv|STRLEN len|U32 flags
953
954 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
955 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
956 reallocating the buffer if necessary.  This means that lexing code that
957 runs later will see the characters as if they had appeared in the input.
958 It is not recommended to do this as part of normal parsing, and most
959 uses of this facility run the risk of the inserted characters being
960 interpreted in an unintended manner.
961
962 The string to be inserted is represented by C<len> octets starting
963 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
964 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
965 The characters are recoded for the lexer buffer, according to how the
966 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
967 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
968 function is more convenient.
969
970 =cut
971 */
972
973 void
974 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
975 {
976     dVAR;
977     char *bufptr;
978     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
979     if (flags & ~(LEX_STUFF_UTF8))
980         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
981     if (UTF) {
982         if (flags & LEX_STUFF_UTF8) {
983             goto plain_copy;
984         } else {
985             STRLEN highhalf = 0;    /* Count of variants */
986             const char *p, *e = pv+len;
987             for (p = pv; p != e; p++) {
988                 if (! UTF8_IS_INVARIANT(*p)) {
989                     highhalf++;
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             SvCUR_set(PL_parser->linestr,
998                 SvCUR(PL_parser->linestr) + len+highhalf);
999             PL_parser->bufend += len+highhalf;
1000             for (p = pv; p != e; p++) {
1001                 U8 c = (U8)*p;
1002                 if (! UTF8_IS_INVARIANT(c)) {
1003                     *bufptr++ = UTF8_TWO_BYTE_HI(c);
1004                     *bufptr++ = UTF8_TWO_BYTE_LO(c);
1005                 } else {
1006                     *bufptr++ = (char)c;
1007                 }
1008             }
1009         }
1010     } else {
1011         if (flags & LEX_STUFF_UTF8) {
1012             STRLEN highhalf = 0;
1013             const char *p, *e = pv+len;
1014             for (p = pv; p != e; p++) {
1015                 U8 c = (U8)*p;
1016                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1017                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1018                                 "non-Latin-1 character into Latin-1 input");
1019                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1020                     p++;
1021                     highhalf++;
1022                 } else if (! UTF8_IS_INVARIANT(c)) {
1023                     /* malformed UTF-8 */
1024                     ENTER;
1025                     SAVESPTR(PL_warnhook);
1026                     PL_warnhook = PERL_WARNHOOK_FATAL;
1027                     utf8n_to_uvchr((U8*)p, e-p, NULL, 0);
1028                     LEAVE;
1029                 }
1030             }
1031             if (!highhalf)
1032                 goto plain_copy;
1033             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1034             bufptr = PL_parser->bufptr;
1035             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1036             SvCUR_set(PL_parser->linestr,
1037                 SvCUR(PL_parser->linestr) + len-highhalf);
1038             PL_parser->bufend += len-highhalf;
1039             p = pv;
1040             while (p < e) {
1041                 if (UTF8_IS_INVARIANT(*p)) {
1042                     *bufptr++ = *p;
1043                     p++;
1044                 }
1045                 else {
1046                     assert(p < e -1 );
1047                     *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1048                     p += 2;
1049                 }
1050             }
1051         } else {
1052           plain_copy:
1053             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1054             bufptr = PL_parser->bufptr;
1055             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1056             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1057             PL_parser->bufend += len;
1058             Copy(pv, bufptr, len, char);
1059         }
1060     }
1061 }
1062
1063 /*
1064 =for apidoc Amx|void|lex_stuff_pv|const char *pv|U32 flags
1065
1066 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1067 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1068 reallocating the buffer if necessary.  This means that lexing code that
1069 runs later will see the characters as if they had appeared in the input.
1070 It is not recommended to do this as part of normal parsing, and most
1071 uses of this facility run the risk of the inserted characters being
1072 interpreted in an unintended manner.
1073
1074 The string to be inserted is represented by octets starting at C<pv>
1075 and continuing to the first nul.  These octets are interpreted as either
1076 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1077 in C<flags>.  The characters are recoded for the lexer buffer, according
1078 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1079 If it is not convenient to nul-terminate a string to be inserted, the
1080 L</lex_stuff_pvn> function is more appropriate.
1081
1082 =cut
1083 */
1084
1085 void
1086 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1087 {
1088     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1089     lex_stuff_pvn(pv, strlen(pv), flags);
1090 }
1091
1092 /*
1093 =for apidoc Amx|void|lex_stuff_sv|SV *sv|U32 flags
1094
1095 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1096 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1097 reallocating the buffer if necessary.  This means that lexing code that
1098 runs later will see the characters as if they had appeared in the input.
1099 It is not recommended to do this as part of normal parsing, and most
1100 uses of this facility run the risk of the inserted characters being
1101 interpreted in an unintended manner.
1102
1103 The string to be inserted is the string value of C<sv>.  The characters
1104 are recoded for the lexer buffer, according to how the buffer is currently
1105 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1106 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1107 need to construct a scalar.
1108
1109 =cut
1110 */
1111
1112 void
1113 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1114 {
1115     char *pv;
1116     STRLEN len;
1117     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1118     if (flags)
1119         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1120     pv = SvPV(sv, len);
1121     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1122 }
1123
1124 /*
1125 =for apidoc Amx|void|lex_unstuff|char *ptr
1126
1127 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1128 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1129 This hides the discarded text from any lexing code that runs later,
1130 as if the text had never appeared.
1131
1132 This is not the normal way to consume lexed text.  For that, use
1133 L</lex_read_to>.
1134
1135 =cut
1136 */
1137
1138 void
1139 Perl_lex_unstuff(pTHX_ char *ptr)
1140 {
1141     char *buf, *bufend;
1142     STRLEN unstuff_len;
1143     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1144     buf = PL_parser->bufptr;
1145     if (ptr < buf)
1146         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1147     if (ptr == buf)
1148         return;
1149     bufend = PL_parser->bufend;
1150     if (ptr > bufend)
1151         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1152     unstuff_len = ptr - buf;
1153     Move(ptr, buf, bufend+1-ptr, char);
1154     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1155     PL_parser->bufend = bufend - unstuff_len;
1156 }
1157
1158 /*
1159 =for apidoc Amx|void|lex_read_to|char *ptr
1160
1161 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1162 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1163 performing the correct bookkeeping whenever a newline character is passed.
1164 This is the normal way to consume lexed text.
1165
1166 Interpretation of the buffer's octets can be abstracted out by
1167 using the slightly higher-level functions L</lex_peek_unichar> and
1168 L</lex_read_unichar>.
1169
1170 =cut
1171 */
1172
1173 void
1174 Perl_lex_read_to(pTHX_ char *ptr)
1175 {
1176     char *s;
1177     PERL_ARGS_ASSERT_LEX_READ_TO;
1178     s = PL_parser->bufptr;
1179     if (ptr < s || ptr > PL_parser->bufend)
1180         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1181     for (; s != ptr; s++)
1182         if (*s == '\n') {
1183             COPLINE_INC_WITH_HERELINES;
1184             PL_parser->linestart = s+1;
1185         }
1186     PL_parser->bufptr = ptr;
1187 }
1188
1189 /*
1190 =for apidoc Amx|void|lex_discard_to|char *ptr
1191
1192 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1193 up to C<ptr>.  The remaining content of the buffer will be moved, and
1194 all pointers into the buffer updated appropriately.  C<ptr> must not
1195 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1196 it is not permitted to discard text that has yet to be lexed.
1197
1198 Normally it is not necessarily to do this directly, because it suffices to
1199 use the implicit discarding behaviour of L</lex_next_chunk> and things
1200 based on it.  However, if a token stretches across multiple lines,
1201 and the lexing code has kept multiple lines of text in the buffer for
1202 that purpose, then after completion of the token it would be wise to
1203 explicitly discard the now-unneeded earlier lines, to avoid future
1204 multi-line tokens growing the buffer without bound.
1205
1206 =cut
1207 */
1208
1209 void
1210 Perl_lex_discard_to(pTHX_ char *ptr)
1211 {
1212     char *buf;
1213     STRLEN discard_len;
1214     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1215     buf = SvPVX(PL_parser->linestr);
1216     if (ptr < buf)
1217         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1218     if (ptr == buf)
1219         return;
1220     if (ptr > PL_parser->bufptr)
1221         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1222     discard_len = ptr - buf;
1223     if (PL_parser->oldbufptr < ptr)
1224         PL_parser->oldbufptr = ptr;
1225     if (PL_parser->oldoldbufptr < ptr)
1226         PL_parser->oldoldbufptr = ptr;
1227     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1228         PL_parser->last_uni = NULL;
1229     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1230         PL_parser->last_lop = NULL;
1231     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1232     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1233     PL_parser->bufend -= discard_len;
1234     PL_parser->bufptr -= discard_len;
1235     PL_parser->oldbufptr -= discard_len;
1236     PL_parser->oldoldbufptr -= discard_len;
1237     if (PL_parser->last_uni)
1238         PL_parser->last_uni -= discard_len;
1239     if (PL_parser->last_lop)
1240         PL_parser->last_lop -= discard_len;
1241 }
1242
1243 /*
1244 =for apidoc Amx|bool|lex_next_chunk|U32 flags
1245
1246 Reads in the next chunk of text to be lexed, appending it to
1247 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1248 looked to the end of the current chunk and wants to know more.  It is
1249 usual, but not necessary, for lexing to have consumed the entirety of
1250 the current chunk at this time.
1251
1252 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1253 chunk (i.e., the current chunk has been entirely consumed), normally the
1254 current chunk will be discarded at the same time that the new chunk is
1255 read in.  If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1256 will not be discarded.  If the current chunk has not been entirely
1257 consumed, then it will not be discarded regardless of the flag.
1258
1259 Returns true if some new text was added to the buffer, or false if the
1260 buffer has reached the end of the input text.
1261
1262 =cut
1263 */
1264
1265 #define LEX_FAKE_EOF 0x80000000
1266 #define LEX_NO_TERM  0x40000000 /* here-doc */
1267
1268 bool
1269 Perl_lex_next_chunk(pTHX_ U32 flags)
1270 {
1271     SV *linestr;
1272     char *buf;
1273     STRLEN old_bufend_pos, new_bufend_pos;
1274     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1275     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1276     bool got_some_for_debugger = 0;
1277     bool got_some;
1278     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1279         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1280     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1281         return FALSE;
1282     linestr = PL_parser->linestr;
1283     buf = SvPVX(linestr);
1284     if (!(flags & LEX_KEEP_PREVIOUS)
1285           && PL_parser->bufptr == PL_parser->bufend)
1286     {
1287         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1288         linestart_pos = 0;
1289         if (PL_parser->last_uni != PL_parser->bufend)
1290             PL_parser->last_uni = NULL;
1291         if (PL_parser->last_lop != PL_parser->bufend)
1292             PL_parser->last_lop = NULL;
1293         last_uni_pos = last_lop_pos = 0;
1294         *buf = 0;
1295         SvCUR(linestr) = 0;
1296     } else {
1297         old_bufend_pos = PL_parser->bufend - buf;
1298         bufptr_pos = PL_parser->bufptr - buf;
1299         oldbufptr_pos = PL_parser->oldbufptr - buf;
1300         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1301         linestart_pos = PL_parser->linestart - buf;
1302         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1303         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1304     }
1305     if (flags & LEX_FAKE_EOF) {
1306         goto eof;
1307     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1308         got_some = 0;
1309     } else if (filter_gets(linestr, old_bufend_pos)) {
1310         got_some = 1;
1311         got_some_for_debugger = 1;
1312     } else if (flags & LEX_NO_TERM) {
1313         got_some = 0;
1314     } else {
1315         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1316             SvPVCLEAR(linestr);
1317         eof:
1318         /* End of real input.  Close filehandle (unless it was STDIN),
1319          * then add implicit termination.
1320          */
1321         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1322             PerlIO_clearerr(PL_parser->rsfp);
1323         else if (PL_parser->rsfp)
1324             (void)PerlIO_close(PL_parser->rsfp);
1325         PL_parser->rsfp = NULL;
1326         PL_parser->in_pod = PL_parser->filtered = 0;
1327         if (!PL_in_eval && PL_minus_p) {
1328             sv_catpvs(linestr,
1329                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1330             PL_minus_n = PL_minus_p = 0;
1331         } else if (!PL_in_eval && PL_minus_n) {
1332             sv_catpvs(linestr, /*{*/";}");
1333             PL_minus_n = 0;
1334         } else
1335             sv_catpvs(linestr, ";");
1336         got_some = 1;
1337     }
1338     buf = SvPVX(linestr);
1339     new_bufend_pos = SvCUR(linestr);
1340     PL_parser->bufend = buf + new_bufend_pos;
1341     PL_parser->bufptr = buf + bufptr_pos;
1342     PL_parser->oldbufptr = buf + oldbufptr_pos;
1343     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1344     PL_parser->linestart = buf + linestart_pos;
1345     if (PL_parser->last_uni)
1346         PL_parser->last_uni = buf + last_uni_pos;
1347     if (PL_parser->last_lop)
1348         PL_parser->last_lop = buf + last_lop_pos;
1349     if (PL_parser->preambling != NOLINE) {
1350         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1351         PL_parser->preambling = NOLINE;
1352     }
1353     if (   got_some_for_debugger
1354         && PERLDB_LINE_OR_SAVESRC
1355         && PL_curstash != PL_debstash)
1356     {
1357         /* debugger active and we're not compiling the debugger code,
1358          * so store the line into the debugger's array of lines
1359          */
1360         update_debugger_info(NULL, buf+old_bufend_pos,
1361             new_bufend_pos-old_bufend_pos);
1362     }
1363     return got_some;
1364 }
1365
1366 /*
1367 =for apidoc Amx|I32|lex_peek_unichar|U32 flags
1368
1369 Looks ahead one (Unicode) character in the text currently being lexed.
1370 Returns the codepoint (unsigned integer value) of the next character,
1371 or -1 if lexing has reached the end of the input text.  To consume the
1372 peeked character, use L</lex_read_unichar>.
1373
1374 If the next character is in (or extends into) the next chunk of input
1375 text, the next chunk will be read in.  Normally the current chunk will be
1376 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1377 bit set, then the current chunk will not be discarded.
1378
1379 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1380 is encountered, an exception is generated.
1381
1382 =cut
1383 */
1384
1385 I32
1386 Perl_lex_peek_unichar(pTHX_ U32 flags)
1387 {
1388     dVAR;
1389     char *s, *bufend;
1390     if (flags & ~(LEX_KEEP_PREVIOUS))
1391         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1392     s = PL_parser->bufptr;
1393     bufend = PL_parser->bufend;
1394     if (UTF) {
1395         U8 head;
1396         I32 unichar;
1397         STRLEN len, retlen;
1398         if (s == bufend) {
1399             if (!lex_next_chunk(flags))
1400                 return -1;
1401             s = PL_parser->bufptr;
1402             bufend = PL_parser->bufend;
1403         }
1404         head = (U8)*s;
1405         if (UTF8_IS_INVARIANT(head))
1406             return head;
1407         if (UTF8_IS_START(head)) {
1408             len = UTF8SKIP(&head);
1409             while ((STRLEN)(bufend-s) < len) {
1410                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1411                     break;
1412                 s = PL_parser->bufptr;
1413                 bufend = PL_parser->bufend;
1414             }
1415         }
1416         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1417         if (retlen == (STRLEN)-1) {
1418             /* malformed UTF-8 */
1419             ENTER;
1420             SAVESPTR(PL_warnhook);
1421             PL_warnhook = PERL_WARNHOOK_FATAL;
1422             utf8n_to_uvchr((U8*)s, bufend-s, NULL, 0);
1423             LEAVE;
1424         }
1425         return unichar;
1426     } else {
1427         if (s == bufend) {
1428             if (!lex_next_chunk(flags))
1429                 return -1;
1430             s = PL_parser->bufptr;
1431         }
1432         return (U8)*s;
1433     }
1434 }
1435
1436 /*
1437 =for apidoc Amx|I32|lex_read_unichar|U32 flags
1438
1439 Reads the next (Unicode) character in the text currently being lexed.
1440 Returns the codepoint (unsigned integer value) of the character read,
1441 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1442 if lexing has reached the end of the input text.  To non-destructively
1443 examine the next character, use L</lex_peek_unichar> instead.
1444
1445 If the next character is in (or extends into) the next chunk of input
1446 text, the next chunk will be read in.  Normally the current chunk will be
1447 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1448 bit set, then the current chunk will not be discarded.
1449
1450 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1451 is encountered, an exception is generated.
1452
1453 =cut
1454 */
1455
1456 I32
1457 Perl_lex_read_unichar(pTHX_ U32 flags)
1458 {
1459     I32 c;
1460     if (flags & ~(LEX_KEEP_PREVIOUS))
1461         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1462     c = lex_peek_unichar(flags);
1463     if (c != -1) {
1464         if (c == '\n')
1465             COPLINE_INC_WITH_HERELINES;
1466         if (UTF)
1467             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1468         else
1469             ++(PL_parser->bufptr);
1470     }
1471     return c;
1472 }
1473
1474 /*
1475 =for apidoc Amx|void|lex_read_space|U32 flags
1476
1477 Reads optional spaces, in Perl style, in the text currently being
1478 lexed.  The spaces may include ordinary whitespace characters and
1479 Perl-style comments.  C<#line> directives are processed if encountered.
1480 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1481 at a non-space character (or the end of the input text).
1482
1483 If spaces extend into the next chunk of input text, the next chunk will
1484 be read in.  Normally the current chunk will be discarded at the same
1485 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1486 chunk will not be discarded.
1487
1488 =cut
1489 */
1490
1491 #define LEX_NO_INCLINE    0x40000000
1492 #define LEX_NO_NEXT_CHUNK 0x80000000
1493
1494 void
1495 Perl_lex_read_space(pTHX_ U32 flags)
1496 {
1497     char *s, *bufend;
1498     const bool can_incline = !(flags & LEX_NO_INCLINE);
1499     bool need_incline = 0;
1500     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1501         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1502     s = PL_parser->bufptr;
1503     bufend = PL_parser->bufend;
1504     while (1) {
1505         char c = *s;
1506         if (c == '#') {
1507             do {
1508                 c = *++s;
1509             } while (!(c == '\n' || (c == 0 && s == bufend)));
1510         } else if (c == '\n') {
1511             s++;
1512             if (can_incline) {
1513                 PL_parser->linestart = s;
1514                 if (s == bufend)
1515                     need_incline = 1;
1516                 else
1517                     incline(s);
1518             }
1519         } else if (isSPACE(c)) {
1520             s++;
1521         } else if (c == 0 && s == bufend) {
1522             bool got_more;
1523             line_t l;
1524             if (flags & LEX_NO_NEXT_CHUNK)
1525                 break;
1526             PL_parser->bufptr = s;
1527             l = CopLINE(PL_curcop);
1528             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1529             got_more = lex_next_chunk(flags);
1530             CopLINE_set(PL_curcop, l);
1531             s = PL_parser->bufptr;
1532             bufend = PL_parser->bufend;
1533             if (!got_more)
1534                 break;
1535             if (can_incline && need_incline && PL_parser->rsfp) {
1536                 incline(s);
1537                 need_incline = 0;
1538             }
1539         } else if (!c) {
1540             s++;
1541         } else {
1542             break;
1543         }
1544     }
1545     PL_parser->bufptr = s;
1546 }
1547
1548 /*
1549
1550 =for apidoc EXMp|bool|validate_proto|SV *name|SV *proto|bool warn
1551
1552 This function performs syntax checking on a prototype, C<proto>.
1553 If C<warn> is true, any illegal characters or mismatched brackets
1554 will trigger illegalproto warnings, declaring that they were
1555 detected in the prototype for C<name>.
1556
1557 The return value is C<true> if this is a valid prototype, and
1558 C<false> if it is not, regardless of whether C<warn> was C<true> or
1559 C<false>.
1560
1561 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1562
1563 =cut
1564
1565  */
1566
1567 bool
1568 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn)
1569 {
1570     STRLEN len, origlen;
1571     char *p = proto ? SvPV(proto, len) : NULL;
1572     bool bad_proto = FALSE;
1573     bool in_brackets = FALSE;
1574     bool after_slash = FALSE;
1575     char greedy_proto = ' ';
1576     bool proto_after_greedy_proto = FALSE;
1577     bool must_be_last = FALSE;
1578     bool underscore = FALSE;
1579     bool bad_proto_after_underscore = FALSE;
1580
1581     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1582
1583     if (!proto)
1584         return TRUE;
1585
1586     origlen = len;
1587     for (; len--; p++) {
1588         if (!isSPACE(*p)) {
1589             if (must_be_last)
1590                 proto_after_greedy_proto = TRUE;
1591             if (underscore) {
1592                 if (!strchr(";@%", *p))
1593                     bad_proto_after_underscore = TRUE;
1594                 underscore = FALSE;
1595             }
1596             if (!strchr("$@%*;[]&\\_+", *p) || *p == '\0') {
1597                 bad_proto = TRUE;
1598             }
1599             else {
1600                 if (*p == '[')
1601                     in_brackets = TRUE;
1602                 else if (*p == ']')
1603                     in_brackets = FALSE;
1604                 else if ((*p == '@' || *p == '%')
1605                          && !after_slash
1606                          && !in_brackets )
1607                 {
1608                     must_be_last = TRUE;
1609                     greedy_proto = *p;
1610                 }
1611                 else if (*p == '_')
1612                     underscore = TRUE;
1613             }
1614             if (*p == '\\')
1615                 after_slash = TRUE;
1616             else
1617                 after_slash = FALSE;
1618         }
1619     }
1620
1621     if (warn) {
1622         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1623         p -= origlen;
1624         p = SvUTF8(proto)
1625             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1626                              origlen, UNI_DISPLAY_ISPRINT)
1627             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1628
1629         if (proto_after_greedy_proto)
1630             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1631                         "Prototype after '%c' for %"SVf" : %s",
1632                         greedy_proto, SVfARG(name), p);
1633         if (in_brackets)
1634             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1635                         "Missing ']' in prototype for %"SVf" : %s",
1636                         SVfARG(name), p);
1637         if (bad_proto)
1638             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1639                         "Illegal character in prototype for %"SVf" : %s",
1640                         SVfARG(name), p);
1641         if (bad_proto_after_underscore)
1642             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1643                         "Illegal character after '_' in prototype for %"SVf" : %s",
1644                         SVfARG(name), p);
1645     }
1646
1647     return (! (proto_after_greedy_proto || bad_proto) );
1648 }
1649
1650 /*
1651  * S_incline
1652  * This subroutine has nothing to do with tilting, whether at windmills
1653  * or pinball tables.  Its name is short for "increment line".  It
1654  * increments the current line number in CopLINE(PL_curcop) and checks
1655  * to see whether the line starts with a comment of the form
1656  *    # line 500 "foo.pm"
1657  * If so, it sets the current line number and file to the values in the comment.
1658  */
1659
1660 STATIC void
1661 S_incline(pTHX_ const char *s)
1662 {
1663     const char *t;
1664     const char *n;
1665     const char *e;
1666     line_t line_num;
1667     UV uv;
1668
1669     PERL_ARGS_ASSERT_INCLINE;
1670
1671     COPLINE_INC_WITH_HERELINES;
1672     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1673      && s+1 == PL_bufend && *s == ';') {
1674         /* fake newline in string eval */
1675         CopLINE_dec(PL_curcop);
1676         return;
1677     }
1678     if (*s++ != '#')
1679         return;
1680     while (SPACE_OR_TAB(*s))
1681         s++;
1682     if (strEQs(s, "line"))
1683         s += 4;
1684     else
1685         return;
1686     if (SPACE_OR_TAB(*s))
1687         s++;
1688     else
1689         return;
1690     while (SPACE_OR_TAB(*s))
1691         s++;
1692     if (!isDIGIT(*s))
1693         return;
1694
1695     n = s;
1696     while (isDIGIT(*s))
1697         s++;
1698     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1699         return;
1700     while (SPACE_OR_TAB(*s))
1701         s++;
1702     if (*s == '"' && (t = strchr(s+1, '"'))) {
1703         s++;
1704         e = t + 1;
1705     }
1706     else {
1707         t = s;
1708         while (*t && !isSPACE(*t))
1709             t++;
1710         e = t;
1711     }
1712     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1713         e++;
1714     if (*e != '\n' && *e != '\0')
1715         return;         /* false alarm */
1716
1717     if (!grok_atoUV(n, &uv, &e))
1718         return;
1719     line_num = ((line_t)uv) - 1;
1720
1721     if (t - s > 0) {
1722         const STRLEN len = t - s;
1723
1724         if (!PL_rsfp && !PL_parser->filtered) {
1725             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1726              * to *{"::_<newfilename"} */
1727             /* However, the long form of evals is only turned on by the
1728                debugger - usually they're "(eval %lu)" */
1729             GV * const cfgv = CopFILEGV(PL_curcop);
1730             if (cfgv) {
1731                 char smallbuf[128];
1732                 STRLEN tmplen2 = len;
1733                 char *tmpbuf2;
1734                 GV *gv2;
1735
1736                 if (tmplen2 + 2 <= sizeof smallbuf)
1737                     tmpbuf2 = smallbuf;
1738                 else
1739                     Newx(tmpbuf2, tmplen2 + 2, char);
1740
1741                 tmpbuf2[0] = '_';
1742                 tmpbuf2[1] = '<';
1743
1744                 memcpy(tmpbuf2 + 2, s, tmplen2);
1745                 tmplen2 += 2;
1746
1747                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1748                 if (!isGV(gv2)) {
1749                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1750                     /* adjust ${"::_<newfilename"} to store the new file name */
1751                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1752                     /* The line number may differ. If that is the case,
1753                        alias the saved lines that are in the array.
1754                        Otherwise alias the whole array. */
1755                     if (CopLINE(PL_curcop) == line_num) {
1756                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1757                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1758                     }
1759                     else if (GvAV(cfgv)) {
1760                         AV * const av = GvAV(cfgv);
1761                         const I32 start = CopLINE(PL_curcop)+1;
1762                         I32 items = AvFILLp(av) - start;
1763                         if (items > 0) {
1764                             AV * const av2 = GvAVn(gv2);
1765                             SV **svp = AvARRAY(av) + start;
1766                             I32 l = (I32)line_num+1;
1767                             while (items--)
1768                                 av_store(av2, l++, SvREFCNT_inc(*svp++));
1769                         }
1770                     }
1771                 }
1772
1773                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1774             }
1775         }
1776         CopFILE_free(PL_curcop);
1777         CopFILE_setn(PL_curcop, s, len);
1778     }
1779     CopLINE_set(PL_curcop, line_num);
1780 }
1781
1782 STATIC void
1783 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1784 {
1785     AV *av = CopFILEAVx(PL_curcop);
1786     if (av) {
1787         SV * sv;
1788         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1789         else {
1790             sv = *av_fetch(av, 0, 1);
1791             SvUPGRADE(sv, SVt_PVMG);
1792         }
1793         if (!SvPOK(sv)) SvPVCLEAR(sv);
1794         if (orig_sv)
1795             sv_catsv(sv, orig_sv);
1796         else
1797             sv_catpvn(sv, buf, len);
1798         if (!SvIOK(sv)) {
1799             (void)SvIOK_on(sv);
1800             SvIV_set(sv, 0);
1801         }
1802         if (PL_parser->preambling == NOLINE)
1803             av_store(av, CopLINE(PL_curcop), sv);
1804     }
1805 }
1806
1807 /*
1808  * skipspace
1809  * Called to gobble the appropriate amount and type of whitespace.
1810  * Skips comments as well.
1811  * Returns the next character after the whitespace that is skipped.
1812  *
1813  * peekspace
1814  * Same thing, but look ahead without incrementing line numbers or
1815  * adjusting PL_linestart.
1816  */
1817
1818 #define skipspace(s) skipspace_flags(s, 0)
1819 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1820
1821 STATIC char *
1822 S_skipspace_flags(pTHX_ char *s, U32 flags)
1823 {
1824     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1825     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1826         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1827             s++;
1828     } else {
1829         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1830         PL_bufptr = s;
1831         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1832                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1833                     LEX_NO_NEXT_CHUNK : 0));
1834         s = PL_bufptr;
1835         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1836         if (PL_linestart > PL_bufptr)
1837             PL_bufptr = PL_linestart;
1838         return s;
1839     }
1840     return s;
1841 }
1842
1843 /*
1844  * S_check_uni
1845  * Check the unary operators to ensure there's no ambiguity in how they're
1846  * used.  An ambiguous piece of code would be:
1847  *     rand + 5
1848  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1849  * the +5 is its argument.
1850  */
1851
1852 STATIC void
1853 S_check_uni(pTHX)
1854 {
1855     const char *s;
1856     const char *t;
1857
1858     if (PL_oldoldbufptr != PL_last_uni)
1859         return;
1860     while (isSPACE(*PL_last_uni))
1861         PL_last_uni++;
1862     s = PL_last_uni;
1863     while (isWORDCHAR_lazy_if(s,UTF) || *s == '-')
1864         s += UTF ? UTF8SKIP(s) : 1;
1865     if ((t = strchr(s, '(')) && t < PL_bufptr)
1866         return;
1867
1868     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1869                      "Warning: Use of \"%"UTF8f"\" without parentheses is ambiguous",
1870                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1871 }
1872
1873 /*
1874  * LOP : macro to build a list operator.  Its behaviour has been replaced
1875  * with a subroutine, S_lop() for which LOP is just another name.
1876  */
1877
1878 #define LOP(f,x) return lop(f,x,s)
1879
1880 /*
1881  * S_lop
1882  * Build a list operator (or something that might be one).  The rules:
1883  *  - if we have a next token, then it's a list operator (no parens) for
1884  *    which the next token has already been parsed; e.g.,
1885  *       sort foo @args
1886  *       sort foo (@args)
1887  *  - if the next thing is an opening paren, then it's a function
1888  *  - else it's a list operator
1889  */
1890
1891 STATIC I32
1892 S_lop(pTHX_ I32 f, int x, char *s)
1893 {
1894     PERL_ARGS_ASSERT_LOP;
1895
1896     pl_yylval.ival = f;
1897     CLINE;
1898     PL_bufptr = s;
1899     PL_last_lop = PL_oldbufptr;
1900     PL_last_lop_op = (OPCODE)f;
1901     if (PL_nexttoke)
1902         goto lstop;
1903     PL_expect = x;
1904     if (*s == '(')
1905         return REPORT(FUNC);
1906     s = skipspace(s);
1907     if (*s == '(')
1908         return REPORT(FUNC);
1909     else {
1910         lstop:
1911         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1912             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1913         return REPORT(LSTOP);
1914     }
1915 }
1916
1917 /*
1918  * S_force_next
1919  * When the lexer realizes it knows the next token (for instance,
1920  * it is reordering tokens for the parser) then it can call S_force_next
1921  * to know what token to return the next time the lexer is called.  Caller
1922  * will need to set PL_nextval[] and possibly PL_expect to ensure
1923  * the lexer handles the token correctly.
1924  */
1925
1926 STATIC void
1927 S_force_next(pTHX_ I32 type)
1928 {
1929 #ifdef DEBUGGING
1930     if (DEBUG_T_TEST) {
1931         PerlIO_printf(Perl_debug_log, "### forced token:\n");
1932         tokereport(type, &NEXTVAL_NEXTTOKE);
1933     }
1934 #endif
1935     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
1936     PL_nexttype[PL_nexttoke] = type;
1937     PL_nexttoke++;
1938 }
1939
1940 /*
1941  * S_postderef
1942  *
1943  * This subroutine handles postfix deref syntax after the arrow has already
1944  * been emitted.  @* $* etc. are emitted as two separate token right here.
1945  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
1946  * only the first, leaving yylex to find the next.
1947  */
1948
1949 static int
1950 S_postderef(pTHX_ int const funny, char const next)
1951 {
1952     assert(funny == DOLSHARP || strchr("$@%&*", funny));
1953     if (next == '*') {
1954         PL_expect = XOPERATOR;
1955         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
1956             assert('@' == funny || '$' == funny || DOLSHARP == funny);
1957             PL_lex_state = LEX_INTERPEND;
1958             if ('@' == funny)
1959                 force_next(POSTJOIN);
1960         }
1961         force_next(next);
1962         PL_bufptr+=2;
1963     }
1964     else {
1965         if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
1966          && !PL_lex_brackets)
1967             PL_lex_dojoin = 2;
1968         PL_expect = XOPERATOR;
1969         PL_bufptr++;
1970     }
1971     return funny;
1972 }
1973
1974 void
1975 Perl_yyunlex(pTHX)
1976 {
1977     int yyc = PL_parser->yychar;
1978     if (yyc != YYEMPTY) {
1979         if (yyc) {
1980             NEXTVAL_NEXTTOKE = PL_parser->yylval;
1981             if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
1982                 PL_lex_allbrackets--;
1983                 PL_lex_brackets--;
1984                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
1985             } else if (yyc == '('/*)*/) {
1986                 PL_lex_allbrackets--;
1987                 yyc |= (2<<24);
1988             }
1989             force_next(yyc);
1990         }
1991         PL_parser->yychar = YYEMPTY;
1992     }
1993 }
1994
1995 STATIC SV *
1996 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
1997 {
1998     SV * const sv = newSVpvn_utf8(start, len,
1999                           !IN_BYTES
2000                           && UTF
2001                           && !is_utf8_invariant_string((const U8*)start, len)
2002                           && is_utf8_string((const U8*)start, len));
2003     return sv;
2004 }
2005
2006 /*
2007  * S_force_word
2008  * When the lexer knows the next thing is a word (for instance, it has
2009  * just seen -> and it knows that the next char is a word char, then
2010  * it calls S_force_word to stick the next word into the PL_nexttoke/val
2011  * lookahead.
2012  *
2013  * Arguments:
2014  *   char *start : buffer position (must be within PL_linestr)
2015  *   int token   : PL_next* will be this type of bare word
2016  *                 (e.g., METHOD,BAREWORD)
2017  *   int check_keyword : if true, Perl checks to make sure the word isn't
2018  *       a keyword (do this if the word is a label, e.g. goto FOO)
2019  *   int allow_pack : if true, : characters will also be allowed (require,
2020  *       use, etc. do this)
2021  */
2022
2023 STATIC char *
2024 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2025 {
2026     char *s;
2027     STRLEN len;
2028
2029     PERL_ARGS_ASSERT_FORCE_WORD;
2030
2031     start = skipspace(start);
2032     s = start;
2033     if (isIDFIRST_lazy_if(s,UTF)
2034         || (allow_pack && *s == ':' && s[1] == ':') )
2035     {
2036         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2037         if (check_keyword) {
2038           char *s2 = PL_tokenbuf;
2039           STRLEN len2 = len;
2040           if (allow_pack && len > 6 && strEQs(s2, "CORE::"))
2041             s2 += 6, len2 -= 6;
2042           if (keyword(s2, len2, 0))
2043             return start;
2044         }
2045         if (token == METHOD) {
2046             s = skipspace(s);
2047             if (*s == '(')
2048                 PL_expect = XTERM;
2049             else {
2050                 PL_expect = XOPERATOR;
2051             }
2052         }
2053         NEXTVAL_NEXTTOKE.opval
2054             = (OP*)newSVOP(OP_CONST,0,
2055                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2056         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2057         force_next(token);
2058     }
2059     return s;
2060 }
2061
2062 /*
2063  * S_force_ident
2064  * Called when the lexer wants $foo *foo &foo etc, but the program
2065  * text only contains the "foo" portion.  The first argument is a pointer
2066  * to the "foo", and the second argument is the type symbol to prefix.
2067  * Forces the next token to be a "BAREWORD".
2068  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2069  */
2070
2071 STATIC void
2072 S_force_ident(pTHX_ const char *s, int kind)
2073 {
2074     PERL_ARGS_ASSERT_FORCE_IDENT;
2075
2076     if (s[0]) {
2077         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2078         OP* const o = (OP*)newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2079                                                                 UTF ? SVf_UTF8 : 0));
2080         NEXTVAL_NEXTTOKE.opval = o;
2081         force_next(BAREWORD);
2082         if (kind) {
2083             o->op_private = OPpCONST_ENTERED;
2084             /* XXX see note in pp_entereval() for why we forgo typo
2085                warnings if the symbol must be introduced in an eval.
2086                GSAR 96-10-12 */
2087             gv_fetchpvn_flags(s, len,
2088                               (PL_in_eval ? GV_ADDMULTI
2089                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2090                               kind == '$' ? SVt_PV :
2091                               kind == '@' ? SVt_PVAV :
2092                               kind == '%' ? SVt_PVHV :
2093                               SVt_PVGV
2094                               );
2095         }
2096     }
2097 }
2098
2099 static void
2100 S_force_ident_maybe_lex(pTHX_ char pit)
2101 {
2102     NEXTVAL_NEXTTOKE.ival = pit;
2103     force_next('p');
2104 }
2105
2106 NV
2107 Perl_str_to_version(pTHX_ SV *sv)
2108 {
2109     NV retval = 0.0;
2110     NV nshift = 1.0;
2111     STRLEN len;
2112     const char *start = SvPV_const(sv,len);
2113     const char * const end = start + len;
2114     const bool utf = SvUTF8(sv) ? TRUE : FALSE;
2115
2116     PERL_ARGS_ASSERT_STR_TO_VERSION;
2117
2118     while (start < end) {
2119         STRLEN skip;
2120         UV n;
2121         if (utf)
2122             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2123         else {
2124             n = *(U8*)start;
2125             skip = 1;
2126         }
2127         retval += ((NV)n)/nshift;
2128         start += skip;
2129         nshift *= 1000;
2130     }
2131     return retval;
2132 }
2133
2134 /*
2135  * S_force_version
2136  * Forces the next token to be a version number.
2137  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2138  * and if "guessing" is TRUE, then no new token is created (and the caller
2139  * must use an alternative parsing method).
2140  */
2141
2142 STATIC char *
2143 S_force_version(pTHX_ char *s, int guessing)
2144 {
2145     OP *version = NULL;
2146     char *d;
2147
2148     PERL_ARGS_ASSERT_FORCE_VERSION;
2149
2150     s = skipspace(s);
2151
2152     d = s;
2153     if (*d == 'v')
2154         d++;
2155     if (isDIGIT(*d)) {
2156         while (isDIGIT(*d) || *d == '_' || *d == '.')
2157             d++;
2158         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2159             SV *ver;
2160             s = scan_num(s, &pl_yylval);
2161             version = pl_yylval.opval;
2162             ver = cSVOPx(version)->op_sv;
2163             if (SvPOK(ver) && !SvNIOK(ver)) {
2164                 SvUPGRADE(ver, SVt_PVNV);
2165                 SvNV_set(ver, str_to_version(ver));
2166                 SvNOK_on(ver);          /* hint that it is a version */
2167             }
2168         }
2169         else if (guessing) {
2170             return s;
2171         }
2172     }
2173
2174     /* NOTE: The parser sees the package name and the VERSION swapped */
2175     NEXTVAL_NEXTTOKE.opval = version;
2176     force_next(BAREWORD);
2177
2178     return s;
2179 }
2180
2181 /*
2182  * S_force_strict_version
2183  * Forces the next token to be a version number using strict syntax rules.
2184  */
2185
2186 STATIC char *
2187 S_force_strict_version(pTHX_ char *s)
2188 {
2189     OP *version = NULL;
2190     const char *errstr = NULL;
2191
2192     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2193
2194     while (isSPACE(*s)) /* leading whitespace */
2195         s++;
2196
2197     if (is_STRICT_VERSION(s,&errstr)) {
2198         SV *ver = newSV(0);
2199         s = (char *)scan_version(s, ver, 0);
2200         version = newSVOP(OP_CONST, 0, ver);
2201     }
2202     else if ((*s != ';' && *s != '{' && *s != '}' )
2203              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2204     {
2205         PL_bufptr = s;
2206         if (errstr)
2207             yyerror(errstr); /* version required */
2208         return s;
2209     }
2210
2211     /* NOTE: The parser sees the package name and the VERSION swapped */
2212     NEXTVAL_NEXTTOKE.opval = version;
2213     force_next(BAREWORD);
2214
2215     return s;
2216 }
2217
2218 /*
2219  * S_tokeq
2220  * Tokenize a quoted string passed in as an SV.  It finds the next
2221  * chunk, up to end of string or a backslash.  It may make a new
2222  * SV containing that chunk (if HINT_NEW_STRING is on).  It also
2223  * turns \\ into \.
2224  */
2225
2226 STATIC SV *
2227 S_tokeq(pTHX_ SV *sv)
2228 {
2229     char *s;
2230     char *send;
2231     char *d;
2232     SV *pv = sv;
2233
2234     PERL_ARGS_ASSERT_TOKEQ;
2235
2236     assert (SvPOK(sv));
2237     assert (SvLEN(sv));
2238     assert (!SvIsCOW(sv));
2239     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2240         goto finish;
2241     s = SvPVX(sv);
2242     send = SvEND(sv);
2243     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2244     while (s < send && !(*s == '\\' && s[1] == '\\'))
2245         s++;
2246     if (s == send)
2247         goto finish;
2248     d = s;
2249     if ( PL_hints & HINT_NEW_STRING ) {
2250         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2251                             SVs_TEMP | SvUTF8(sv));
2252     }
2253     while (s < send) {
2254         if (*s == '\\') {
2255             if (s + 1 < send && (s[1] == '\\'))
2256                 s++;            /* all that, just for this */
2257         }
2258         *d++ = *s++;
2259     }
2260     *d = '\0';
2261     SvCUR_set(sv, d - SvPVX_const(sv));
2262   finish:
2263     if ( PL_hints & HINT_NEW_STRING )
2264        return new_constant(NULL, 0, "q", sv, pv, "q", 1);
2265     return sv;
2266 }
2267
2268 /*
2269  * Now come three functions related to double-quote context,
2270  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2271  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2272  * interact with PL_lex_state, and create fake ( ... ) argument lists
2273  * to handle functions and concatenation.
2274  * For example,
2275  *   "foo\lbar"
2276  * is tokenised as
2277  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2278  */
2279
2280 /*
2281  * S_sublex_start
2282  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2283  *
2284  * Pattern matching will set PL_lex_op to the pattern-matching op to
2285  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2286  *
2287  * OP_CONST and OP_READLINE are easy--just make the new op and return.
2288  *
2289  * Everything else becomes a FUNC.
2290  *
2291  * Sets PL_lex_state to LEX_INTERPPUSH unless (ival was OP_NULL or we
2292  * had an OP_CONST or OP_READLINE).  This just sets us up for a
2293  * call to S_sublex_push().
2294  */
2295
2296 STATIC I32
2297 S_sublex_start(pTHX)
2298 {
2299     const I32 op_type = pl_yylval.ival;
2300
2301     if (op_type == OP_NULL) {
2302         pl_yylval.opval = PL_lex_op;
2303         PL_lex_op = NULL;
2304         return THING;
2305     }
2306     if (op_type == OP_CONST) {
2307         SV *sv = PL_lex_stuff;
2308         PL_lex_stuff = NULL;
2309         sv = tokeq(sv);
2310
2311         if (SvTYPE(sv) == SVt_PVIV) {
2312             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2313             STRLEN len;
2314             const char * const p = SvPV_const(sv, len);
2315             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2316             SvREFCNT_dec(sv);
2317             sv = nsv;
2318         }
2319         pl_yylval.opval = (OP*)newSVOP(op_type, 0, sv);
2320         return THING;
2321     }
2322
2323     PL_parser->lex_super_state = PL_lex_state;
2324     PL_parser->lex_sub_inwhat = (U16)op_type;
2325     PL_parser->lex_sub_op = PL_lex_op;
2326     PL_lex_state = LEX_INTERPPUSH;
2327
2328     PL_expect = XTERM;
2329     if (PL_lex_op) {
2330         pl_yylval.opval = PL_lex_op;
2331         PL_lex_op = NULL;
2332         return PMFUNC;
2333     }
2334     else
2335         return FUNC;
2336 }
2337
2338 /*
2339  * S_sublex_push
2340  * Create a new scope to save the lexing state.  The scope will be
2341  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2342  * to the uc, lc, etc. found before.
2343  * Sets PL_lex_state to LEX_INTERPCONCAT.
2344  */
2345
2346 STATIC I32
2347 S_sublex_push(pTHX)
2348 {
2349     LEXSHARED *shared;
2350     const bool is_heredoc = PL_multi_close == '<';
2351     ENTER;
2352
2353     PL_lex_state = PL_parser->lex_super_state;
2354     SAVEI8(PL_lex_dojoin);
2355     SAVEI32(PL_lex_brackets);
2356     SAVEI32(PL_lex_allbrackets);
2357     SAVEI32(PL_lex_formbrack);
2358     SAVEI8(PL_lex_fakeeof);
2359     SAVEI32(PL_lex_casemods);
2360     SAVEI32(PL_lex_starts);
2361     SAVEI8(PL_lex_state);
2362     SAVESPTR(PL_lex_repl);
2363     SAVEVPTR(PL_lex_inpat);
2364     SAVEI16(PL_lex_inwhat);
2365     if (is_heredoc)
2366     {
2367         SAVECOPLINE(PL_curcop);
2368         SAVEI32(PL_multi_end);
2369         SAVEI32(PL_parser->herelines);
2370         PL_parser->herelines = 0;
2371     }
2372     SAVEIV(PL_multi_close);
2373     SAVEPPTR(PL_bufptr);
2374     SAVEPPTR(PL_bufend);
2375     SAVEPPTR(PL_oldbufptr);
2376     SAVEPPTR(PL_oldoldbufptr);
2377     SAVEPPTR(PL_last_lop);
2378     SAVEPPTR(PL_last_uni);
2379     SAVEPPTR(PL_linestart);
2380     SAVESPTR(PL_linestr);
2381     SAVEGENERICPV(PL_lex_brackstack);
2382     SAVEGENERICPV(PL_lex_casestack);
2383     SAVEGENERICPV(PL_parser->lex_shared);
2384     SAVEBOOL(PL_parser->lex_re_reparsing);
2385     SAVEI32(PL_copline);
2386
2387     /* The here-doc parser needs to be able to peek into outer lexing
2388        scopes to find the body of the here-doc.  So we put PL_linestr and
2389        PL_bufptr into lex_shared, to â€˜share’ those values.
2390      */
2391     PL_parser->lex_shared->ls_linestr = PL_linestr;
2392     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2393
2394     PL_linestr = PL_lex_stuff;
2395     PL_lex_repl = PL_parser->lex_sub_repl;
2396     PL_lex_stuff = NULL;
2397     PL_parser->lex_sub_repl = NULL;
2398
2399     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2400        set for an inner quote-like operator and then an error causes scope-
2401        popping.  We must not have a PL_lex_stuff value left dangling, as
2402        that breaks assumptions elsewhere.  See bug #123617.  */
2403     SAVEGENERICSV(PL_lex_stuff);
2404     SAVEGENERICSV(PL_parser->lex_sub_repl);
2405
2406     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2407         = SvPVX(PL_linestr);
2408     PL_bufend += SvCUR(PL_linestr);
2409     PL_last_lop = PL_last_uni = NULL;
2410     SAVEFREESV(PL_linestr);
2411     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2412
2413     PL_lex_dojoin = FALSE;
2414     PL_lex_brackets = PL_lex_formbrack = 0;
2415     PL_lex_allbrackets = 0;
2416     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2417     Newx(PL_lex_brackstack, 120, char);
2418     Newx(PL_lex_casestack, 12, char);
2419     PL_lex_casemods = 0;
2420     *PL_lex_casestack = '\0';
2421     PL_lex_starts = 0;
2422     PL_lex_state = LEX_INTERPCONCAT;
2423     if (is_heredoc)
2424         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2425     PL_copline = NOLINE;
2426     
2427     Newxz(shared, 1, LEXSHARED);
2428     shared->ls_prev = PL_parser->lex_shared;
2429     PL_parser->lex_shared = shared;
2430
2431     PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2432     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2433     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2434         PL_lex_inpat = PL_parser->lex_sub_op;
2435     else
2436         PL_lex_inpat = NULL;
2437
2438     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2439     PL_in_eval &= ~EVAL_RE_REPARSING;
2440
2441     return '(';
2442 }
2443
2444 /*
2445  * S_sublex_done
2446  * Restores lexer state after a S_sublex_push.
2447  */
2448
2449 STATIC I32
2450 S_sublex_done(pTHX)
2451 {
2452     if (!PL_lex_starts++) {
2453         SV * const sv = newSVpvs("");
2454         if (SvUTF8(PL_linestr))
2455             SvUTF8_on(sv);
2456         PL_expect = XOPERATOR;
2457         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
2458         return THING;
2459     }
2460
2461     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2462         PL_lex_state = LEX_INTERPCASEMOD;
2463         return yylex();
2464     }
2465
2466     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2467     assert(PL_lex_inwhat != OP_TRANSR);
2468     if (PL_lex_repl) {
2469         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2470         PL_linestr = PL_lex_repl;
2471         PL_lex_inpat = 0;
2472         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2473         PL_bufend += SvCUR(PL_linestr);
2474         PL_last_lop = PL_last_uni = NULL;
2475         PL_lex_dojoin = FALSE;
2476         PL_lex_brackets = 0;
2477         PL_lex_allbrackets = 0;
2478         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2479         PL_lex_casemods = 0;
2480         *PL_lex_casestack = '\0';
2481         PL_lex_starts = 0;
2482         if (SvEVALED(PL_lex_repl)) {
2483             PL_lex_state = LEX_INTERPNORMAL;
2484             PL_lex_starts++;
2485             /*  we don't clear PL_lex_repl here, so that we can check later
2486                 whether this is an evalled subst; that means we rely on the
2487                 logic to ensure sublex_done() is called again only via the
2488                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2489         }
2490         else {
2491             PL_lex_state = LEX_INTERPCONCAT;
2492             PL_lex_repl = NULL;
2493         }
2494         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2495             CopLINE(PL_curcop) +=
2496                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2497                  + PL_parser->herelines;
2498             PL_parser->herelines = 0;
2499         }
2500         return '/';
2501     }
2502     else {
2503         const line_t l = CopLINE(PL_curcop);
2504         LEAVE;
2505         if (PL_multi_close == '<')
2506             PL_parser->herelines += l - PL_multi_end;
2507         PL_bufend = SvPVX(PL_linestr);
2508         PL_bufend += SvCUR(PL_linestr);
2509         PL_expect = XOPERATOR;
2510         return ')';
2511     }
2512 }
2513
2514 PERL_STATIC_INLINE SV*
2515 S_get_and_check_backslash_N_name(pTHX_ const char* s, const char* const e)
2516 {
2517     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2518      * interior, hence to the "}".  Finds what the name resolves to, returning
2519      * an SV* containing it; NULL if no valid one found */
2520
2521     SV* res = newSVpvn_flags(s, e - s, UTF ? SVf_UTF8 : 0);
2522
2523     HV * table;
2524     SV **cvp;
2525     SV *cv;
2526     SV *rv;
2527     HV *stash;
2528     const U8* first_bad_char_loc;
2529     const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2530
2531     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2532
2533     if (!SvCUR(res)) {
2534         Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
2535                        "Unknown charname '' is deprecated");
2536         return res;
2537     }
2538
2539     if (UTF && ! is_utf8_string_loc((U8 *) backslash_ptr,
2540                                      e - backslash_ptr,
2541                                      &first_bad_char_loc))
2542     {
2543         /* If warnings are on, this will print a more detailed analysis of what
2544          * is wrong than the error message below */
2545         utf8n_to_uvchr(first_bad_char_loc,
2546                        e - ((char *) first_bad_char_loc),
2547                        NULL, 0);
2548
2549         /* We deliberately don't try to print the malformed character, which
2550          * might not print very well; it also may be just the first of many
2551          * malformations, so don't print what comes after it */
2552         yyerror_pv(Perl_form(aTHX_
2553             "Malformed UTF-8 character immediately after '%.*s'",
2554             (int) (first_bad_char_loc - (U8 *) backslash_ptr), backslash_ptr),
2555                    SVf_UTF8);
2556         return NULL;
2557     }
2558
2559     res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2560                         /* include the <}> */
2561                         e - backslash_ptr + 1);
2562     if (! SvPOK(res)) {
2563         SvREFCNT_dec_NN(res);
2564         return NULL;
2565     }
2566
2567     /* See if the charnames handler is the Perl core's, and if so, we can skip
2568      * the validation needed for a user-supplied one, as Perl's does its own
2569      * validation. */
2570     table = GvHV(PL_hintgv);             /* ^H */
2571     cvp = hv_fetchs(table, "charnames", FALSE);
2572     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2573         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2574     {
2575         const char * const name = HvNAME(stash);
2576         if (HvNAMELEN(stash) == sizeof("_charnames")-1
2577          && strEQ(name, "_charnames")) {
2578            return res;
2579        }
2580     }
2581
2582     /* Here, it isn't Perl's charname handler.  We can't rely on a
2583      * user-supplied handler to validate the input name.  For non-ut8 input,
2584      * look to see that the first character is legal.  Then loop through the
2585      * rest checking that each is a continuation */
2586
2587     /* This code makes the reasonable assumption that the only Latin1-range
2588      * characters that begin a character name alias are alphabetic, otherwise
2589      * would have to create a isCHARNAME_BEGIN macro */
2590
2591     if (! UTF) {
2592         if (! isALPHAU(*s)) {
2593             goto bad_charname;
2594         }
2595         s++;
2596         while (s < e) {
2597             if (! isCHARNAME_CONT(*s)) {
2598                 goto bad_charname;
2599             }
2600             if (*s == ' ' && *(s-1) == ' ') {
2601                 goto multi_spaces;
2602             }
2603             s++;
2604         }
2605     }
2606     else {
2607         /* Similarly for utf8.  For invariants can check directly; for other
2608          * Latin1, can calculate their code point and check; otherwise  use a
2609          * swash */
2610         if (UTF8_IS_INVARIANT(*s)) {
2611             if (! isALPHAU(*s)) {
2612                 goto bad_charname;
2613             }
2614             s++;
2615         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2616             if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2617                 goto bad_charname;
2618             }
2619             s += 2;
2620         }
2621         else {
2622             if (! PL_utf8_charname_begin) {
2623                 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2624                 PL_utf8_charname_begin = _core_swash_init("utf8",
2625                                                         "_Perl_Charname_Begin",
2626                                                         &PL_sv_undef,
2627                                                         1, 0, NULL, &flags);
2628             }
2629             if (! swash_fetch(PL_utf8_charname_begin, (U8 *) s, TRUE)) {
2630                 goto bad_charname;
2631             }
2632             s += UTF8SKIP(s);
2633         }
2634
2635         while (s < e) {
2636             if (UTF8_IS_INVARIANT(*s)) {
2637                 if (! isCHARNAME_CONT(*s)) {
2638                     goto bad_charname;
2639                 }
2640                 if (*s == ' ' && *(s-1) == ' ') {
2641                     goto multi_spaces;
2642                 }
2643                 s++;
2644             }
2645             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2646                 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2647                 {
2648                     goto bad_charname;
2649                 }
2650                 s += 2;
2651             }
2652             else {
2653                 if (! PL_utf8_charname_continue) {
2654                     U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2655                     PL_utf8_charname_continue = _core_swash_init("utf8",
2656                                                 "_Perl_Charname_Continue",
2657                                                 &PL_sv_undef,
2658                                                 1, 0, NULL, &flags);
2659                 }
2660                 if (! swash_fetch(PL_utf8_charname_continue, (U8 *) s, TRUE)) {
2661                     goto bad_charname;
2662                 }
2663                 s += UTF8SKIP(s);
2664             }
2665         }
2666     }
2667     if (*(s-1) == ' ') {
2668         yyerror_pv(
2669             Perl_form(aTHX_
2670             "charnames alias definitions may not contain trailing "
2671             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2672             (int)(s - backslash_ptr + 1), backslash_ptr,
2673             (int)(e - s + 1), s + 1
2674             ),
2675         UTF ? SVf_UTF8 : 0);
2676         return NULL;
2677     }
2678
2679     if (SvUTF8(res)) { /* Don't accept malformed input */
2680         const U8* first_bad_char_loc;
2681         STRLEN len;
2682         const char* const str = SvPV_const(res, len);
2683         if (! is_utf8_string_loc((U8 *) str, len, &first_bad_char_loc)) {
2684             /* If warnings are on, this will print a more detailed analysis of
2685              * what is wrong than the error message below */
2686             utf8n_to_uvchr(first_bad_char_loc,
2687                            (char *) first_bad_char_loc - str,
2688                            NULL, 0);
2689
2690             /* We deliberately don't try to print the malformed character,
2691              * which might not print very well; it also may be just the first
2692              * of many malformations, so don't print what comes after it */
2693             yyerror_pv(
2694               Perl_form(aTHX_
2695                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2696                  (int) (e - backslash_ptr + 1), backslash_ptr,
2697                  (int) ((char *) first_bad_char_loc - str), str
2698               ),
2699               SVf_UTF8);
2700             return NULL;
2701         }
2702     }
2703
2704     return res;
2705
2706   bad_charname: {
2707
2708         /* The final %.*s makes sure that should the trailing NUL be missing
2709          * that this print won't run off the end of the string */
2710         yyerror_pv(
2711           Perl_form(aTHX_
2712             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2713             (int)(s - backslash_ptr + 1), backslash_ptr,
2714             (int)(e - s + 1), s + 1
2715           ),
2716           UTF ? SVf_UTF8 : 0);
2717         return NULL;
2718     }
2719
2720   multi_spaces:
2721         yyerror_pv(
2722           Perl_form(aTHX_
2723             "charnames alias definitions may not contain a sequence of "
2724             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2725             (int)(s - backslash_ptr + 1), backslash_ptr,
2726             (int)(e - s + 1), s + 1
2727           ),
2728           UTF ? SVf_UTF8 : 0);
2729         return NULL;
2730 }
2731
2732 /*
2733   scan_const
2734
2735   Extracts the next constant part of a pattern, double-quoted string,
2736   or transliteration.  This is terrifying code.
2737
2738   For example, in parsing the double-quoted string "ab\x63$d", it would
2739   stop at the '$' and return an OP_CONST containing 'abc'.
2740
2741   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2742   processing a pattern (PL_lex_inpat is true), a transliteration
2743   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2744
2745   Returns a pointer to the character scanned up to. If this is
2746   advanced from the start pointer supplied (i.e. if anything was
2747   successfully parsed), will leave an OP_CONST for the substring scanned
2748   in pl_yylval. Caller must intuit reason for not parsing further
2749   by looking at the next characters herself.
2750
2751   In patterns:
2752     expand:
2753       \N{FOO}  => \N{U+hex_for_character_FOO}
2754       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2755
2756     pass through:
2757         all other \-char, including \N and \N{ apart from \N{ABC}
2758
2759     stops on:
2760         @ and $ where it appears to be a var, but not for $ as tail anchor
2761         \l \L \u \U \Q \E
2762         (?{  or  (??{
2763
2764   In transliterations:
2765     characters are VERY literal, except for - not at the start or end
2766     of the string, which indicates a range. If the range is in bytes,
2767     scan_const expands the range to the full set of intermediate
2768     characters. If the range is in utf8, the hyphen is replaced with
2769     a certain range mark which will be handled by pmtrans() in op.c.
2770
2771   In double-quoted strings:
2772     backslashes:
2773       double-quoted style: \r and \n
2774       constants: \x31, etc.
2775       deprecated backrefs: \1 (in substitution replacements)
2776       case and quoting: \U \Q \E
2777     stops on @ and $
2778
2779   scan_const does *not* construct ops to handle interpolated strings.
2780   It stops processing as soon as it finds an embedded $ or @ variable
2781   and leaves it to the caller to work out what's going on.
2782
2783   embedded arrays (whether in pattern or not) could be:
2784       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2785
2786   $ in double-quoted strings must be the symbol of an embedded scalar.
2787
2788   $ in pattern could be $foo or could be tail anchor.  Assumption:
2789   it's a tail anchor if $ is the last thing in the string, or if it's
2790   followed by one of "()| \r\n\t"
2791
2792   \1 (backreferences) are turned into $1 in substitutions
2793
2794   The structure of the code is
2795       while (there's a character to process) {
2796           handle transliteration ranges
2797           skip regexp comments /(?#comment)/ and codes /(?{code})/
2798           skip #-initiated comments in //x patterns
2799           check for embedded arrays
2800           check for embedded scalars
2801           if (backslash) {
2802               deprecate \1 in substitution replacements
2803               handle string-changing backslashes \l \U \Q \E, etc.
2804               switch (what was escaped) {
2805                   handle \- in a transliteration (becomes a literal -)
2806                   if a pattern and not \N{, go treat as regular character
2807                   handle \132 (octal characters)
2808                   handle \x15 and \x{1234} (hex characters)
2809                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2810                   handle \cV (control characters)
2811                   handle printf-style backslashes (\f, \r, \n, etc)
2812               } (end switch)
2813               continue
2814           } (end if backslash)
2815           handle regular character
2816     } (end while character to read)
2817                 
2818 */
2819
2820 STATIC char *
2821 S_scan_const(pTHX_ char *start)
2822 {
2823     char *send = PL_bufend;             /* end of the constant */
2824     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
2825                                            on sizing. */
2826     char *s = start;                    /* start of the constant */
2827     char *d = SvPVX(sv);                /* destination for copies */
2828     bool dorange = FALSE;               /* are we in a translit range? */
2829     bool didrange = FALSE;              /* did we just finish a range? */
2830     bool in_charclass = FALSE;          /* within /[...]/ */
2831     bool has_utf8 = FALSE;              /* Output constant is UTF8 */
2832     bool  this_utf8 = cBOOL(UTF);       /* Is the source string assumed to be
2833                                            UTF8?  But, this can show as true
2834                                            when the source isn't utf8, as for
2835                                            example when it is entirely composed
2836                                            of hex constants */
2837     SV *res;                            /* result from charnames */
2838     STRLEN offset_to_max;   /* The offset in the output to where the range
2839                                high-end character is temporarily placed */
2840
2841     /* Note on sizing:  The scanned constant is placed into sv, which is
2842      * initialized by newSV() assuming one byte of output for every byte of
2843      * input.  This routine expects newSV() to allocate an extra byte for a
2844      * trailing NUL, which this routine will append if it gets to the end of
2845      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2846      * CAPITAL LETTER A}), or more output than input if the constant ends up
2847      * recoded to utf8, but each time a construct is found that might increase
2848      * the needed size, SvGROW() is called.  Its size parameter each time is
2849      * based on the best guess estimate at the time, namely the length used so
2850      * far, plus the length the current construct will occupy, plus room for
2851      * the trailing NUL, plus one byte for every input byte still unscanned */ 
2852
2853     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2854                        before set */
2855 #ifdef EBCDIC
2856     int backslash_N = 0;            /* ? was the character from \N{} */
2857     int non_portable_endpoint = 0;  /* ? In a range is an endpoint
2858                                        platform-specific like \x65 */
2859 #endif
2860
2861     PERL_ARGS_ASSERT_SCAN_CONST;
2862
2863     assert(PL_lex_inwhat != OP_TRANSR);
2864     if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
2865         /* If we are doing a trans and we know we want UTF8 set expectation */
2866         has_utf8   = PL_parser->lex_sub_op->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF);
2867         this_utf8  = PL_parser->lex_sub_op->op_private & (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
2868     }
2869
2870     /* Protect sv from errors and fatal warnings. */
2871     ENTER_with_name("scan_const");
2872     SAVEFREESV(sv);
2873
2874     while (s < send
2875            || dorange   /* Handle tr/// range at right edge of input */
2876     ) {
2877
2878         /* get transliterations out of the way (they're most literal) */
2879         if (PL_lex_inwhat == OP_TRANS) {
2880
2881             /* But there isn't any special handling necessary unless there is a
2882              * range, so for most cases we just drop down and handle the value
2883              * as any other.  There are two exceptions.
2884              *
2885              * 1.  A minus sign indicates that we are actually going to have
2886              *     a range.  In this case, skip the '-', set a flag, then drop
2887              *     down to handle what should be the end range value.
2888              * 2.  After we've handled that value, the next time through, that
2889              *     flag is set and we fix up the range.
2890              *
2891              * Ranges entirely within Latin1 are expanded out entirely, in
2892              * order to avoid the significant overhead of making a swash.
2893              * Ranges that extend above Latin1 have to have a swash, so there
2894              * is no advantage to abbreviating them here, so they are stored
2895              * here as Min, ILLEGAL_UTF8_BYTE, Max.  The illegal byte signifies
2896              * a hyphen without any possible ambiguity.  On EBCDIC machines, if
2897              * the range is expressed as Unicode, the Latin1 portion is
2898              * expanded out even if the entire range extends above Latin1.
2899              * This is because each code point in it has to be processed here
2900              * individually to get its native translation */
2901
2902             if (! dorange) {
2903
2904                 /* Here, we don't think we're in a range.  If we've processed
2905                  * at least one character, then see if this next one is a '-',
2906                  * indicating the previous one was the start of a range.  But
2907                  * don't bother if we're too close to the end for the minus to
2908                  * mean that. */
2909                 if (*s != '-' || s >= send - 1 || s == start) {
2910
2911                     /* A regular character.  Process like any other, but first
2912                      * clear any flags */
2913                     didrange = FALSE;
2914                     dorange = FALSE;
2915 #ifdef EBCDIC
2916                     non_portable_endpoint = 0;
2917                     backslash_N = 0;
2918 #endif
2919                     /* Drops down to generic code to process current byte */
2920                 }
2921                 else {
2922                     if (didrange) { /* Something like y/A-C-Z// */
2923                         Perl_croak(aTHX_ "Ambiguous range in transliteration operator");
2924                     }
2925
2926                     dorange = TRUE;
2927
2928                     s++;    /* Skip past the minus */
2929
2930                     /* d now points to where the end-range character will be
2931                      * placed.  Save it so won't have to go finding it later,
2932                      * and drop down to get that character.  (Actually we
2933                      * instead save the offset, to handle the case where a
2934                      * realloc in the meantime could change the actual
2935                      * pointer).  We'll finish processing the range the next
2936                      * time through the loop */
2937                     offset_to_max = d - SvPVX_const(sv);
2938                 }
2939             }  /* End of not a range */
2940             else {
2941                 /* Here we have parsed a range.  Now must handle it.  At this
2942                  * point:
2943                  * 'sv' is a SV* that contains the output string we are
2944                  *      constructing.  The final two characters in that string
2945                  *      are the range start and range end, in order.
2946                  * 'd'  points to just beyond the range end in the 'sv' string,
2947                  *      where we would next place something
2948                  * 'offset_to_max' is the offset in 'sv' at which the character
2949                  *      before 'd' begins.
2950                  */
2951                 const char * max_ptr = SvPVX_const(sv) + offset_to_max;
2952                 const char * min_ptr;
2953                 IV range_min;
2954                 IV range_max;   /* last character in range */
2955                 STRLEN save_offset;
2956                 STRLEN grow;
2957 #ifndef EBCDIC  /* Not meaningful except in EBCDIC, so initialize to false */
2958                 const bool convert_unicode = FALSE;
2959                 const IV real_range_max = 0;
2960 #else
2961                 bool convert_unicode;
2962                 IV real_range_max = 0;
2963 #endif
2964
2965                 /* Get the range-ends code point values. */
2966                 if (has_utf8) {
2967                     /* We know the utf8 is valid, because we just constructed
2968                      * it ourselves in previous loop iterations */
2969                     min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
2970                     range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
2971                     range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
2972                 }
2973                 else {
2974                     min_ptr = max_ptr - 1;
2975                     range_min = * (U8*) min_ptr;
2976                     range_max = * (U8*) max_ptr;
2977                 }
2978
2979 #ifdef EBCDIC
2980                 /* On EBCDIC platforms, we may have to deal with portable
2981                  * ranges.  These happen if at least one range endpoint is a
2982                  * Unicode value (\N{...}), or if the range is a subset of
2983                  * [A-Z] or [a-z], and both ends are literal characters,
2984                  * like 'A', and not like \x{C1} */
2985                 if ((convert_unicode
2986                      = cBOOL(backslash_N)   /* \N{} forces Unicode, hence
2987                                                portable range */
2988                       || (   ! non_portable_endpoint
2989                           && ((  isLOWER_A(range_min) && isLOWER_A(range_max))
2990                              || (isUPPER_A(range_min) && isUPPER_A(range_max))))
2991                 )) {
2992
2993                     /* Special handling is needed for these portable ranges.
2994                      * They are defined to all be in Unicode terms, which
2995                      * include all Unicode code points between the end points.
2996                      * Convert to Unicode to get the Unicode range.  Later we
2997                      * will convert each code point in the range back to
2998                      * native.  */
2999                     range_min = NATIVE_TO_UNI(range_min);
3000                     range_max = NATIVE_TO_UNI(range_max);
3001                 }
3002 #endif
3003
3004                 if (range_min > range_max) {
3005                     if (convert_unicode) {
3006                         /* Need to convert back to native for meaningful
3007                          * messages for this platform */
3008                         range_min = UNI_TO_NATIVE(range_min);
3009                         range_max = UNI_TO_NATIVE(range_max);
3010                     }
3011
3012                     /* Use the characters themselves for the error message if
3013                      * ASCII printables; otherwise some visible representation
3014                      * of them */
3015                     if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3016                         Perl_croak(aTHX_
3017                          "Invalid range \"%c-%c\" in transliteration operator",
3018                          (char)range_min, (char)range_max);
3019                     }
3020                     else if (convert_unicode) {
3021                         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3022                         Perl_croak(aTHX_
3023                                "Invalid range \"\\N{U+%04"UVXf"}-\\N{U+%04"UVXf"}\""
3024                                " in transliteration operator",
3025                                range_min, range_max);
3026                     }
3027                     else {
3028                         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3029                         Perl_croak(aTHX_
3030                                "Invalid range \"\\x{%04"UVXf"}-\\x{%04"UVXf"}\""
3031                                " in transliteration operator",
3032                                range_min, range_max);
3033                     }
3034                 }
3035
3036                 if (has_utf8) {
3037
3038                     /* We try to avoid creating a swash.  If the upper end of
3039                      * this range is below 256, this range won't force a swash;
3040                      * otherwise it does force a swash, and as long as we have
3041                      * to have one, we might as well not expand things out.
3042                      * But if it's EBCDIC, we may have to look at each
3043                      * character below 256 if we have to convert to/from
3044                      * Unicode values */
3045                     if (range_max > 255
3046 #ifdef EBCDIC
3047                         && (range_min > 255 || ! convert_unicode)
3048 #endif
3049                     ) {
3050                         /* Move the high character one byte to the right; then
3051                          * insert between it and the range begin, an illegal
3052                          * byte which serves to indicate this is a range (using
3053                          * a '-' could be ambiguous). */
3054                         char *e = d++;
3055                         while (e-- > max_ptr) {
3056                             *(e + 1) = *e;
3057                         }
3058                         *(e + 1) = (char) ILLEGAL_UTF8_BYTE;
3059                         goto range_done;
3060                     }
3061
3062                     /* Here, we're going to expand out the range.  For EBCDIC
3063                      * the range can extend above 255 (not so in ASCII), so
3064                      * for EBCDIC, split it into the parts above and below
3065                      * 255/256 */
3066 #ifdef EBCDIC
3067                     if (range_max > 255) {
3068                         real_range_max = range_max;
3069                         range_max = 255;
3070                     }
3071 #endif
3072                 }
3073
3074                 /* Here we need to expand out the string to contain each
3075                  * character in the range.  Grow the output to handle this */
3076
3077                 save_offset  = min_ptr - SvPVX_const(sv);
3078
3079                 /* The base growth is the number of code points in the range */
3080                 grow = range_max - range_min + 1;
3081                 if (has_utf8) {
3082
3083                     /* But if the output is UTF-8, some of those characters may
3084                      * need two bytes (since the maximum range value here is
3085                      * 255, the max bytes per character is two).  On ASCII
3086                      * platforms, it's not much trouble to get an accurate
3087                      * count of what's needed.  But on EBCDIC, the ones that
3088                      * need 2 bytes are scattered around, so just use a worst
3089                      * case value instead of calculating for that platform.  */
3090 #ifdef EBCDIC
3091                     grow *= 2;
3092 #else
3093                     /* Only those above 127 require 2 bytes.  This may be
3094                      * everything in the range, or not */
3095                     if (range_min > 127) {
3096                         grow *= 2;
3097                     }
3098                     else if (range_max > 127) {
3099                         grow += range_max - 127;
3100                     }
3101 #endif
3102                 }
3103
3104                 /* Subtract 3 for the bytes that were already accounted for
3105                  * (min, max, and the hyphen) */
3106                 d = save_offset + SvGROW(sv, SvLEN(sv) + grow - 3);
3107
3108                 /* Here, we expand out the range.  On ASCII platforms, the
3109                  * compiler should optimize out the 'convert_unicode==TRUE'
3110                  * portion of this */
3111                 if (convert_unicode) {
3112                     IV i;
3113
3114                     /* Recall that the min and max are now in Unicode terms, so
3115                      * we have to convert each character to its native
3116                      * equivalent */
3117                     if (has_utf8) {
3118                         for (i = range_min; i <= range_max; i++) {
3119                             append_utf8_from_native_byte(LATIN1_TO_NATIVE((U8) i),
3120                                                          (U8 **) &d);
3121                         }
3122                     }
3123                     else {
3124                         for (i = range_min; i <= range_max; i++) {
3125                             *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3126                         }
3127                     }
3128                 }
3129                 else {
3130                     IV i;
3131
3132                     /* Here, no conversions are necessary, which means that the
3133                      * first character in the range is already in 'd' and
3134                      * valid, so we can skip overwriting it */
3135                     if (has_utf8) {
3136                         d += UTF8SKIP(d);
3137                         for (i = range_min + 1; i <= range_max; i++) {
3138                             append_utf8_from_native_byte((U8) i, (U8 **) &d);
3139                         }
3140                     }
3141                     else {
3142                         d++;
3143                         for (i = range_min + 1; i <= range_max; i++) {
3144                             *d++ = (char)i;
3145                         }
3146                     }
3147                 }
3148
3149                 /* (Compilers should optimize this out for non-EBCDIC).  If the
3150                  * original range extended above 255, add in that portion */
3151                 if (real_range_max) {
3152                     *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3153                     *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3154                     if (real_range_max > 0x101)
3155                         *d++ = (char) ILLEGAL_UTF8_BYTE;
3156                     if (real_range_max > 0x100)
3157                         d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3158                 }
3159
3160               range_done:
3161                 /* mark the range as done, and continue */
3162                 didrange = TRUE;
3163                 dorange = FALSE;
3164 #ifdef EBCDIC
3165                 non_portable_endpoint = 0;
3166                 backslash_N = 0;
3167 #endif
3168                 continue;
3169             } /* End of is a range */
3170         } /* End of transliteration.  Joins main code after these else's */
3171         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3172             char *s1 = s-1;
3173             int esc = 0;
3174             while (s1 >= start && *s1-- == '\\')
3175                 esc = !esc;
3176             if (!esc)
3177                 in_charclass = TRUE;
3178         }
3179
3180         else if (*s == ']' && PL_lex_inpat &&  in_charclass) {
3181             char *s1 = s-1;
3182             int esc = 0;
3183             while (s1 >= start && *s1-- == '\\')
3184                 esc = !esc;
3185             if (!esc)
3186                 in_charclass = FALSE;
3187         }
3188
3189         /* skip for regexp comments /(?#comment)/, except for the last
3190          * char, which will be done separately.
3191          * Stop on (?{..}) and friends */
3192
3193         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3194             if (s[2] == '#') {
3195                 while (s+1 < send && *s != ')')
3196                     *d++ = *s++;
3197             }
3198             else if (!PL_lex_casemods
3199                      && (    s[2] == '{' /* This should match regcomp.c */
3200                          || (s[2] == '?' && s[3] == '{')))
3201             {
3202                 break;
3203             }
3204         }
3205
3206         /* likewise skip #-initiated comments in //x patterns */
3207         else if (*s == '#'
3208                  && PL_lex_inpat
3209                  && !in_charclass
3210                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3211         {
3212             while (s+1 < send && *s != '\n')
3213                 *d++ = *s++;
3214         }
3215
3216         /* no further processing of single-quoted regex */
3217         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3218             goto default_action;
3219
3220         /* check for embedded arrays
3221            (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3222            */
3223         else if (*s == '@' && s[1]) {
3224             if (UTF ? isIDFIRST_utf8((U8*)s+1) : isWORDCHAR_A(s[1]))
3225                 break;
3226             if (strchr(":'{$", s[1]))
3227                 break;
3228             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3229                 break; /* in regexp, neither @+ nor @- are interpolated */
3230         }
3231
3232         /* check for embedded scalars.  only stop if we're sure it's a
3233            variable.
3234         */
3235         else if (*s == '$') {
3236             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3237                 break;
3238             if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
3239                 if (s[1] == '\\') {
3240                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3241                                    "Possible unintended interpolation of $\\ in regex");
3242                 }
3243                 break;          /* in regexp, $ might be tail anchor */
3244             }
3245         }
3246
3247         /* End of else if chain - OP_TRANS rejoin rest */
3248
3249         /* backslashes */
3250         if (*s == '\\' && s+1 < send) {
3251             char* e;    /* Can be used for ending '}', etc. */
3252
3253             s++;
3254
3255             /* warn on \1 - \9 in substitution replacements, but note that \11
3256              * is an octal; and \19 is \1 followed by '9' */
3257             if (PL_lex_inwhat == OP_SUBST
3258                 && !PL_lex_inpat
3259                 && isDIGIT(*s)
3260                 && *s != '0'
3261                 && !isDIGIT(s[1]))
3262             {
3263                 /* diag_listed_as: \%d better written as $%d */
3264                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3265                 *--s = '$';
3266                 break;
3267             }
3268
3269             /* string-change backslash escapes */
3270             if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQF", *s)) {
3271                 --s;
3272                 break;
3273             }
3274             /* In a pattern, process \N, but skip any other backslash escapes.
3275              * This is because we don't want to translate an escape sequence
3276              * into a meta symbol and have the regex compiler use the meta
3277              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3278              * in spite of this, we do have to process \N here while the proper
3279              * charnames handler is in scope.  See bugs #56444 and #62056.
3280              *
3281              * There is a complication because \N in a pattern may also stand
3282              * for 'match a non-nl', and not mean a charname, in which case its
3283              * processing should be deferred to the regex compiler.  To be a
3284              * charname it must be followed immediately by a '{', and not look
3285              * like \N followed by a curly quantifier, i.e., not something like
3286              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3287              * quantifier */
3288             else if (PL_lex_inpat
3289                     && (*s != 'N'
3290                         || s[1] != '{'
3291                         || regcurly(s + 1)))
3292             {
3293                 *d++ = '\\';
3294                 goto default_action;
3295             }
3296
3297             switch (*s) {
3298             default:
3299                 {
3300                     if ((isALPHANUMERIC(*s)))
3301                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3302                                        "Unrecognized escape \\%c passed through",
3303                                        *s);
3304                     /* default action is to copy the quoted character */
3305                     goto default_action;
3306                 }
3307
3308             /* eg. \132 indicates the octal constant 0132 */
3309             case '0': case '1': case '2': case '3':
3310             case '4': case '5': case '6': case '7':
3311                 {
3312                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
3313                     STRLEN len = 3;
3314                     uv = grok_oct(s, &len, &flags, NULL);
3315                     s += len;
3316                     if (len < 3 && s < send && isDIGIT(*s)
3317                         && ckWARN(WARN_MISC))
3318                     {
3319                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3320                                     "%s", form_short_octal_warning(s, len));
3321                     }
3322                 }
3323                 goto NUM_ESCAPE_INSERT;
3324
3325             /* eg. \o{24} indicates the octal constant \024 */
3326             case 'o':
3327                 {
3328                     const char* error;
3329
3330                     bool valid = grok_bslash_o(&s, &uv, &error,
3331                                                TRUE, /* Output warning */
3332                                                FALSE, /* Not strict */
3333                                                TRUE, /* Output warnings for
3334                                                          non-portables */
3335                                                UTF);
3336                     if (! valid) {
3337                         yyerror(error);
3338                         continue;
3339                     }
3340                     goto NUM_ESCAPE_INSERT;
3341                 }
3342
3343             /* eg. \x24 indicates the hex constant 0x24 */
3344             case 'x':
3345                 {
3346                     const char* error;
3347
3348                     bool valid = grok_bslash_x(&s, &uv, &error,
3349                                                TRUE, /* Output warning */
3350                                                FALSE, /* Not strict */
3351                                                TRUE,  /* Output warnings for
3352                                                          non-portables */
3353                                                UTF);
3354                     if (! valid) {
3355                         yyerror(error);
3356                         continue;
3357                     }
3358                 }
3359
3360               NUM_ESCAPE_INSERT:
3361                 /* Insert oct or hex escaped character. */
3362                 
3363                 /* Here uv is the ordinal of the next character being added */
3364                 if (UVCHR_IS_INVARIANT(uv)) {
3365                     *d++ = (char) uv;
3366                 }
3367                 else {
3368                     if (!has_utf8 && uv > 255) {
3369                         /* Might need to recode whatever we have accumulated so
3370                          * far if it contains any chars variant in utf8 or
3371                          * utf-ebcdic. */
3372                           
3373                         SvCUR_set(sv, d - SvPVX_const(sv));
3374                         SvPOK_on(sv);
3375                         *d = '\0';
3376                         /* See Note on sizing above.  */
3377                         sv_utf8_upgrade_flags_grow(
3378                                        sv,
3379                                        SV_GMAGIC|SV_FORCE_UTF8_UPGRADE
3380                                                   /* Above-latin1 in string
3381                                                    * implies no encoding */
3382                                                   |SV_UTF8_NO_ENCODING,
3383                                        UVCHR_SKIP(uv) + (STRLEN)(send - s) + 1);
3384                         d = SvPVX(sv) + SvCUR(sv);
3385                         has_utf8 = TRUE;
3386                     }
3387
3388                     if (has_utf8) {
3389                        /* Usually, there will already be enough room in 'sv'
3390                         * since such escapes are likely longer than any UTF-8
3391                         * sequence they can end up as.  This isn't the case on
3392                         * EBCDIC where \x{40000000} contains 12 bytes, and the
3393                         * UTF-8 for it contains 14.  And, we have to allow for
3394                         * a trailing NUL.  It probably can't happen on ASCII
3395                         * platforms, but be safe */
3396                         const STRLEN needed = d - SvPVX(sv) + UVCHR_SKIP(uv)
3397                                             + 1;
3398                         if (UNLIKELY(needed > SvLEN(sv))) {
3399                             SvCUR_set(sv, d - SvPVX_const(sv));
3400                             d = sv_grow(sv, needed) + SvCUR(sv);
3401                         }
3402
3403                         d = (char*)uvchr_to_utf8((U8*)d, uv);
3404                         if (PL_lex_inwhat == OP_TRANS
3405                             && PL_parser->lex_sub_op)
3406                         {
3407                             PL_parser->lex_sub_op->op_private |=
3408                                 (PL_lex_repl ? OPpTRANS_FROM_UTF
3409                                              : OPpTRANS_TO_UTF);
3410                         }
3411                     }
3412                     else {
3413                         *d++ = (char)uv;
3414                     }
3415                 }
3416 #ifdef EBCDIC
3417                 non_portable_endpoint++;
3418 #endif
3419                 continue;
3420
3421             case 'N':
3422                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3423                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3424                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3425                  * GRAVE} (except y/// can't handle the latter, croaking).  For
3426                  * convenience all three forms are referred to as "named
3427                  * characters" below.
3428                  *
3429                  * For patterns, \N also can mean to match a non-newline.  Code
3430                  * before this 'switch' statement should already have handled
3431                  * this situation, and hence this code only has to deal with
3432                  * the named character cases.
3433                  *
3434                  * For non-patterns, the named characters are converted to
3435                  * their string equivalents.  In patterns, named characters are
3436                  * not converted to their ultimate forms for the same reasons
3437                  * that other escapes aren't.  Instead, they are converted to
3438                  * the \N{U+...} form to get the value from the charnames that
3439                  * is in effect right now, while preserving the fact that it
3440                  * was a named character, so that the regex compiler knows
3441                  * this.
3442                  *
3443                  * The structure of this section of code (besides checking for
3444                  * errors and upgrading to utf8) is:
3445                  *    If the named character is of the form \N{U+...}, pass it
3446                  *      through if a pattern; otherwise convert the code point
3447                  *      to utf8
3448                  *    Otherwise must be some \N{NAME}: convert to
3449                  *      \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3450                  *
3451                  * Transliteration is an exception.  The conversion to utf8 is
3452                  * only done if the code point requires it to be representable.
3453                  *
3454                  * Here, 's' points to the 'N'; the test below is guaranteed to
3455                  * succeed if we are being called on a pattern, as we already
3456                  * know from a test above that the next character is a '{'.  A
3457                  * non-pattern \N must mean 'named character', which requires
3458                  * braces */
3459                 s++;
3460                 if (*s != '{') {
3461                     yyerror("Missing braces on \\N{}"); 
3462                     continue;
3463                 }
3464                 s++;
3465
3466                 /* If there is no matching '}', it is an error. */
3467                 if (! (e = strchr(s, '}'))) {
3468                     if (! PL_lex_inpat) {
3469                         yyerror("Missing right brace on \\N{}");
3470                     } else {
3471                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3472                     }
3473                     continue;
3474                 }
3475
3476                 /* Here it looks like a named character */
3477
3478                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3479                     s += 2;         /* Skip to next char after the 'U+' */
3480                     if (PL_lex_inpat) {
3481
3482                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3483                         /* Check the syntax.  */
3484                         const char *orig_s;
3485                         orig_s = s - 5;
3486                         if (!isXDIGIT(*s)) {
3487                           bad_NU:
3488                             yyerror(
3489                                 "Invalid hexadecimal number in \\N{U+...}"
3490                             );
3491                             s = e + 1;
3492                             continue;
3493                         }
3494                         while (++s < e) {
3495                             if (isXDIGIT(*s))
3496                                 continue;
3497                             else if ((*s == '.' || *s == '_')
3498                                   && isXDIGIT(s[1]))
3499                                 continue;
3500                             goto bad_NU;
3501                         }
3502
3503                         /* Pass everything through unchanged.
3504                          * +1 is for the '}' */
3505                         Copy(orig_s, d, e - orig_s + 1, char);
3506                         d += e - orig_s + 1;
3507                     }
3508                     else {  /* Not a pattern: convert the hex to string */
3509                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3510                                 | PERL_SCAN_SILENT_ILLDIGIT
3511                                 | PERL_SCAN_DISALLOW_PREFIX;
3512                         STRLEN len = e - s;
3513                         uv = grok_hex(s, &len, &flags, NULL);
3514                         if (len == 0 || (len != (STRLEN)(e - s)))
3515                             goto bad_NU;
3516
3517                          /* For non-tr///, if the destination is not in utf8,
3518                           * unconditionally recode it to be so.  This is
3519                           * because \N{} implies Unicode semantics, and scalars
3520                           * have to be in utf8 to guarantee those semantics.
3521                           * tr/// doesn't care about Unicode rules, so no need
3522                           * there to upgrade to UTF-8 for small enough code
3523                           * points */
3524                         if (! has_utf8 && (   uv > 0xFF
3525                                            || PL_lex_inwhat != OP_TRANS))
3526                         {
3527                             SvCUR_set(sv, d - SvPVX_const(sv));
3528                             SvPOK_on(sv);
3529                             *d = '\0';
3530                             /* See Note on sizing above.  */
3531                             sv_utf8_upgrade_flags_grow(
3532                                     sv,
3533                                     SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3534                                     OFFUNISKIP(uv) + (STRLEN)(send - e) + 1);
3535                             d = SvPVX(sv) + SvCUR(sv);
3536                             has_utf8 = TRUE;
3537                         }
3538
3539                         /* Add the (Unicode) code point to the output. */
3540                         if (! has_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3541                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3542                         }
3543                         else {
3544                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv, 0);
3545                         }
3546                     }
3547                 }
3548                 else /* Here is \N{NAME} but not \N{U+...}. */
3549                      if ((res = get_and_check_backslash_N_name(s, e)))
3550                 {
3551                     STRLEN len;
3552                     const char *str = SvPV_const(res, len);
3553                     if (PL_lex_inpat) {
3554
3555                         if (! len) { /* The name resolved to an empty string */
3556                             Copy("\\N{}", d, 4, char);
3557                             d += 4;
3558                         }
3559                         else {
3560                             /* In order to not lose information for the regex
3561                             * compiler, pass the result in the specially made
3562                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3563                             * the code points in hex of each character
3564                             * returned by charnames */
3565
3566                             const char *str_end = str + len;
3567                             const STRLEN off = d - SvPVX_const(sv);
3568
3569                             if (! SvUTF8(res)) {
3570                                 /* For the non-UTF-8 case, we can determine the
3571                                  * exact length needed without having to parse
3572                                  * through the string.  Each character takes up
3573                                  * 2 hex digits plus either a trailing dot or
3574                                  * the "}" */
3575                                 const char initial_text[] = "\\N{U+";
3576                                 const STRLEN initial_len = sizeof(initial_text)
3577                                                            - 1;
3578                                 d = off + SvGROW(sv, off
3579                                                     + 3 * len
3580
3581                                                     /* +1 for trailing NUL */
3582                                                     + initial_len + 1
3583
3584                                                     + (STRLEN)(send - e));
3585                                 Copy(initial_text, d, initial_len, char);
3586                                 d += initial_len;
3587                                 while (str < str_end) {
3588                                     char hex_string[4];
3589                                     int len =
3590                                         my_snprintf(hex_string,
3591                                                   sizeof(hex_string),
3592                                                   "%02X.",
3593
3594                                                   /* The regex compiler is
3595                                                    * expecting Unicode, not
3596                                                    * native */
3597                                                   NATIVE_TO_LATIN1(*str));
3598                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3599                                                            sizeof(hex_string));
3600                                     Copy(hex_string, d, 3, char);
3601                                     d += 3;
3602                                     str++;
3603                                 }
3604                                 d--;    /* Below, we will overwrite the final
3605                                            dot with a right brace */
3606                             }
3607                             else {
3608                                 STRLEN char_length; /* cur char's byte length */
3609
3610                                 /* and the number of bytes after this is
3611                                  * translated into hex digits */
3612                                 STRLEN output_length;
3613
3614                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3615                                  * for max('U+', '.'); and 1 for NUL */
3616                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3617
3618                                 /* Get the first character of the result. */
3619                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3620                                                         len,
3621                                                         &char_length,
3622                                                         UTF8_ALLOW_ANYUV);
3623                                 /* Convert first code point to Unicode hex,
3624                                  * including the boiler plate before it. */
3625                                 output_length =
3626                                     my_snprintf(hex_string, sizeof(hex_string),
3627                                              "\\N{U+%X",
3628                                              (unsigned int) NATIVE_TO_UNI(uv));
3629
3630                                 /* Make sure there is enough space to hold it */
3631                                 d = off + SvGROW(sv, off
3632                                                     + output_length
3633                                                     + (STRLEN)(send - e)
3634                                                     + 2);       /* '}' + NUL */
3635                                 /* And output it */
3636                                 Copy(hex_string, d, output_length, char);
3637                                 d += output_length;
3638
3639                                 /* For each subsequent character, append dot and
3640                                 * its Unicode code point in hex */
3641                                 while ((str += char_length) < str_end) {
3642                                     const STRLEN off = d - SvPVX_const(sv);
3643                                     U32 uv = utf8n_to_uvchr((U8 *) str,
3644                                                             str_end - str,
3645                                                             &char_length,
3646                                                             UTF8_ALLOW_ANYUV);
3647                                     output_length =
3648                                         my_snprintf(hex_string,
3649                                              sizeof(hex_string),
3650                                              ".%X",
3651                                              (unsigned int) NATIVE_TO_UNI(uv));
3652
3653                                     d = off + SvGROW(sv, off
3654                                                         + output_length
3655                                                         + (STRLEN)(send - e)
3656                                                         + 2);   /* '}' +  NUL */
3657                                     Copy(hex_string, d, output_length, char);
3658                                     d += output_length;
3659                                 }
3660                             }
3661
3662                             *d++ = '}'; /* Done.  Add the trailing brace */
3663                         }
3664                     }
3665                     else { /* Here, not in a pattern.  Convert the name to a
3666                             * string. */
3667
3668                         if (PL_lex_inwhat == OP_TRANS) {
3669                             str = SvPV_const(res, len);
3670                             if (len > ((SvUTF8(res))
3671                                        ? UTF8SKIP(str)
3672                                        : 1U))
3673                             {
3674                                 yyerror(Perl_form(aTHX_
3675                                     "%.*s must not be a named sequence"
3676                                     " in transliteration operator",
3677                                         /*  +1 to include the "}" */
3678                                     (int) (e + 1 - start), start));
3679                                 goto end_backslash_N;
3680                             }
3681                         }
3682                         else if (! SvUTF8(res)) {
3683                             /* Make sure \N{} return is UTF-8.  This is because
3684                              * \N{} implies Unicode semantics, and scalars have
3685                              * to be in utf8 to guarantee those semantics; but
3686                              * not needed in tr/// */
3687                             sv_utf8_upgrade_flags(res, SV_UTF8_NO_ENCODING);
3688                             str = SvPV_const(res, len);
3689                         }
3690
3691                          /* Upgrade destination to be utf8 if this new
3692                           * component is */
3693                         if (! has_utf8 && SvUTF8(res)) {
3694                             SvCUR_set(sv, d - SvPVX_const(sv));
3695                             SvPOK_on(sv);
3696                             *d = '\0';
3697                             /* See Note on sizing above.  */
3698                             sv_utf8_upgrade_flags_grow(sv,
3699                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3700                                                 len + (STRLEN)(send - s) + 1);
3701                             d = SvPVX(sv) + SvCUR(sv);
3702                             has_utf8 = TRUE;
3703                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3704
3705                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3706                              * set correctly here). */
3707                             const STRLEN off = d - SvPVX_const(sv);
3708                             d = off + SvGROW(sv, off + len + (STRLEN)(send - s) + 1);
3709                         }
3710                         Copy(str, d, len, char);
3711                         d += len;
3712                     }
3713
3714                     SvREFCNT_dec(res);
3715
3716                 } /* End \N{NAME} */
3717
3718               end_backslash_N:
3719 #ifdef EBCDIC
3720                 backslash_N++; /* \N{} is defined to be Unicode */
3721 #endif
3722                 s = e + 1;  /* Point to just after the '}' */
3723                 continue;
3724
3725             /* \c is a control character */
3726             case 'c':
3727                 s++;
3728                 if (s < send) {
3729                     *d++ = grok_bslash_c(*s++, 1);
3730                 }
3731                 else {
3732                     yyerror("Missing control char name in \\c");
3733                 }
3734 #ifdef EBCDIC
3735                 non_portable_endpoint++;
3736 #endif
3737                 continue;
3738
3739             /* printf-style backslashes, formfeeds, newlines, etc */
3740             case 'b':
3741                 *d++ = '\b';
3742                 break;
3743             case 'n':
3744                 *d++ = '\n';
3745                 break;
3746             case 'r':
3747                 *d++ = '\r';
3748                 break;
3749             case 'f':
3750                 *d++ = '\f';
3751                 break;
3752             case 't':
3753                 *d++ = '\t';
3754                 break;
3755             case 'e':
3756                 *d++ = ESC_NATIVE;
3757                 break;
3758             case 'a':
3759                 *d++ = '\a';
3760                 break;
3761             } /* end switch */
3762
3763             s++;
3764             continue;
3765         } /* end if (backslash) */
3766
3767     default_action:
3768         /* If we started with encoded form, or already know we want it,
3769            then encode the next character */
3770         if (! NATIVE_BYTE_IS_INVARIANT((U8)(*s)) && (this_utf8 || has_utf8)) {
3771             STRLEN len  = 1;
3772
3773             /* One might think that it is wasted effort in the case of the
3774              * source being utf8 (this_utf8 == TRUE) to take the next character
3775              * in the source, convert it to an unsigned value, and then convert
3776              * it back again.  But the source has not been validated here.  The
3777              * routine that does the conversion checks for errors like
3778              * malformed utf8 */
3779
3780             const UV nextuv   = (this_utf8)
3781                                 ? utf8n_to_uvchr((U8*)s, send - s, &len, 0)
3782                                 : (UV) ((U8) *s);
3783             const STRLEN need = UVCHR_SKIP(nextuv);
3784             if (!has_utf8) {
3785                 SvCUR_set(sv, d - SvPVX_const(sv));
3786                 SvPOK_on(sv);
3787                 *d = '\0';
3788                 /* See Note on sizing above.  */
3789                 sv_utf8_upgrade_flags_grow(sv,
3790                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3791                                         need + (STRLEN)(send - s) + 1);
3792                 d = SvPVX(sv) + SvCUR(sv);
3793                 has_utf8 = TRUE;
3794             } else if (need > len) {
3795                 /* encoded value larger than old, may need extra space (NOTE:
3796                  * SvCUR() is not set correctly here).   See Note on sizing
3797                  * above.  */
3798                 const STRLEN off = d - SvPVX_const(sv);
3799                 d = SvGROW(sv, off + need + (STRLEN)(send - s) + 1) + off;
3800             }
3801             s += len;
3802
3803             d = (char*)uvchr_to_utf8((U8*)d, nextuv);
3804         }
3805         else {
3806             *d++ = *s++;
3807         }
3808     } /* while loop to process each character */
3809
3810     /* terminate the string and set up the sv */
3811     *d = '\0';
3812     SvCUR_set(sv, d - SvPVX_const(sv));
3813     if (SvCUR(sv) >= SvLEN(sv))
3814         Perl_croak(aTHX_ "panic: constant overflowed allocated space, %"UVuf
3815                    " >= %"UVuf, (UV)SvCUR(sv), (UV)SvLEN(sv));
3816
3817     SvPOK_on(sv);
3818     if (has_utf8) {
3819         SvUTF8_on(sv);
3820         if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
3821             PL_parser->lex_sub_op->op_private |=
3822                     (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
3823         }
3824     }
3825
3826     /* shrink the sv if we allocated more than we used */
3827     if (SvCUR(sv) + 5 < SvLEN(sv)) {
3828         SvPV_shrink_to_cur(sv);
3829     }
3830
3831     /* return the substring (via pl_yylval) only if we parsed anything */
3832     if (s > start) {
3833         char *s2 = start;
3834         for (; s2 < s; s2++) {
3835             if (*s2 == '\n')
3836                 COPLINE_INC_WITH_HERELINES;
3837         }
3838         SvREFCNT_inc_simple_void_NN(sv);
3839         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
3840             && ! PL_parser->lex_re_reparsing)
3841         {
3842             const char *const key = PL_lex_inpat ? "qr" : "q";
3843             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
3844             const char *type;
3845             STRLEN typelen;
3846
3847             if (PL_lex_inwhat == OP_TRANS) {
3848                 type = "tr";
3849                 typelen = 2;
3850             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
3851                 type = "s";
3852                 typelen = 1;
3853             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
3854                 type = "q";
3855                 typelen = 1;
3856             } else  {
3857                 type = "qq";
3858                 typelen = 2;
3859             }
3860
3861             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
3862                                 type, typelen);
3863         }
3864         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
3865     }
3866     LEAVE_with_name("scan_const");
3867     return s;
3868 }
3869
3870 /* S_intuit_more
3871  * Returns TRUE if there's more to the expression (e.g., a subscript),
3872  * FALSE otherwise.
3873  *
3874  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
3875  *
3876  * ->[ and ->{ return TRUE
3877  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
3878  * { and [ outside a pattern are always subscripts, so return TRUE
3879  * if we're outside a pattern and it's not { or [, then return FALSE
3880  * if we're in a pattern and the first char is a {
3881  *   {4,5} (any digits around the comma) returns FALSE
3882  * if we're in a pattern and the first char is a [
3883  *   [] returns FALSE
3884  *   [SOMETHING] has a funky algorithm to decide whether it's a
3885  *      character class or not.  It has to deal with things like
3886  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
3887  * anything else returns TRUE
3888  */
3889
3890 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
3891
3892 STATIC int
3893 S_intuit_more(pTHX_ char *s)
3894 {
3895     PERL_ARGS_ASSERT_INTUIT_MORE;
3896
3897     if (PL_lex_brackets)
3898         return TRUE;
3899     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
3900         return TRUE;
3901     if (*s == '-' && s[1] == '>'
3902      && FEATURE_POSTDEREF_QQ_IS_ENABLED
3903      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
3904         ||(s[2] == '@' && strchr("*[{",s[3])) ))
3905         return TRUE;
3906     if (*s != '{' && *s != '[')
3907         return FALSE;
3908     if (!PL_lex_inpat)
3909         return TRUE;
3910
3911     /* In a pattern, so maybe we have {n,m}. */
3912     if (*s == '{') {
3913         if (regcurly(s)) {
3914             return FALSE;
3915         }
3916         return TRUE;
3917     }
3918
3919     /* On the other hand, maybe we have a character class */
3920
3921     s++;
3922     if (*s == ']' || *s == '^')
3923         return FALSE;
3924     else {
3925         /* this is terrifying, and it works */
3926         int weight;
3927         char seen[256];
3928         const char * const send = strchr(s,']');
3929         unsigned char un_char, last_un_char;
3930         char tmpbuf[sizeof PL_tokenbuf * 4];
3931
3932         if (!send)              /* has to be an expression */
3933             return TRUE;
3934         weight = 2;             /* let's weigh the evidence */
3935
3936         if (*s == '$')
3937             weight -= 3;
3938         else if (isDIGIT(*s)) {
3939             if (s[1] != ']') {
3940                 if (isDIGIT(s[1]) && s[2] == ']')
3941                     weight -= 10;
3942             }
3943             else
3944                 weight -= 100;
3945         }
3946         Zero(seen,256,char);
3947         un_char = 255;
3948         for (; s < send; s++) {
3949             last_un_char = un_char;
3950             un_char = (unsigned char)*s;
3951             switch (*s) {
3952             case '@':
3953             case '&':
3954             case '$':
3955                 weight -= seen[un_char] * 10;
3956                 if (isWORDCHAR_lazy_if(s+1,UTF)) {
3957                     int len;
3958                     char *tmp = PL_bufend;
3959                     PL_bufend = (char*)send;
3960                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
3961                     PL_bufend = tmp;
3962                     len = (int)strlen(tmpbuf);
3963                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
3964                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
3965                         weight -= 100;
3966                     else
3967                         weight -= 10;
3968                 }
3969                 else if (*s == '$'
3970                          && s[1]
3971                          && strchr("[#!%*<>()-=",s[1]))
3972                 {
3973                     if (/*{*/ strchr("])} =",s[2]))
3974                         weight -= 10;
3975                     else
3976                         weight -= 1;
3977                 }
3978                 break;
3979             case '\\':
3980                 un_char = 254;
3981                 if (s[1]) {
3982                     if (strchr("wds]",s[1]))
3983                         weight += 100;
3984                     else if (seen[(U8)'\''] || seen[(U8)'"'])
3985                         weight += 1;
3986                     else if (strchr("rnftbxcav",s[1]))
3987                         weight += 40;
3988                     else if (isDIGIT(s[1])) {
3989                         weight += 40;
3990                         while (s[1] && isDIGIT(s[1]))
3991                             s++;
3992                     }
3993                 }
3994                 else
3995                     weight += 100;
3996                 break;
3997             case '-':
3998                 if (s[1] == '\\')
3999                     weight += 50;
4000                 if (strchr("aA01! ",last_un_char))
4001                     weight += 30;
4002                 if (strchr("zZ79~",s[1]))
4003                     weight += 30;
4004                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4005                     weight -= 5;        /* cope with negative subscript */
4006                 break;
4007             default:
4008                 if (!isWORDCHAR(last_un_char)
4009                     && !(last_un_char == '$' || last_un_char == '@'
4010                          || last_un_char == '&')
4011                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4012                     char *d = s;
4013                     while (isALPHA(*s))
4014                         s++;
4015                     if (keyword(d, s - d, 0))
4016                         weight -= 150;
4017                 }
4018                 if (un_char == last_un_char + 1)
4019                     weight += 5;
4020                 weight -= seen[un_char];
4021                 break;
4022             }
4023             seen[un_char]++;
4024         }
4025         if (weight >= 0)        /* probably a character class */
4026             return FALSE;
4027     }
4028
4029     return TRUE;
4030 }
4031
4032 /*
4033  * S_intuit_method
4034  *
4035  * Does all the checking to disambiguate
4036  *   foo bar
4037  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
4038  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4039  *
4040  * First argument is the stuff after the first token, e.g. "bar".
4041  *
4042  * Not a method if foo is a filehandle.
4043  * Not a method if foo is a subroutine prototyped to take a filehandle.
4044  * Not a method if it's really "Foo $bar"
4045  * Method if it's "foo $bar"
4046  * Not a method if it's really "print foo $bar"
4047  * Method if it's really "foo package::" (interpreted as package->foo)
4048  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4049  * Not a method if bar is a filehandle or package, but is quoted with
4050  *   =>
4051  */
4052
4053 STATIC int
4054 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4055 {
4056     char *s = start + (*start == '$');
4057     char tmpbuf[sizeof PL_tokenbuf];
4058     STRLEN len;
4059     GV* indirgv;
4060         /* Mustn't actually add anything to a symbol table.
4061            But also don't want to "initialise" any placeholder
4062            constants that might already be there into full
4063            blown PVGVs with attached PVCV.  */
4064     GV * const gv =
4065         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4066
4067     PERL_ARGS_ASSERT_INTUIT_METHOD;
4068
4069     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4070             return 0;
4071     if (cv && SvPOK(cv)) {
4072         const char *proto = CvPROTO(cv);
4073         if (proto) {
4074             while (*proto && (isSPACE(*proto) || *proto == ';'))
4075                 proto++;
4076             if (*proto == '*')
4077                 return 0;
4078         }
4079     }
4080
4081     if (*start == '$') {
4082         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4083             || isUPPER(*PL_tokenbuf))
4084             return 0;
4085         s = skipspace(s);
4086         PL_bufptr = start;
4087         PL_expect = XREF;
4088         return *s == '(' ? FUNCMETH : METHOD;
4089     }
4090
4091     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4092     /* start is the beginning of the possible filehandle/object,
4093      * and s is the end of it
4094      * tmpbuf is a copy of it (but with single quotes as double colons)
4095      */
4096
4097     if (!keyword(tmpbuf, len, 0)) {
4098         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4099             len -= 2;
4100             tmpbuf[len] = '\0';
4101             goto bare_package;
4102         }
4103         indirgv = gv_fetchpvn_flags(tmpbuf, len,
4104                                     GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4105                                     SVt_PVCV);
4106         if (indirgv && SvTYPE(indirgv) != SVt_NULL
4107          && (!isGV(indirgv) || GvCVu(indirgv)))
4108             return 0;
4109         /* filehandle or package name makes it a method */
4110         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4111             s = skipspace(s);
4112             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4113                 return 0;       /* no assumptions -- "=>" quotes bareword */
4114       bare_package:
4115             NEXTVAL_NEXTTOKE.opval = (OP*)newSVOP(OP_CONST, 0,
4116                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4117             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4118             PL_expect = XTERM;
4119             force_next(BAREWORD);
4120             PL_bufptr = s;
4121             return *s == '(' ? FUNCMETH : METHOD;
4122         }
4123     }
4124     return 0;
4125 }
4126
4127 /* Encoded script support. filter_add() effectively inserts a
4128  * 'pre-processing' function into the current source input stream.
4129  * Note that the filter function only applies to the current source file
4130  * (e.g., it will not affect files 'require'd or 'use'd by this one).
4131  *
4132  * The datasv parameter (which may be NULL) can be used to pass
4133  * private data to this instance of the filter. The filter function
4134  * can recover the SV using the FILTER_DATA macro and use it to
4135  * store private buffers and state information.
4136  *
4137  * The supplied datasv parameter is upgraded to a PVIO type
4138  * and the IoDIRP/IoANY field is used to store the function pointer,
4139  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4140  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4141  * private use must be set using malloc'd pointers.
4142  */
4143
4144 SV *
4145 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4146 {
4147     if (!funcp)
4148         return NULL;
4149
4150     if (!PL_parser)
4151         return NULL;
4152
4153     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4154         Perl_croak(aTHX_ "Source filters apply only to byte streams");
4155
4156     if (!PL_rsfp_filters)
4157         PL_rsfp_filters = newAV();
4158     if (!datasv)
4159         datasv = newSV(0);
4160     SvUPGRADE(datasv, SVt_PVIO);
4161     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4162     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4163     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4164                           FPTR2DPTR(void *, IoANY(datasv)),
4165                           SvPV_nolen(datasv)));
4166     av_unshift(PL_rsfp_filters, 1);
4167     av_store(PL_rsfp_filters, 0, datasv) ;
4168     if (
4169         !PL_parser->filtered
4170      && PL_parser->lex_flags & LEX_EVALBYTES
4171      && PL_bufptr < PL_bufend
4172     ) {
4173         const char *s = PL_bufptr;
4174         while (s < PL_bufend) {
4175             if (*s == '\n') {
4176                 SV *linestr = PL_parser->linestr;
4177                 char *buf = SvPVX(linestr);
4178                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4179                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4180                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4181                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4182                 STRLEN const last_uni_pos =
4183                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4184                 STRLEN const last_lop_pos =
4185                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4186                 av_push(PL_rsfp_filters, linestr);
4187                 PL_parser->linestr = 
4188                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4189                 buf = SvPVX(PL_parser->linestr);
4190                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4191                 PL_parser->bufptr = buf + bufptr_pos;
4192                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4193                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4194                 PL_parser->linestart = buf + linestart_pos;
4195                 if (PL_parser->last_uni)
4196                     PL_parser->last_uni = buf + last_uni_pos;
4197                 if (PL_parser->last_lop)
4198                     PL_parser->last_lop = buf + last_lop_pos;
4199                 SvLEN(linestr) = SvCUR(linestr);
4200                 SvCUR(linestr) = s-SvPVX(linestr);
4201                 PL_parser->filtered = 1;
4202                 break;
4203             }
4204             s++;
4205         }
4206     }
4207     return(datasv);
4208 }
4209
4210
4211 /* Delete most recently added instance of this filter function. */
4212 void
4213 Perl_filter_del(pTHX_ filter_t funcp)
4214 {
4215     SV *datasv;
4216
4217     PERL_ARGS_ASSERT_FILTER_DEL;
4218
4219 #ifdef DEBUGGING
4220     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4221                           FPTR2DPTR(void*, funcp)));
4222 #endif
4223     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4224         return;
4225     /* if filter is on top of stack (usual case) just pop it off */
4226     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4227     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4228         sv_free(av_pop(PL_rsfp_filters));
4229
4230         return;
4231     }
4232     /* we need to search for the correct entry and clear it     */
4233     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4234 }
4235
4236
4237 /* Invoke the idxth filter function for the current rsfp.        */
4238 /* maxlen 0 = read one text line */
4239 I32
4240 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4241 {
4242     filter_t funcp;
4243     SV *datasv = NULL;
4244     /* This API is bad. It should have been using unsigned int for maxlen.
4245        Not sure if we want to change the API, but if not we should sanity
4246        check the value here.  */
4247     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4248
4249     PERL_ARGS_ASSERT_FILTER_READ;
4250
4251     if (!PL_parser || !PL_rsfp_filters)
4252         return -1;
4253     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4254         /* Provide a default input filter to make life easy.    */
4255         /* Note that we append to the line. This is handy.      */
4256         DEBUG_P(PerlIO_printf(Perl_debug_log,
4257                               "filter_read %d: from rsfp\n", idx));
4258         if (correct_length) {
4259             /* Want a block */
4260             int len ;
4261             const int old_len = SvCUR(buf_sv);
4262
4263             /* ensure buf_sv is large enough */
4264             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4265             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4266                                    correct_length)) <= 0) {
4267                 if (PerlIO_error(PL_rsfp))
4268                     return -1;          /* error */
4269                 else
4270                     return 0 ;          /* end of file */
4271             }
4272             SvCUR_set(buf_sv, old_len + len) ;
4273             SvPVX(buf_sv)[old_len + len] = '\0';
4274         } else {
4275             /* Want a line */
4276             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4277                 if (PerlIO_error(PL_rsfp))
4278                     return -1;          /* error */
4279                 else
4280                     return 0 ;          /* end of file */
4281             }
4282         }
4283         return SvCUR(buf_sv);
4284     }
4285     /* Skip this filter slot if filter has been deleted */
4286     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4287         DEBUG_P(PerlIO_printf(Perl_debug_log,
4288                               "filter_read %d: skipped (filter deleted)\n",
4289                               idx));
4290         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4291     }
4292     if (SvTYPE(datasv) != SVt_PVIO) {
4293         if (correct_length) {
4294             /* Want a block */
4295             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4296             if (!remainder) return 0; /* eof */
4297             if (correct_length > remainder) correct_length = remainder;
4298             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4299             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4300         } else {
4301             /* Want a line */
4302             const char *s = SvEND(datasv);
4303             const char *send = SvPVX(datasv) + SvLEN(datasv);
4304             while (s < send) {
4305                 if (*s == '\n') {
4306                     s++;
4307                     break;
4308                 }
4309                 s++;
4310             }
4311             if (s == send) return 0; /* eof */
4312             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4313             SvCUR_set(datasv, s-SvPVX(datasv));
4314         }
4315         return SvCUR(buf_sv);
4316     }
4317     /* Get function pointer hidden within datasv        */
4318     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4319     DEBUG_P(PerlIO_printf(Perl_debug_log,
4320                           "filter_read %d: via function %p (%s)\n",
4321                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4322     /* Call function. The function is expected to       */
4323     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4324     /* Return: <0:error, =0:eof, >0:not eof             */
4325     return (*funcp)(aTHX_ idx, buf_sv, correct_length);
4326 }
4327
4328 STATIC char *
4329 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4330 {
4331     PERL_ARGS_ASSERT_FILTER_GETS;
4332
4333 #ifdef PERL_CR_FILTER
4334     if (!PL_rsfp_filters) {
4335         filter_add(S_cr_textfilter,NULL);
4336     }
4337 #endif
4338     if (PL_rsfp_filters) {
4339         if (!append)
4340             SvCUR_set(sv, 0);   /* start with empty line        */
4341         if (FILTER_READ(0, sv, 0) > 0)
4342             return ( SvPVX(sv) ) ;
4343         else
4344             return NULL ;
4345     }
4346     else
4347         return (sv_gets(sv, PL_rsfp, append));
4348 }
4349
4350 STATIC HV *
4351 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4352 {
4353     GV *gv;
4354
4355     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4356
4357     if (len == 11 && *pkgname == '_' && strEQ(pkgname, "__PACKAGE__"))
4358         return PL_curstash;
4359
4360     if (len > 2
4361         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4362         && (gv = gv_fetchpvn_flags(pkgname,
4363                                    len,
4364                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4365     {
4366         return GvHV(gv);                        /* Foo:: */
4367     }
4368
4369     /* use constant CLASS => 'MyClass' */
4370     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4371     if (gv && GvCV(gv)) {
4372         SV * const sv = cv_const_sv(GvCV(gv));
4373         if (sv)
4374             return gv_stashsv(sv, 0);
4375     }
4376
4377     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4378 }
4379
4380
4381 STATIC char *
4382 S_tokenize_use(pTHX_ int is_use, char *s) {
4383     PERL_ARGS_ASSERT_TOKENIZE_USE;
4384
4385     if (PL_expect != XSTATE)
4386         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4387                     is_use ? "use" : "no"));
4388     PL_expect = XTERM;
4389     s = skipspace(s);
4390     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4391         s = force_version(s, TRUE);
4392         if (*s == ';' || *s == '}'
4393                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4394             NEXTVAL_NEXTTOKE.opval = NULL;
4395             force_next(BAREWORD);
4396         }
4397         else if (*s == 'v') {
4398             s = force_word(s,BAREWORD,FALSE,TRUE);
4399             s = force_version(s, FALSE);
4400         }
4401     }
4402     else {
4403         s = force_word(s,BAREWORD,FALSE,TRUE);
4404         s = force_version(s, FALSE);
4405     }
4406     pl_yylval.ival = is_use;
4407     return s;
4408 }
4409 #ifdef DEBUGGING
4410     static const char* const exp_name[] =
4411         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4412           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4413           "SIGVAR", "TERMORDORDOR"
4414         };
4415 #endif
4416
4417 #define word_takes_any_delimiter(p,l) S_word_takes_any_delimiter(p,l)
4418 STATIC bool
4419 S_word_takes_any_delimiter(char *p, STRLEN len)
4420 {
4421     return (len == 1 && strchr("msyq", p[0]))
4422             || (len == 2
4423                 && ((p[0] == 't' && p[1] == 'r')
4424                     || (p[0] == 'q' && strchr("qwxr", p[1]))));
4425 }
4426
4427 static void
4428 S_check_scalar_slice(pTHX_ char *s)
4429 {
4430     s++;
4431     while (*s == ' ' || *s == '\t') s++;
4432     if (*s == 'q' && s[1] == 'w'
4433      && !isWORDCHAR_lazy_if(s+2,UTF))
4434         return;
4435     while (*s && (isWORDCHAR_lazy_if(s,UTF) || strchr(" \t$#+-'\"", *s)))
4436         s += UTF ? UTF8SKIP(s) : 1;
4437     if (*s == '}' || *s == ']')
4438         pl_yylval.ival = OPpSLICEWARNING;
4439 }
4440
4441 #define lex_token_boundary() S_lex_token_boundary(aTHX)
4442 static void
4443 S_lex_token_boundary(pTHX)
4444 {
4445     PL_oldoldbufptr = PL_oldbufptr;
4446     PL_oldbufptr = PL_bufptr;
4447 }
4448
4449 #define vcs_conflict_marker(s) S_vcs_conflict_marker(aTHX_ s)
4450 static char *
4451 S_vcs_conflict_marker(pTHX_ char *s)
4452 {
4453     lex_token_boundary();
4454     PL_bufptr = s;
4455     yyerror("Version control conflict marker");
4456     while (s < PL_bufend && *s != '\n')
4457         s++;
4458     return s;
4459 }
4460
4461 /*
4462   yylex
4463
4464   Works out what to call the token just pulled out of the input
4465   stream.  The yacc parser takes care of taking the ops we return and
4466   stitching them into a tree.
4467
4468   Returns:
4469     The type of the next token
4470
4471   Structure:
4472       Check if we have already built the token; if so, use it.
4473       Switch based on the current state:
4474           - if we have a case modifier in a string, deal with that
4475           - handle other cases of interpolation inside a string
4476           - scan the next line if we are inside a format
4477       In the normal state, switch on the next character:
4478           - default:
4479             if alphabetic, go to key lookup
4480             unrecognized character - croak
4481           - 0/4/26: handle end-of-line or EOF
4482           - cases for whitespace
4483           - \n and #: handle comments and line numbers
4484           - various operators, brackets and sigils
4485           - numbers
4486           - quotes
4487           - 'v': vstrings (or go to key lookup)
4488           - 'x' repetition operator (or go to key lookup)
4489           - other ASCII alphanumerics (key lookup begins here):
4490               word before => ?
4491               keyword plugin
4492               scan built-in keyword (but do nothing with it yet)
4493               check for statement label
4494               check for lexical subs
4495                   goto just_a_word if there is one
4496               see whether built-in keyword is overridden
4497               switch on keyword number:
4498                   - default: just_a_word:
4499                       not a built-in keyword; handle bareword lookup
4500                       disambiguate between method and sub call
4501                       fall back to bareword
4502                   - cases for built-in keywords
4503 */
4504
4505
4506 int
4507 Perl_yylex(pTHX)
4508 {
4509     dVAR;
4510     char *s = PL_bufptr;
4511     char *d;
4512     STRLEN len;
4513     bool bof = FALSE;
4514     const bool saw_infix_sigil = cBOOL(PL_parser->saw_infix_sigil);
4515     U8 formbrack = 0;
4516     U32 fake_eof = 0;
4517
4518     /* orig_keyword, gvp, and gv are initialized here because
4519      * jump to the label just_a_word_zero can bypass their
4520      * initialization later. */
4521     I32 orig_keyword = 0;
4522     GV *gv = NULL;
4523     GV **gvp = NULL;
4524
4525     DEBUG_T( {
4526         SV* tmp = newSVpvs("");
4527         PerlIO_printf(Perl_debug_log, "### %"IVdf":LEX_%s/X%s %s\n",
4528             (IV)CopLINE(PL_curcop),
4529             lex_state_names[PL_lex_state],
4530             exp_name[PL_expect],
4531             pv_display(tmp, s, strlen(s), 0, 60));
4532         SvREFCNT_dec(tmp);
4533     } );
4534
4535     /* when we've already built the next token, just pull it out of the queue */
4536     if (PL_nexttoke) {
4537         PL_nexttoke--;
4538         pl_yylval = PL_nextval[PL_nexttoke];
4539         {
4540             I32 next_type;
4541             next_type = PL_nexttype[PL_nexttoke];
4542             if (next_type & (7<<24)) {
4543                 if (next_type & (1<<24)) {
4544                     if (PL_lex_brackets > 100)
4545                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
4546                     PL_lex_brackstack[PL_lex_brackets++] =
4547                         (char) ((next_type >> 16) & 0xff);
4548                 }
4549                 if (next_type & (2<<24))
4550                     PL_lex_allbrackets++;
4551                 if (next_type & (4<<24))
4552                     PL_lex_allbrackets--;
4553                 next_type &= 0xffff;
4554             }
4555             return REPORT(next_type == 'p' ? pending_ident() : next_type);
4556         }
4557     }
4558
4559     switch (PL_lex_state) {
4560     case LEX_NORMAL:
4561     case LEX_INTERPNORMAL:
4562         break;
4563
4564     /* interpolated case modifiers like \L \U, including \Q and \E.
4565        when we get here, PL_bufptr is at the \
4566     */
4567     case LEX_INTERPCASEMOD:
4568 #ifdef DEBUGGING
4569         if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
4570             Perl_croak(aTHX_
4571                        "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
4572                        PL_bufptr, PL_bufend, *PL_bufptr);
4573 #endif
4574         /* handle \E or end of string */
4575         if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
4576             /* if at a \E */
4577             if (PL_lex_casemods) {
4578                 const char oldmod = PL_lex_casestack[--PL_lex_casemods];
4579                 PL_lex_casestack[PL_lex_casemods] = '\0';
4580
4581                 if (PL_bufptr != PL_bufend
4582                     && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
4583                         || oldmod == 'F')) {
4584                     PL_bufptr += 2;
4585                     PL_lex_state = LEX_INTERPCONCAT;
4586                 }
4587                 PL_lex_allbrackets--;
4588                 return REPORT(')');
4589             }
4590             else if ( PL_bufptr != PL_bufend && PL_bufptr[1] == 'E' ) {
4591                /* Got an unpaired \E */
4592                Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4593                         "Useless use of \\E");
4594             }
4595             if (PL_bufptr != PL_bufend)
4596                 PL_bufptr += 2;
4597             PL_lex_state = LEX_INTERPCONCAT;
4598             return yylex();
4599         }
4600         else {
4601             DEBUG_T({ PerlIO_printf(Perl_debug_log,
4602               "### Saw case modifier\n"); });
4603             s = PL_bufptr + 1;
4604             if (s[1] == '\\' && s[2] == 'E') {
4605                 PL_bufptr = s + 3;
4606                 PL_lex_state = LEX_INTERPCONCAT;
4607                 return yylex();
4608             }
4609             else {
4610                 I32 tmp;
4611                 if (strnEQ(s, "L\\u", 3) || strnEQ(s, "U\\l", 3))
4612                     tmp = *s, *s = s[2], s[2] = (char)tmp;      /* misordered... */
4613                 if ((*s == 'L' || *s == 'U' || *s == 'F')
4614                     && (strchr(PL_lex_casestack, 'L')
4615                         || strchr(PL_lex_casestack, 'U')
4616                         || strchr(PL_lex_casestack, 'F')))
4617                 {
4618                     PL_lex_casestack[--PL_lex_casemods] = '\0';
4619                     PL_lex_allbrackets--;
4620                     return REPORT(')');
4621                 }
4622                 if (PL_lex_casemods > 10)
4623                     Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
4624                 PL_lex_casestack[PL_lex_casemods++] = *s;
4625                 PL_lex_casestack[PL_lex_casemods] = '\0';
4626                 PL_lex_state = LEX_INTERPCONCAT;
4627                 NEXTVAL_NEXTTOKE.ival = 0;
4628                 force_next((2<<24)|'(');
4629                 if (*s == 'l')
4630                     NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
4631                 else if (*s == 'u')
4632                     NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
4633                 else if (*s == 'L')
4634                     NEXTVAL_NEXTTOKE.ival = OP_LC;
4635                 else if (*s == 'U')
4636                     NEXTVAL_NEXTTOKE.ival = OP_UC;
4637                 else if (*s == 'Q')
4638                     NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
4639                 else if (*s == 'F')
4640                     NEXTVAL_NEXTTOKE.ival = OP_FC;
4641                 else
4642                     Perl_croak(aTHX_ "panic: yylex, *s=%u", *s);
4643                 PL_bufptr = s + 1;
4644             }
4645             force_next(FUNC);
4646             if (PL_lex_starts) {
4647                 s = PL_bufptr;
4648                 PL_lex_starts = 0;
4649                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4650                 if (PL_lex_casemods == 1 && PL_lex_inpat)
4651                     TOKEN(',');
4652                 else
4653                     AopNOASSIGN(OP_CONCAT);
4654             }
4655             else
4656                 return yylex();
4657         }
4658
4659     case LEX_INTERPPUSH:
4660         return REPORT(sublex_push());
4661
4662     case LEX_INTERPSTART:
4663         if (PL_bufptr == PL_bufend)
4664             return REPORT(sublex_done());
4665         DEBUG_T({ if(*PL_bufptr != '(') PerlIO_printf(Perl_debug_log,
4666               "### Interpolated variable\n"); });
4667         PL_expect = XTERM;
4668         /* for /@a/, we leave the joining for the regex engine to do
4669          * (unless we're within \Q etc) */
4670         PL_lex_dojoin = (*PL_bufptr == '@'
4671                             && (!PL_lex_inpat || PL_lex_casemods));
4672         PL_lex_state = LEX_INTERPNORMAL;
4673         if (PL_lex_dojoin) {
4674             NEXTVAL_NEXTTOKE.ival = 0;
4675             force_next(',');
4676             force_ident("\"", '$');
4677             NEXTVAL_NEXTTOKE.ival = 0;
4678             force_next('$');
4679             NEXTVAL_NEXTTOKE.ival = 0;
4680             force_next((2<<24)|'(');
4681             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
4682             force_next(FUNC);
4683         }
4684         /* Convert (?{...}) and friends to 'do {...}' */
4685         if (PL_lex_inpat && *PL_bufptr == '(') {
4686             PL_parser->lex_shared->re_eval_start = PL_bufptr;
4687             PL_bufptr += 2;
4688             if (*PL_bufptr != '{')
4689                 PL_bufptr++;
4690             PL_expect = XTERMBLOCK;
4691             force_next(DO);
4692         }
4693
4694         if (PL_lex_starts++) {
4695             s = PL_bufptr;
4696             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4697             if (!PL_lex_casemods && PL_lex_inpat)
4698                 TOKEN(',');
4699             else
4700                 AopNOASSIGN(OP_CONCAT);
4701         }
4702         return yylex();
4703
4704     case LEX_INTERPENDMAYBE:
4705         if (intuit_more(PL_bufptr)) {
4706             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
4707             break;
4708         }
4709         /* FALLTHROUGH */
4710
4711     case LEX_INTERPEND:
4712         if (PL_lex_dojoin) {
4713             const U8 dojoin_was = PL_lex_dojoin;
4714             PL_lex_dojoin = FALSE;
4715             PL_lex_state = LEX_INTERPCONCAT;
4716             PL_lex_allbrackets--;
4717             return REPORT(dojoin_was == 1 ? (int)')' : (int)POSTJOIN);
4718         }
4719         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
4720             && SvEVALED(PL_lex_repl))
4721         {
4722             if (PL_bufptr != PL_bufend)
4723                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
4724             PL_lex_repl = NULL;
4725         }
4726         /* Paranoia.  re_eval_start is adjusted when S_scan_heredoc sets
4727            re_eval_str.  If the here-doc body’s length equals the previous
4728            value of re_eval_start, re_eval_start will now be null.  So
4729            check re_eval_str as well. */
4730         if (PL_parser->lex_shared->re_eval_start
4731          || PL_parser->lex_shared->re_eval_str) {
4732             SV *sv;
4733             if (*PL_bufptr != ')')
4734                 Perl_croak(aTHX_ "Sequence (?{...}) not terminated with ')'");
4735             PL_bufptr++;
4736             /* having compiled a (?{..}) expression, return the original
4737              * text too, as a const */
4738             if (PL_parser->lex_shared->re_eval_str) {
4739                 sv = PL_parser->lex_shared->re_eval_str;
4740                 PL_parser->lex_shared->re_eval_str = NULL;
4741                 SvCUR_set(sv,
4742                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
4743                 SvPV_shrink_to_cur(sv);
4744             }
4745             else sv = newSVpvn(PL_parser->lex_shared->re_eval_start,
4746                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
4747             NEXTVAL_NEXTTOKE.opval =
4748                     (OP*)newSVOP(OP_CONST, 0,
4749                                  sv);
4750             force_next(THING);
4751             PL_parser->lex_shared->re_eval_start = NULL;
4752             PL_expect = XTERM;
4753             return REPORT(',');
4754         }
4755
4756         /* FALLTHROUGH */
4757     case LEX_INTERPCONCAT:
4758 #ifdef DEBUGGING
4759         if (PL_lex_brackets)
4760             Perl_croak(aTHX_ "panic: INTERPCONCAT, lex_brackets=%ld",
4761                        (long) PL_lex_brackets);
4762 #endif
4763         if (PL_bufptr == PL_bufend)
4764             return REPORT(sublex_done());
4765
4766         /* m'foo' still needs to be parsed for possible (?{...}) */
4767         if (SvIVX(PL_linestr) == '\'' && !PL_lex_inpat) {
4768             SV *sv = newSVsv(PL_linestr);
4769             sv = tokeq(sv);
4770             pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
4771             s = PL_bufend;
4772         }
4773         else {
4774             s = scan_const(PL_bufptr);
4775             if (*s == '\\')
4776                 PL_lex_state = LEX_INTERPCASEMOD;
4777             else
4778                 PL_lex_state = LEX_INTERPSTART;
4779         }
4780
4781         if (s != PL_bufptr) {
4782             NEXTVAL_NEXTTOKE = pl_yylval;
4783             PL_expect = XTERM;
4784             force_next(THING);
4785             if (PL_lex_starts++) {
4786                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4787                 if (!PL_lex_casemods && PL_lex_inpat)
4788                     TOKEN(',');
4789                 else
4790                     AopNOASSIGN(OP_CONCAT);
4791             }
4792             else {
4793                 PL_bufptr = s;
4794                 return yylex();
4795             }
4796         }
4797
4798         return yylex();
4799     case LEX_FORMLINE:
4800         s = scan_formline(PL_bufptr);
4801         if (!PL_lex_formbrack)
4802         {
4803             formbrack = 1;
4804             goto rightbracket;
4805         }
4806         PL_bufptr = s;
4807         return yylex();
4808     }
4809
4810     /* We really do *not* want PL_linestr ever becoming a COW. */
4811     assert (!SvIsCOW(PL_linestr));
4812     s = PL_bufptr;
4813     PL_oldoldbufptr = PL_oldbufptr;
4814     PL_oldbufptr = s;
4815     PL_parser->saw_infix_sigil = 0;
4816
4817     if (PL_in_my == KEY_sigvar) {
4818         /* we expect the sigil and optional var name part of a
4819          * signature element here. Since a '$' is not necessarily
4820          * followed by a var name, handle it specially here; the general
4821          * yylex code would otherwise try to interpret whatever follows
4822          * as a var; e.g. ($, ...) would be seen as the var '$,'
4823          */
4824
4825         char sigil;
4826
4827         s = skipspace(s);
4828         sigil = *s++;
4829         PL_bufptr = s; /* for error reporting */
4830         switch (sigil) {
4831         case '$':
4832         case '@':
4833         case '%':
4834             /* spot stuff that looks like an prototype */
4835             if (strchr("$:@%&*;\\[]", *s)) {
4836                 yyerror("Illegal character following sigil in a subroutine signature");
4837                 break;
4838             }
4839             /* '$#' is banned, while '$ # comment' isn't */
4840             if (*s == '#') {
4841                 yyerror("'#' not allowed immediately following a sigil in a subroutine signature");
4842                 break;
4843             }
4844             s = skipspace(s);
4845             if (isIDFIRST_lazy_if(s, UTF)) {
4846                 char *dest = PL_tokenbuf + 1;
4847                 /* read var name, including sigil, into PL_tokenbuf */
4848                 PL_tokenbuf[0] = sigil;
4849                 parse_ident(&s, &dest, dest + sizeof(PL_tokenbuf) - 1,
4850                     0, cBOOL(UTF), FALSE);
4851                 *dest = '\0';
4852                 assert(PL_tokenbuf[1]); /* we have a variable name */
4853                 NEXTVAL_NEXTTOKE.ival = sigil;
4854                 force_next('p'); /* force a signature pending identifier */
4855             }
4856             else
4857                 PL_in_my = 0;
4858             PL_expect = XOPERATOR;
4859             break;
4860
4861         case ')':
4862             PL_expect = XBLOCK;
4863             break;
4864         case ',': /* handle ($a,,$b) */
4865             break;
4866
4867         default:
4868             PL_in_my = 0;
4869             yyerror("A signature parameter must start with '$', '@' or '%'");
4870             /* very crude error recovery: skip to likely next signature
4871              * element */
4872             while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4873                 s++;
4874             break;
4875         }
4876         TOKEN(sigil);
4877     }
4878
4879   retry:
4880     switch (*s) {
4881     default:
4882         if (UTF) {
4883             if (! isUTF8_CHAR((U8 *) s, (U8 *) PL_bufend)) {
4884                 ENTER;
4885                 SAVESPTR(PL_warnhook);
4886                 PL_warnhook = PERL_WARNHOOK_FATAL;
4887                 utf8n_to_uvchr((U8*)s, PL_bufend-s, NULL, 0);
4888                 LEAVE;
4889             }
4890             if (isIDFIRST_utf8((U8*)s)) {
4891                 goto keylookup;
4892             }
4893         }
4894         else if (isALNUMC(*s)) {
4895             goto keylookup;
4896         }
4897     {
4898         SV *dsv = newSVpvs_flags("", SVs_TEMP);
4899         const char *c = UTF ? sv_uni_display(dsv, newSVpvn_flags(s,
4900                                                     UTF8SKIP(s),
4901                                                     SVs_TEMP | SVf_UTF8),
4902                                             10, UNI_DISPLAY_ISPRINT)
4903                             : Perl_form(aTHX_ "\\x%02X", (unsigned char)*s);
4904         len = UTF ? Perl_utf8_length(aTHX_ (U8 *) PL_linestart, (U8 *) s) : (STRLEN) (s - PL_linestart);
4905         if (len > UNRECOGNIZED_PRECEDE_COUNT) {
4906             d = UTF ? (char *) utf8_hop((U8 *) s, -UNRECOGNIZED_PRECEDE_COUNT) : s - UNRECOGNIZED_PRECEDE_COUNT;
4907         } else {
4908             d = PL_linestart;
4909         }
4910         Perl_croak(aTHX_  "Unrecognized character %s; marked by <-- HERE after %"UTF8f"<-- HERE near column %d", c,
4911                           UTF8fARG(UTF, (s - d), d),
4912                          (int) len + 1);
4913     }
4914     case 4:
4915     case 26:
4916         goto fake_eof;                  /* emulate EOF on ^D or ^Z */
4917     case 0:
4918         if ((!PL_rsfp || PL_lex_inwhat)
4919          && (!PL_parser->filtered || s+1 < PL_bufend)) {
4920             PL_last_uni = 0;
4921             PL_last_lop = 0;
4922             if (PL_lex_brackets
4923                 && PL_lex_brackstack[PL_lex_brackets-1] != XFAKEEOF)
4924             {
4925                 yyerror((const char *)
4926                         (PL_lex_formbrack
4927                          ? "Format not terminated"
4928                          : "Missing right curly or square bracket"));
4929             }
4930             DEBUG_T( { PerlIO_printf(Perl_debug_log,
4931                         "### Tokener got EOF\n");
4932             } );
4933             TOKEN(0);
4934         }
4935         if (s++ < PL_bufend)
4936             goto retry;                 /* ignore stray nulls */
4937         PL_last_uni = 0;
4938         PL_last_lop = 0;
4939         if (!PL_in_eval && !PL_preambled) {
4940             PL_preambled = TRUE;
4941             if (PL_perldb) {
4942                 /* Generate a string of Perl code to load the debugger.
4943                  * If PERL5DB is set, it will return the contents of that,
4944                  * otherwise a compile-time require of perl5db.pl.  */
4945
4946                 const char * const pdb = PerlEnv_getenv("PERL5DB");
4947
4948                 if (pdb) {
4949                     sv_setpv(PL_linestr, pdb);
4950                     sv_catpvs(PL_linestr,";");
4951                 } else {
4952                     SETERRNO(0,SS_NORMAL);
4953                     sv_setpvs(PL_linestr, "BEGIN { require 'perl5db.pl' };");
4954                 }
4955                 PL_parser->preambling = CopLINE(PL_curcop);
4956             } else
4957                 SvPVCLEAR(PL_linestr);
4958             if (PL_preambleav) {
4959                 SV **svp = AvARRAY(PL_preambleav);
4960                 SV **const end = svp + AvFILLp(PL_preambleav);
4961                 while(svp <= end) {
4962                     sv_catsv(PL_linestr, *svp);
4963                     ++svp;
4964                     sv_catpvs(PL_linestr, ";");
4965                 }
4966                 sv_free(MUTABLE_SV(PL_preambleav));
4967                 PL_preambleav = NULL;
4968             }
4969             if (PL_minus_E)
4970                 sv_catpvs(PL_linestr,
4971                           "use feature ':5." STRINGIFY(PERL_VERSION) "';");
4972             if (PL_minus_n || PL_minus_p) {
4973                 sv_catpvs(PL_linestr, "LINE: while (<>) {"/*}*/);
4974                 if (PL_minus_l)
4975                     sv_catpvs(PL_linestr,"chomp;");
4976                 if (PL_minus_a) {
4977                     if (PL_minus_F) {
4978                         if ((*PL_splitstr == '/' || *PL_splitstr == '\''
4979                              || *PL_splitstr == '"')
4980                               && strchr(PL_splitstr + 1, *PL_splitstr))
4981                             Perl_sv_catpvf(aTHX_ PL_linestr, "our @F=split(%s);", PL_splitstr);
4982                         else {
4983                             /* "q\0${splitstr}\0" is legal perl. Yes, even NUL
4984                                bytes can be used as quoting characters.  :-) */
4985                             const char *splits = PL_splitstr;
4986                             sv_catpvs(PL_linestr, "our @F=split(q\0");
4987                             do {
4988                                 /* Need to \ \s  */
4989                                 if (*splits == '\\')
4990                                     sv_catpvn(PL_linestr, splits, 1);
4991                                 sv_catpvn(PL_linestr, splits, 1);
4992                             } while (*splits++);
4993                             /* This loop will embed the trailing NUL of
4994                                PL_linestr as the last thing it does before
4995                                terminating.  */
4996                             sv_catpvs(PL_linestr, ");");
4997                         }
4998                     }
4999                     else
5000                         sv_catpvs(PL_linestr,"our @F=split(' ');");
5001                 }
5002             }
5003             sv_catpvs(PL_linestr, "\n");
5004             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5005             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5006             PL_last_lop = PL_last_uni = NULL;
5007             if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
5008                 update_debugger_info(PL_linestr, NULL, 0);
5009             goto retry;
5010         }
5011         do {
5012             fake_eof = 0;
5013             bof = PL_rsfp ? TRUE : FALSE;
5014             if (0) {
5015               fake_eof:
5016                 fake_eof = LEX_FAKE_EOF;
5017             }
5018             PL_bufptr = PL_bufend;
5019             COPLINE_INC_WITH_HERELINES;
5020             if (!lex_next_chunk(fake_eof)) {
5021                 CopLINE_dec(PL_curcop);
5022                 s = PL_bufptr;
5023                 TOKEN(';');     /* not infinite loop because rsfp is NULL now */
5024             }
5025             CopLINE_dec(PL_curcop);
5026             s = PL_bufptr;
5027             /* If it looks like the start of a BOM or raw UTF-16,
5028              * check if it in fact is. */
5029             if (bof && PL_rsfp
5030                 && (*s == 0
5031                     || *(U8*)s == BOM_UTF8_FIRST_BYTE
5032                         || *(U8*)s >= 0xFE
5033                         || s[1] == 0))
5034             {
5035                 Off_t offset = (IV)PerlIO_tell(PL_rsfp);
5036                 bof = (offset == (Off_t)SvCUR(PL_linestr));
5037 #if defined(PERLIO_USING_CRLF) && defined(PERL_TEXTMODE_SCRIPTS)
5038                 /* offset may include swallowed CR */
5039                 if (!bof)
5040                     bof = (offset == (Off_t)SvCUR(PL_linestr)+1);
5041 #endif
5042                 if (bof) {
5043                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5044                     s = swallow_bom((U8*)s);
5045                 }
5046             }
5047             if (PL_parser->in_pod) {
5048                 /* Incest with pod. */
5049                 if (*s == '=' && strEQs(s, "=cut") && !isALPHA(s[4])) {
5050                     SvPVCLEAR(PL_linestr);
5051                     PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5052                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5053                     PL_last_lop = PL_last_uni = NULL;
5054                     PL_parser->in_pod = 0;
5055                 }
5056             }
5057             if (PL_rsfp || PL_parser->filtered)
5058                 incline(s);
5059         } while (PL_parser->in_pod);
5060         PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = PL_linestart = s;
5061         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5062         PL_last_lop = PL_last_uni = NULL;
5063         if (CopLINE(PL_curcop) == 1) {
5064             while (s < PL_bufend && isSPACE(*s))
5065                 s++;
5066             if (*s == ':' && s[1] != ':') /* for csh execing sh scripts */
5067                 s++;
5068             d = NULL;
5069             if (!PL_in_eval) {
5070                 if (*s == '#' && *(s+1) == '!')
5071                     d = s + 2;
5072 #ifdef ALTERNATE_SHEBANG
5073                 else {
5074                     static char const as[] = ALTERNATE_SHEBANG;
5075                     if (*s == as[0] && strnEQ(s, as, sizeof(as) - 1))
5076                         d = s + (sizeof(as) - 1);
5077                 }
5078 #endif /* ALTERNATE_SHEBANG */
5079             }
5080             if (d) {
5081                 char *ipath;
5082                 char *ipathend;
5083
5084                 while (isSPACE(*d))
5085                     d++;
5086                 ipath = d;
5087                 while (*d && !isSPACE(*d))
5088                     d++;
5089                 ipathend = d;
5090
5091 #ifdef ARG_ZERO_IS_SCRIPT
5092                 if (ipathend > ipath) {
5093                     /*
5094                      * HP-UX (at least) sets argv[0] to the script name,
5095                      * which makes $^X incorrect.  And Digital UNIX and Linux,
5096                      * at least, set argv[0] to the basename of the Perl
5097                      * interpreter. So, having found "#!", we'll set it right.
5098                      */
5099                     SV* copfilesv = CopFILESV(PL_curcop);
5100                     if (copfilesv) {
5101                         SV * const x =
5102                             GvSV(gv_fetchpvs("\030", GV_ADD|GV_NOTQUAL,
5103                                              SVt_PV)); /* $^X */
5104                         assert(SvPOK(x) || SvGMAGICAL(x));
5105                         if (sv_eq(x, copfilesv)) {
5106                             sv_setpvn(x, ipath, ipathend - ipath);
5107                             SvSETMAGIC(x);
5108                         }
5109                         else {
5110                             STRLEN blen;
5111                             STRLEN llen;
5112                             const char *bstart = SvPV_const(copfilesv, blen);
5113                             const char * const lstart = SvPV_const(x, llen);
5114                             if (llen < blen) {
5115                                 bstart += blen - llen;
5116                                 if (strnEQ(bstart, lstart, llen) &&     bstart[-1] == '/') {
5117                                     sv_setpvn(x, ipath, ipathend - ipath);
5118                                     SvSETMAGIC(x);
5119                                 }
5120                             }
5121                         }
5122                     }
5123                     else {
5124                         /* Anything to do if no copfilesv? */
5125                     }
5126                     TAINT_NOT;  /* $^X is always tainted, but that's OK */
5127                 }
5128 #endif /* ARG_ZERO_IS_SCRIPT */
5129
5130                 /*
5131                  * Look for options.
5132                  */
5133                 d = instr(s,"perl -");
5134                 if (!d) {
5135                     d = instr(s,"perl");
5136                     if (d && d[4] == '6')
5137                         d = NULL;
5138 #if defined(DOSISH)
5139                     /* avoid getting into infinite loops when shebang
5140                      * line contains "Perl" rather than "perl" */
5141                     if (!d) {
5142                         for (d = ipathend-4; d >= ipath; --d) {
5143                             if (isALPHA_FOLD_EQ(*d, 'p')
5144                                 && !ibcmp(d, "perl", 4))
5145                             {
5146                                 break;
5147                             }
5148                         }
5149                         if (d < ipath)
5150                             d = NULL;
5151                     }
5152 #endif
5153                 }
5154 #ifdef ALTERNATE_SHEBANG
5155                 /*
5156                  * If the ALTERNATE_SHEBANG on this system starts with a
5157                  * character that can be part of a Perl expression, then if
5158                  * we see it but not "perl", we're probably looking at the
5159                  * start of Perl code, not a request to hand off to some
5160                  * other interpreter.  Similarly, if "perl" is there, but
5161                  * not in the first 'word' of the line, we assume the line
5162                  * contains the start of the Perl program.
5163                  */
5164                 if (d && *s != '#') {
5165                     const char *c = ipath;
5166                     while (*c && !strchr("; \t\r\n\f\v#", *c))
5167                         c++;
5168                     if (c < d)
5169                         d = NULL;       /* "perl" not in first word; ignore */
5170                     else
5171                         *s = '#';       /* Don't try to parse shebang line */
5172                 }
5173 #endif /* ALTERNATE_SHEBANG */
5174                 if (!d
5175                     && *s == '#'
5176                     && ipathend > ipath
5177                     && !PL_minus_c
5178                     && !instr(s,"indir")
5179                     && instr(PL_origargv[0],"perl"))
5180                 {
5181                     dVAR;
5182                     char **newargv;
5183
5184                     *ipathend = '\0';
5185                     s = ipathend + 1;
5186                     while (s < PL_bufend && isSPACE(*s))
5187                         s++;
5188                     if (s < PL_bufend) {
5189                         Newx(newargv,PL_origargc+3,char*);
5190                         newargv[1] = s;
5191                         while (s < PL_bufend && !isSPACE(*s))
5192                             s++;
5193                         *s = '\0';
5194                         Copy(PL_origargv+1, newargv+2, PL_origargc+1, char*);
5195                     }
5196                     else
5197                         newargv = PL_origargv;
5198                     newargv[0] = ipath;
5199                     PERL_FPU_PRE_EXEC
5200                     PerlProc_execv(ipath, EXEC_ARGV_CAST(newargv));
5201                     PERL_FPU_POST_EXEC
5202                     Perl_croak(aTHX_ "Can't exec %s", ipath);
5203                 }
5204                 if (d) {
5205                     while (*d && !isSPACE(*d))
5206                         d++;
5207                     while (SPACE_OR_TAB(*d))
5208                         d++;
5209
5210                     if (*d++ == '-') {
5211                         const bool switches_done = PL_doswitches;
5212                         const U32 oldpdb = PL_perldb;
5213                         const bool oldn = PL_minus_n;
5214                         const bool oldp = PL_minus_p;
5215                         const char *d1 = d;
5216
5217                         do {
5218                             bool baduni = FALSE;
5219                             if (*d1 == 'C') {
5220                                 const char *d2 = d1 + 1;
5221                                 if (parse_unicode_opts((const char **)&d2)
5222                                     != PL_unicode)
5223                                     baduni = TRUE;
5224                             }
5225                             if (baduni || isALPHA_FOLD_EQ(*d1, 'M')) {
5226                                 const char * const m = d1;
5227                                 while (*d1 && !isSPACE(*d1))
5228                                     d1++;
5229                                 Perl_croak(aTHX_ "Too late for \"-%.*s\" option",
5230                                       (int)(d1 - m), m);
5231                             }
5232                             d1 = moreswitches(d1);
5233                         } while (d1);
5234                         if (PL_doswitches && !switches_done) {
5235                             int argc = PL_origargc;
5236                             char **argv = PL_origargv;
5237                             do {
5238                                 argc--,argv++;
5239                             } while (argc && argv[0][0] == '-' && argv[0][1]);
5240                             init_argv_symbols(argc,argv);
5241                         }
5242                         if (   (PERLDB_LINE_OR_SAVESRC && !oldpdb)
5243                             || ((PL_minus_n || PL_minus_p) && !(oldn || oldp)))
5244                               /* if we have already added "LINE: while (<>) {",
5245                                  we must not do it again */
5246                         {
5247                             SvPVCLEAR(PL_linestr);
5248                             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5249                             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5250                             PL_last_lop = PL_last_uni = NULL;
5251                             PL_preambled = FALSE;
5252                             if (PERLDB_LINE_OR_SAVESRC)
5253                                 (void)gv_fetchfile(PL_origfilename);
5254                             goto retry;
5255                         }
5256                     }
5257                 }
5258             }
5259         }
5260         if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
5261             PL_lex_state = LEX_FORMLINE;
5262             force_next(FORMRBRACK);
5263             TOKEN(';');
5264         }
5265         goto retry;
5266     case '\r':
5267 #ifdef PERL_STRICT_CR
5268         Perl_warn(aTHX_ "Illegal character \\%03o (carriage return)", '\r');
5269         Perl_croak(aTHX_
5270       "\t(Maybe you didn't strip carriage returns after a network transfer?)\n");
5271 #endif
5272     case ' ': case '\t': case '\f': case '\v':
5273         s++;
5274         goto retry;
5275     case '#':
5276     case '\n':
5277         if (PL_lex_state != LEX_NORMAL
5278             || (PL_in_eval && !PL_rsfp && !PL_parser->filtered))
5279         {
5280             const bool in_comment = *s == '#';
5281             if (*s == '#' && s == PL_linestart && PL_in_eval
5282              && !PL_rsfp && !PL_parser->filtered) {
5283                 /* handle eval qq[#line 1 "foo"\n ...] */
5284                 CopLINE_dec(PL_curcop);
5285                 incline(s);
5286             }
5287             d = s;
5288             while (d < PL_bufend && *d != '\n')
5289                 d++;
5290             if (d < PL_bufend)
5291                 d++;
5292             else if (d > PL_bufend)
5293                 /* Found by Ilya: feed random input to Perl. */
5294                 Perl_croak(aTHX_ "panic: input overflow, %p > %p",
5295                            d, PL_bufend);
5296             s = d;
5297             if (in_comment && d == PL_bufend
5298                 && PL_lex_state == LEX_INTERPNORMAL
5299                 && PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
5300                 && SvEVALED(PL_lex_repl) && d[-1] == '}') s--;
5301             else
5302                 incline(s);
5303             if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
5304                 PL_lex_state = LEX_FORMLINE;
5305                 force_next(FORMRBRACK);
5306                 TOKEN(';');
5307             }
5308         }
5309         else {
5310             while (s < PL_bufend && *s != '\n')
5311                 s++;
5312             if (s < PL_bufend)
5313                 {
5314                     s++;
5315                     if (s < PL_bufend)
5316                         incline(s);
5317                 }
5318             else if (s > PL_bufend)
5319                 /* Found by Ilya: feed random input to Perl. */
5320                 Perl_croak(aTHX_ "panic: input overflow");
5321         }
5322         goto retry;
5323     case '-':
5324         if (s[1] && isALPHA(s[1]) && !isWORDCHAR(s[2])) {
5325             I32 ftst = 0;
5326             char tmp;
5327
5328             s++;
5329             PL_bufptr = s;
5330             tmp = *s++;
5331
5332             while (s < PL_bufend && SPACE_OR_TAB(*s))
5333                 s++;
5334
5335             if (strEQs(s,"=>")) {
5336                 s = force_word(PL_bufptr,BAREWORD,FALSE,FALSE);
5337                 DEBUG_T( { printbuf("### Saw unary minus before =>, forcing word %s\n", s); } );
5338                 OPERATOR('-');          /* unary minus */
5339             }
5340             switch (tmp) {
5341             case 'r': ftst = OP_FTEREAD;        break;
5342             case 'w': ftst = OP_FTEWRITE;       break;
5343             case 'x': ftst = OP_FTEEXEC;        break;
5344             case 'o': ftst = OP_FTEOWNED;       break;
5345             case 'R': ftst = OP_FTRREAD;        break;
5346             case 'W': ftst = OP_FTRWRITE;       break;
5347             case 'X': ftst = OP_FTREXEC;        break;
5348             case 'O': ftst = OP_FTROWNED;       break;
5349             case 'e': ftst = OP_FTIS;           break;
5350             case 'z': ftst = OP_FTZERO;         break;
5351             case 's': ftst = OP_FTSIZE;         break;
5352             case 'f': ftst = OP_FTFILE;         break;
5353             case 'd': ftst = OP_FTDIR;          break;
5354             case 'l': ftst = OP_FTLINK;         break;
5355             case 'p': ftst = OP_FTPIPE;         break;
5356             case 'S': ftst = OP_FTSOCK;         break;
5357             case 'u': ftst = OP_FTSUID;         break;
5358             case 'g': ftst = OP_FTSGID;         break;
5359             case 'k': ftst = OP_FTSVTX;         break;
5360             case 'b': ftst = OP_FTBLK;          break;
5361             case 'c': ftst = OP_FTCHR;          break;
5362             case 't': ftst = OP_FTTTY;          break;
5363             case 'T': ftst = OP_FTTEXT;         break;
5364             case 'B': ftst = OP_FTBINARY;       break;
5365             case 'M': case 'A': case 'C':
5366                 gv_fetchpvs("\024", GV_ADD|GV_NOTQUAL, SVt_PV);
5367                 switch (tmp) {
5368                 case 'M': ftst = OP_FTMTIME;    break;
5369                 case 'A': ftst = OP_FTATIME;    break;
5370                 case 'C': ftst = OP_FTCTIME;    break;
5371                 default:                        break;
5372                 }
5373                 break;
5374             default:
5375                 break;
5376             }
5377             if (ftst) {
5378                 PL_last_uni = PL_oldbufptr;
5379                 PL_last_lop_op = (OPCODE)ftst;
5380                 DEBUG_T( { PerlIO_printf(Perl_debug_log,
5381                         "### Saw file test %c\n", (int)tmp);
5382                 } );
5383                 FTST(ftst);
5384             }
5385             else {
5386                 /* Assume it was a minus followed by a one-letter named
5387                  * subroutine call (or a -bareword), then. */
5388                 DEBUG_T( { PerlIO_printf(Perl_debug_log,
5389                         "### '-%c' looked like a file test but was not\n",
5390                         (int) tmp);
5391                 } );
5392                 s = --PL_bufptr;
5393             }
5394         }
5395         {
5396             const char tmp = *s++;
5397             if (*s == tmp) {
5398                 s++;
5399                 if (PL_expect == XOPERATOR)
5400                     TERM(POSTDEC);
5401                 else
5402                     OPERATOR(PREDEC);
5403             }
5404             else if (*s == '>') {
5405                 s++;
5406                 s = skipspace(s);
5407                 if (((*s == '$' || *s == '&') && s[1] == '*')
5408                   ||(*s == '$' && s[1] == '#' && s[2] == '*')
5409                   ||((*s == '@' || *s == '%') && strchr("*[{", s[1]))
5410                   ||(*s == '*' && (s[1] == '*' || s[1] == '{'))
5411                  )
5412                 {
5413                     PL_expect = XPOSTDEREF;
5414                     TOKEN(ARROW);
5415                 }
5416                 if (isIDFIRST_lazy_if(s,UTF)) {
5417                     s = force_word(s,METHOD,FALSE,TRUE);
5418                     TOKEN(ARROW);
5419                 }
5420                 else if (*s == '$')
5421                     OPERATOR(ARROW);
5422                 else
5423                     TERM(ARROW);
5424             }
5425             if (PL_expect == XOPERATOR) {
5426                 if (*s == '='
5427                     && !PL_lex_allbrackets
5428                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5429                 {
5430                     s--;
5431                     TOKEN(0);
5432                 }
5433                 Aop(OP_SUBTRACT);
5434             }
5435             else {
5436                 if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5437                     check_uni();
5438                 OPERATOR('-');          /* unary minus */
5439             }
5440         }
5441
5442     case '+':
5443         {
5444             const char tmp = *s++;
5445             if (*s == tmp) {
5446                 s++;
5447                 if (PL_expect == XOPERATOR)
5448                     TERM(POSTINC);
5449                 else
5450                     OPERATOR(PREINC);
5451             }
5452             if (PL_expect == XOPERATOR) {
5453                 if (*s == '='
5454                     && !PL_lex_allbrackets
5455                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5456                 {
5457                     s--;
5458                     TOKEN(0);
5459                 }
5460                 Aop(OP_ADD);
5461             }
5462             else {
5463                 if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5464                     check_uni();
5465                 OPERATOR('+');
5466             }
5467         }
5468
5469     case '*':
5470         if (PL_expect == XPOSTDEREF) POSTDEREF('*');
5471         if (PL_expect != XOPERATOR) {
5472             s = scan_ident(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE);
5473             PL_expect = XOPERATOR;
5474             force_ident(PL_tokenbuf, '*');
5475             if (!*PL_tokenbuf)
5476                 PREREF('*');
5477             TERM('*');
5478         }
5479         s++;
5480         if (*s == '*') {
5481             s++;
5482             if (*s == '=' && !PL_lex_allbrackets
5483                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5484             {
5485                 s -= 2;
5486                 TOKEN(0);
5487             }
5488             PWop(OP_POW);
5489         }
5490         if (*s == '='
5491             && !PL_lex_allbrackets
5492             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5493         {
5494             s--;
5495             TOKEN(0);
5496         }
5497         PL_parser->saw_infix_sigil = 1;
5498         Mop(OP_MULTIPLY);
5499
5500     case '%':
5501     {
5502         if (PL_expect == XOPERATOR) {
5503             if (s[1] == '='
5504                 && !PL_lex_allbrackets
5505                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5506             {
5507                 TOKEN(0);
5508             }
5509             ++s;
5510             PL_parser->saw_infix_sigil = 1;
5511             Mop(OP_MODULO);
5512         }
5513         else if (PL_expect == XPOSTDEREF) POSTDEREF('%');
5514         PL_tokenbuf[0] = '%';
5515         s = scan_ident(s, PL_tokenbuf + 1,
5516                 sizeof PL_tokenbuf - 1, FALSE);
5517         pl_yylval.ival = 0;
5518         if (!PL_tokenbuf[1]) {
5519             PREREF('%');
5520         }
5521         if ((PL_expect != XREF || PL_oldoldbufptr == PL_last_lop) && intuit_more(s)) {
5522             if (*s == '[')
5523                 PL_tokenbuf[0] = '@';
5524         }
5525         PL_expect = XOPERATOR;
5526         force_ident_maybe_lex('%');
5527         TERM('%');
5528     }
5529     case '^':
5530         d = s;
5531         bof = FEATURE_BITWISE_IS_ENABLED;
5532         if (bof && s[1] == '.')
5533             s++;
5534         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
5535                 (s[1] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE))
5536         {
5537             s = d;
5538             TOKEN(0);
5539         }
5540         s++;
5541         BOop(bof ? d == s-2 ? OP_SBIT_XOR : OP_NBIT_XOR : OP_BIT_XOR);
5542     case '[':
5543         if (PL_lex_brackets > 100)
5544             Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
5545         PL_lex_brackstack[PL_lex_brackets++] = 0;
5546         PL_lex_allbrackets++;
5547         {
5548             const char tmp = *s++;
5549             OPERATOR(tmp);
5550         }
5551     case '~':
5552         if (s[1] == '~'
5553             && (PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR))
5554         {
5555             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
5556                 TOKEN(0);
5557             s += 2;
5558             Perl_ck_warner_d(aTHX_
5559                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
5560                 "Smartmatch is experimental");
5561             Eop(OP_SMARTMATCH);
5562         }
5563         s++;
5564         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.') {
5565             s++;
5566             BCop(OP_SCOMPLEMENT);
5567         }
5568         BCop(bof ? OP_NCOMPLEMENT : OP_COMPLEMENT);
5569     case ',':
5570         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
5571             TOKEN(0);
5572         s++;
5573         OPERATOR(',');
5574     case ':':
5575         if (s[1] == ':') {
5576             len = 0;
5577             goto just_a_word_zero_gv;
5578         }
5579         s++;
5580         {
5581         OP *attrs;
5582
5583         switch (PL_expect) {
5584         case XOPERATOR:
5585             if (!PL_in_my || PL_lex_state != LEX_NORMAL)
5586                 break;
5587             PL_bufptr = s;      /* update in case we back off */
5588             if (*s == '=') {
5589                 Perl_croak(aTHX_
5590                            "Use of := for an empty attribute list is not allowed");
5591             }
5592             goto grabattrs;
5593         case XATTRBLOCK:
5594             PL_expect = XBLOCK;
5595             goto grabattrs;
5596         case XATTRTERM:
5597             PL_expect = XTERMBLOCK;
5598          grabattrs:
5599             s = skipspace(s);
5600             attrs = NULL;
5601             while (isIDFIRST_lazy_if(s,UTF)) {
5602                 I32 tmp;
5603                 SV *sv;
5604                 d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
5605                 if (isLOWER(*s) && (tmp = keyword(PL_tokenbuf, len, 0))) {
5606                     if (tmp < 0) tmp = -tmp;
5607                     switch (tmp) {
5608                     case KEY_or:
5609                     case KEY_and:
5610                     case KEY_for:
5611                     case KEY_foreach:
5612                     case KEY_unless:
5613                     case KEY_if:
5614                     case KEY_while:
5615                     case KEY_until:
5616                         goto got_attrs;
5617                     default:
5618                         break;
5619                     }
5620                 }
5621                 sv = newSVpvn_flags(s, len, UTF ? SVf_UTF8 : 0);
5622                 if (*d == '(') {
5623                     d = scan_str(d,TRUE,TRUE,FALSE,NULL);
5624                     if (!d) {
5625                         if (attrs)
5626                             op_free(attrs);
5627                         sv_free(sv);
5628                         Perl_croak(aTHX_ "Unterminated attribute parameter in attribute list");
5629                     }
5630                     COPLINE_SET_FROM_MULTI_END;
5631                 }
5632                 if (PL_lex_stuff) {
5633                     sv_catsv(sv, PL_lex_stuff);
5634                     attrs = op_append_elem(OP_LIST, attrs,
5635                                         newSVOP(OP_CONST, 0, sv));
5636                     SvREFCNT_dec_NN(PL_lex_stuff);
5637                     PL_lex_stuff = NULL;
5638                 }
5639                 else {
5640                     if (len == 6 && strnEQ(SvPVX(sv), "unique", len)) {
5641                         sv_free(sv);
5642                         if (PL_in_my == KEY_our) {
5643                             deprecate(":unique");
5644                         }
5645                         else
5646                             Perl_croak(aTHX_ "The 'unique' attribute may only be applied to 'our' variables");
5647                     }
5648
5649                     /* NOTE: any CV attrs applied here need to be part of
5650                        the CVf_BUILTIN_ATTRS define in cv.h! */
5651                     else if (!PL_in_my && len == 6 && strnEQ(SvPVX(sv), "lvalue", len)) {
5652                         sv_free(sv);
5653                         CvLVALUE_on(PL_compcv);
5654                     }
5655                     else if (!PL_in_my && len == 6 && strnEQ(SvPVX(sv), "locked", len)) {
5656                         sv_free(sv);
5657                         deprecate(":locked");
5658                     }
5659                     else if (!PL_in_my && len == 6 && strnEQ(SvPVX(sv), "method", len)) {
5660                         sv_free(sv);
5661                         CvMETHOD_on(PL_compcv);
5662                     }
5663                     else if (!PL_in_my && len == 5
5664                           && strnEQ(SvPVX(sv), "const", len))
5665                     {
5666                         sv_free(sv);
5667                         Perl_ck_warner_d(aTHX_
5668                             packWARN(WARN_EXPERIMENTAL__CONST_ATTR),
5669                            ":const is experimental"
5670                         );
5671                         CvANONCONST_on(PL_compcv);
5672                         if (!CvANON(PL_compcv))
5673                             yyerror(":const is not permitted on named "
5674                                     "subroutines");
5675                     }
5676                     /* After we've set the flags, it could be argued that
5677                        we don't need to do the attributes.pm-based setting
5678                        process, and shouldn't bother appending recognized
5679                        flags.  To experiment with that, uncomment the
5680                        following "else".  (Note that's already been
5681                        uncommented.  That keeps the above-applied built-in
5682                        attributes from being intercepted (and possibly
5683                        rejected) by a package's attribute routines, but is
5684                        justified by the performance win for the common case
5685                        of applying only built-in attributes.) */
5686                     else
5687                         attrs = op_append_elem(OP_LIST, attrs,
5688                                             newSVOP(OP_CONST, 0,
5689                                                     sv));
5690                 }
5691                 s = skipspace(d);
5692                 if (*s == ':' && s[1] != ':')
5693                     s = skipspace(s+1);
5694                 else if (s == d)
5695                     break;      /* require real whitespace or :'s */
5696                 /* XXX losing whitespace on sequential attributes here */
5697             }
5698             {
5699                 if (*s != ';'
5700                     && *s != '}'
5701                     && !(PL_expect == XOPERATOR
5702                          ? (*s == '=' ||  *s == ')')
5703                          : (*s == '{' ||  *s == '(')))
5704                 {
5705                     const char q = ((*s == '\'') ? '"' : '\'');
5706                     /* If here for an expression, and parsed no attrs, back
5707                        off. */
5708                     if (PL_expect == XOPERATOR && !attrs) {
5709                         s = PL_bufptr;
5710                         break;
5711                     }
5712                     /* MUST advance bufptr here to avoid bogus "at end of line"
5713                        context messages from yyerror().
5714                     */
5715                     PL_bufptr = s;
5716                     yyerror( (const char *)
5717                              (*s
5718                               ? Perl_form(aTHX_ "Invalid separator character "
5719                                           "%c%c%c in attribute list", q, *s, q)
5720                               : "Unterminated attribute list" ) );
5721                     if (attrs)
5722                         op_free(attrs);
5723                     OPERATOR(':');
5724                 }
5725             }
5726         got_attrs:
5727             if (attrs) {
5728                 NEXTVAL_NEXTTOKE.opval = attrs;
5729                 force_next(THING);
5730             }
5731             TOKEN(COLONATTR);
5732         }
5733         }
5734         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING) {
5735             s--;
5736             TOKEN(0);
5737         }
5738         PL_lex_allbrackets--;
5739         OPERATOR(':');
5740     case '(':
5741         s++;
5742         if (PL_last_lop == PL_oldoldbufptr || PL_last_uni == PL_oldoldbufptr)
5743             PL_oldbufptr = PL_oldoldbufptr;             /* allow print(STDOUT 123) */
5744         else
5745             PL_expect = XTERM;
5746         s = skipspace(s);
5747         PL_lex_allbrackets++;
5748         TOKEN('(');
5749     case ';':
5750         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
5751             TOKEN(0);
5752         CLINE;
5753         s++;
5754         PL_expect = XSTATE;
5755         TOKEN(';');
5756     case ')':
5757         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING)
5758             TOKEN(0);
5759         s++;
5760         PL_lex_allbrackets--;
5761         s = skipspace(s);
5762         if (*s == '{')
5763             PREBLOCK(')');
5764         TERM(')');
5765     case ']':
5766         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
5767             TOKEN(0);
5768         s++;
5769         if (PL_lex_brackets <= 0)
5770             /* diag_listed_as: Unmatched right %s bracket */
5771             yyerror("Unmatched right square bracket");
5772         else
5773             --PL_lex_brackets;
5774         PL_lex_allbrackets--;
5775         if (PL_lex_state == LEX_INTERPNORMAL) {
5776             if (PL_lex_brackets == 0) {
5777                 if (*s == '-' && s[1] == '>')
5778                     PL_lex_state = LEX_INTERPENDMAYBE;
5779                 else if (*s != '[' && *s != '{')
5780                     PL_lex_state = LEX_INTERPEND;
5781             }
5782         }
5783         TERM(']');
5784     case '{':
5785         s++;
5786       leftbracket:
5787         if (PL_lex_brackets > 100) {
5788             Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
5789         }
5790         switch (PL_expect) {
5791         case XTERM:
5792         case XTERMORDORDOR:
5793             PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5794             PL_lex_allbrackets++;
5795             OPERATOR(HASHBRACK);
5796         case XOPERATOR:
5797             while (s < PL_bufend && SPACE_OR_TAB(*s))
5798                 s++;
5799             d = s;
5800             PL_tokenbuf[0] = '\0';
5801             if (d < PL_bufend && *d == '-') {
5802                 PL_tokenbuf[0] = '-';
5803                 d++;
5804                 while (d < PL_bufend && SPACE_OR_TAB(*d))
5805                     d++;
5806             }
5807             if (d < PL_bufend && isIDFIRST_lazy_if(d,UTF)) {
5808                 d = scan_word(d, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
5809                               FALSE, &len);
5810                 while (d < PL_bufend && SPACE_OR_TAB(*d))
5811                     d++;
5812                 if (*d == '}') {
5813                     const char minus = (PL_tokenbuf[0] == '-');
5814                     s = force_word(s + minus, BAREWORD, FALSE, TRUE);
5815                     if (minus)
5816                         force_next('-');
5817                 }
5818             }
5819             /* FALLTHROUGH */
5820         case XATTRTERM:
5821         case XTERMBLOCK:
5822             PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5823             PL_lex_allbrackets++;
5824             PL_expect = XSTATE;
5825             break;
5826         case XATTRBLOCK:
5827         case XBLOCK:
5828             PL_lex_brackstack[PL_lex_brackets++] = XSTATE;
5829             PL_lex_allbrackets++;
5830             PL_expect = XSTATE;
5831             break;
5832         case XBLOCKTERM:
5833             PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5834             PL_lex_allbrackets++;
5835             PL_expect = XSTATE;
5836             break;
5837         default: {
5838                 const char *t;
5839                 if (PL_oldoldbufptr == PL_last_lop)
5840                     PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5841                 else
5842                     PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5843                 PL_lex_allbrackets++;
5844                 s = skipspace(s);
5845                 if (*s == '}') {
5846                     if (PL_expect == XREF && PL_lex_state == LEX_INTERPNORMAL) {
5847                         PL_expect = XTERM;
5848                         /* This hack is to get the ${} in the message. */
5849                         PL_bufptr = s+1;
5850                         yyerror("syntax error");
5851                         break;
5852                     }
5853                     OPERATOR(HASHBRACK);
5854                 }
5855                 if (PL_expect == XREF && PL_oldoldbufptr != PL_last_lop) {
5856                     /* ${...} or @{...} etc., but not print {...}
5857                      * Skip the disambiguation and treat this as a block.
5858                      */
5859                     goto block_expectation;
5860                 }
5861                 /* This hack serves to disambiguate a pair of curlies
5862                  * as being a block or an anon hash.  Normally, expectation
5863                  * determines that, but in cases where we're not in a
5864                  * position to expect anything in particular (like inside
5865                  * eval"") we have to resolve the ambiguity.  This code
5866                  * covers the case where the first term in the curlies is a
5867                  * quoted string.  Most other cases need to be explicitly
5868                  * disambiguated by prepending a "+" before the opening
5869                  * curly in order to force resolution as an anon hash.
5870                  *
5871                  * XXX should probably propagate the outer expectation
5872                  * into eval"" to rely less on this hack, but that could
5873                  * potentially break current behavior of eval"".
5874                  * GSAR 97-07-21
5875                  */
5876                 t = s;
5877                 if (*s == '\'' || *s == '"' || *s == '`') {
5878                     /* common case: get past first string, handling escapes */
5879                     for (t++; t < PL_bufend && *t != *s;)
5880                         if (*t++ == '\\')
5881                             t++;
5882                     t++;
5883                 }
5884                 else if (*s == 'q') {
5885                     if (++t < PL_bufend
5886                         && (!isWORDCHAR(*t)
5887                             || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
5888                                 && !isWORDCHAR(*t))))
5889                     {
5890                         /* skip q//-like construct */
5891                         const char *tmps;
5892                         char open, close, term;
5893                         I32 brackets = 1;
5894
5895                         while (t < PL_bufend && isSPACE(*t))
5896                             t++;
5897                         /* check for q => */
5898                         if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
5899                             OPERATOR(HASHBRACK);
5900                         }
5901                         term = *t;
5902                         open = term;
5903                         if (term && (tmps = strchr("([{< )]}> )]}>",term)))
5904                             term = tmps[5];
5905                         close = term;
5906                         if (open == close)
5907                             for (t++; t < PL_bufend; t++) {
5908                                 if (*t == '\\' && t+1 < PL_bufend && open != '\\')
5909                                     t++;
5910                                 else if (*t == open)
5911                                     break;
5912                             }
5913                         else {
5914                             for (t++; t < PL_bufend; t++) {
5915                                 if (*t == '\\' && t+1 < PL_bufend)
5916                                     t++;
5917                                 else if (*t == close && --brackets <= 0)
5918                                     break;
5919                                 else if (*t == open)
5920                                     brackets++;
5921                             }
5922                         }
5923                         t++;
5924                     }
5925                     else
5926                         /* skip plain q word */
5927                         while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
5928                             t += UTF ? UTF8SKIP(t) : 1;
5929                 }
5930                 else if (isWORDCHAR_lazy_if(t,UTF)) {
5931                     t += UTF ? UTF8SKIP(t) : 1;
5932                     while (t < PL_bufend && isWORDCHAR_lazy_if(t,UTF))
5933                         t += UTF ? UTF8SKIP(t) : 1;
5934                 }
5935                 while (t < PL_bufend && isSPACE(*t))
5936                     t++;
5937                 /* if comma follows first term, call it an anon hash */
5938                 /* XXX it could be a comma expression with loop modifiers */
5939                 if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
5940                                    || (*t == '=' && t[1] == '>')))
5941                     OPERATOR(HASHBRACK);
5942                 if (PL_expect == XREF)
5943                 {
5944                   block_expectation:
5945                     /* If there is an opening brace or 'sub:', treat it
5946                        as a term to make ${{...}}{k} and &{sub:attr...}
5947                        dwim.  Otherwise, treat it as a statement, so
5948                        map {no strict; ...} works.
5949                      */
5950                     s = skipspace(s);
5951                     if (*s == '{') {
5952                         PL_expect = XTERM;
5953                         break;
5954                     }
5955                     if (strEQs(s, "sub")) {
5956                         d = s + 3;
5957                         d = skipspace(d);
5958                         if (*d == ':') {
5959                             PL_expect = XTERM;
5960                             break;
5961                         }
5962                     }
5963                     PL_expect = XSTATE;
5964                 }
5965                 else {
5966                     PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
5967                     PL_expect = XSTATE;
5968                 }
5969             }
5970             break;
5971         }
5972         pl_yylval.ival = CopLINE(PL_curcop);
5973         PL_copline = NOLINE;   /* invalidate current command line number */
5974         TOKEN(formbrack ? '=' : '{');
5975     case '}':
5976         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
5977             TOKEN(0);
5978       rightbracket:
5979         s++;
5980         if (PL_lex_brackets <= 0)
5981             /* diag_listed_as: Unmatched right %s bracket */
5982             yyerror("Unmatched right curly bracket");
5983         else
5984             PL_expect = (expectation)PL_lex_brackstack[--PL_lex_brackets];
5985         PL_lex_allbrackets--;
5986         if (PL_lex_state == LEX_INTERPNORMAL) {
5987             if (PL_lex_brackets == 0) {
5988                 if (PL_expect & XFAKEBRACK) {
5989                     PL_expect &= XENUMMASK;
5990                     PL_lex_state = LEX_INTERPEND;
5991                     PL_bufptr = s;
5992                     return yylex();     /* ignore fake brackets */
5993                 }
5994                 if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
5995                  && SvEVALED(PL_lex_repl))
5996                     PL_lex_state = LEX_INTERPEND;
5997                 else if (*s == '-' && s[1] == '>')
5998                     PL_lex_state = LEX_INTERPENDMAYBE;
5999                 else if (*s != '[' && *s != '{')
6000                     PL_lex_state = LEX_INTERPEND;
6001             }
6002         }
6003         if (PL_expect & XFAKEBRACK) {
6004             PL_expect &= XENUMMASK;
6005             PL_bufptr = s;
6006             return yylex();             /* ignore fake brackets */
6007         }
6008         force_next(formbrack ? '.' : '}');
6009         if (formbrack) LEAVE;
6010         if (formbrack == 2) { /* means . where arguments were expected */
6011             force_next(';');
6012             TOKEN(FORMRBRACK);
6013         }
6014         TOKEN(';');
6015     case '&':
6016         if (PL_expect == XPOSTDEREF) POSTDEREF('&');
6017         s++;
6018         if (*s++ == '&') {
6019             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6020                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6021                 s -= 2;
6022                 TOKEN(0);
6023             }
6024             AOPERATOR(ANDAND);
6025         }
6026         s--;
6027         if (PL_expect == XOPERATOR) {
6028             if (PL_bufptr == PL_linestart && ckWARN(WARN_SEMICOLON)
6029                 && isIDFIRST_lazy_if(s,UTF))
6030             {
6031                 CopLINE_dec(PL_curcop);
6032                 Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6033                 CopLINE_inc(PL_curcop);
6034             }
6035             d = s;
6036             if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6037                 s++;
6038             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6039                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6040                 s = d;
6041                 s--;
6042                 TOKEN(0);
6043             }
6044             if (d == s) {
6045                 PL_parser->saw_infix_sigil = 1;
6046                 BAop(bof ? OP_NBIT_AND : OP_BIT_AND);
6047             }
6048             else
6049                 BAop(OP_SBIT_AND);
6050         }
6051
6052         PL_tokenbuf[0] = '&';
6053         s = scan_ident(s - 1, PL_tokenbuf + 1,
6054                        sizeof PL_tokenbuf - 1, TRUE);
6055         pl_yylval.ival = (OPpENTERSUB_AMPER<<8);
6056         if (PL_tokenbuf[1]) {
6057             force_ident_maybe_lex('&');
6058         }
6059         else
6060             PREREF('&');
6061         TERM('&');
6062
6063     case '|':
6064         s++;
6065         if (*s++ == '|') {
6066             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6067                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6068                 s -= 2;
6069                 TOKEN(0);
6070             }
6071             AOPERATOR(OROR);
6072         }
6073         s--;
6074         d = s;
6075         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6076             s++;
6077         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6078                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6079             s = d - 1;
6080             TOKEN(0);
6081         }
6082         BOop(bof ? s == d ? OP_NBIT_OR : OP_SBIT_OR : OP_BIT_OR);
6083     case '=':
6084         s++;
6085         {
6086             const char tmp = *s++;
6087             if (tmp == '=') {
6088                 if ((s == PL_linestart+2 || s[-3] == '\n') && strEQs(s, "=====")) {
6089                     s = vcs_conflict_marker(s + 5);
6090                     goto retry;
6091                 }
6092                 if (!PL_lex_allbrackets
6093                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6094                 {
6095                     s -= 2;
6096                     TOKEN(0);
6097                 }
6098                 Eop(OP_EQ);
6099             }
6100             if (tmp == '>') {
6101                 if (!PL_lex_allbrackets
6102                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
6103                 {
6104                     s -= 2;
6105                     TOKEN(0);
6106                 }
6107                 OPERATOR(',');
6108             }
6109             if (tmp == '~')
6110                 PMop(OP_MATCH);
6111             if (tmp && isSPACE(*s) && ckWARN(WARN_SYNTAX)
6112                 && strchr("+-*/%.^&|<",tmp))
6113                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6114                             "Reversed %c= operator",(int)tmp);
6115             s--;
6116             if (PL_expect == XSTATE
6117                 && isALPHA(tmp)
6118                 && (s == PL_linestart+1 || s[-2] == '\n') )
6119             {
6120                 if ((PL_in_eval && !PL_rsfp && !PL_parser->filtered)
6121                     || PL_lex_state != LEX_NORMAL) {
6122                     d = PL_bufend;
6123                     while (s < d) {
6124                         if (*s++ == '\n') {
6125                             incline(s);
6126                             if (strEQs(s,"=cut")) {
6127                                 s = strchr(s,'\n');
6128                                 if (s)
6129                                     s++;
6130                                 else
6131                                     s = d;
6132                                 incline(s);
6133                                 goto retry;
6134                             }
6135                         }
6136                     }
6137                     goto retry;
6138                 }
6139                 s = PL_bufend;
6140                 PL_parser->in_pod = 1;
6141                 goto retry;
6142             }
6143         }
6144         if (PL_expect == XBLOCK) {
6145             const char *t = s;
6146 #ifdef PERL_STRICT_CR
6147             while (SPACE_OR_TAB(*t))
6148 #else
6149             while (SPACE_OR_TAB(*t) || *t == '\r')
6150 #endif
6151                 t++;
6152             if (*t == '\n' || *t == '#') {
6153                 formbrack = 1;
6154                 ENTER;
6155                 SAVEI8(PL_parser->form_lex_state);
6156                 SAVEI32(PL_lex_formbrack);
6157                 PL_parser->form_lex_state = PL_lex_state;
6158                 PL_lex_formbrack = PL_lex_brackets + 1;
6159                 goto leftbracket;
6160             }
6161         }
6162         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6163             s--;
6164             TOKEN(0);
6165         }
6166         pl_yylval.ival = 0;
6167         OPERATOR(ASSIGNOP);
6168     case '!':
6169         s++;
6170         {
6171             const char tmp = *s++;
6172             if (tmp == '=') {
6173                 /* was this !=~ where !~ was meant?
6174                  * warn on m:!=~\s+([/?]|[msy]\W|tr\W): */
6175
6176                 if (*s == '~' && ckWARN(WARN_SYNTAX)) {
6177                     const char *t = s+1;
6178
6179                     while (t < PL_bufend && isSPACE(*t))
6180                         ++t;
6181
6182                     if (*t == '/' || *t == '?'
6183                         || ((*t == 'm' || *t == 's' || *t == 'y')
6184                             && !isWORDCHAR(t[1]))
6185                         || (*t == 't' && t[1] == 'r' && !isWORDCHAR(t[2])))
6186                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6187                                     "!=~ should be !~");
6188                 }
6189                 if (!PL_lex_allbrackets
6190                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6191                 {
6192                     s -= 2;
6193                     TOKEN(0);
6194                 }
6195                 Eop(OP_NE);
6196             }
6197             if (tmp == '~')
6198                 PMop(OP_NOT);
6199         }
6200         s--;
6201         OPERATOR('!');
6202     case '<':
6203         if (PL_expect != XOPERATOR) {
6204             if (s[1] != '<' && !strchr(s,'>'))
6205                 check_uni();
6206             if (s[1] == '<' && s[2] != '>') {
6207                 if ((s == PL_linestart || s[-1] == '\n') && strEQs(s+2, "<<<<<")) {
6208                     s = vcs_conflict_marker(s + 7);
6209                     goto retry;
6210                 }
6211                 s = scan_heredoc(s);
6212             }
6213             else
6214                 s = scan_inputsymbol(s);
6215             PL_expect = XOPERATOR;
6216             TOKEN(sublex_start());
6217         }
6218         s++;
6219         {
6220             char tmp = *s++;
6221             if (tmp == '<') {
6222                 if ((s == PL_linestart+2 || s[-3] == '\n') && strEQs(s, "<<<<<")) {
6223                     s = vcs_conflict_marker(s + 5);
6224                     goto retry;
6225                 }
6226                 if (*s == '=' && !PL_lex_allbrackets
6227                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6228                 {
6229                     s -= 2;
6230                     TOKEN(0);
6231                 }
6232                 SHop(OP_LEFT_SHIFT);
6233             }
6234             if (tmp == '=') {
6235                 tmp = *s++;
6236                 if (tmp == '>') {
6237                     if (!PL_lex_allbrackets
6238                         && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6239                     {
6240                         s -= 3;
6241                         TOKEN(0);
6242                     }
6243                     Eop(OP_NCMP);
6244                 }
6245                 s--;
6246                 if (!PL_lex_allbrackets
6247                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6248                 {
6249                     s -= 2;
6250                     TOKEN(0);
6251                 }
6252                 Rop(OP_LE);
6253             }
6254         }
6255         s--;
6256         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6257             s--;
6258             TOKEN(0);
6259         }
6260         Rop(OP_LT);
6261     case '>':
6262         s++;
6263         {
6264             const char tmp = *s++;
6265             if (tmp == '>') {
6266                 if ((s == PL_linestart+2 || s[-3] == '\n') && strEQs(s, ">>>>>")) {
6267                     s = vcs_conflict_marker(s + 5);
6268                     goto retry;
6269                 }
6270                 if (*s == '=' && !PL_lex_allbrackets
6271                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6272                 {
6273                     s -= 2;
6274                     TOKEN(0);
6275                 }
6276                 SHop(OP_RIGHT_SHIFT);
6277             }
6278             else if (tmp == '=') {
6279                 if (!PL_lex_allbrackets
6280                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6281                 {
6282                     s -= 2;
6283                     TOKEN(0);
6284                 }
6285                 Rop(OP_GE);
6286             }
6287         }
6288         s--;
6289         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6290             s--;
6291             TOKEN(0);
6292         }
6293         Rop(OP_GT);
6294
6295     case '$':
6296         CLINE;
6297
6298         if (PL_expect == XOPERATOR) {
6299             if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack) {
6300                 return deprecate_commaless_var_list();
6301             }
6302         }
6303         else if (PL_expect == XPOSTDEREF) {
6304             if (s[1] == '#') {
6305                 s++;
6306                 POSTDEREF(DOLSHARP);
6307             }
6308             POSTDEREF('$');
6309         }
6310
6311         if (s[1] == '#' && (isIDFIRST_lazy_if(s+2,UTF) || strchr("{$:+-@", s[2]))) {
6312             PL_tokenbuf[0] = '@';
6313             s = scan_ident(s + 1, PL_tokenbuf + 1,
6314                            sizeof PL_tokenbuf - 1, FALSE);
6315             if (PL_expect == XOPERATOR) {
6316                 d = s;
6317                 if (PL_bufptr > s) {
6318                     d = PL_bufptr-1;
6319                     PL_bufptr = PL_oldbufptr;
6320                 }
6321                 no_op("Array length", d);
6322             }
6323             if (!PL_tokenbuf[1])
6324                 PREREF(DOLSHARP);
6325             PL_expect = XOPERATOR;
6326             force_ident_maybe_lex('#');
6327             TOKEN(DOLSHARP);
6328         }
6329
6330         PL_tokenbuf[0] = '$';
6331         s = scan_ident(s, PL_tokenbuf + 1,
6332                        sizeof PL_tokenbuf - 1, FALSE);
6333         if (PL_expect == XOPERATOR) {
6334             d = s;
6335             if (PL_bufptr > s) {
6336                 d = PL_bufptr-1;
6337                 PL_bufptr = PL_oldbufptr;
6338             }
6339             no_op("Scalar", d);
6340         }
6341         if (!PL_tokenbuf[1]) {
6342             if (s == PL_bufend)
6343                 yyerror("Final $ should be \\$ or $name");
6344             PREREF('$');
6345         }
6346
6347         d = s;
6348         {
6349             const char tmp = *s;
6350             if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
6351                 s = skipspace(s);
6352
6353             if ((PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6354                 && intuit_more(s)) {
6355                 if (*s == '[') {
6356                     PL_tokenbuf[0] = '@';
6357                     if (ckWARN(WARN_SYNTAX)) {
6358                         char *t = s+1;
6359
6360                         while (isSPACE(*t) || isWORDCHAR_lazy_if(t,UTF) || *t == '$')
6361                             t += UTF ? UTF8SKIP(t) : 1;
6362                         if (*t++ == ',') {
6363                             PL_bufptr = skipspace(PL_bufptr); /* XXX can realloc */
6364                             while (t < PL_bufend && *t != ']')
6365                                 t++;
6366                             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6367                                         "Multidimensional syntax %"UTF8f" not supported",
6368                                         UTF8fARG(UTF,(int)((t - PL_bufptr) + 1), PL_bufptr));
6369                         }
6370                     }
6371                 }
6372                 else if (*s == '{') {
6373                     char *t;
6374                     PL_tokenbuf[0] = '%';
6375                     if (strEQ(PL_tokenbuf+1, "SIG")  && ckWARN(WARN_SYNTAX)
6376                         && (t = strchr(s, '}')) && (t = strchr(t, '=')))
6377                         {
6378                             char tmpbuf[sizeof PL_tokenbuf];
6379                             do {
6380                                 t++;
6381                             } while (isSPACE(*t));
6382                             if (isIDFIRST_lazy_if(t,UTF)) {
6383                                 STRLEN len;
6384                                 t = scan_word(t, tmpbuf, sizeof tmpbuf, TRUE,
6385                                               &len);
6386                                 while (isSPACE(*t))
6387                                     t++;
6388                                 if (*t == ';'
6389                                        && get_cvn_flags(tmpbuf, len, UTF ? SVf_UTF8 : 0))
6390                                     Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6391                                         "You need to quote \"%"UTF8f"\"",
6392                                          UTF8fARG(UTF, len, tmpbuf));
6393                             }
6394                         }
6395                 }
6396             }
6397
6398             PL_expect = XOPERATOR;
6399             if (PL_lex_state == LEX_NORMAL && isSPACE((char)tmp)) {
6400                 const bool islop = (PL_last_lop == PL_oldoldbufptr);
6401                 if (!islop || PL_last_lop_op == OP_GREPSTART)
6402                     PL_expect = XOPERATOR;
6403                 else if (strchr("$@\"'`q", *s))
6404                     PL_expect = XTERM;          /* e.g. print $fh "foo" */
6405                 else if (strchr("&*<%", *s) && isIDFIRST_lazy_if(s+1,UTF))
6406                     PL_expect = XTERM;          /* e.g. print $fh &sub */
6407                 else if (isIDFIRST_lazy_if(s,UTF)) {
6408                     char tmpbuf[sizeof PL_tokenbuf];
6409                     int t2;
6410                     scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
6411                     if ((t2 = keyword(tmpbuf, len, 0))) {
6412                         /* binary operators exclude handle interpretations */
6413                         switch (t2) {
6414                         case -KEY_x:
6415                         case -KEY_eq:
6416                         case -KEY_ne:
6417                         case -KEY_gt:
6418                         case -KEY_lt:
6419                         case -KEY_ge:
6420                         case -KEY_le:
6421                         case -KEY_cmp:
6422                             break;
6423                         default:
6424                             PL_expect = XTERM;  /* e.g. print $fh length() */
6425                             break;
6426                         }
6427                     }
6428                     else {
6429                         PL_expect = XTERM;      /* e.g. print $fh subr() */
6430                     }
6431                 }
6432                 else if (isDIGIT(*s))
6433                     PL_expect = XTERM;          /* e.g. print $fh 3 */
6434                 else if (*s == '.' && isDIGIT(s[1]))
6435                     PL_expect = XTERM;          /* e.g. print $fh .3 */
6436                 else if ((*s == '?' || *s == '-' || *s == '+')
6437                          && !isSPACE(s[1]) && s[1] != '=')
6438                     PL_expect = XTERM;          /* e.g. print $fh -1 */
6439                 else if (*s == '/' && !isSPACE(s[1]) && s[1] != '='
6440                          && s[1] != '/')
6441                     PL_expect = XTERM;          /* e.g. print $fh /.../
6442                                                    XXX except DORDOR operator
6443                                                 */
6444                 else if (*s == '<' && s[1] == '<' && !isSPACE(s[2])
6445                          && s[2] != '=')
6446                     PL_expect = XTERM;          /* print $fh <<"EOF" */
6447             }
6448         }
6449         force_ident_maybe_lex('$');
6450         TOKEN('$');
6451
6452     case '@':
6453         if (PL_expect == XPOSTDEREF)
6454             POSTDEREF('@');
6455         PL_tokenbuf[0] = '@';
6456         s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6457         if (PL_expect == XOPERATOR) {
6458             d = s;
6459             if (PL_bufptr > s) {
6460                 d = PL_bufptr-1;
6461                 PL_bufptr = PL_oldbufptr;
6462             }
6463             no_op("Array", d);
6464         }
6465         pl_yylval.ival = 0;
6466         if (!PL_tokenbuf[1]) {
6467             PREREF('@');
6468         }
6469         if (PL_lex_state == LEX_NORMAL)
6470             s = skipspace(s);
6471         if ((PL_expect != XREF || PL_oldoldbufptr == PL_last_lop) && intuit_more(s)) {
6472             if (*s == '{')
6473                 PL_tokenbuf[0] = '%';
6474
6475             /* Warn about @ where they meant $. */
6476             if (*s == '[' || *s == '{') {
6477                 if (ckWARN(WARN_SYNTAX)) {
6478                     S_check_scalar_slice(aTHX_ s);
6479                 }
6480             }
6481         }
6482         PL_expect = XOPERATOR;
6483         force_ident_maybe_lex('@');
6484         TERM('@');
6485
6486      case '/':                  /* may be division, defined-or, or pattern */
6487         if ((PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR) && s[1] == '/') {
6488             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6489                     (s[2] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC))
6490                 TOKEN(0);
6491             s += 2;
6492             AOPERATOR(DORDOR);
6493         }
6494         else if (PL_expect == XOPERATOR) {
6495             s++;
6496             if (*s == '=' && !PL_lex_allbrackets
6497                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6498             {
6499                 s--;
6500                 TOKEN(0);
6501             }
6502             Mop(OP_DIVIDE);
6503         }
6504         else {
6505             /* Disable warning on "study /blah/" */
6506             if (PL_oldoldbufptr == PL_last_uni
6507              && (*PL_last_uni != 's' || s - PL_last_uni < 5
6508                  || memNE(PL_last_uni, "study", 5)
6509                  || isWORDCHAR_lazy_if(PL_last_uni+5,UTF)
6510              ))
6511                 check_uni();
6512             s = scan_pat(s,OP_MATCH);
6513             TERM(sublex_start());
6514         }
6515
6516      case '?':                  /* conditional */
6517         s++;
6518         if (!PL_lex_allbrackets
6519             && PL_lex_fakeeof >= LEX_FAKEEOF_IFELSE)
6520         {
6521             s--;
6522             TOKEN(0);
6523         }
6524         PL_lex_allbrackets++;
6525         OPERATOR('?');
6526
6527     case '.':
6528         if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack
6529 #ifdef PERL_STRICT_CR
6530             && s[1] == '\n'
6531 #else
6532             && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n'))
6533 #endif
6534             && (s == PL_linestart || s[-1] == '\n') )
6535         {
6536             PL_expect = XSTATE;
6537             formbrack = 2; /* dot seen where arguments expected */
6538             goto rightbracket;
6539         }
6540         if (PL_expect == XSTATE && s[1] == '.' && s[2] == '.') {
6541             s += 3;
6542             OPERATOR(YADAYADA);
6543         }
6544         if (PL_expect == XOPERATOR || !isDIGIT(s[1])) {
6545             char tmp = *s++;
6546             if (*s == tmp) {
6547                 if (!PL_lex_allbrackets
6548                     && PL_lex_fakeeof >= LEX_FAKEEOF_RANGE)
6549                 {
6550                     s--;
6551                     TOKEN(0);
6552                 }
6553                 s++;
6554                 if (*s == tmp) {
6555                     s++;
6556                     pl_yylval.ival = OPf_SPECIAL;
6557                 }
6558                 else
6559                     pl_yylval.ival = 0;
6560                 OPERATOR(DOTDOT);
6561             }
6562             if (*s == '=' && !PL_lex_allbrackets
6563                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6564             {
6565                 s--;
6566                 TOKEN(0);
6567             }
6568             Aop(OP_CONCAT);
6569         }
6570         /* FALLTHROUGH */
6571     case '0': case '1': case '2': case '3': case '4':
6572     case '5': case '6': case '7': case '8': case '9':
6573         s = scan_num(s, &pl_yylval);
6574         DEBUG_T( { printbuf("### Saw number in %s\n", s); } );
6575         if (PL_expect == XOPERATOR)
6576             no_op("Number",s);
6577         TERM(THING);
6578
6579     case '\'':
6580         if (   PL_expect == XOPERATOR
6581             && (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack))
6582                 return deprecate_commaless_var_list();
6583
6584         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6585         if (!s)
6586             missingterm(NULL);
6587         COPLINE_SET_FROM_MULTI_END;
6588         DEBUG_T( { printbuf("### Saw string before %s\n", s); } );
6589         if (PL_expect == XOPERATOR) {
6590             no_op("String",s);
6591         }
6592         pl_yylval.ival = OP_CONST;
6593         TERM(sublex_start());
6594
6595     case '"':
6596         if (   PL_expect == XOPERATOR
6597             && (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack))
6598                 return deprecate_commaless_var_list();
6599
6600         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6601         DEBUG_T( {
6602             if (s)
6603                 printbuf("### Saw string before %s\n", s);
6604             else
6605                 PerlIO_printf(Perl_debug_log,
6606                              "### Saw unterminated string\n");
6607         } );
6608         if (PL_expect == XOPERATOR) {
6609                 no_op("String",s);
6610         }
6611         if (!s)
6612             missingterm(NULL);
6613         pl_yylval.ival = OP_CONST;
6614         /* FIXME. I think that this can be const if char *d is replaced by
6615            more localised variables.  */
6616         for (d = SvPV(PL_lex_stuff, len); len; len--, d++) {
6617             if (*d == '$' || *d == '@' || *d == '\\' || !UTF8_IS_INVARIANT((U8)*d)) {
6618                 pl_yylval.ival = OP_STRINGIFY;
6619                 break;
6620             }
6621         }
6622         if (pl_yylval.ival == OP_CONST)
6623             COPLINE_SET_FROM_MULTI_END;
6624         TERM(sublex_start());
6625
6626     case '`':
6627         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6628         DEBUG_T( {
6629             if (s)
6630                 printbuf("### Saw backtick string before %s\n", s);
6631             else
6632                 PerlIO_printf(Perl_debug_log,
6633                              "### Saw unterminated backtick string\n");
6634         } );
6635         if (PL_expect == XOPERATOR)
6636             no_op("Backticks",s);
6637         if (!s)
6638             missingterm(NULL);
6639         pl_yylval.ival = OP_BACKTICK;
6640         TERM(sublex_start());
6641
6642     case '\\':
6643         s++;
6644         if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6645          && isDIGIT(*s))
6646             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),"Can't use \\%c to mean $%c in expression",
6647                            *s, *s);
6648         if (PL_expect == XOPERATOR)
6649             no_op("Backslash",s);
6650         OPERATOR(REFGEN);
6651
6652     case 'v':
6653         if (isDIGIT(s[1]) && PL_expect != XOPERATOR) {
6654             char *start = s + 2;
6655             while (isDIGIT(*start) || *start == '_')
6656                 start++;
6657             if (*start == '.' && isDIGIT(start[1])) {
6658                 s = scan_num(s, &pl_yylval);
6659                 TERM(THING);
6660             }
6661             else if ((*start == ':' && start[1] == ':')
6662                   || (PL_expect == XSTATE && *start == ':'))
6663                 goto keylookup;
6664             else if (PL_expect == XSTATE) {
6665                 d = start;
6666                 while (d < PL_bufend && isSPACE(*d)) d++;
6667                 if (*d == ':') goto keylookup;
6668             }
6669             /* avoid v123abc() or $h{v1}, allow C<print v10;> */
6670             if (!isALPHA(*start) && (PL_expect == XTERM
6671                         || PL_expect == XREF || PL_expect == XSTATE
6672                         || PL_expect == XTERMORDORDOR)) {
6673                 GV *const gv = gv_fetchpvn_flags(s, start - s,
6674                                                     UTF ? SVf_UTF8 : 0, SVt_PVCV);
6675                 if (!gv) {
6676                     s = scan_num(s, &pl_yylval);
6677                     TERM(THING);
6678                 }
6679             }
6680         }
6681         goto keylookup;
6682     case 'x':
6683         if (isDIGIT(s[1]) && PL_expect == XOPERATOR) {
6684             s++;
6685             Mop(OP_REPEAT);
6686         }
6687         goto keylookup;
6688
6689     case '_':
6690     case 'a': case 'A':
6691     case 'b': case 'B':
6692     case 'c': case 'C':
6693     case 'd': case 'D':
6694     case 'e': case 'E':
6695     case 'f': case 'F':
6696     case 'g': case 'G':
6697     case 'h': case 'H':
6698     case 'i': case 'I':
6699     case 'j': case 'J':
6700     case 'k': case 'K':
6701     case 'l': case 'L':
6702     case 'm': case 'M':
6703     case 'n': case 'N':
6704     case 'o': case 'O':
6705     case 'p': case 'P':
6706     case 'q': case 'Q':
6707     case 'r': case 'R':
6708     case 's': case 'S':
6709     case 't': case 'T':
6710     case 'u': case 'U':
6711               case 'V':
6712     case 'w': case 'W':
6713               case 'X':
6714     case 'y': case 'Y':
6715     case 'z': case 'Z':
6716
6717       keylookup: {
6718         bool anydelim;
6719         bool lex;
6720         I32 tmp;
6721         SV *sv;
6722         CV *cv;
6723         PADOFFSET off;
6724         OP *rv2cv_op;
6725
6726         lex = FALSE;
6727         orig_keyword = 0;
6728         off = 0;
6729         sv = NULL;
6730         cv = NULL;
6731         gv = NULL;
6732         gvp = NULL;
6733         rv2cv_op = NULL;
6734
6735         PL_bufptr = s;
6736         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
6737
6738         /* Some keywords can be followed by any delimiter, including ':' */
6739         anydelim = word_takes_any_delimiter(PL_tokenbuf, len);
6740
6741         /* x::* is just a word, unless x is "CORE" */
6742         if (!anydelim && *s == ':' && s[1] == ':') {
6743             if (strEQ(PL_tokenbuf, "CORE")) goto case_KEY_CORE;
6744             goto just_a_word;
6745         }
6746
6747         d = s;
6748         while (d < PL_bufend && isSPACE(*d))
6749                 d++;    /* no comments skipped here, or s### is misparsed */
6750
6751         /* Is this a word before a => operator? */
6752         if (*d == '=' && d[1] == '>') {
6753           fat_arrow:
6754             CLINE;
6755             pl_yylval.opval
6756                 = (OP*)newSVOP(OP_CONST, 0,
6757                                S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
6758             pl_yylval.opval->op_private = OPpCONST_BARE;
6759             TERM(BAREWORD);
6760         }
6761
6762         /* Check for plugged-in keyword */
6763         {
6764             OP *o;
6765             int result;
6766             char *saved_bufptr = PL_bufptr;
6767             PL_bufptr = s;
6768             result = PL_keyword_plugin(aTHX_ PL_tokenbuf, len, &o);
6769             s = PL_bufptr;
6770             if (result == KEYWORD_PLUGIN_DECLINE) {
6771                 /* not a plugged-in keyword */
6772                 PL_bufptr = saved_bufptr;
6773             } else if (result == KEYWORD_PLUGIN_STMT) {
6774                 pl_yylval.opval = o;
6775                 CLINE;
6776                 if (!PL_nexttoke) PL_expect = XSTATE;
6777                 return REPORT(PLUGSTMT);
6778             } else if (result == KEYWORD_PLUGIN_EXPR) {
6779                 pl_yylval.opval = o;
6780                 CLINE;
6781                 if (!PL_nexttoke) PL_expect = XOPERATOR;
6782                 return REPORT(PLUGEXPR);
6783             } else {
6784                 Perl_croak(aTHX_ "Bad plugin affecting keyword '%s'",
6785                                         PL_tokenbuf);
6786             }
6787         }
6788
6789         /* Check for built-in keyword */
6790         tmp = keyword(PL_tokenbuf, len, 0);
6791
6792         /* Is this a label? */
6793         if (!anydelim && PL_expect == XSTATE
6794               && d < PL_bufend && *d == ':' && *(d + 1) != ':') {
6795             s = d + 1;
6796             pl_yylval.pval = savepvn(PL_tokenbuf, len+1);
6797             pl_yylval.pval[len] = '\0';
6798             pl_yylval.pval[len+1] = UTF ? 1 : 0;
6799             CLINE;
6800             TOKEN(LABEL);
6801         }
6802
6803         /* Check for lexical sub */
6804         if (PL_expect != XOPERATOR) {
6805             char tmpbuf[sizeof PL_tokenbuf + 1];
6806             *tmpbuf = '&';
6807             Copy(PL_tokenbuf, tmpbuf+1, len, char);
6808             off = pad_findmy_pvn(tmpbuf, len+1, 0);
6809             if (off != NOT_IN_PAD) {
6810                 assert(off); /* we assume this is boolean-true below */
6811                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
6812                     HV *  const stash = PAD_COMPNAME_OURSTASH(off);
6813                     HEK * const stashname = HvNAME_HEK(stash);
6814                     sv = newSVhek(stashname);
6815                     sv_catpvs(sv, "::");
6816                     sv_catpvn_flags(sv, PL_tokenbuf, len,
6817                                     (UTF ? SV_CATUTF8 : SV_CATBYTES));
6818                     gv = gv_fetchsv(sv, GV_NOADD_NOINIT | SvUTF8(sv),
6819                                     SVt_PVCV);
6820                     off = 0;
6821                     if (!gv) {
6822                         sv_free(sv);
6823                         sv = NULL;
6824                         goto just_a_word;
6825                     }
6826                 }
6827                 else {
6828                     rv2cv_op = newOP(OP_PADANY, 0);
6829                     rv2cv_op->op_targ = off;
6830                     cv = find_lexical_cv(off);
6831                 }
6832                 lex = TRUE;
6833                 goto just_a_word;
6834             }
6835             off = 0;
6836         }
6837
6838         if (tmp < 0) {                  /* second-class keyword? */
6839             GV *ogv = NULL;     /* override (winner) */
6840             GV *hgv = NULL;     /* hidden (loser) */
6841             if (PL_expect != XOPERATOR && (*s != ':' || s[1] != ':')) {
6842                 CV *cv;
6843                 if ((gv = gv_fetchpvn_flags(PL_tokenbuf, len,
6844                                             (UTF ? SVf_UTF8 : 0)|GV_NOTQUAL,
6845                                             SVt_PVCV))
6846                     && (cv = GvCVu(gv)))
6847                 {
6848                     if (GvIMPORTED_CV(gv))
6849                         ogv = gv;
6850                     else if (! CvMETHOD(cv))
6851                         hgv = gv;
6852                 }
6853                 if (!ogv
6854                     && (gvp = (GV**)hv_fetch(PL_globalstash, PL_tokenbuf,
6855                                                               len, FALSE))
6856                     && (gv = *gvp)
6857                     && (isGV_with_GP(gv)
6858                         ? GvCVu(gv) && GvIMPORTED_CV(gv)
6859                         :   SvPCS_IMPORTED(gv)
6860                         && (gv_init(gv, PL_globalstash, PL_tokenbuf,
6861                                                                  len, 0), 1)))
6862                 {
6863                     ogv = gv;
6864                 }
6865             }
6866             if (ogv) {
6867                 orig_keyword = tmp;
6868                 tmp = 0;                /* overridden by import or by GLOBAL */
6869             }
6870             else if (gv && !gvp
6871                      && -tmp==KEY_lock  /* XXX generalizable kludge */
6872                      && GvCVu(gv))
6873             {
6874                 tmp = 0;                /* any sub overrides "weak" keyword */
6875             }
6876             else {                      /* no override */
6877                 tmp = -tmp;
6878                 if (tmp == KEY_dump) {
6879                     Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
6880                                    "dump() better written as CORE::dump()");
6881                 }
6882                 gv = NULL;
6883                 gvp = 0;
6884                 if (hgv && tmp != KEY_x)        /* never ambiguous */
6885                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
6886                                    "Ambiguous call resolved as CORE::%s(), "
6887                                    "qualify as such or use &",
6888                                    GvENAME(hgv));
6889             }
6890         }
6891
6892         if (tmp && tmp != KEY___DATA__ && tmp != KEY___END__
6893          && (!anydelim || *s != '#')) {
6894             /* no override, and not s### either; skipspace is safe here
6895              * check for => on following line */
6896             bool arrow;
6897             STRLEN bufoff = PL_bufptr - SvPVX(PL_linestr);
6898             STRLEN   soff = s         - SvPVX(PL_linestr);
6899             s = peekspace(s);
6900             arrow = *s == '=' && s[1] == '>';
6901             PL_bufptr = SvPVX(PL_linestr) + bufoff;
6902             s         = SvPVX(PL_linestr) +   soff;
6903             if (arrow)
6904                 goto fat_arrow;
6905         }
6906
6907       reserved_word:
6908         switch (tmp) {
6909
6910         default:                        /* not a keyword */
6911             /* Trade off - by using this evil construction we can pull the
6912                variable gv into the block labelled keylookup. If not, then
6913                we have to give it function scope so that the goto from the
6914                earlier ':' case doesn't bypass the initialisation.  */
6915             if (0) {
6916             just_a_word_zero_gv:
6917                 sv = NULL;
6918                 cv = NULL;
6919                 gv = NULL;
6920                 gvp = NULL;
6921                 rv2cv_op = NULL;
6922                 orig_keyword = 0;
6923                 lex = 0;
6924                 off = 0;
6925             }
6926           just_a_word: {
6927                 int pkgname = 0;
6928                 const char lastchar = (PL_bufptr == PL_oldoldbufptr ? 0 : PL_bufptr[-1]);
6929                 bool safebw;
6930
6931
6932                 /* Get the rest if it looks like a package qualifier */
6933
6934                 if (*s == '\'' || (*s == ':' && s[1] == ':')) {
6935                     STRLEN morelen;
6936                     s = scan_word(s, PL_tokenbuf + len, sizeof PL_tokenbuf - len,
6937                                   TRUE, &morelen);
6938                     if (!morelen)
6939                         Perl_croak(aTHX_ "Bad name after %"UTF8f"%s",
6940                                 UTF8fARG(UTF, len, PL_tokenbuf),
6941                                 *s == '\'' ? "'" : "::");
6942                     len += morelen;
6943                     pkgname = 1;
6944                 }
6945
6946                 if (PL_expect == XOPERATOR) {
6947                     if (PL_bufptr == PL_linestart) {
6948                         CopLINE_dec(PL_curcop);
6949                         Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6950                         CopLINE_inc(PL_curcop);
6951                     }
6952                     else
6953                         no_op("Bareword",s);
6954                 }
6955
6956                 /* See if the name is "Foo::",
6957                    in which case Foo is a bareword
6958                    (and a package name). */
6959
6960                 if (len > 2
6961                     && PL_tokenbuf[len - 2] == ':'
6962                     && PL_tokenbuf[len - 1] == ':')
6963                 {
6964                     if (ckWARN(WARN_BAREWORD)
6965                         && ! gv_fetchpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0, SVt_PVHV))
6966                         Perl_warner(aTHX_ packWARN(WARN_BAREWORD),
6967                           "Bareword \"%"UTF8f"\" refers to nonexistent package",
6968                            UTF8fARG(UTF, len, PL_tokenbuf));
6969                     len -= 2;
6970                     PL_tokenbuf[len] = '\0';
6971                     gv = NULL;
6972                     gvp = 0;
6973                     safebw = TRUE;
6974                 }
6975                 else {
6976                     safebw = FALSE;
6977                 }
6978
6979                 /* if we saw a global override before, get the right name */
6980
6981                 if (!sv)
6982                   sv = S_newSV_maybe_utf8(aTHX_ PL_tokenbuf,
6983                                                 len);
6984                 if (gvp) {
6985                     SV * const tmp_sv = sv;
6986                     sv = newSVpvs("CORE::GLOBAL::");
6987                     sv_catsv(sv, tmp_sv);
6988                     SvREFCNT_dec(tmp_sv);
6989                 }
6990
6991
6992                 /* Presume this is going to be a bareword of some sort. */
6993                 CLINE;
6994                 pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
6995                 pl_yylval.opval->op_private = OPpCONST_BARE;
6996
6997                 /* And if "Foo::", then that's what it certainly is. */
6998                 if (safebw)
6999                     goto safe_bareword;
7000
7001                 if (!off)
7002                 {
7003                     OP *const_op = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(sv));
7004                     const_op->op_private = OPpCONST_BARE;
7005                     rv2cv_op =
7006                         newCVREF(OPpMAY_RETURN_CONSTANT<<8, const_op);
7007                     cv = lex
7008                         ? isGV(gv)
7009                             ? GvCV(gv)
7010                             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
7011                                 ? (CV *)SvRV(gv)
7012                                 : ((CV *)gv)
7013                         : rv2cv_op_cv(rv2cv_op, RV2CVOPCV_RETURN_STUB);
7014                 }
7015
7016                 /* Use this var to track whether intuit_method has been
7017                    called.  intuit_method returns 0 or > 255.  */
7018                 tmp = 1;
7019
7020                 /* See if it's the indirect object for a list operator. */
7021
7022                 if (PL_oldoldbufptr
7023                     && PL_oldoldbufptr < PL_bufptr
7024                     && (PL_oldoldbufptr == PL_last_lop
7025                         || PL_oldoldbufptr == PL_last_uni)
7026                     && /* NO SKIPSPACE BEFORE HERE! */
7027                        (PL_expect == XREF
7028                         || ((PL_opargs[PL_last_lop_op] >> OASHIFT)& 7)
7029                                                                == OA_FILEREF))
7030                 {
7031                     bool immediate_paren = *s == '(';
7032
7033                     /* (Now we can afford to cross potential line boundary.) */
7034                     s = skipspace(s);
7035
7036                     /* Two barewords in a row may indicate method call. */
7037
7038                     if ((isIDFIRST_lazy_if(s,UTF) || *s == '$')
7039                         && (tmp = intuit_method(s, lex ? NULL : sv, cv)))
7040                     {
7041                         goto method;
7042                     }
7043
7044                     /* If not a declared subroutine, it's an indirect object. */
7045                     /* (But it's an indir obj regardless for sort.) */
7046                     /* Also, if "_" follows a filetest operator, it's a bareword */
7047
7048                     if (
7049                         ( !immediate_paren && (PL_last_lop_op == OP_SORT
7050                          || (!cv
7051                              && (PL_last_lop_op != OP_MAPSTART
7052                                  && PL_last_lop_op != OP_GREPSTART))))
7053                        || (PL_tokenbuf[0] == '_' && PL_tokenbuf[1] == '\0'
7054                             && ((PL_opargs[PL_last_lop_op] & OA_CLASS_MASK)
7055                                                             == OA_FILESTATOP))
7056                        )
7057                     {
7058                         PL_expect = (PL_last_lop == PL_oldoldbufptr) ? XTERM : XOPERATOR;
7059                         goto bareword;
7060                     }
7061                 }
7062
7063                 PL_expect = XOPERATOR;
7064                 s = skipspace(s);
7065
7066                 /* Is this a word before a => operator? */
7067                 if (*s == '=' && s[1] == '>' && !pkgname) {
7068                     op_free(rv2cv_op);
7069                     CLINE;
7070                     if (gvp || (lex && !off)) {
7071                         assert (cSVOPx(pl_yylval.opval)->op_sv == sv);
7072                         /* This is our own scalar, created a few lines
7073                            above, so this is safe. */
7074                         SvREADONLY_off(sv);
7075                         sv_setpv(sv, PL_tokenbuf);
7076                         if (UTF && !IN_BYTES
7077                          && is_utf8_string((U8*)PL_tokenbuf, len))
7078                               SvUTF8_on(sv);
7079                         SvREADONLY_on(sv);
7080                     }
7081                     TERM(BAREWORD);
7082                 }
7083
7084                 /* If followed by a paren, it's certainly a subroutine. */
7085                 if (*s == '(') {
7086                     CLINE;
7087                     if (cv) {
7088                         d = s + 1;
7089                         while (SPACE_OR_TAB(*d))
7090                             d++;
7091                         if (*d == ')' && (sv = cv_const_sv_or_av(cv))) {
7092                             s = d + 1;
7093                             goto its_constant;
7094                         }
7095                     }
7096                     NEXTVAL_NEXTTOKE.opval =
7097                         off ? rv2cv_op : pl_yylval.opval;
7098                     if (off)
7099                          op_free(pl_yylval.opval), force_next(PRIVATEREF);
7100                     else op_free(rv2cv_op),        force_next(BAREWORD);
7101                     pl_yylval.ival = 0;
7102                     TOKEN('&');
7103                 }
7104
7105                 /* If followed by var or block, call it a method (unless sub) */
7106
7107                 if ((*s == '$' || *s == '{') && !cv) {
7108                     op_free(rv2cv_op);
7109                     PL_last_lop = PL_oldbufptr;
7110                     PL_last_lop_op = OP_METHOD;
7111                     if (!PL_lex_allbrackets
7112                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7113                     {
7114                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7115                     }
7116                     PL_expect = XBLOCKTERM;
7117                     PL_bufptr = s;
7118                     return REPORT(METHOD);
7119                 }
7120
7121                 /* If followed by a bareword, see if it looks like indir obj. */
7122
7123                 if (tmp == 1 && !orig_keyword
7124                         && (isIDFIRST_lazy_if(s,UTF) || *s == '$')
7125                         && (tmp = intuit_method(s, lex ? NULL : sv, cv))) {
7126                   method:
7127                     if (lex && !off) {
7128                         assert(cSVOPx(pl_yylval.opval)->op_sv == sv);
7129                         SvREADONLY_off(sv);
7130                         sv_setpvn(sv, PL_tokenbuf, len);
7131                         if (UTF && !IN_BYTES
7132                          && is_utf8_string((U8*)PL_tokenbuf, len))
7133                             SvUTF8_on (sv);
7134                         else SvUTF8_off(sv);
7135                     }
7136                     op_free(rv2cv_op);
7137                     if (tmp == METHOD && !PL_lex_allbrackets
7138                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7139                     {
7140                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7141                     }
7142                     return REPORT(tmp);
7143                 }
7144
7145                 /* Not a method, so call it a subroutine (if defined) */
7146
7147                 if (cv) {
7148                     /* Check for a constant sub */
7149                     if ((sv = cv_const_sv_or_av(cv))) {
7150                   its_constant:
7151                         op_free(rv2cv_op);
7152                         SvREFCNT_dec(((SVOP*)pl_yylval.opval)->op_sv);
7153                         ((SVOP*)pl_yylval.opval)->op_sv = SvREFCNT_inc_simple(sv);
7154                         if (SvTYPE(sv) == SVt_PVAV)
7155                             pl_yylval.opval = newUNOP(OP_RV2AV, OPf_PARENS,
7156                                                       pl_yylval.opval);
7157                         else {
7158                             pl_yylval.opval->op_private = 0;
7159                             pl_yylval.opval->op_folded = 1;
7160                             pl_yylval.opval->op_flags |= OPf_SPECIAL;
7161                         }
7162                         TOKEN(BAREWORD);
7163                     }
7164
7165                     op_free(pl_yylval.opval);
7166                     pl_yylval.opval =
7167                         off ? (OP *)newCVREF(0, rv2cv_op) : rv2cv_op;
7168                     pl_yylval.opval->op_private |= OPpENTERSUB_NOPAREN;
7169                     PL_last_lop = PL_oldbufptr;
7170                     PL_last_lop_op = OP_ENTERSUB;
7171                     /* Is there a prototype? */
7172                     if (
7173                         SvPOK(cv))
7174                     {
7175                         STRLEN protolen = CvPROTOLEN(cv);
7176                         const char *proto = CvPROTO(cv);
7177                         bool optional;
7178                         proto = S_strip_spaces(aTHX_ proto, &protolen);
7179                         if (!protolen)
7180                             TERM(FUNC0SUB);
7181                         if ((optional = *proto == ';'))
7182                           do
7183                             proto++;
7184                           while (*proto == ';');
7185                         if (
7186                             (
7187                                 (
7188                                     *proto == '$' || *proto == '_'
7189                                  || *proto == '*' || *proto == '+'
7190                                 )
7191                              && proto[1] == '\0'
7192                             )
7193                          || (
7194                              *proto == '\\' && proto[1] && proto[2] == '\0'
7195                             )
7196                         )
7197                             UNIPROTO(UNIOPSUB,optional);
7198                         if (*proto == '\\' && proto[1] == '[') {
7199                             const char *p = proto + 2;
7200                             while(*p && *p != ']')
7201                                 ++p;
7202                             if(*p == ']' && !p[1])
7203                                 UNIPROTO(UNIOPSUB,optional);
7204                         }
7205                         if (*proto == '&' && *s == '{') {
7206                             if (PL_curstash)
7207                                 sv_setpvs(PL_subname, "__ANON__");
7208                             else
7209                                 sv_setpvs(PL_subname, "__ANON__::__ANON__");
7210                             if (!PL_lex_allbrackets
7211                                 && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7212                             {
7213                                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7214                             }
7215                             PREBLOCK(LSTOPSUB);
7216                         }
7217                     }
7218                     NEXTVAL_NEXTTOKE.opval = pl_yylval.opval;
7219                     PL_expect = XTERM;
7220                     force_next(off ? PRIVATEREF : BAREWORD);
7221                     if (!PL_lex_allbrackets
7222                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7223                     {
7224                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7225                     }
7226                     TOKEN(NOAMP);
7227                 }
7228
7229                 /* Call it a bare word */
7230
7231                 if (PL_hints & HINT_STRICT_SUBS)
7232                     pl_yylval.opval->op_private |= OPpCONST_STRICT;
7233                 else {
7234                 bareword:
7235                     /* after "print" and similar functions (corresponding to
7236                      * "F? L" in opcode.pl), whatever wasn't already parsed as
7237                      * a filehandle should be subject to "strict subs".
7238                      * Likewise for the optional indirect-object argument to system
7239                      * or exec, which can't be a bareword */
7240                     if ((PL_last_lop_op == OP_PRINT
7241                             || PL_last_lop_op == OP_PRTF
7242                             || PL_last_lop_op == OP_SAY
7243                             || PL_last_lop_op == OP_SYSTEM
7244                             || PL_last_lop_op == OP_EXEC)
7245                             && (PL_hints & HINT_STRICT_SUBS))
7246                         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7247                     if (lastchar != '-') {
7248                         if (ckWARN(WARN_RESERVED)) {
7249                             d = PL_tokenbuf;
7250                             while (isLOWER(*d))
7251                                 d++;
7252                             if (!*d && !gv_stashpv(PL_tokenbuf, UTF ? SVf_UTF8 : 0))
7253                             {
7254                                 /* PL_warn_reserved is constant */
7255                                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
7256                                 Perl_warner(aTHX_ packWARN(WARN_RESERVED), PL_warn_reserved,
7257                                        PL_tokenbuf);
7258                                 GCC_DIAG_RESTORE;
7259                             }
7260                         }
7261                     }
7262                 }
7263                 op_free(rv2cv_op);
7264
7265             safe_bareword:
7266                 if ((lastchar == '*' || lastchar == '%' || lastchar == '&')
7267                  && saw_infix_sigil) {
7268                     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7269                                      "Operator or semicolon missing before %c%"UTF8f,
7270                                      lastchar,
7271                                      UTF8fARG(UTF, strlen(PL_tokenbuf),
7272                                               PL_tokenbuf));
7273                     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7274                                      "Ambiguous use of %c resolved as operator %c",
7275                                      lastchar, lastchar);
7276                 }
7277                 TOKEN(BAREWORD);
7278             }
7279
7280         case KEY___FILE__:
7281             FUN0OP(
7282                 (OP*)newSVOP(OP_CONST, 0, newSVpv(CopFILE(PL_curcop),0))
7283             );
7284
7285         case KEY___LINE__:
7286             FUN0OP(
7287                 (OP*)newSVOP(OP_CONST, 0,
7288                     Perl_newSVpvf(aTHX_ "%"IVdf, (IV)CopLINE(PL_curcop)))
7289             );
7290
7291         case KEY___PACKAGE__:
7292             FUN0OP(
7293                 (OP*)newSVOP(OP_CONST, 0,
7294                                         (PL_curstash
7295                                          ? newSVhek(HvNAME_HEK(PL_curstash))
7296                                          : &PL_sv_undef))
7297             );
7298
7299         case KEY___DATA__:
7300         case KEY___END__: {
7301             GV *gv;
7302             if (PL_rsfp && (!PL_in_eval || PL_tokenbuf[2] == 'D')) {
7303                 HV * const stash = PL_tokenbuf[2] == 'D' && PL_curstash
7304                                         ? PL_curstash
7305                                         : PL_defstash;
7306                 gv = (GV *)*hv_fetchs(stash, "DATA", 1);
7307                 if (!isGV(gv))
7308                     gv_init(gv,stash,"DATA",4,0);
7309                 GvMULTI_on(gv);
7310                 if (!GvIO(gv))
7311                     GvIOp(gv) = newIO();
7312                 IoIFP(GvIOp(gv)) = PL_rsfp;
7313 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
7314                 {
7315                     const int fd = PerlIO_fileno(PL_rsfp);
7316                     if (fd >= 3) {
7317                         fcntl(fd,F_SETFD, FD_CLOEXEC);
7318                     }
7319                 }
7320 #endif
7321                 /* Mark this internal pseudo-handle as clean */
7322                 IoFLAGS(GvIOp(gv)) |= IOf_UNTAINT;
7323                 if ((PerlIO*)PL_rsfp == PerlIO_stdin())
7324                     IoTYPE(GvIOp(gv)) = IoTYPE_STD;
7325                 else
7326                     IoTYPE(GvIOp(gv)) = IoTYPE_RDONLY;
7327 #if defined(WIN32) && !defined(PERL_TEXTMODE_SCRIPTS)
7328                 /* if the script was opened in binmode, we need to revert
7329                  * it to text mode for compatibility; but only iff it has CRs
7330                  * XXX this is a questionable hack at best. */
7331                 if (PL_bufend-PL_bufptr > 2
7332                     && PL_bufend[-1] == '\n' && PL_bufend[-2] == '\r')
7333                 {
7334                     Off_t loc = 0;
7335                     if (IoTYPE(GvIOp(gv)) == IoTYPE_RDONLY) {
7336                         loc = PerlIO_tell(PL_rsfp);
7337                         (void)PerlIO_seek(PL_rsfp, 0L, 0);
7338                     }
7339 #ifdef NETWARE
7340                         if (PerlLIO_setmode(PL_rsfp, O_TEXT) != -1) {
7341 #else
7342                     if (PerlLIO_setmode(PerlIO_fileno(PL_rsfp), O_TEXT) != -1) {
7343 #endif  /* NETWARE */
7344                         if (loc > 0)
7345                             PerlIO_seek(PL_rsfp, loc, 0);
7346                     }
7347                 }
7348 #endif
7349 #ifdef PERLIO_LAYERS
7350                 if (!IN_BYTES) {
7351                     if (UTF)
7352                         PerlIO_apply_layers(aTHX_ PL_rsfp, NULL, ":utf8");
7353                 }
7354 #endif
7355                 PL_rsfp = NULL;
7356             }
7357             goto fake_eof;
7358         }
7359
7360         case KEY___SUB__:
7361             FUN0OP(CvCLONE(PL_compcv)
7362                         ? newOP(OP_RUNCV, 0)
7363                         : newPVOP(OP_RUNCV,0,NULL));
7364
7365         case KEY_AUTOLOAD:
7366         case KEY_DESTROY:
7367         case KEY_BEGIN:
7368         case KEY_UNITCHECK:
7369         case KEY_CHECK:
7370         case KEY_INIT:
7371         case KEY_END:
7372             if (PL_expect == XSTATE) {
7373                 s = PL_bufptr;
7374                 goto really_sub;
7375             }
7376             goto just_a_word;
7377
7378         case_KEY_CORE:
7379             {
7380                 STRLEN olen = len;
7381                 d = s;
7382                 s += 2;
7383                 s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
7384                 if ((*s == ':' && s[1] == ':')
7385                  || (!(tmp = keyword(PL_tokenbuf, len, 1)) && *s == '\''))
7386                 {
7387                     s = d;
7388                     len = olen;
7389                     Copy(PL_bufptr, PL_tokenbuf, olen, char);
7390                     goto just_a_word;
7391                 }
7392                 if (!tmp)
7393                     Perl_croak(aTHX_ "CORE::%"UTF8f" is not a keyword",
7394                                       UTF8fARG(UTF, len, PL_tokenbuf));
7395                 if (tmp < 0)
7396                     tmp = -tmp;
7397                 else if (tmp == KEY_require || tmp == KEY_do
7398                       || tmp == KEY_glob)
7399                     /* that's a way to remember we saw "CORE::" */
7400                     orig_keyword = tmp;
7401                 goto reserved_word;
7402             }
7403
7404         case KEY_abs:
7405             UNI(OP_ABS);
7406
7407         case KEY_alarm:
7408             UNI(OP_ALARM);
7409
7410         case KEY_accept:
7411             LOP(OP_ACCEPT,XTERM);
7412
7413         case KEY_and:
7414             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7415                 return REPORT(0);
7416             OPERATOR(ANDOP);
7417
7418         case KEY_atan2:
7419             LOP(OP_ATAN2,XTERM);
7420
7421         case KEY_bind:
7422             LOP(OP_BIND,XTERM);
7423
7424         case KEY_binmode:
7425             LOP(OP_BINMODE,XTERM);
7426
7427         case KEY_bless:
7428             LOP(OP_BLESS,XTERM);
7429
7430         case KEY_break:
7431             FUN0(OP_BREAK);
7432
7433         case KEY_chop:
7434             UNI(OP_CHOP);
7435
7436         case KEY_continue:
7437                     /* We have to disambiguate the two senses of
7438                       "continue". If the next token is a '{' then
7439                       treat it as the start of a continue block;
7440                       otherwise treat it as a control operator.
7441                      */
7442                     s = skipspace(s);
7443                     if (*s == '{')
7444             PREBLOCK(CONTINUE);
7445                     else
7446                         FUN0(OP_CONTINUE);
7447
7448         case KEY_chdir:
7449             /* may use HOME */
7450             (void)gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV);
7451             UNI(OP_CHDIR);
7452
7453         case KEY_close:
7454             UNI(OP_CLOSE);
7455
7456         case KEY_closedir:
7457             UNI(OP_CLOSEDIR);
7458
7459         case KEY_cmp:
7460             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7461                 return REPORT(0);
7462             Eop(OP_SCMP);
7463
7464         case KEY_caller:
7465             UNI(OP_CALLER);
7466
7467         case KEY_crypt:
7468 #ifdef FCRYPT
7469             if (!PL_cryptseen) {
7470                 PL_cryptseen = TRUE;
7471                 init_des();
7472             }
7473 #endif
7474             LOP(OP_CRYPT,XTERM);
7475
7476         case KEY_chmod:
7477             LOP(OP_CHMOD,XTERM);
7478
7479         case KEY_chown:
7480             LOP(OP_CHOWN,XTERM);
7481
7482         case KEY_connect:
7483             LOP(OP_CONNECT,XTERM);
7484
7485         case KEY_chr:
7486             UNI(OP_CHR);
7487
7488         case KEY_cos:
7489             UNI(OP_COS);
7490
7491         case KEY_chroot:
7492             UNI(OP_CHROOT);
7493
7494         case KEY_default:
7495             PREBLOCK(DEFAULT);
7496
7497         case KEY_do:
7498             s = skipspace(s);
7499             if (*s == '{')
7500                 PRETERMBLOCK(DO);
7501             if (*s != '\'') {
7502                 *PL_tokenbuf = '&';
7503                 d = scan_word(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
7504                               1, &len);
7505                 if (len && (len != 4 || strNE(PL_tokenbuf+1, "CORE"))
7506                  && !keyword(PL_tokenbuf + 1, len, 0)) {
7507                     SSize_t off = s-SvPVX(PL_linestr);
7508                     d = skipspace(d);
7509                     s = SvPVX(PL_linestr)+off;
7510                     if (*d == '(') {
7511                         force_ident_maybe_lex('&');
7512                         s = d;
7513                     }
7514                 }
7515             }
7516             if (orig_keyword == KEY_do) {
7517                 orig_keyword = 0;
7518                 pl_yylval.ival = 1;
7519             }
7520             else
7521                 pl_yylval.ival = 0;
7522             OPERATOR(DO);
7523
7524         case KEY_die:
7525             PL_hints |= HINT_BLOCK_SCOPE;
7526             LOP(OP_DIE,XTERM);
7527
7528         case KEY_defined:
7529             UNI(OP_DEFINED);
7530
7531         case KEY_delete:
7532             UNI(OP_DELETE);
7533
7534         case KEY_dbmopen:
7535             Perl_populate_isa(aTHX_ STR_WITH_LEN("AnyDBM_File::ISA"),
7536                               STR_WITH_LEN("NDBM_File::"),
7537                               STR_WITH_LEN("DB_File::"),
7538                               STR_WITH_LEN("GDBM_File::"),
7539                               STR_WITH_LEN("SDBM_File::"),
7540                               STR_WITH_LEN("ODBM_File::"),
7541                               NULL);
7542             LOP(OP_DBMOPEN,XTERM);
7543
7544         case KEY_dbmclose:
7545             UNI(OP_DBMCLOSE);
7546
7547         case KEY_dump:
7548             LOOPX(OP_DUMP);
7549
7550         case KEY_else:
7551             PREBLOCK(ELSE);
7552
7553         case KEY_elsif:
7554             pl_yylval.ival = CopLINE(PL_curcop);
7555             OPERATOR(ELSIF);
7556
7557         case KEY_eq:
7558             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7559                 return REPORT(0);
7560             Eop(OP_SEQ);
7561
7562         case KEY_exists:
7563             UNI(OP_EXISTS);
7564         
7565         case KEY_exit:
7566             UNI(OP_EXIT);
7567
7568         case KEY_eval:
7569             s = skipspace(s);
7570             if (*s == '{') { /* block eval */
7571                 PL_expect = XTERMBLOCK;
7572                 UNIBRACK(OP_ENTERTRY);
7573             }
7574             else { /* string eval */
7575                 PL_expect = XTERM;
7576                 UNIBRACK(OP_ENTEREVAL);
7577             }
7578
7579         case KEY_evalbytes:
7580             PL_expect = XTERM;
7581             UNIBRACK(-OP_ENTEREVAL);
7582
7583         case KEY_eof:
7584             UNI(OP_EOF);
7585
7586         case KEY_exp:
7587             UNI(OP_EXP);
7588
7589         case KEY_each:
7590             UNI(OP_EACH);
7591
7592         case KEY_exec:
7593             LOP(OP_EXEC,XREF);
7594
7595         case KEY_endhostent:
7596             FUN0(OP_EHOSTENT);
7597
7598         case KEY_endnetent:
7599             FUN0(OP_ENETENT);
7600
7601         case KEY_endservent:
7602             FUN0(OP_ESERVENT);
7603
7604         case KEY_endprotoent:
7605             FUN0(OP_EPROTOENT);
7606
7607         case KEY_endpwent:
7608             FUN0(OP_EPWENT);
7609
7610         case KEY_endgrent:
7611             FUN0(OP_EGRENT);
7612
7613         case KEY_for:
7614         case KEY_foreach:
7615             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7616                 return REPORT(0);
7617             pl_yylval.ival = CopLINE(PL_curcop);
7618             s = skipspace(s);
7619             if (PL_expect == XSTATE && isIDFIRST_lazy_if(s,UTF)) {
7620                 char *p = s;
7621
7622                 if ((PL_bufend - p) >= 3
7623                     && strEQs(p, "my") && isSPACE(*(p + 2)))
7624                 {
7625                     p += 2;
7626                 }
7627                 else if ((PL_bufend - p) >= 4
7628                          && strEQs(p, "our") && isSPACE(*(p + 3)))
7629                     p += 3;
7630                 p = skipspace(p);
7631                 /* skip optional package name, as in "for my abc $x (..)" */
7632                 if (isIDFIRST_lazy_if(p,UTF)) {
7633                     p = scan_word(p, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
7634                     p = skipspace(p);
7635                 }
7636                 if (*p != '$' && *p != '\\')
7637                     Perl_croak(aTHX_ "Missing $ on loop variable");
7638             }
7639             OPERATOR(FOR);
7640
7641         case KEY_formline:
7642             LOP(OP_FORMLINE,XTERM);
7643
7644         case KEY_fork:
7645             FUN0(OP_FORK);
7646
7647         case KEY_fc:
7648             UNI(OP_FC);
7649
7650         case KEY_fcntl:
7651             LOP(OP_FCNTL,XTERM);
7652
7653         case KEY_fileno:
7654             UNI(OP_FILENO);
7655
7656         case KEY_flock:
7657             LOP(OP_FLOCK,XTERM);
7658
7659         case KEY_gt:
7660             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7661                 return REPORT(0);
7662             Rop(OP_SGT);
7663
7664         case KEY_ge:
7665             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7666                 return REPORT(0);
7667             Rop(OP_SGE);
7668
7669         case KEY_grep:
7670             LOP(OP_GREPSTART, XREF);
7671
7672         case KEY_goto:
7673             LOOPX(OP_GOTO);
7674
7675         case KEY_gmtime:
7676             UNI(OP_GMTIME);
7677
7678         case KEY_getc:
7679             UNIDOR(OP_GETC);
7680
7681         case KEY_getppid:
7682             FUN0(OP_GETPPID);
7683
7684         case KEY_getpgrp:
7685             UNI(OP_GETPGRP);
7686
7687         case KEY_getpriority:
7688             LOP(OP_GETPRIORITY,XTERM);
7689
7690         case KEY_getprotobyname:
7691             UNI(OP_GPBYNAME);
7692
7693         case KEY_getprotobynumber:
7694             LOP(OP_GPBYNUMBER,XTERM);
7695
7696         case KEY_getprotoent:
7697             FUN0(OP_GPROTOENT);
7698
7699         case KEY_getpwent:
7700             FUN0(OP_GPWENT);
7701
7702         case KEY_getpwnam:
7703             UNI(OP_GPWNAM);
7704
7705         case KEY_getpwuid:
7706             UNI(OP_GPWUID);
7707
7708         case KEY_getpeername:
7709             UNI(OP_GETPEERNAME);
7710
7711         case KEY_gethostbyname:
7712             UNI(OP_GHBYNAME);
7713
7714         case KEY_gethostbyaddr:
7715             LOP(OP_GHBYADDR,XTERM);
7716
7717         case KEY_gethostent:
7718             FUN0(OP_GHOSTENT);
7719
7720         case KEY_getnetbyname:
7721             UNI(OP_GNBYNAME);
7722
7723         case KEY_getnetbyaddr:
7724             LOP(OP_GNBYADDR,XTERM);
7725
7726         case KEY_getnetent:
7727             FUN0(OP_GNETENT);
7728
7729         case KEY_getservbyname:
7730             LOP(OP_GSBYNAME,XTERM);
7731
7732         case KEY_getservbyport:
7733             LOP(OP_GSBYPORT,XTERM);
7734
7735         case KEY_getservent:
7736             FUN0(OP_GSERVENT);
7737
7738         case KEY_getsockname:
7739             UNI(OP_GETSOCKNAME);
7740
7741         case KEY_getsockopt:
7742             LOP(OP_GSOCKOPT,XTERM);
7743
7744         case KEY_getgrent:
7745             FUN0(OP_GGRENT);
7746
7747         case KEY_getgrnam:
7748             UNI(OP_GGRNAM);
7749
7750         case KEY_getgrgid:
7751             UNI(OP_GGRGID);
7752
7753         case KEY_getlogin:
7754             FUN0(OP_GETLOGIN);
7755
7756         case KEY_given:
7757             pl_yylval.ival = CopLINE(PL_curcop);
7758             Perl_ck_warner_d(aTHX_
7759                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
7760                 "given is experimental");
7761             OPERATOR(GIVEN);
7762
7763         case KEY_glob:
7764             LOP(
7765              orig_keyword==KEY_glob ? -OP_GLOB : OP_GLOB,
7766              XTERM
7767             );
7768
7769         case KEY_hex:
7770             UNI(OP_HEX);
7771
7772         case KEY_if:
7773             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7774                 return REPORT(0);
7775             pl_yylval.ival = CopLINE(PL_curcop);
7776             OPERATOR(IF);
7777
7778         case KEY_index:
7779             LOP(OP_INDEX,XTERM);
7780
7781         case KEY_int:
7782             UNI(OP_INT);
7783
7784         case KEY_ioctl:
7785             LOP(OP_IOCTL,XTERM);
7786
7787         case KEY_join:
7788             LOP(OP_JOIN,XTERM);
7789
7790         case KEY_keys:
7791             UNI(OP_KEYS);
7792
7793         case KEY_kill:
7794             LOP(OP_KILL,XTERM);
7795
7796         case KEY_last:
7797             LOOPX(OP_LAST);
7798         
7799         case KEY_lc:
7800             UNI(OP_LC);
7801
7802         case KEY_lcfirst:
7803             UNI(OP_LCFIRST);
7804
7805         case KEY_local:
7806             OPERATOR(LOCAL);
7807
7808         case KEY_length:
7809             UNI(OP_LENGTH);
7810
7811         case KEY_lt:
7812             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7813                 return REPORT(0);
7814             Rop(OP_SLT);
7815
7816         case KEY_le:
7817             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7818                 return REPORT(0);
7819             Rop(OP_SLE);
7820
7821         case KEY_localtime:
7822             UNI(OP_LOCALTIME);
7823
7824         case KEY_log:
7825             UNI(OP_LOG);
7826
7827         case KEY_link:
7828             LOP(OP_LINK,XTERM);
7829
7830         case KEY_listen:
7831             LOP(OP_LISTEN,XTERM);
7832
7833         case KEY_lock:
7834             UNI(OP_LOCK);
7835
7836         case KEY_lstat:
7837             UNI(OP_LSTAT);
7838
7839         case KEY_m:
7840             s = scan_pat(s,OP_MATCH);
7841             TERM(sublex_start());
7842
7843         case KEY_map:
7844             LOP(OP_MAPSTART, XREF);
7845
7846         case KEY_mkdir:
7847             LOP(OP_MKDIR,XTERM);
7848
7849         case KEY_msgctl:
7850             LOP(OP_MSGCTL,XTERM);
7851
7852         case KEY_msgget:
7853             LOP(OP_MSGGET,XTERM);
7854
7855         case KEY_msgrcv:
7856             LOP(OP_MSGRCV,XTERM);
7857
7858         case KEY_msgsnd:
7859             LOP(OP_MSGSND,XTERM);
7860
7861         case KEY_our:
7862         case KEY_my:
7863         case KEY_state:
7864             if (PL_in_my) {
7865                 PL_bufptr = s;
7866                 yyerror(Perl_form(aTHX_
7867                                   "Can't redeclare \"%s\" in \"%s\"",
7868                                    tmp      == KEY_my    ? "my" :
7869                                    tmp      == KEY_state ? "state" : "our",
7870                                    PL_in_my == KEY_my    ? "my" :
7871                                    PL_in_my == KEY_state ? "state" : "our"));
7872             }
7873             PL_in_my = (U16)tmp;
7874             s = skipspace(s);
7875             if (isIDFIRST_lazy_if(s,UTF)) {
7876                 s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
7877                 if (len == 3 && strEQs(PL_tokenbuf, "sub"))
7878                     goto really_sub;
7879                 PL_in_my_stash = find_in_my_stash(PL_tokenbuf, len);
7880                 if (!PL_in_my_stash) {
7881                     char tmpbuf[1024];
7882                     int len;
7883                     PL_bufptr = s;
7884                     len = my_snprintf(tmpbuf, sizeof(tmpbuf), "No such class %.1000s", PL_tokenbuf);
7885                     PERL_MY_SNPRINTF_POST_GUARD(len, sizeof(tmpbuf));
7886                     yyerror_pv(tmpbuf, UTF ? SVf_UTF8 : 0);
7887                 }
7888             }
7889             else if (*s == '\\') {
7890                 if (!FEATURE_MYREF_IS_ENABLED)
7891                     Perl_croak(aTHX_ "The experimental declared_refs "
7892                                      "feature is not enabled");
7893                 Perl_ck_warner_d(aTHX_
7894                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
7895                     "Declaring references is experimental");
7896             }
7897             OPERATOR(MY);
7898
7899         case KEY_next:
7900             LOOPX(OP_NEXT);
7901
7902         case KEY_ne:
7903             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7904                 return REPORT(0);
7905             Eop(OP_SNE);
7906
7907         case KEY_no:
7908             s = tokenize_use(0, s);
7909             TOKEN(USE);
7910
7911         case KEY_not:
7912             if (*s == '(' || (s = skipspace(s), *s == '('))
7913                 FUN1(OP_NOT);
7914             else {
7915                 if (!PL_lex_allbrackets
7916                     && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7917                 {
7918                     PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7919                 }
7920                 OPERATOR(NOTOP);
7921             }
7922
7923         case KEY_open:
7924             s = skipspace(s);
7925             if (isIDFIRST_lazy_if(s,UTF)) {
7926           const char *t;
7927           d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE,
7928               &len);
7929                 for (t=d; isSPACE(*t);)
7930                     t++;
7931                 if ( *t && strchr("|&*+-=!?:.", *t) && ckWARN_d(WARN_PRECEDENCE)
7932                     /* [perl #16184] */
7933                     && !(t[0] == '=' && t[1] == '>')
7934                     && !(t[0] == ':' && t[1] == ':')
7935                     && !keyword(s, d-s, 0)
7936                 ) {
7937                     Perl_warner(aTHX_ packWARN(WARN_PRECEDENCE),
7938                        "Precedence problem: open %"UTF8f" should be open(%"UTF8f")",
7939                         UTF8fARG(UTF, d-s, s), UTF8fARG(UTF, d-s, s));
7940                 }
7941             }
7942             LOP(OP_OPEN,XTERM);
7943
7944         case KEY_or:
7945             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7946                 return REPORT(0);
7947             pl_yylval.ival = OP_OR;
7948             OPERATOR(OROP);
7949
7950         case KEY_ord:
7951             UNI(OP_ORD);
7952
7953         case KEY_oct:
7954             UNI(OP_OCT);
7955
7956         case KEY_opendir:
7957             LOP(OP_OPEN_DIR,XTERM);
7958
7959         case KEY_print:
7960             checkcomma(s,PL_tokenbuf,"filehandle");
7961             LOP(OP_PRINT,XREF);
7962
7963         case KEY_printf:
7964             checkcomma(s,PL_tokenbuf,"filehandle");
7965             LOP(OP_PRTF,XREF);
7966
7967         case KEY_prototype:
7968             UNI(OP_PROTOTYPE);
7969
7970         case KEY_push:
7971             LOP(OP_PUSH,XTERM);
7972
7973         case KEY_pop:
7974             UNIDOR(OP_POP);
7975
7976         case KEY_pos:
7977             UNIDOR(OP_POS);
7978         
7979         case KEY_pack:
7980             LOP(OP_PACK,XTERM);
7981
7982         case KEY_package:
7983             s = force_word(s,BAREWORD,FALSE,TRUE);
7984             s = skipspace(s);
7985             s = force_strict_version(s);
7986             PREBLOCK(PACKAGE);
7987
7988         case KEY_pipe:
7989             LOP(OP_PIPE_OP,XTERM);
7990
7991         case KEY_q:
7992             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
7993             if (!s)
7994                 missingterm(NULL);
7995             COPLINE_SET_FROM_MULTI_END;
7996             pl_yylval.ival = OP_CONST;
7997             TERM(sublex_start());
7998
7999         case KEY_quotemeta:
8000             UNI(OP_QUOTEMETA);
8001
8002         case KEY_qw: {
8003             OP *words = NULL;
8004             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8005             if (!s)
8006                 missingterm(NULL);
8007             COPLINE_SET_FROM_MULTI_END;
8008             PL_expect = XOPERATOR;
8009             if (SvCUR(PL_lex_stuff)) {
8010                 int warned_comma = !ckWARN(WARN_QW);
8011                 int warned_comment = warned_comma;
8012                 d = SvPV_force(PL_lex_stuff, len);
8013                 while (len) {
8014                     for (; isSPACE(*d) && len; --len, ++d)
8015                         /**/;
8016                     if (len) {
8017                         SV *sv;
8018                         const char *b = d;
8019                         if (!warned_comma || !warned_comment) {
8020                             for (; !isSPACE(*d) && len; --len, ++d) {
8021                                 if (!warned_comma && *d == ',') {
8022                                     Perl_warner(aTHX_ packWARN(WARN_QW),
8023                                         "Possible attempt to separate words with commas");
8024                                     ++warned_comma;
8025                                 }
8026                                 else if (!warned_comment && *d == '#') {
8027                                     Perl_warner(aTHX_ packWARN(WARN_QW),
8028                                         "Possible attempt to put comments in qw() list");
8029                                     ++warned_comment;
8030                                 }
8031                             }
8032                         }
8033                         else {
8034                             for (; !isSPACE(*d) && len; --len, ++d)
8035                                 /**/;
8036                         }
8037                         sv = newSVpvn_utf8(b, d-b, DO_UTF8(PL_lex_stuff));
8038                         words = op_append_elem(OP_LIST, words,
8039                                             newSVOP(OP_CONST, 0, tokeq(sv)));
8040                     }
8041                 }
8042             }
8043             if (!words)
8044                 words = newNULLLIST();
8045             SvREFCNT_dec_NN(PL_lex_stuff);
8046             PL_lex_stuff = NULL;
8047             PL_expect = XOPERATOR;
8048             pl_yylval.opval = sawparens(words);
8049             TOKEN(QWLIST);
8050         }
8051
8052         case KEY_qq:
8053             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8054             if (!s)
8055                 missingterm(NULL);
8056             pl_yylval.ival = OP_STRINGIFY;
8057             if (SvIVX(PL_lex_stuff) == '\'')
8058                 SvIV_set(PL_lex_stuff, 0);      /* qq'$foo' should interpolate */
8059             TERM(sublex_start());
8060
8061         case KEY_qr:
8062             s = scan_pat(s,OP_QR);
8063             TERM(sublex_start());
8064
8065         case KEY_qx:
8066             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8067             if (!s)
8068                 missingterm(NULL);
8069             pl_yylval.ival = OP_BACKTICK;
8070             TERM(sublex_start());
8071
8072         case KEY_return:
8073             OLDLOP(OP_RETURN);
8074
8075         case KEY_require:
8076             s = skipspace(s);
8077             if (isDIGIT(*s)) {
8078                 s = force_version(s, FALSE);
8079             }
8080             else if (*s != 'v' || !isDIGIT(s[1])
8081                     || (s = force_version(s, TRUE), *s == 'v'))
8082             {
8083                 *PL_tokenbuf = '\0';
8084                 s = force_word(s,BAREWORD,TRUE,TRUE);
8085                 if (isIDFIRST_lazy_if(PL_tokenbuf,UTF))
8086                     gv_stashpvn(PL_tokenbuf, strlen(PL_tokenbuf),
8087                                 GV_ADD | (UTF ? SVf_UTF8 : 0));
8088                 else if (*s == '<')
8089                     yyerror("<> at require-statement should be quotes");
8090             }
8091             if (orig_keyword == KEY_require) {
8092                 orig_keyword = 0;
8093                 pl_yylval.ival = 1;
8094             }
8095             else 
8096                 pl_yylval.ival = 0;
8097             PL_expect = PL_nexttoke ? XOPERATOR : XTERM;
8098             PL_bufptr = s;
8099             PL_last_uni = PL_oldbufptr;
8100             PL_last_lop_op = OP_REQUIRE;
8101             s = skipspace(s);
8102             return REPORT( (int)REQUIRE );
8103
8104         case KEY_reset:
8105             UNI(OP_RESET);
8106
8107         case KEY_redo:
8108             LOOPX(OP_REDO);
8109
8110         case KEY_rename:
8111             LOP(OP_RENAME,XTERM);
8112
8113         case KEY_rand:
8114             UNI(OP_RAND);
8115
8116         case KEY_rmdir:
8117             UNI(OP_RMDIR);
8118
8119         case KEY_rindex:
8120             LOP(OP_RINDEX,XTERM);
8121
8122         case KEY_read:
8123             LOP(OP_READ,XTERM);
8124
8125         case KEY_readdir:
8126             UNI(OP_READDIR);
8127
8128         case KEY_readline:
8129             UNIDOR(OP_READLINE);
8130
8131         case KEY_readpipe:
8132             UNIDOR(OP_BACKTICK);
8133
8134         case KEY_rewinddir:
8135             UNI(OP_REWINDDIR);
8136
8137         case KEY_recv:
8138             LOP(OP_RECV,XTERM);
8139
8140         case KEY_reverse:
8141             LOP(OP_REVERSE,XTERM);
8142
8143         case KEY_readlink:
8144             UNIDOR(OP_READLINK);
8145
8146         case KEY_ref:
8147             UNI(OP_REF);
8148
8149         case KEY_s:
8150             s = scan_subst(s);
8151             if (pl_yylval.opval)
8152                 TERM(sublex_start());
8153             else
8154                 TOKEN(1);       /* force error */
8155
8156         case KEY_say:
8157             checkcomma(s,PL_tokenbuf,"filehandle");
8158             LOP(OP_SAY,XREF);
8159
8160         case KEY_chomp:
8161             UNI(OP_CHOMP);
8162         
8163         case KEY_scalar:
8164             UNI(OP_SCALAR);
8165
8166         case KEY_select:
8167             LOP(OP_SELECT,XTERM);
8168
8169         case KEY_seek:
8170             LOP(OP_SEEK,XTERM);
8171
8172         case KEY_semctl:
8173             LOP(OP_SEMCTL,XTERM);
8174
8175         case KEY_semget:
8176             LOP(OP_SEMGET,XTERM);
8177
8178         case KEY_semop:
8179             LOP(OP_SEMOP,XTERM);
8180
8181         case KEY_send:
8182             LOP(OP_SEND,XTERM);
8183
8184         case KEY_setpgrp:
8185             LOP(OP_SETPGRP,XTERM);
8186
8187         case KEY_setpriority:
8188             LOP(OP_SETPRIORITY,XTERM);
8189
8190         case KEY_sethostent:
8191             UNI(OP_SHOSTENT);
8192
8193         case KEY_setnetent:
8194             UNI(OP_SNETENT);
8195
8196         case KEY_setservent:
8197             UNI(OP_SSERVENT);
8198
8199         case KEY_setprotoent:
8200             UNI(OP_SPROTOENT);
8201
8202         case KEY_setpwent:
8203             FUN0(OP_SPWENT);
8204
8205         case KEY_setgrent:
8206             FUN0(OP_SGRENT);
8207
8208         case KEY_seekdir:
8209             LOP(OP_SEEKDIR,XTERM);
8210
8211         case KEY_setsockopt:
8212             LOP(OP_SSOCKOPT,XTERM);
8213
8214         case KEY_shift:
8215             UNIDOR(OP_SHIFT);
8216
8217         case KEY_shmctl:
8218             LOP(OP_SHMCTL,XTERM);
8219
8220         case KEY_shmget:
8221             LOP(OP_SHMGET,XTERM);
8222
8223         case KEY_shmread:
8224             LOP(OP_SHMREAD,XTERM);
8225
8226         case KEY_shmwrite:
8227             LOP(OP_SHMWRITE,XTERM);
8228
8229         case KEY_shutdown:
8230             LOP(OP_SHUTDOWN,XTERM);
8231
8232         case KEY_sin:
8233             UNI(OP_SIN);
8234
8235         case KEY_sleep:
8236             UNI(OP_SLEEP);
8237
8238         case KEY_socket:
8239             LOP(OP_SOCKET,XTERM);
8240
8241         case KEY_socketpair:
8242             LOP(OP_SOCKPAIR,XTERM);
8243
8244         case KEY_sort:
8245             checkcomma(s,PL_tokenbuf,"subroutine name");
8246             s = skipspace(s);
8247             PL_expect = XTERM;
8248             s = force_word(s,BAREWORD,TRUE,TRUE);
8249             LOP(OP_SORT,XREF);
8250
8251         case KEY_split:
8252             LOP(OP_SPLIT,XTERM);
8253
8254         case KEY_sprintf:
8255             LOP(OP_SPRINTF,XTERM);
8256
8257         case KEY_splice:
8258             LOP(OP_SPLICE,XTERM);
8259
8260         case KEY_sqrt:
8261             UNI(OP_SQRT);
8262
8263         case KEY_srand:
8264             UNI(OP_SRAND);
8265
8266         case KEY_stat:
8267             UNI(OP_STAT);
8268
8269         case KEY_study:
8270             UNI(OP_STUDY);
8271
8272         case KEY_substr:
8273             LOP(OP_SUBSTR,XTERM);
8274
8275         case KEY_format:
8276         case KEY_sub:
8277           really_sub:
8278             {
8279                 char * const tmpbuf = PL_tokenbuf + 1;
8280                 expectation attrful;
8281                 bool have_name, have_proto;
8282                 const int key = tmp;
8283                 SV *format_name = NULL;
8284
8285                 SSize_t off = s-SvPVX(PL_linestr);
8286                 s = skipspace(s);
8287                 d = SvPVX(PL_linestr)+off;
8288
8289                 if (isIDFIRST_lazy_if(s,UTF)
8290                     || *s == '\''
8291                     || (*s == ':' && s[1] == ':'))
8292                 {
8293
8294                     PL_expect = XBLOCK;
8295                     attrful = XATTRBLOCK;
8296                     d = scan_word(s, tmpbuf, sizeof PL_tokenbuf - 1, TRUE,
8297                                   &len);
8298                     if (key == KEY_format)
8299                         format_name = S_newSV_maybe_utf8(aTHX_ s, d - s);
8300                     *PL_tokenbuf = '&';
8301                     if (memchr(tmpbuf, ':', len) || key != KEY_sub
8302                      || pad_findmy_pvn(
8303                             PL_tokenbuf, len + 1, 0
8304                         ) != NOT_IN_PAD)
8305                         sv_setpvn(PL_subname, tmpbuf, len);
8306                     else {
8307                         sv_setsv(PL_subname,PL_curstname);
8308                         sv_catpvs(PL_subname,"::");
8309                         sv_catpvn(PL_subname,tmpbuf,len);
8310                     }
8311                     if (SvUTF8(PL_linestr))
8312                         SvUTF8_on(PL_subname);
8313                     have_name = TRUE;
8314
8315
8316                     s = skipspace(d);
8317                 }
8318                 else {
8319                     if (key == KEY_my || key == KEY_our || key==KEY_state)
8320                     {
8321                         *d = '\0';
8322                         /* diag_listed_as: Missing name in "%s sub" */
8323                         Perl_croak(aTHX_
8324                                   "Missing name in \"%s\"", PL_bufptr);
8325                     }
8326                     PL_expect = XTERMBLOCK;
8327                     attrful = XATTRTERM;
8328                     sv_setpvs(PL_subname,"?");
8329                     have_name = FALSE;
8330                 }
8331
8332                 if (key == KEY_format) {
8333                     if (format_name) {
8334                         NEXTVAL_NEXTTOKE.opval
8335                             = (OP*)newSVOP(OP_CONST,0, format_name);
8336                         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
8337                         force_next(BAREWORD);
8338                     }
8339                     PREBLOCK(FORMAT);
8340                 }
8341
8342                 /* Look for a prototype */
8343                 if (*s == '(' && !FEATURE_SIGNATURES_IS_ENABLED) {
8344                     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8345                     COPLINE_SET_FROM_MULTI_END;
8346                     if (!s)
8347                         Perl_croak(aTHX_ "Prototype not terminated");
8348                     (void)validate_proto(PL_subname, PL_lex_stuff, ckWARN(WARN_ILLEGALPROTO));
8349                     have_proto = TRUE;
8350
8351                     s = skipspace(s);
8352                 }
8353                 else
8354                     have_proto = FALSE;
8355
8356                 if (*s == ':' && s[1] != ':')
8357                     PL_expect = attrful;
8358                 else if ((*s != '{' && *s != '(') && key != KEY_format) {
8359                     assert(key == KEY_sub || key == KEY_AUTOLOAD ||
8360                            key == KEY_DESTROY || key == KEY_BEGIN ||
8361                            key == KEY_UNITCHECK || key == KEY_CHECK ||
8362                            key == KEY_INIT || key == KEY_END ||
8363                            key == KEY_my || key == KEY_state ||
8364                            key == KEY_our);
8365                     if (!have_name)
8366                         Perl_croak(aTHX_ "Illegal declaration of anonymous subroutine");
8367                     else if (*s != ';' && *s != '}')
8368                         Perl_croak(aTHX_ "Illegal declaration of subroutine %"SVf, SVfARG(PL_subname));
8369                 }
8370
8371                 if (have_proto) {
8372                     NEXTVAL_NEXTTOKE.opval =
8373                         (OP*)newSVOP(OP_CONST, 0, PL_lex_stuff);
8374                     PL_lex_stuff = NULL;
8375                     force_next(THING);
8376                 }
8377                 if (!have_name) {
8378                     if (PL_curstash)
8379                         sv_setpvs(PL_subname, "__ANON__");
8380                     else
8381                         sv_setpvs(PL_subname, "__ANON__::__ANON__");
8382                     TOKEN(ANONSUB);
8383                 }
8384                 force_ident_maybe_lex('&');
8385                 TOKEN(SUB);
8386             }
8387
8388         case KEY_system:
8389             LOP(OP_SYSTEM,XREF);
8390
8391         case KEY_symlink:
8392             LOP(OP_SYMLINK,XTERM);
8393
8394         case KEY_syscall:
8395             LOP(OP_SYSCALL,XTERM);
8396
8397         case KEY_sysopen:
8398             LOP(OP_SYSOPEN,XTERM);
8399
8400         case KEY_sysseek:
8401             LOP(OP_SYSSEEK,XTERM);
8402
8403         case KEY_sysread:
8404             LOP(OP_SYSREAD,XTERM);
8405
8406         case KEY_syswrite:
8407             LOP(OP_SYSWRITE,XTERM);
8408
8409         case KEY_tr:
8410         case KEY_y:
8411             s = scan_trans(s);
8412             TERM(sublex_start());
8413
8414         case KEY_tell:
8415             UNI(OP_TELL);
8416
8417         case KEY_telldir:
8418             UNI(OP_TELLDIR);
8419
8420         case KEY_tie:
8421             LOP(OP_TIE,XTERM);
8422
8423         case KEY_tied:
8424             UNI(OP_TIED);
8425
8426         case KEY_time:
8427             FUN0(OP_TIME);
8428
8429         case KEY_times:
8430             FUN0(OP_TMS);
8431
8432         case KEY_truncate:
8433             LOP(OP_TRUNCATE,XTERM);
8434
8435         case KEY_uc:
8436             UNI(OP_UC);
8437
8438         case KEY_ucfirst:
8439             UNI(OP_UCFIRST);
8440
8441         case KEY_untie:
8442             UNI(OP_UNTIE);
8443
8444         case KEY_until:
8445             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8446                 return REPORT(0);
8447             pl_yylval.ival = CopLINE(PL_curcop);
8448             OPERATOR(UNTIL);
8449
8450         case KEY_unless:
8451             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8452                 return REPORT(0);
8453             pl_yylval.ival = CopLINE(PL_curcop);
8454             OPERATOR(UNLESS);
8455
8456         case KEY_unlink:
8457             LOP(OP_UNLINK,XTERM);
8458
8459         case KEY_undef:
8460             UNIDOR(OP_UNDEF);
8461
8462         case KEY_unpack:
8463             LOP(OP_UNPACK,XTERM);
8464
8465         case KEY_utime:
8466             LOP(OP_UTIME,XTERM);
8467
8468         case KEY_umask:
8469             UNIDOR(OP_UMASK);
8470
8471         case KEY_unshift:
8472             LOP(OP_UNSHIFT,XTERM);
8473
8474         case KEY_use:
8475             s = tokenize_use(1, s);
8476             TOKEN(USE);
8477
8478         case KEY_values:
8479             UNI(OP_VALUES);
8480
8481         case KEY_vec:
8482             LOP(OP_VEC,XTERM);
8483
8484         case KEY_when:
8485             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8486                 return REPORT(0);
8487             pl_yylval.ival = CopLINE(PL_curcop);
8488             Perl_ck_warner_d(aTHX_
8489                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8490                 "when is experimental");
8491             OPERATOR(WHEN);
8492
8493         case KEY_while:
8494             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8495                 return REPORT(0);
8496             pl_yylval.ival = CopLINE(PL_curcop);
8497             OPERATOR(WHILE);
8498
8499         case KEY_warn:
8500             PL_hints |= HINT_BLOCK_SCOPE;
8501             LOP(OP_WARN,XTERM);
8502
8503         case KEY_wait:
8504             FUN0(OP_WAIT);
8505
8506         case KEY_waitpid:
8507             LOP(OP_WAITPID,XTERM);
8508
8509         case KEY_wantarray:
8510             FUN0(OP_WANTARRAY);
8511
8512         case KEY_write:
8513             /* Make sure $^L is defined. 0x0C is CTRL-L on ASCII platforms, and
8514              * we use the same number on EBCDIC */
8515             gv_fetchpvs("\x0C", GV_ADD|GV_NOTQUAL, SVt_PV);
8516             UNI(OP_ENTERWRITE);
8517
8518         case KEY_x:
8519             if (PL_expect == XOPERATOR) {
8520                 if (*s == '=' && !PL_lex_allbrackets
8521                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8522                 {
8523                     return REPORT(0);
8524                 }
8525                 Mop(OP_REPEAT);
8526             }
8527             check_uni();
8528             goto just_a_word;
8529
8530         case KEY_xor:
8531             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8532                 return REPORT(0);
8533             pl_yylval.ival = OP_XOR;
8534             OPERATOR(OROP);
8535         }
8536     }}
8537 }
8538
8539 /*
8540   S_pending_ident
8541
8542   Looks up an identifier in the pad or in a package
8543
8544   is_sig indicates that this is a subroutine signature variable
8545   rather than a plain pad var.
8546
8547   Returns:
8548     PRIVATEREF if this is a lexical name.
8549     BAREWORD   if this belongs to a package.
8550
8551   Structure:
8552       if we're in a my declaration
8553           croak if they tried to say my($foo::bar)
8554           build the ops for a my() declaration
8555       if it's an access to a my() variable
8556           build ops for access to a my() variable
8557       if in a dq string, and they've said @foo and we can't find @foo
8558           warn
8559       build ops for a bareword
8560 */
8561
8562 static int
8563 S_pending_ident(pTHX)
8564 {
8565     PADOFFSET tmp = 0;
8566     const char pit = (char)pl_yylval.ival;
8567     const STRLEN tokenbuf_len = strlen(PL_tokenbuf);
8568     /* All routes through this function want to know if there is a colon.  */
8569     const char *const has_colon = (const char*) memchr (PL_tokenbuf, ':', tokenbuf_len);
8570
8571     DEBUG_T({ PerlIO_printf(Perl_debug_log,
8572           "### Pending identifier '%s'\n", PL_tokenbuf); });
8573
8574     /* if we're in a my(), we can't allow dynamics here.
8575        $foo'bar has already been turned into $foo::bar, so
8576        just check for colons.
8577
8578        if it's a legal name, the OP is a PADANY.
8579     */
8580     if (PL_in_my) {
8581         if (PL_in_my == KEY_our) {      /* "our" is merely analogous to "my" */
8582             if (has_colon)
8583                 yyerror_pv(Perl_form(aTHX_ "No package name allowed for "
8584                                   "variable %s in \"our\"",
8585                                   PL_tokenbuf), UTF ? SVf_UTF8 : 0);
8586             tmp = allocmy(PL_tokenbuf, tokenbuf_len, UTF ? SVf_UTF8 : 0);
8587         }
8588         else {
8589             OP *o;
8590             if (has_colon) {
8591                 /* "my" variable %s can't be in a package */
8592                 /* PL_no_myglob is constant */
8593                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
8594                 yyerror_pv(Perl_form(aTHX_ PL_no_myglob,
8595                             PL_in_my == KEY_my ? "my" : "state",
8596                             *PL_tokenbuf == '&' ? "subroutin" : "variabl",
8597                             PL_tokenbuf),
8598                             UTF ? SVf_UTF8 : 0);
8599                 GCC_DIAG_RESTORE;
8600             }
8601
8602             if (PL_in_my == KEY_sigvar) {
8603                 /* A signature 'padop' needs in addition, an op_first to
8604                  * point to a child sigdefelem, and an extra field to hold
8605                  * the signature index. We can achieve both by using an
8606                  * UNOP_AUX and (ab)using the op_aux field to hold the
8607                  * index. If we ever need more fields, use a real malloced
8608                  * aux strut instead.
8609                  */
8610                 o = newUNOP_AUX(OP_ARGELEM, 0, NULL,
8611                                     INT2PTR(UNOP_AUX_item *,
8612                                         (PL_parser->sig_elems)));
8613                 o->op_private |= (  PL_tokenbuf[0] == '$' ? OPpARGELEM_SV
8614                                   : PL_tokenbuf[0] == '@' ? OPpARGELEM_AV
8615                                   :                         OPpARGELEM_HV);
8616             }
8617             else
8618                 o = newOP(OP_PADANY, 0);
8619             o->op_targ = allocmy(PL_tokenbuf, tokenbuf_len,
8620                                                         UTF ? SVf_UTF8 : 0);
8621             if (PL_in_my == KEY_sigvar)
8622                 PL_in_my = 0;
8623
8624             pl_yylval.opval = o;
8625             return PRIVATEREF;
8626         }
8627     }
8628
8629     /*
8630        build the ops for accesses to a my() variable.
8631     */
8632
8633     if (!has_colon) {
8634         if (!PL_in_my)
8635             tmp = pad_findmy_pvn(PL_tokenbuf, tokenbuf_len,
8636                                  0);
8637         if (tmp != NOT_IN_PAD) {
8638             /* might be an "our" variable" */
8639             if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
8640                 /* build ops for a bareword */
8641                 HV *  const stash = PAD_COMPNAME_OURSTASH(tmp);
8642                 HEK * const stashname = HvNAME_HEK(stash);
8643                 SV *  const sym = newSVhek(stashname);
8644                 sv_catpvs(sym, "::");
8645                 sv_catpvn_flags(sym, PL_tokenbuf+1, tokenbuf_len - 1, (UTF ? SV_CATUTF8 : SV_CATBYTES ));
8646                 pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sym);
8647                 pl_yylval.opval->op_private = OPpCONST_ENTERED;
8648                 if (pit != '&')
8649                   gv_fetchsv(sym,
8650                     GV_ADDMULTI,
8651                     ((PL_tokenbuf[0] == '$') ? SVt_PV
8652                      : (PL_tokenbuf[0] == '@') ? SVt_PVAV
8653                      : SVt_PVHV));
8654                 return BAREWORD;
8655             }
8656
8657             pl_yylval.opval = newOP(OP_PADANY, 0);
8658             pl_yylval.opval->op_targ = tmp;
8659             return PRIVATEREF;
8660         }
8661     }
8662
8663     /*
8664        Whine if they've said @foo or @foo{key} in a doublequoted string,
8665        and @foo (or %foo) isn't a variable we can find in the symbol
8666        table.
8667     */
8668     if (ckWARN(WARN_AMBIGUOUS)
8669         && pit == '@'
8670         && PL_lex_state != LEX_NORMAL
8671         && !PL_lex_brackets)
8672     {
8673         GV *const gv = gv_fetchpvn_flags(PL_tokenbuf + 1, tokenbuf_len - 1,
8674                                          ( UTF ? SVf_UTF8 : 0 ) | GV_ADDMG,
8675                                          SVt_PVAV);
8676         if ((!gv || ((PL_tokenbuf[0] == '@') ? !GvAV(gv) : !GvHV(gv)))
8677            )
8678         {
8679             /* Downgraded from fatal to warning 20000522 mjd */
8680             Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
8681                         "Possible unintended interpolation of %"UTF8f
8682                         " in string",
8683                         UTF8fARG(UTF, tokenbuf_len, PL_tokenbuf));
8684         }
8685     }
8686
8687     /* build ops for a bareword */
8688     pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0,
8689                                    newSVpvn_flags(PL_tokenbuf + 1,
8690                                                       tokenbuf_len - 1,
8691                                                       UTF ? SVf_UTF8 : 0 ));
8692     pl_yylval.opval->op_private = OPpCONST_ENTERED;
8693     if (pit != '&')
8694         gv_fetchpvn_flags(PL_tokenbuf+1, tokenbuf_len - 1,
8695                      (PL_in_eval ? GV_ADDMULTI : GV_ADD)
8696                      | ( UTF ? SVf_UTF8 : 0 ),
8697                      ((PL_tokenbuf[0] == '$') ? SVt_PV
8698                       : (PL_tokenbuf[0] == '@') ? SVt_PVAV
8699                       : SVt_PVHV));
8700     return BAREWORD;
8701 }
8702
8703 STATIC void
8704 S_checkcomma(pTHX_ const char *s, const char *name, const char *what)
8705 {
8706     PERL_ARGS_ASSERT_CHECKCOMMA;
8707
8708     if (*s == ' ' && s[1] == '(') {     /* XXX gotta be a better way */
8709         if (ckWARN(WARN_SYNTAX)) {
8710             int level = 1;
8711             const char *w;
8712             for (w = s+2; *w && level; w++) {
8713                 if (*w == '(')
8714                     ++level;
8715                 else if (*w == ')')
8716                     --level;
8717             }
8718             while (isSPACE(*w))
8719                 ++w;
8720             /* the list of chars below is for end of statements or
8721              * block / parens, boolean operators (&&, ||, //) and branch
8722              * constructs (or, and, if, until, unless, while, err, for).
8723              * Not a very solid hack... */
8724             if (!*w || !strchr(";&/|})]oaiuwef!=", *w))
8725                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
8726                             "%s (...) interpreted as function",name);
8727         }
8728     }
8729     while (s < PL_bufend && isSPACE(*s))
8730         s++;
8731     if (*s == '(')
8732         s++;
8733     while (s < PL_bufend && isSPACE(*s))
8734         s++;
8735     if (isIDFIRST_lazy_if(s,UTF)) {
8736         const char * const w = s;
8737         s += UTF ? UTF8SKIP(s) : 1;
8738         while (isWORDCHAR_lazy_if(s,UTF))
8739             s += UTF ? UTF8SKIP(s) : 1;
8740         while (s < PL_bufend && isSPACE(*s))
8741             s++;
8742         if (*s == ',') {
8743             GV* gv;
8744             PADOFFSET off;
8745             if (keyword(w, s - w, 0))
8746                 return;
8747
8748             gv = gv_fetchpvn_flags(w, s - w, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
8749             if (gv && GvCVu(gv))
8750                 return;
8751             if (s - w <= 254) {
8752                 char tmpbuf[256];
8753                 Copy(w, tmpbuf+1, s - w, char);
8754                 *tmpbuf = '&';
8755                 off = pad_findmy_pvn(tmpbuf, s-w+1, 0);
8756                 if (off != NOT_IN_PAD) return;
8757             }
8758             Perl_croak(aTHX_ "No comma allowed after %s", what);
8759         }
8760     }
8761 }
8762
8763 /* S_new_constant(): do any overload::constant lookup.
8764
8765    Either returns sv, or mortalizes/frees sv and returns a new SV*.
8766    Best used as sv=new_constant(..., sv, ...).
8767    If s, pv are NULL, calls subroutine with one argument,
8768    and <type> is used with error messages only.
8769    <type> is assumed to be well formed UTF-8 */
8770
8771 STATIC SV *
8772 S_new_constant(pTHX_ const char *s, STRLEN len, const char *key, STRLEN keylen,
8773                SV *sv, SV *pv, const char *type, STRLEN typelen)
8774 {
8775     dSP;
8776     HV * table = GvHV(PL_hintgv);                /* ^H */
8777     SV *res;
8778     SV *errsv = NULL;
8779     SV **cvp;
8780     SV *cv, *typesv;
8781     const char *why1 = "", *why2 = "", *why3 = "";
8782
8783     PERL_ARGS_ASSERT_NEW_CONSTANT;
8784     /* We assume that this is true: */
8785     if (*key == 'c') { assert (strEQ(key, "charnames")); }
8786     assert(type || s);
8787
8788     /* charnames doesn't work well if there have been errors found */
8789     if (PL_error_count > 0 && *key == 'c')
8790     {
8791         SvREFCNT_dec_NN(sv);
8792         return &PL_sv_undef;
8793     }
8794
8795     sv_2mortal(sv);                     /* Parent created it permanently */
8796     if (!table
8797         || ! (PL_hints & HINT_LOCALIZE_HH)
8798         || ! (cvp = hv_fetch(table, key, keylen, FALSE))
8799         || ! SvOK(*cvp))
8800     {
8801         char *msg;
8802         
8803         /* Here haven't found what we're looking for.  If it is charnames,
8804          * perhaps it needs to be loaded.  Try doing that before giving up */
8805         if (*key == 'c') {
8806             Perl_load_module(aTHX_
8807                             0,
8808                             newSVpvs("_charnames"),
8809                              /* version parameter; no need to specify it, as if
8810                               * we get too early a version, will fail anyway,
8811                               * not being able to find '_charnames' */
8812                             NULL,
8813                             newSVpvs(":full"),
8814                             newSVpvs(":short"),
8815                             NULL);
8816             assert(sp == PL_stack_sp);
8817             table = GvHV(PL_hintgv);
8818             if (table
8819                 && (PL_hints & HINT_LOCALIZE_HH)
8820                 && (cvp = hv_fetch(table, key, keylen, FALSE))
8821                 && SvOK(*cvp))
8822             {
8823                 goto now_ok;
8824             }
8825         }
8826         if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
8827             msg = Perl_form(aTHX_
8828                                "Constant(%.*s) unknown",
8829                                 (int)(type ? typelen : len),
8830                                 (type ? type: s));
8831         }
8832         else {
8833             why1 = "$^H{";
8834             why2 = key;
8835             why3 = "} is not defined";
8836         report:
8837             if (*key == 'c') {
8838                 msg = Perl_form(aTHX_
8839                             /* The +3 is for '\N{'; -4 for that, plus '}' */
8840                             "Unknown charname '%.*s'", (int)typelen - 4, type + 3
8841                       );
8842             }
8843             else {
8844                 msg = Perl_form(aTHX_ "Constant(%.*s): %s%s%s",
8845                                     (int)(type ? typelen : len),
8846                                     (type ? type: s), why1, why2, why3);
8847             }
8848         }
8849         yyerror_pv(msg, UTF ? SVf_UTF8 : 0);
8850         return SvREFCNT_inc_simple_NN(sv);
8851     }
8852   now_ok:
8853     cv = *cvp;
8854     if (!pv && s)
8855         pv = newSVpvn_flags(s, len, SVs_TEMP);
8856     if (type && pv)
8857         typesv = newSVpvn_flags(type, typelen, SVs_TEMP);
8858     else
8859         typesv = &PL_sv_undef;
8860
8861     PUSHSTACKi(PERLSI_OVERLOAD);
8862     ENTER ;
8863     SAVETMPS;
8864
8865     PUSHMARK(SP) ;
8866     EXTEND(sp, 3);
8867     if (pv)
8868         PUSHs(pv);
8869     PUSHs(sv);
8870     if (pv)
8871         PUSHs(typesv);
8872     PUTBACK;
8873     call_sv(cv, G_SCALAR | ( PL_in_eval ? 0 : G_EVAL));
8874
8875     SPAGAIN ;
8876
8877     /* Check the eval first */
8878     if (!PL_in_eval && ((errsv = ERRSV), SvTRUE_NN(errsv))) {
8879         STRLEN errlen;
8880         const char * errstr;
8881         sv_catpvs(errsv, "Propagated");
8882         errstr = SvPV_const(errsv, errlen);
8883         yyerror_pvn(errstr, errlen, 0); /* Duplicates the message inside eval */
8884         (void)POPs;
8885         res = SvREFCNT_inc_simple_NN(sv);
8886     }
8887     else {
8888         res = POPs;
8889         SvREFCNT_inc_simple_void_NN(res);
8890     }
8891
8892     PUTBACK ;
8893     FREETMPS ;
8894     LEAVE ;
8895     POPSTACK;
8896
8897     if (!SvOK(res)) {
8898         why1 = "Call to &{$^H{";
8899         why2 = key;
8900         why3 = "}} did not return a defined value";
8901         sv = res;
8902         (void)sv_2mortal(sv);
8903         goto report;
8904     }
8905
8906     return res;
8907 }
8908
8909 PERL_STATIC_INLINE void
8910 S_parse_ident(pTHX_ char **s, char **d, char * const e, int allow_package,
8911                     bool is_utf8, bool check_dollar) {
8912     PERL_ARGS_ASSERT_PARSE_IDENT;
8913
8914     for (;;) {
8915         if (*d >= e)
8916             Perl_croak(aTHX_ "%s", ident_too_long);
8917         if (is_utf8 && isIDFIRST_utf8((U8*)*s)) {
8918              /* The UTF-8 case must come first, otherwise things
8919              * like c\N{COMBINING TILDE} would start failing, as the
8920              * isWORDCHAR_A case below would gobble the 'c' up.
8921              */
8922
8923             char *t = *s + UTF8SKIP(*s);
8924             while (isIDCONT_utf8((U8*)t))
8925                 t += UTF8SKIP(t);
8926             if (*d + (t - *s) > e)
8927                 Perl_croak(aTHX_ "%s", ident_too_long);
8928             Copy(*s, *d, t - *s, char);
8929             *d += t - *s;
8930             *s = t;
8931         }
8932         else if ( isWORDCHAR_A(**s) ) {
8933             do {
8934                 *(*d)++ = *(*s)++;
8935             } while (isWORDCHAR_A(**s) && *d < e);
8936         }
8937         else if (allow_package && **s == '\'' && isIDFIRST_lazy_if(*s+1,is_utf8)) {
8938             *(*d)++ = ':';
8939             *(*d)++ = ':';
8940             (*s)++;
8941         }
8942         else if (allow_package && **s == ':' && (*s)[1] == ':'
8943            /* Disallow things like Foo::$bar. For the curious, this is
8944             * the code path that triggers the "Bad name after" warning
8945             * when looking for barewords.
8946             */
8947            && !(check_dollar && (*s)[2] == '$')) {
8948             *(*d)++ = *(*s)++;
8949             *(*d)++ = *(*s)++;
8950         }
8951         else
8952             break;
8953     }
8954     return;
8955 }
8956
8957 /* Returns a NUL terminated string, with the length of the string written to
8958    *slp
8959    */
8960 STATIC char *
8961 S_scan_word(pTHX_ char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
8962 {
8963     char *d = dest;
8964     char * const e = d + destlen - 3;  /* two-character token, ending NUL */
8965     bool is_utf8 = cBOOL(UTF);
8966
8967     PERL_ARGS_ASSERT_SCAN_WORD;
8968
8969     parse_ident(&s, &d, e, allow_package, is_utf8, TRUE);
8970     *d = '\0';
8971     *slp = d - dest;
8972     return s;
8973 }
8974
8975 /* Is the byte 'd' a legal single character identifier name?  'u' is true
8976  * iff Unicode semantics are to be used.  The legal ones are any of:
8977  *  a) all ASCII characters except:
8978  *          1) control and space-type ones, like NUL, SOH, \t, and SPACE;
8979  *          2) '{'
8980  *     The final case currently doesn't get this far in the program, so we
8981  *     don't test for it.  If that were to change, it would be ok to allow it.
8982  *  b) When not under Unicode rules, any upper Latin1 character
8983  *  c) Otherwise, when unicode rules are used, all XIDS characters.
8984  *
8985  *      Because all ASCII characters have the same representation whether
8986  *      encoded in UTF-8 or not, we can use the foo_A macros below and '\0' and
8987  *      '{' without knowing if is UTF-8 or not. */
8988 #define VALID_LEN_ONE_IDENT(s, is_utf8)                                       \
8989     (isGRAPH_A(*(s)) || ((is_utf8)                                            \
8990                          ? isIDFIRST_utf8((U8*) (s))                          \
8991                          : (isGRAPH_L1(*s)                                    \
8992                             && LIKELY((U8) *(s) != LATIN1_TO_NATIVE(0xAD)))))
8993
8994 STATIC char *
8995 S_scan_ident(pTHX_ char *s, char *dest, STRLEN destlen, I32 ck_uni)
8996 {
8997     I32 herelines = PL_parser->herelines;
8998     SSize_t bracket = -1;
8999     char funny = *s++;
9000     char *d = dest;
9001     char * const e = d + destlen - 3;    /* two-character token, ending NUL */
9002     bool is_utf8 = cBOOL(UTF);
9003     I32 orig_copline = 0, tmp_copline = 0;
9004
9005     PERL_ARGS_ASSERT_SCAN_IDENT;
9006
9007     if (isSPACE(*s) || !*s)
9008         s = skipspace(s);
9009     if (isDIGIT(*s)) {
9010         while (isDIGIT(*s)) {
9011             if (d >= e)
9012                 Perl_croak(aTHX_ "%s", ident_too_long);
9013             *d++ = *s++;
9014         }
9015     }
9016     else {  /* See if it is a "normal" identifier */
9017         parse_ident(&s, &d, e, 1, is_utf8, FALSE);
9018     }
9019     *d = '\0';
9020     d = dest;
9021     if (*d) {
9022         /* Either a digit variable, or parse_ident() found an identifier
9023            (anything valid as a bareword), so job done and return.  */
9024         if (PL_lex_state != LEX_NORMAL)
9025             PL_lex_state = LEX_INTERPENDMAYBE;
9026         return s;
9027     }
9028
9029     /* Here, it is not a run-of-the-mill identifier name */
9030
9031     if (*s == '$' && s[1]
9032         && (isIDFIRST_lazy_if(s+1,is_utf8)
9033             || isDIGIT_A((U8)s[1])
9034             || s[1] == '$'
9035             || s[1] == '{'
9036             || strEQs(s+1,"::")) )
9037     {
9038         /* Dereferencing a value in a scalar variable.
9039            The alternatives are different syntaxes for a scalar variable.
9040            Using ' as a leading package separator isn't allowed. :: is.   */
9041         return s;
9042     }
9043     /* Handle the opening { of @{...}, &{...}, *{...}, %{...}, ${...}  */
9044     if (*s == '{') {
9045         bracket = s - SvPVX(PL_linestr);
9046         s++;
9047         orig_copline = CopLINE(PL_curcop);
9048         if (s < PL_bufend && isSPACE(*s)) {
9049             s = skipspace(s);
9050         }
9051     }
9052     if ((s <= PL_bufend - (is_utf8)
9053                           ? UTF8SKIP(s)
9054                           : 1)
9055         && VALID_LEN_ONE_IDENT(s, is_utf8))
9056     {
9057         if (is_utf8) {
9058             const STRLEN skip = UTF8SKIP(s);
9059             STRLEN i;
9060             d[skip] = '\0';
9061             for ( i = 0; i < skip; i++ )
9062                 d[i] = *s++;
9063         }
9064         else {
9065             *d = *s++;
9066             d[1] = '\0';
9067         }
9068     }
9069     /* Convert $^F, ${^F} and the ^F of ${^FOO} to control characters */
9070     if (*d == '^' && *s && isCONTROLVAR(*s)) {
9071         *d = toCTRL(*s);
9072         s++;
9073     }
9074     /* Warn about ambiguous code after unary operators if {...} notation isn't
9075        used.  There's no difference in ambiguity; it's merely a heuristic
9076        about when not to warn.  */
9077     else if (ck_uni && bracket == -1)
9078         check_uni();
9079     if (bracket != -1) {
9080         bool skip;
9081         char *s2;
9082         /* If we were processing {...} notation then...  */
9083         if (isIDFIRST_lazy_if(d,is_utf8)) {
9084             /* if it starts as a valid identifier, assume that it is one.
9085                (the later check for } being at the expected point will trap
9086                cases where this doesn't pan out.)  */
9087             d += is_utf8 ? UTF8SKIP(d) : 1;
9088             parse_ident(&s, &d, e, 1, is_utf8, TRUE);
9089             *d = '\0';
9090             tmp_copline = CopLINE(PL_curcop);
9091             if (s < PL_bufend && isSPACE(*s)) {
9092                 s = skipspace(s);
9093             }
9094             if ((*s == '[' || (*s == '{' && strNE(dest, "sub")))) {
9095                 /* ${foo[0]} and ${foo{bar}} notation.  */
9096                 if (ckWARN(WARN_AMBIGUOUS) && keyword(dest, d - dest, 0)) {
9097                     const char * const brack =
9098                         (const char *)
9099                         ((*s == '[') ? "[...]" : "{...}");
9100                     orig_copline = CopLINE(PL_curcop);
9101                     CopLINE_set(PL_curcop, tmp_copline);
9102    /* diag_listed_as: Ambiguous use of %c{%s[...]} resolved to %c%s[...] */
9103                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9104                         "Ambiguous use of %c{%s%s} resolved to %c%s%s",
9105                         funny, dest, brack, funny, dest, brack);
9106                     CopLINE_set(PL_curcop, orig_copline);
9107                 }
9108                 bracket++;
9109                 PL_lex_brackstack[PL_lex_brackets++] = (char)(XOPERATOR | XFAKEBRACK);
9110                 PL_lex_allbrackets++;
9111                 return s;
9112             }
9113         }
9114         /* Handle extended ${^Foo} variables
9115          * 1999-02-27 mjd-perl-patch@plover.com */
9116         else if (! isPRINT(*d) /* isCNTRL(d), plus all non-ASCII */
9117                  && isWORDCHAR(*s))
9118         {
9119             d++;
9120             while (isWORDCHAR(*s) && d < e) {
9121                 *d++ = *s++;
9122             }
9123             if (d >= e)
9124                 Perl_croak(aTHX_ "%s", ident_too_long);
9125             *d = '\0';
9126         }
9127
9128         if ( !tmp_copline )
9129             tmp_copline = CopLINE(PL_curcop);
9130         if ((skip = s < PL_bufend && isSPACE(*s)))
9131             /* Avoid incrementing line numbers or resetting PL_linestart,
9132                in case we have to back up.  */
9133             s2 = peekspace(s);
9134         else
9135             s2 = s;
9136             
9137         /* Expect to find a closing } after consuming any trailing whitespace.
9138          */
9139         if (*s2 == '}') {
9140             /* Now increment line numbers if applicable.  */
9141             if (skip)
9142                 s = skipspace(s);
9143             s++;
9144             if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
9145                 PL_lex_state = LEX_INTERPEND;
9146                 PL_expect = XREF;
9147             }
9148             if (PL_lex_state == LEX_NORMAL) {
9149                 if (ckWARN(WARN_AMBIGUOUS)
9150                     && (keyword(dest, d - dest, 0)
9151                         || get_cvn_flags(dest, d - dest, is_utf8
9152                            ? SVf_UTF8
9153                            : 0)))
9154                 {
9155                     SV *tmp = newSVpvn_flags( dest, d - dest,
9156                                         SVs_TEMP | (is_utf8 ? SVf_UTF8 : 0) );
9157                     if (funny == '#')
9158                         funny = '@';
9159                     orig_copline = CopLINE(PL_curcop);
9160                     CopLINE_set(PL_curcop, tmp_copline);
9161                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9162                         "Ambiguous use of %c{%"SVf"} resolved to %c%"SVf,
9163                         funny, SVfARG(tmp), funny, SVfARG(tmp));
9164                     CopLINE_set(PL_curcop, orig_copline);
9165                 }
9166             }
9167         }
9168         else {
9169             /* Didn't find the closing } at the point we expected, so restore
9170                state such that the next thing to process is the opening { and */
9171             s = SvPVX(PL_linestr) + bracket; /* let the parser handle it */
9172             CopLINE_set(PL_curcop, orig_copline);
9173             PL_parser->herelines = herelines;
9174             *dest = '\0';
9175         }
9176     }
9177     else if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets && !intuit_more(s))
9178         PL_lex_state = LEX_INTERPEND;
9179     return s;
9180 }
9181
9182 static bool
9183 S_pmflag(pTHX_ const char* const valid_flags, U32 * pmfl, char** s, char* charset, unsigned int * x_mod_count) {
9184
9185     /* Adds, subtracts to/from 'pmfl' based on the next regex modifier flag
9186      * found in the parse starting at 's', based on the subset that are valid
9187      * in this context input to this routine in 'valid_flags'. Advances s.
9188      * Returns TRUE if the input should be treated as a valid flag, so the next
9189      * char may be as well; otherwise FALSE. 'charset' should point to a NUL
9190      * upon first call on the current regex.  This routine will set it to any
9191      * charset modifier found.  The caller shouldn't change it.  This way,
9192      * another charset modifier encountered in the parse can be detected as an
9193      * error, as we have decided to allow only one */
9194
9195     const char c = **s;
9196     STRLEN charlen = UTF ? UTF8SKIP(*s) : 1;
9197
9198     if ( charlen != 1 || ! strchr(valid_flags, c) ) {
9199         if (isWORDCHAR_lazy_if(*s, UTF)) {
9200             yyerror_pv(Perl_form(aTHX_ "Unknown regexp modifier \"/%.*s\"", (int)charlen, *s),
9201                        UTF ? SVf_UTF8 : 0);
9202             (*s) += charlen;
9203             /* Pretend that it worked, so will continue processing before
9204              * dieing */
9205             return TRUE;
9206         }
9207         return FALSE;
9208     }
9209
9210     switch (c) {
9211
9212         CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, *x_mod_count);
9213         case GLOBAL_PAT_MOD:      *pmfl |= PMf_GLOBAL; break;
9214         case CONTINUE_PAT_MOD:    *pmfl |= PMf_CONTINUE; break;
9215         case ONCE_PAT_MOD:        *pmfl |= PMf_KEEP; break;
9216         case KEEPCOPY_PAT_MOD:    *pmfl |= RXf_PMf_KEEPCOPY; break;
9217         case NONDESTRUCT_PAT_MOD: *pmfl |= PMf_NONDESTRUCT; break;
9218         case LOCALE_PAT_MOD:
9219             if (*charset) {
9220                 goto multiple_charsets;
9221             }
9222             set_regex_charset(pmfl, REGEX_LOCALE_CHARSET);
9223             *charset = c;
9224             break;
9225         case UNICODE_PAT_MOD:
9226             if (*charset) {
9227                 goto multiple_charsets;
9228             }
9229             set_regex_charset(pmfl, REGEX_UNICODE_CHARSET);
9230             *charset = c;
9231             break;
9232         case ASCII_RESTRICT_PAT_MOD:
9233             if (! *charset) {
9234                 set_regex_charset(pmfl, REGEX_ASCII_RESTRICTED_CHARSET);
9235             }
9236             else {
9237
9238                 /* Error if previous modifier wasn't an 'a', but if it was, see
9239                  * if, and accept, a second occurrence (only) */
9240                 if (*charset != 'a'
9241                     || get_regex_charset(*pmfl)
9242                         != REGEX_ASCII_RESTRICTED_CHARSET)
9243                 {
9244                         goto multiple_charsets;
9245                 }
9246                 set_regex_charset(pmfl, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
9247             }
9248             *charset = c;
9249             break;
9250         case DEPENDS_PAT_MOD:
9251             if (*charset) {
9252                 goto multiple_charsets;
9253             }
9254             set_regex_charset(pmfl, REGEX_DEPENDS_CHARSET);
9255             *charset = c;
9256             break;
9257     }
9258
9259     (*s)++;
9260     return TRUE;
9261
9262     multiple_charsets:
9263         if (*charset != c) {
9264             yyerror(Perl_form(aTHX_ "Regexp modifiers \"/%c\" and \"/%c\" are mutually exclusive", *charset, c));
9265         }
9266         else if (c == 'a') {
9267   /* diag_listed_as: Regexp modifier "/%c" may appear a maximum of twice */
9268             yyerror("Regexp modifier \"/a\" may appear a maximum of twice");
9269         }
9270         else {
9271             yyerror(Perl_form(aTHX_ "Regexp modifier \"/%c\" may not appear twice", c));
9272         }
9273
9274         /* Pretend that it worked, so will continue processing before dieing */
9275         (*s)++;
9276         return TRUE;
9277 }
9278
9279 STATIC char *
9280 S_scan_pat(pTHX_ char *start, I32 type)
9281 {
9282     PMOP *pm;
9283     char *s;
9284     const char * const valid_flags =
9285         (const char *)((type == OP_QR) ? QR_PAT_MODS : M_PAT_MODS);
9286     char charset = '\0';    /* character set modifier */
9287     unsigned int x_mod_count = 0;
9288
9289     PERL_ARGS_ASSERT_SCAN_PAT;
9290
9291     s = scan_str(start,TRUE,FALSE, (PL_in_eval & EVAL_RE_REPARSING), NULL);
9292     if (!s)
9293         Perl_croak(aTHX_ "Search pattern not terminated");
9294
9295     pm = (PMOP*)newPMOP(type, 0);
9296     if (PL_multi_open == '?') {
9297         /* This is the only point in the code that sets PMf_ONCE:  */
9298         pm->op_pmflags |= PMf_ONCE;
9299
9300         /* Hence it's safe to do this bit of PMOP book-keeping here, which
9301            allows us to restrict the list needed by reset to just the ??
9302            matches.  */
9303         assert(type != OP_TRANS);
9304         if (PL_curstash) {
9305             MAGIC *mg = mg_find((const SV *)PL_curstash, PERL_MAGIC_symtab);
9306             U32 elements;
9307             if (!mg) {
9308                 mg = sv_magicext(MUTABLE_SV(PL_curstash), 0, PERL_MAGIC_symtab, 0, 0,
9309                                  0);
9310             }
9311             elements = mg->mg_len / sizeof(PMOP**);
9312             Renewc(mg->mg_ptr, elements + 1, PMOP*, char);
9313             ((PMOP**)mg->mg_ptr) [elements++] = pm;
9314             mg->mg_len = elements * sizeof(PMOP**);
9315             PmopSTASH_set(pm,PL_curstash);
9316         }
9317     }
9318
9319     /* if qr/...(?{..}).../, then need to parse the pattern within a new
9320      * anon CV. False positives like qr/[(?{]/ are harmless */
9321
9322     if (type == OP_QR) {
9323         STRLEN len;
9324         char *e, *p = SvPV(PL_lex_stuff, len);
9325         e = p + len;
9326         for (; p < e; p++) {
9327             if (p[0] == '(' && p[1] == '?'
9328                 && (p[2] == '{' || (p[2] == '?' && p[3] == '{')))
9329             {
9330                 pm->op_pmflags |= PMf_HAS_CV;
9331                 break;
9332             }
9333         }
9334         pm->op_pmflags |= PMf_IS_QR;
9335     }
9336
9337     while (*s && S_pmflag(aTHX_ valid_flags, &(pm->op_pmflags),
9338                                 &s, &charset, &x_mod_count))
9339     {};
9340     /* issue a warning if /c is specified,but /g is not */
9341     if ((pm->op_pmflags & PMf_CONTINUE) && !(pm->op_pmflags & PMf_GLOBAL))
9342     {
9343         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), 
9344                        "Use of /c modifier is meaningless without /g" );
9345     }
9346
9347     if (UNLIKELY((x_mod_count) > 1)) {
9348         yyerror("Only one /x regex modifier is allowed");
9349     }
9350
9351     PL_lex_op = (OP*)pm;
9352     pl_yylval.ival = OP_MATCH;
9353     return s;
9354 }
9355
9356 STATIC char *
9357 S_scan_subst(pTHX_ char *start)
9358 {
9359     char *s;
9360     PMOP *pm;
9361     I32 first_start;
9362     line_t first_line;
9363     I32 es = 0;
9364     char charset = '\0';    /* character set modifier */
9365     unsigned int x_mod_count = 0;
9366     char *t;
9367
9368     PERL_ARGS_ASSERT_SCAN_SUBST;
9369
9370     pl_yylval.ival = OP_NULL;
9371
9372     s = scan_str(start, TRUE, FALSE, FALSE, &t);
9373
9374     if (!s)
9375         Perl_croak(aTHX_ "Substitution pattern not terminated");
9376
9377     s = t;
9378
9379     first_start = PL_multi_start;
9380     first_line = CopLINE(PL_curcop);
9381     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
9382     if (!s) {
9383         SvREFCNT_dec_NN(PL_lex_stuff);
9384         PL_lex_stuff = NULL;
9385         Perl_croak(aTHX_ "Substitution replacement not terminated");
9386     }
9387     PL_multi_start = first_start;       /* so whole substitution is taken together */
9388
9389     pm = (PMOP*)newPMOP(OP_SUBST, 0);
9390
9391
9392     while (*s) {
9393         if (*s == EXEC_PAT_MOD) {
9394             s++;
9395             es++;
9396         }
9397         else if (! S_pmflag(aTHX_ S_PAT_MODS, &(pm->op_pmflags),
9398                                   &s, &charset, &x_mod_count))
9399         {
9400             break;
9401         }
9402     }
9403
9404     if (UNLIKELY((x_mod_count) > 1)) {
9405         yyerror("Only one /x regex modifier is allowed");
9406     }
9407
9408     if ((pm->op_pmflags & PMf_CONTINUE)) {
9409         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Use of /c modifier is meaningless in s///" );
9410     }
9411
9412     if (es) {
9413         SV * const repl = newSVpvs("");
9414
9415         PL_multi_end = 0;
9416         pm->op_pmflags |= PMf_EVAL;
9417         while (es-- > 0) {
9418             if (es)
9419                 sv_catpvs(repl, "eval ");
9420             else
9421                 sv_catpvs(repl, "do ");
9422         }
9423         sv_catpvs(repl, "{");
9424         sv_catsv(repl, PL_parser->lex_sub_repl);
9425         sv_catpvs(repl, "}");
9426         SvEVALED_on(repl);
9427         SvREFCNT_dec(PL_parser->lex_sub_repl);
9428         PL_parser->lex_sub_repl = repl;
9429     }
9430     if (CopLINE(PL_curcop) != first_line) {
9431         sv_upgrade(PL_parser->lex_sub_repl, SVt_PVNV);
9432         ((XPVNV*)SvANY(PL_parser->lex_sub_repl))->xnv_u.xnv_lines =
9433             CopLINE(PL_curcop) - first_line;
9434         CopLINE_set(PL_curcop, first_line);
9435     }
9436
9437     PL_lex_op = (OP*)pm;
9438     pl_yylval.ival = OP_SUBST;
9439     return s;
9440 }
9441
9442 STATIC char *
9443 S_scan_trans(pTHX_ char *start)
9444 {
9445     char* s;
9446     OP *o;
9447     U8 squash;
9448     U8 del;
9449     U8 complement;
9450     bool nondestruct = 0;
9451     char *t;
9452
9453     PERL_ARGS_ASSERT_SCAN_TRANS;
9454
9455     pl_yylval.ival = OP_NULL;
9456
9457     s = scan_str(start,FALSE,FALSE,FALSE,&t);
9458     if (!s)
9459         Perl_croak(aTHX_ "Transliteration pattern not terminated");
9460
9461     s = t;
9462
9463     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
9464     if (!s) {
9465         SvREFCNT_dec_NN(PL_lex_stuff);
9466         PL_lex_stuff = NULL;
9467         Perl_croak(aTHX_ "Transliteration replacement not terminated");
9468     }
9469
9470     complement = del = squash = 0;
9471     while (1) {
9472         switch (*s) {
9473         case 'c':
9474             complement = OPpTRANS_COMPLEMENT;
9475             break;
9476         case 'd':
9477             del = OPpTRANS_DELETE;
9478             break;
9479         case 's':
9480             squash = OPpTRANS_SQUASH;
9481             break;
9482         case 'r':
9483             nondestruct = 1;
9484             break;
9485         default:
9486             goto no_more;
9487         }
9488         s++;
9489     }
9490   no_more:
9491
9492     o = newPVOP(nondestruct ? OP_TRANSR : OP_TRANS, 0, (char*)NULL);
9493     o->op_private &= ~OPpTRANS_ALL;
9494     o->op_private |= del|squash|complement|
9495       (DO_UTF8(PL_lex_stuff)? OPpTRANS_FROM_UTF : 0)|
9496       (DO_UTF8(PL_parser->lex_sub_repl) ? OPpTRANS_TO_UTF   : 0);
9497
9498     PL_lex_op = o;
9499     pl_yylval.ival = nondestruct ? OP_TRANSR : OP_TRANS;
9500
9501
9502     return s;
9503 }
9504
9505 /* scan_heredoc
9506    Takes a pointer to the first < in <<FOO.
9507    Returns a pointer to the byte following <<FOO.
9508
9509    This function scans a heredoc, which involves different methods
9510    depending on whether we are in a string eval, quoted construct, etc.
9511    This is because PL_linestr could containing a single line of input, or
9512    a whole string being evalled, or the contents of the current quote-
9513    like operator.
9514
9515    The two basic methods are:
9516     - Steal lines from the input stream
9517     - Scan the heredoc in PL_linestr and remove it therefrom
9518
9519    In a file scope or filtered eval, the first method is used; in a
9520    string eval, the second.
9521
9522    In a quote-like operator, we have to choose between the two,
9523    depending on where we can find a newline.  We peek into outer lex-
9524    ing scopes until we find one with a newline in it.  If we reach the
9525    outermost lexing scope and it is a file, we use the stream method.
9526    Otherwise it is treated as an eval.
9527 */
9528
9529 STATIC char *
9530 S_scan_heredoc(pTHX_ char *s)
9531 {
9532     I32 op_type = OP_SCALAR;
9533     I32 len;
9534     SV *tmpstr;
9535     char term;
9536     char *d;
9537     char *e;
9538     char *peek;
9539     const bool infile = PL_rsfp || PL_parser->filtered;
9540     const line_t origline = CopLINE(PL_curcop);
9541     LEXSHARED *shared = PL_parser->lex_shared;
9542
9543     PERL_ARGS_ASSERT_SCAN_HEREDOC;
9544
9545     s += 2;
9546     d = PL_tokenbuf + 1;
9547     e = PL_tokenbuf + sizeof PL_tokenbuf - 1;
9548     *PL_tokenbuf = '\n';
9549     peek = s;
9550     while (SPACE_OR_TAB(*peek))
9551         peek++;
9552     if (*peek == '`' || *peek == '\'' || *peek =='"') {
9553         s = peek;
9554         term = *s++;
9555         s = delimcpy(d, e, s, PL_bufend, term, &len);
9556         if (s == PL_bufend)
9557             Perl_croak(aTHX_ "Unterminated delimiter for here document");
9558         d += len;
9559         s++;
9560     }
9561     else {
9562         if (*s == '\\')
9563             /* <<\FOO is equivalent to <<'FOO' */
9564             s++, term = '\'';
9565         else
9566             term = '"';
9567         if (!isWORDCHAR_lazy_if(s,UTF))
9568             deprecate("bare << to mean <<\"\"");
9569         peek = s;
9570         while (isWORDCHAR_lazy_if(peek,UTF)) {
9571             peek += UTF ? UTF8SKIP(peek) : 1;
9572         }
9573         len = (peek - s >= e - d) ? (e - d) : (peek - s);
9574         Copy(s, d, len, char);
9575         s += len;
9576         d += len;
9577     }
9578     if (d >= PL_tokenbuf + sizeof PL_tokenbuf - 1)
9579         Perl_croak(aTHX_ "Delimiter for here document is too long");
9580     *d++ = '\n';
9581     *d = '\0';
9582     len = d - PL_tokenbuf;
9583
9584 #ifndef PERL_STRICT_CR
9585     d = strchr(s, '\r');
9586     if (d) {
9587         char * const olds = s;
9588         s = d;
9589         while (s < PL_bufend) {
9590             if (*s == '\r') {
9591                 *d++ = '\n';
9592                 if (*++s == '\n')
9593                     s++;
9594             }
9595             else if (*s == '\n' && s[1] == '\r') {      /* \015\013 on a mac? */
9596                 *d++ = *s++;
9597                 s++;
9598             }
9599             else
9600                 *d++ = *s++;
9601         }
9602         *d = '\0';
9603         PL_bufend = d;
9604         SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
9605         s = olds;
9606     }
9607 #endif
9608
9609     tmpstr = newSV_type(SVt_PVIV);
9610     SvGROW(tmpstr, 80);
9611     if (term == '\'') {
9612         op_type = OP_CONST;
9613         SvIV_set(tmpstr, -1);
9614     }
9615     else if (term == '`') {
9616         op_type = OP_BACKTICK;
9617         SvIV_set(tmpstr, '\\');
9618     }
9619
9620     PL_multi_start = origline + 1 + PL_parser->herelines;
9621     PL_multi_open = PL_multi_close = '<';
9622     /* inside a string eval or quote-like operator */
9623     if (!infile || PL_lex_inwhat) {
9624         SV *linestr;
9625         char *bufend;
9626         char * const olds = s;
9627         PERL_CONTEXT * const cx = CX_CUR();
9628         /* These two fields are not set until an inner lexing scope is
9629            entered.  But we need them set here. */
9630         shared->ls_bufptr  = s;
9631         shared->ls_linestr = PL_linestr;
9632         if (PL_lex_inwhat)
9633           /* Look for a newline.  If the current buffer does not have one,
9634              peek into the line buffer of the parent lexing scope, going
9635              up as many levels as necessary to find one with a newline
9636              after bufptr.
9637            */
9638           while (!(s = (char *)memchr(
9639                     (void *)shared->ls_bufptr, '\n',
9640                     SvEND(shared->ls_linestr)-shared->ls_bufptr
9641                 ))) {
9642             shared = shared->ls_prev;
9643             /* shared is only null if we have gone beyond the outermost
9644                lexing scope.  In a file, we will have broken out of the
9645                loop in the previous iteration.  In an eval, the string buf-
9646                fer ends with "\n;", so the while condition above will have
9647                evaluated to false.  So shared can never be null.  Or so you
9648                might think.  Odd syntax errors like s;@{<<; can gobble up
9649                the implicit semicolon at the end of a flie, causing the
9650                file handle to be closed even when we are not in a string
9651                eval.  So shared may be null in that case.
9652                (Closing '}' here to balance the earlier open brace for
9653                editors that look for matched pairs.) */
9654             if (UNLIKELY(!shared))
9655                 goto interminable;
9656             /* A LEXSHARED struct with a null ls_prev pointer is the outer-
9657                most lexing scope.  In a file, shared->ls_linestr at that
9658                level is just one line, so there is no body to steal. */
9659             if (infile && !shared->ls_prev) {
9660                 s = olds;
9661                 goto streaming;
9662             }
9663           }
9664         else {  /* eval or we've already hit EOF */
9665             s = (char*)memchr((void*)s, '\n', PL_bufend - s);
9666             if (!s)
9667                 goto interminable;
9668         }
9669         linestr = shared->ls_linestr;
9670         bufend = SvEND(linestr);
9671         d = s;
9672         while (s < bufend - len + 1
9673                && memNE(s,PL_tokenbuf,len) )
9674         {
9675             if (*s++ == '\n')
9676                 ++PL_parser->herelines;
9677         }
9678         if (s >= bufend - len + 1) {
9679             goto interminable;
9680         }
9681         sv_setpvn(tmpstr,d+1,s-d);
9682         s += len - 1;
9683         /* the preceding stmt passes a newline */
9684         PL_parser->herelines++;
9685
9686         /* s now points to the newline after the heredoc terminator.
9687            d points to the newline before the body of the heredoc.
9688          */
9689
9690         /* We are going to modify linestr in place here, so set
9691            aside copies of the string if necessary for re-evals or
9692            (caller $n)[6]. */
9693         /* See the Paranoia note in case LEX_INTERPEND in yylex, for why we
9694            check shared->re_eval_str. */
9695         if (shared->re_eval_start || shared->re_eval_str) {
9696             /* Set aside the rest of the regexp */
9697             if (!shared->re_eval_str)
9698                 shared->re_eval_str =
9699                        newSVpvn(shared->re_eval_start,
9700                                 bufend - shared->re_eval_start);
9701             shared->re_eval_start -= s-d;
9702         }
9703         if (cxstack_ix >= 0
9704             && CxTYPE(cx) == CXt_EVAL
9705             && CxOLD_OP_TYPE(cx) == OP_ENTEREVAL
9706             && cx->blk_eval.cur_text == linestr)
9707         {
9708             cx->blk_eval.cur_text = newSVsv(linestr);
9709             SvSCREAM_on(cx->blk_eval.cur_text);
9710         }
9711         /* Copy everything from s onwards back to d. */
9712         Move(s,d,bufend-s + 1,char);
9713         SvCUR_set(linestr, SvCUR(linestr) - (s-d));
9714         /* Setting PL_bufend only applies when we have not dug deeper
9715            into other scopes, because sublex_done sets PL_bufend to
9716            SvEND(PL_linestr). */
9717         if (shared == PL_parser->lex_shared) PL_bufend = SvEND(linestr);
9718         s = olds;
9719     }
9720     else
9721     {
9722       SV *linestr_save;
9723       char *oldbufptr_save;
9724       char *oldoldbufptr_save;
9725      streaming:
9726       SvPVCLEAR(tmpstr);   /* avoid "uninitialized" warning */
9727       term = PL_tokenbuf[1];
9728       len--;
9729       linestr_save = PL_linestr; /* must restore this afterwards */
9730       d = s;                     /* and this */
9731       oldbufptr_save = PL_oldbufptr;
9732       oldoldbufptr_save = PL_oldoldbufptr;
9733       PL_linestr = newSVpvs("");
9734       PL_bufend = SvPVX(PL_linestr);
9735       while (1) {
9736         PL_bufptr = PL_bufend;
9737         CopLINE_set(PL_curcop,
9738                     origline + 1 + PL_parser->herelines);
9739         if (!lex_next_chunk(LEX_NO_TERM)
9740          && (!SvCUR(tmpstr) || SvEND(tmpstr)[-1] != '\n')) {
9741             /* Simply freeing linestr_save might seem simpler here, as it
9742                does not matter what PL_linestr points to, since we are
9743                about to croak; but in a quote-like op, linestr_save
9744                will have been prospectively freed already, via
9745                SAVEFREESV(PL_linestr) in sublex_push, so it’s easier to
9746                restore PL_linestr. */
9747             SvREFCNT_dec_NN(PL_linestr);
9748             PL_linestr = linestr_save;
9749             PL_oldbufptr = oldbufptr_save;
9750             PL_oldoldbufptr = oldoldbufptr_save;
9751             goto interminable;
9752         }
9753         CopLINE_set(PL_curcop, origline);
9754         if (!SvCUR(PL_linestr) || PL_bufend[-1] != '\n') {
9755             s = lex_grow_linestr(SvLEN(PL_linestr) + 3);
9756             /* ^That should be enough to avoid this needing to grow:  */
9757             sv_catpvs(PL_linestr, "\n\0");
9758             assert(s == SvPVX(PL_linestr));
9759             PL_bufend = SvEND(PL_linestr);
9760         }
9761         s = PL_bufptr;
9762         PL_parser->herelines++;
9763         PL_last_lop = PL_last_uni = NULL;
9764 #ifndef PERL_STRICT_CR
9765         if (PL_bufend - PL_linestart >= 2) {
9766             if (   (PL_bufend[-2] == '\r' && PL_bufend[-1] == '\n')
9767                 || (PL_bufend[-2] == '\n' && PL_bufend[-1] == '\r'))
9768             {
9769                 PL_bufend[-2] = '\n';
9770                 PL_bufend--;
9771                 SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
9772             }
9773             else if (PL_bufend[-1] == '\r')
9774                 PL_bufend[-1] = '\n';
9775         }
9776         else if (PL_bufend - PL_linestart == 1 && PL_bufend[-1] == '\r')
9777             PL_bufend[-1] = '\n';
9778 #endif
9779         if (*s == term && PL_bufend-s >= len
9780          && memEQ(s,PL_tokenbuf + 1,len)) {
9781             SvREFCNT_dec(PL_linestr);
9782             PL_linestr = linestr_save;
9783             PL_linestart = SvPVX(linestr_save);
9784             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
9785             PL_oldbufptr = oldbufptr_save;
9786             PL_oldoldbufptr = oldoldbufptr_save;
9787             s = d;
9788             break;
9789         }
9790         else {
9791             sv_catsv(tmpstr,PL_linestr);
9792         }
9793       }
9794     }
9795     PL_multi_end = origline + PL_parser->herelines;
9796     if (SvCUR(tmpstr) + 5 < SvLEN(tmpstr)) {
9797         SvPV_shrink_to_cur(tmpstr);
9798     }
9799     if (!IN_BYTES) {
9800         if (UTF && is_utf8_string((U8*)SvPVX_const(tmpstr), SvCUR(tmpstr)))
9801             SvUTF8_on(tmpstr);
9802     }
9803     PL_lex_stuff = tmpstr;
9804     pl_yylval.ival = op_type;
9805     return s;
9806
9807   interminable:
9808     SvREFCNT_dec(tmpstr);
9809     CopLINE_set(PL_curcop, origline);
9810     missingterm(PL_tokenbuf + 1);
9811 }
9812
9813 /* scan_inputsymbol
9814    takes: position of first '<' in input buffer
9815    returns: position of first char following the matching '>' in
9816             input buffer
9817    side-effects: pl_yylval and lex_op are set.
9818
9819    This code handles:
9820
9821    <>           read from ARGV
9822    <<>>         read from ARGV without magic open
9823    <FH>         read from filehandle
9824    <pkg::FH>    read from package qualified filehandle
9825    <pkg'FH>     read from package qualified filehandle
9826    <$fh>        read from filehandle in $fh
9827    <*.h>        filename glob
9828
9829 */
9830
9831 STATIC char *
9832 S_scan_inputsymbol(pTHX_ char *start)
9833 {
9834     char *s = start;            /* current position in buffer */
9835     char *end;
9836     I32 len;
9837     bool nomagicopen = FALSE;
9838     char *d = PL_tokenbuf;                                      /* start of temp holding space */
9839     const char * const e = PL_tokenbuf + sizeof PL_tokenbuf;    /* end of temp holding space */
9840
9841     PERL_ARGS_ASSERT_SCAN_INPUTSYMBOL;
9842
9843     end = strchr(s, '\n');
9844     if (!end)
9845         end = PL_bufend;
9846     if (s[1] == '<' && s[2] == '>' && s[3] == '>') {
9847         nomagicopen = TRUE;
9848         *d = '\0';
9849         len = 0;
9850         s += 3;
9851     }
9852     else
9853         s = delimcpy(d, e, s + 1, end, '>', &len);      /* extract until > */
9854
9855     /* die if we didn't have space for the contents of the <>,
9856        or if it didn't end, or if we see a newline
9857     */
9858
9859     if (len >= (I32)sizeof PL_tokenbuf)
9860         Perl_croak(aTHX_ "Excessively long <> operator");
9861     if (s >= end)
9862         Perl_croak(aTHX_ "Unterminated <> operator");
9863
9864     s++;
9865
9866     /* check for <$fh>
9867        Remember, only scalar variables are interpreted as filehandles by
9868        this code.  Anything more complex (e.g., <$fh{$num}>) will be
9869        treated as a glob() call.
9870        This code makes use of the fact that except for the $ at the front,
9871        a scalar variable and a filehandle look the same.
9872     */
9873     if (*d == '$' && d[1]) d++;
9874
9875     /* allow <Pkg'VALUE> or <Pkg::VALUE> */
9876     while (*d && (isWORDCHAR_lazy_if(d,UTF) || *d == '\'' || *d == ':'))
9877         d += UTF ? UTF8SKIP(d) : 1;
9878
9879     /* If we've tried to read what we allow filehandles to look like, and
9880        there's still text left, then it must be a glob() and not a getline.
9881        Use scan_str to pull out the stuff between the <> and treat it
9882        as nothing more than a string.
9883     */
9884
9885     if (d - PL_tokenbuf != len) {
9886         pl_yylval.ival = OP_GLOB;
9887         s = scan_str(start,FALSE,FALSE,FALSE,NULL);
9888         if (!s)
9889            Perl_croak(aTHX_ "Glob not terminated");
9890         return s;
9891     }
9892     else {
9893         bool readline_overriden = FALSE;
9894         GV *gv_readline;
9895         /* we're in a filehandle read situation */
9896         d = PL_tokenbuf;
9897
9898         /* turn <> into <ARGV> */
9899         if (!len)
9900             Copy("ARGV",d,5,char);
9901
9902         /* Check whether readline() is overriden */
9903         if ((gv_readline = gv_override("readline",8)))
9904             readline_overriden = TRUE;
9905
9906         /* if <$fh>, create the ops to turn the variable into a
9907            filehandle
9908         */
9909         if (*d == '$') {
9910             /* try to find it in the pad for this block, otherwise find
9911                add symbol table ops
9912             */
9913             const PADOFFSET tmp = pad_findmy_pvn(d, len, 0);
9914             if (tmp != NOT_IN_PAD) {
9915                 if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
9916                     HV * const stash = PAD_COMPNAME_OURSTASH(tmp);
9917                     HEK * const stashname = HvNAME_HEK(stash);
9918                     SV * const sym = sv_2mortal(newSVhek(stashname));
9919                     sv_catpvs(sym, "::");
9920                     sv_catpv(sym, d+1);
9921                     d = SvPVX(sym);
9922                     goto intro_sym;
9923                 }
9924                 else {
9925                     OP * const o = newOP(OP_PADSV, 0);
9926                     o->op_targ = tmp;
9927                     PL_lex_op = readline_overriden
9928                         ? (OP*)newUNOP(OP_ENTERSUB, OPf_STACKED,
9929                                 op_append_elem(OP_LIST, o,
9930                                     newCVREF(0, newGVOP(OP_GV,0,gv_readline))))
9931                         : (OP*)newUNOP(OP_READLINE, 0, o);
9932                 }
9933             }
9934             else {
9935                 GV *gv;
9936                 ++d;
9937               intro_sym:
9938                 gv = gv_fetchpv(d,
9939                                 GV_ADDMULTI | ( UTF ? SVf_UTF8 : 0 ),
9940                                 SVt_PV);
9941                 PL_lex_op = readline_overriden
9942                     ? (OP*)newUNOP(OP_ENTERSUB, OPf_STACKED,
9943                             op_append_elem(OP_LIST,
9944                                 newUNOP(OP_RV2SV, 0, newGVOP(OP_GV, 0, gv)),
9945                                 newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
9946                     : (OP*)newUNOP(OP_READLINE, 0,
9947                             newUNOP(OP_RV2SV, 0,
9948                                 newGVOP(OP_GV, 0, gv)));
9949             }
9950             /* we created the ops in PL_lex_op, so make pl_yylval.ival a null op */
9951             pl_yylval.ival = OP_NULL;
9952         }
9953
9954         /* If it's none of the above, it must be a literal filehandle
9955            (<Foo::BAR> or <FOO>) so build a simple readline OP */
9956         else {
9957             GV * const gv = gv_fetchpv(d, GV_ADD | ( UTF ? SVf_UTF8 : 0 ), SVt_PVIO);
9958             PL_lex_op = readline_overriden
9959                 ? (OP*)newUNOP(OP_ENTERSUB, OPf_STACKED,
9960                         op_append_elem(OP_LIST,
9961                             newGVOP(OP_GV, 0, gv),
9962                             newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
9963                 : (OP*)newUNOP(OP_READLINE, nomagicopen ? OPf_SPECIAL : 0, newGVOP(OP_GV, 0, gv));
9964             pl_yylval.ival = OP_NULL;
9965         }
9966     }
9967
9968     return s;
9969 }
9970
9971
9972 /* scan_str
9973    takes:
9974         start                   position in buffer
9975         keep_bracketed_quoted   preserve \ quoting of embedded delimiters, but
9976                                 only if they are of the open/close form
9977         keep_delims             preserve the delimiters around the string
9978         re_reparse              compiling a run-time /(?{})/:
9979                                    collapse // to /,  and skip encoding src
9980         delimp                  if non-null, this is set to the position of
9981                                 the closing delimiter, or just after it if
9982                                 the closing and opening delimiters differ
9983                                 (i.e., the opening delimiter of a substitu-
9984                                 tion replacement)
9985    returns: position to continue reading from buffer
9986    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
9987         updates the read buffer.
9988
9989    This subroutine pulls a string out of the input.  It is called for:
9990         q               single quotes           q(literal text)
9991         '               single quotes           'literal text'
9992         qq              double quotes           qq(interpolate $here please)
9993         "               double quotes           "interpolate $here please"
9994         qx              backticks               qx(/bin/ls -l)
9995         `               backticks               `/bin/ls -l`
9996         qw              quote words             @EXPORT_OK = qw( func() $spam )
9997         m//             regexp match            m/this/
9998         s///            regexp substitute       s/this/that/
9999         tr///           string transliterate    tr/this/that/
10000         y///            string transliterate    y/this/that/
10001         ($*@)           sub prototypes          sub foo ($)
10002         (stuff)         sub attr parameters     sub foo : attr(stuff)
10003         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
10004         
10005    In most of these cases (all but <>, patterns and transliterate)
10006    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
10007    calls scan_str().  s/// makes yylex() call scan_subst() which calls
10008    scan_str().  tr/// and y/// make yylex() call scan_trans() which
10009    calls scan_str().
10010
10011    It skips whitespace before the string starts, and treats the first
10012    character as the delimiter.  If the delimiter is one of ([{< then
10013    the corresponding "close" character )]}> is used as the closing
10014    delimiter.  It allows quoting of delimiters, and if the string has
10015    balanced delimiters ([{<>}]) it allows nesting.
10016
10017    On success, the SV with the resulting string is put into lex_stuff or,
10018    if that is already non-NULL, into lex_repl. The second case occurs only
10019    when parsing the RHS of the special constructs s/// and tr/// (y///).
10020    For convenience, the terminating delimiter character is stuffed into
10021    SvIVX of the SV.
10022 */
10023
10024 STATIC char *
10025 S_scan_str(pTHX_ char *start, int keep_bracketed_quoted, int keep_delims, int re_reparse,
10026                  char **delimp
10027     )
10028 {
10029     SV *sv;                     /* scalar value: string */
10030     const char *tmps;           /* temp string, used for delimiter matching */
10031     char *s = start;            /* current position in the buffer */
10032     char term;                  /* terminating character */
10033     char *to;                   /* current position in the sv's data */
10034     I32 brackets = 1;           /* bracket nesting level */
10035     bool has_utf8 = FALSE;      /* is there any utf8 content? */
10036     IV termcode;                /* terminating char. code */
10037     U8 termstr[UTF8_MAXBYTES];  /* terminating string */
10038     STRLEN termlen;             /* length of terminating string */
10039     line_t herelines;
10040
10041     PERL_ARGS_ASSERT_SCAN_STR;
10042
10043     /* skip space before the delimiter */
10044     if (isSPACE(*s)) {
10045         s = skipspace(s);
10046     }
10047
10048     /* mark where we are, in case we need to report errors */
10049     CLINE;
10050
10051     /* after skipping whitespace, the next character is the terminator */
10052     term = *s;
10053     if (!UTF) {
10054         termcode = termstr[0] = term;
10055         termlen = 1;
10056     }
10057     else {
10058         termcode = utf8_to_uvchr_buf((U8*)s, (U8*)PL_bufend, &termlen);
10059         Copy(s, termstr, termlen, U8);
10060         if (!UTF8_IS_INVARIANT(term))
10061             has_utf8 = TRUE;
10062     }
10063
10064     /* mark where we are */
10065     PL_multi_start = CopLINE(PL_curcop);
10066     PL_multi_open = termcode;
10067     herelines = PL_parser->herelines;
10068
10069     /* find corresponding closing delimiter */
10070     if (term && (tmps = strchr("([{< )]}> )]}>",term)))
10071         termcode = termstr[0] = term = tmps[5];
10072
10073     PL_multi_close = termcode;
10074
10075     if (PL_multi_open == PL_multi_close) {
10076         keep_bracketed_quoted = FALSE;
10077     }
10078
10079     /* create a new SV to hold the contents.  79 is the SV's initial length.
10080        What a random number. */
10081     sv = newSV_type(SVt_PVIV);
10082     SvGROW(sv, 80);
10083     SvIV_set(sv, termcode);
10084     (void)SvPOK_only(sv);               /* validate pointer */
10085
10086     /* move past delimiter and try to read a complete string */
10087     if (keep_delims)
10088         sv_catpvn(sv, s, termlen);
10089     s += termlen;
10090     for (;;) {
10091         /* extend sv if need be */
10092         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
10093         /* set 'to' to the next character in the sv's string */
10094         to = SvPVX(sv)+SvCUR(sv);
10095
10096         /* if open delimiter is the close delimiter read unbridle */
10097         if (PL_multi_open == PL_multi_close) {
10098             for (; s < PL_bufend; s++,to++) {
10099                 /* embedded newlines increment the current line number */
10100                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
10101                     COPLINE_INC_WITH_HERELINES;
10102                 /* handle quoted delimiters */
10103                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
10104                     if (!keep_bracketed_quoted
10105                         && (s[1] == term
10106                             || (re_reparse && s[1] == '\\'))
10107                     )
10108                         s++;
10109                     else /* any other quotes are simply copied straight through */
10110                         *to++ = *s++;
10111                 }
10112                 /* terminate when run out of buffer (the for() condition), or
10113                    have found the terminator */
10114                 else if (*s == term) {
10115                     if (termlen == 1)
10116                         break;
10117                     if (s+termlen <= PL_bufend && memEQ(s, (char*)termstr, termlen))
10118                         break;
10119                 }
10120                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
10121                     has_utf8 = TRUE;
10122                 *to = *s;
10123             }
10124         }
10125         
10126         /* if the terminator isn't the same as the start character (e.g.,
10127            matched brackets), we have to allow more in the quoting, and
10128            be prepared for nested brackets.
10129         */
10130         else {
10131             /* read until we run out of string, or we find the terminator */
10132             for (; s < PL_bufend; s++,to++) {
10133                 /* embedded newlines increment the line count */
10134                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
10135                     COPLINE_INC_WITH_HERELINES;
10136                 /* backslashes can escape the open or closing characters */
10137                 if (*s == '\\' && s+1 < PL_bufend) {
10138                     if (!keep_bracketed_quoted
10139                        && ( ((UV)s[1] == PL_multi_open)
10140                          || ((UV)s[1] == PL_multi_close) ))
10141                     {
10142                         s++;
10143                     }
10144                     else
10145                         *to++ = *s++;
10146                 }
10147                 /* allow nested opens and closes */
10148                 else if ((UV)*s == PL_multi_close && --brackets <= 0)
10149                     break;
10150                 else if ((UV)*s == PL_multi_open)
10151                     brackets++;
10152                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
10153                     has_utf8 = TRUE;
10154                 *to = *s;
10155             }
10156         }
10157         /* terminate the copied string and update the sv's end-of-string */
10158         *to = '\0';
10159         SvCUR_set(sv, to - SvPVX_const(sv));
10160
10161         /*
10162          * this next chunk reads more into the buffer if we're not done yet
10163          */
10164
10165         if (s < PL_bufend)
10166             break;              /* handle case where we are done yet :-) */
10167
10168 #ifndef PERL_STRICT_CR
10169         if (to - SvPVX_const(sv) >= 2) {
10170             if (   (to[-2] == '\r' && to[-1] == '\n')
10171                 || (to[-2] == '\n' && to[-1] == '\r'))
10172             {
10173                 to[-2] = '\n';
10174                 to--;
10175                 SvCUR_set(sv, to - SvPVX_const(sv));
10176             }
10177             else if (to[-1] == '\r')
10178                 to[-1] = '\n';
10179         }
10180         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
10181             to[-1] = '\n';
10182 #endif
10183         
10184         /* if we're out of file, or a read fails, bail and reset the current
10185            line marker so we can report where the unterminated string began
10186         */
10187         COPLINE_INC_WITH_HERELINES;
10188         PL_bufptr = PL_bufend;
10189         if (!lex_next_chunk(0)) {
10190             sv_free(sv);
10191             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
10192             return NULL;
10193         }
10194         s = PL_bufptr;
10195     }
10196
10197     /* at this point, we have successfully read the delimited string */
10198
10199     if (keep_delims)
10200             sv_catpvn(sv, s, termlen);
10201     s += termlen;
10202
10203     if (has_utf8)
10204         SvUTF8_on(sv);
10205
10206     PL_multi_end = CopLINE(PL_curcop);
10207     CopLINE_set(PL_curcop, PL_multi_start);
10208     PL_parser->herelines = herelines;
10209
10210     /* if we allocated too much space, give some back */
10211     if (SvCUR(sv) + 5 < SvLEN(sv)) {
10212         SvLEN_set(sv, SvCUR(sv) + 1);
10213         SvPV_renew(sv, SvLEN(sv));
10214     }
10215
10216     /* decide whether this is the first or second quoted string we've read
10217        for this op
10218     */
10219
10220     if (PL_lex_stuff)
10221         PL_parser->lex_sub_repl = sv;
10222     else
10223         PL_lex_stuff = sv;
10224     if (delimp) *delimp = PL_multi_open == PL_multi_close ? s-termlen : s;
10225     return s;
10226 }
10227
10228 /*
10229   scan_num
10230   takes: pointer to position in buffer
10231   returns: pointer to new position in buffer
10232   side-effects: builds ops for the constant in pl_yylval.op
10233
10234   Read a number in any of the formats that Perl accepts:
10235
10236   \d(_?\d)*(\.(\d(_?\d)*)?)?[Ee][\+\-]?(\d(_?\d)*)      12 12.34 12.
10237   \.\d(_?\d)*[Ee][\+\-]?(\d(_?\d)*)                     .34
10238   0b[01](_?[01])*                                       binary integers
10239   0[0-7](_?[0-7])*                                      octal integers
10240   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*                         hexadecimal integers
10241   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*(?:\.\d*)?p[+-]?[0-9]+   hexadecimal floats
10242
10243   Like most scan_ routines, it uses the PL_tokenbuf buffer to hold the
10244   thing it reads.
10245
10246   If it reads a number without a decimal point or an exponent, it will
10247   try converting the number to an integer and see if it can do so
10248   without loss of precision.
10249 */
10250
10251 char *
10252 Perl_scan_num(pTHX_ const char *start, YYSTYPE* lvalp)
10253 {
10254     const char *s = start;      /* current position in buffer */
10255     char *d;                    /* destination in temp buffer */
10256     char *e;                    /* end of temp buffer */
10257     NV nv;                              /* number read, as a double */
10258     SV *sv = NULL;                      /* place to put the converted number */
10259     bool floatit;                       /* boolean: int or float? */
10260     const char *lastub = NULL;          /* position of last underbar */
10261     static const char* const number_too_long = "Number too long";
10262     /* Hexadecimal floating point.
10263      *
10264      * In many places (where we have quads and NV is IEEE 754 double)
10265      * we can fit the mantissa bits of a NV into an unsigned quad.
10266      * (Note that UVs might not be quads even when we have quads.)
10267      * This will not work everywhere, though (either no quads, or
10268      * using long doubles), in which case we have to resort to NV,
10269      * which will probably mean horrible loss of precision due to
10270      * multiple fp operations. */
10271     bool hexfp = FALSE;
10272     int total_bits = 0;
10273     int significant_bits = 0;
10274 #if NVSIZE == 8 && defined(HAS_QUAD) && defined(Uquad_t)
10275 #  define HEXFP_UQUAD
10276     Uquad_t hexfp_uquad = 0;
10277     int hexfp_frac_bits = 0;
10278 #else
10279 #  define HEXFP_NV
10280     NV hexfp_nv = 0.0;
10281 #endif
10282     NV hexfp_mult = 1.0;
10283     UV high_non_zero = 0; /* highest digit */
10284     int non_zero_integer_digits = 0;
10285
10286     PERL_ARGS_ASSERT_SCAN_NUM;
10287
10288     /* We use the first character to decide what type of number this is */
10289
10290     switch (*s) {
10291     default:
10292         Perl_croak(aTHX_ "panic: scan_num, *s=%d", *s);
10293
10294     /* if it starts with a 0, it could be an octal number, a decimal in
10295        0.13 disguise, or a hexadecimal number, or a binary number. */
10296     case '0':
10297         {
10298           /* variables:
10299              u          holds the "number so far"
10300              shift      the power of 2 of the base
10301                         (hex == 4, octal == 3, binary == 1)
10302              overflowed was the number more than we can hold?
10303
10304              Shift is used when we add a digit.  It also serves as an "are
10305              we in octal/hex/binary?" indicator to disallow hex characters
10306              when in octal mode.
10307            */
10308             NV n = 0.0;
10309             UV u = 0;
10310             I32 shift;
10311             bool overflowed = FALSE;
10312             bool just_zero  = TRUE;     /* just plain 0 or binary number? */
10313             static const NV nvshift[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
10314             static const char* const bases[5] =
10315               { "", "binary", "", "octal", "hexadecimal" };
10316             static const char* const Bases[5] =
10317               { "", "Binary", "", "Octal", "Hexadecimal" };
10318             static const char* const maxima[5] =
10319               { "",
10320                 "0b11111111111111111111111111111111",
10321                 "",
10322                 "037777777777",
10323                 "0xffffffff" };
10324             const char *base, *Base, *max;
10325
10326             /* check for hex */
10327             if (isALPHA_FOLD_EQ(s[1], 'x')) {
10328                 shift = 4;
10329                 s += 2;
10330                 just_zero = FALSE;
10331             } else if (isALPHA_FOLD_EQ(s[1], 'b')) {
10332                 shift = 1;
10333                 s += 2;
10334                 just_zero = FALSE;
10335             }
10336             /* check for a decimal in disguise */
10337             else if (s[1] == '.' || isALPHA_FOLD_EQ(s[1], 'e'))
10338                 goto decimal;
10339             /* so it must be octal */
10340             else {
10341                 shift = 3;
10342                 s++;
10343             }
10344
10345             if (*s == '_') {
10346                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10347                                "Misplaced _ in number");
10348                lastub = s++;
10349             }
10350
10351             base = bases[shift];
10352             Base = Bases[shift];
10353             max  = maxima[shift];
10354
10355             /* read the rest of the number */
10356             for (;;) {
10357                 /* x is used in the overflow test,
10358                    b is the digit we're adding on. */
10359                 UV x, b;
10360
10361                 switch (*s) {
10362
10363                 /* if we don't mention it, we're done */
10364                 default:
10365                     goto out;
10366
10367                 /* _ are ignored -- but warned about if consecutive */
10368                 case '_':
10369                     if (lastub && s == lastub + 1)
10370                         Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10371                                        "Misplaced _ in number");
10372                     lastub = s++;
10373                     break;
10374
10375                 /* 8 and 9 are not octal */
10376                 case '8': case '9':
10377                     if (shift == 3)
10378                         yyerror(Perl_form(aTHX_ "Illegal octal digit '%c'", *s));
10379                     /* FALLTHROUGH */
10380
10381                 /* octal digits */
10382                 case '2': case '3': case '4':
10383                 case '5': case '6': case '7':
10384                     if (shift == 1)
10385                         yyerror(Perl_form(aTHX_ "Illegal binary digit '%c'", *s));
10386                     /* FALLTHROUGH */
10387
10388                 case '0': case '1':
10389                     b = *s++ & 15;              /* ASCII digit -> value of digit */
10390                     goto digit;
10391
10392                 /* hex digits */
10393                 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
10394                 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
10395                     /* make sure they said 0x */
10396                     if (shift != 4)
10397                         goto out;
10398                     b = (*s++ & 7) + 9;
10399
10400                     /* Prepare to put the digit we have onto the end
10401                        of the number so far.  We check for overflows.
10402                     */
10403
10404                   digit:
10405                     just_zero = FALSE;
10406                     if (!overflowed) {
10407                         x = u << shift; /* make room for the digit */
10408
10409                         total_bits += shift;
10410
10411                         if ((x >> shift) != u
10412                             && !(PL_hints & HINT_NEW_BINARY)) {
10413                             overflowed = TRUE;
10414                             n = (NV) u;
10415                             Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
10416                                              "Integer overflow in %s number",
10417                                              base);
10418                         } else
10419                             u = x | b;          /* add the digit to the end */
10420                     }
10421                     if (overflowed) {
10422                         n *= nvshift[shift];
10423                         /* If an NV has not enough bits in its
10424                          * mantissa to represent an UV this summing of
10425                          * small low-order numbers is a waste of time
10426                          * (because the NV cannot preserve the
10427                          * low-order bits anyway): we could just
10428                          * remember when did we overflow and in the
10429                          * end just multiply n by the right
10430                          * amount. */
10431                         n += (NV) b;
10432                     }
10433
10434                     if (high_non_zero == 0 && b > 0)
10435                         high_non_zero = b;
10436
10437                     if (high_non_zero)
10438                         non_zero_integer_digits++;
10439
10440                     /* this could be hexfp, but peek ahead
10441                      * to avoid matching ".." */
10442                     if (UNLIKELY(HEXFP_PEEK(s))) {
10443                         goto out;
10444                     }
10445
10446                     break;
10447                 }
10448             }
10449
10450           /* if we get here, we had success: make a scalar value from
10451              the number.
10452           */
10453           out:
10454
10455             /* final misplaced underbar check */
10456             if (s[-1] == '_') {
10457                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Misplaced _ in number");
10458             }
10459
10460             if (UNLIKELY(HEXFP_PEEK(s))) {
10461                 /* Do sloppy (on the underbars) but quick detection
10462                  * (and value construction) for hexfp, the decimal
10463                  * detection will shortly be more thorough with the
10464                  * underbar checks. */
10465                 const char* h = s;
10466                 significant_bits = non_zero_integer_digits * shift;
10467 #ifdef HEXFP_UQUAD
10468                 hexfp_uquad = u;
10469 #else /* HEXFP_NV */
10470                 hexfp_nv = u;
10471 #endif
10472                 /* Ignore the leading zero bits of
10473                  * the high (first) non-zero digit. */
10474                 if (high_non_zero) {
10475                     if (high_non_zero < 0x8)
10476                         significant_bits--;
10477                     if (high_non_zero < 0x4)
10478                         significant_bits--;
10479                     if (high_non_zero < 0x2)
10480                         significant_bits--;
10481                 }
10482
10483                 if (*h == '.') {
10484 #ifdef HEXFP_NV
10485                     NV nv_mult = 1.0;
10486 #endif
10487                     bool accumulate = TRUE;
10488                     for (h++; (isXDIGIT(*h) || *h == '_'); h++) {
10489                         if (isXDIGIT(*h)) {
10490                             U8 b = XDIGIT_VALUE(*h);
10491                             significant_bits += shift;
10492 #ifdef HEXFP_UQUAD
10493                             if (accumulate) {
10494                                 if (significant_bits < NV_MANT_DIG) {
10495                                     /* We are in the long "run" of xdigits,
10496                                      * accumulate the full four bits. */
10497                                     hexfp_uquad <<= shift;
10498                                     hexfp_uquad |= b;
10499                                     hexfp_frac_bits += shift;
10500                                 } else {
10501                                     /* We are at a hexdigit either at,
10502                                      * or straddling, the edge of mantissa.
10503                                      * We will try grabbing as many as
10504                                      * possible bits. */
10505                                     int tail =
10506                                       significant_bits - NV_MANT_DIG;
10507                                     if (tail <= 0)
10508                                        tail += shift;
10509                                     hexfp_uquad <<= tail;
10510                                     hexfp_uquad |= b >> (shift - tail);
10511                                     hexfp_frac_bits += tail;
10512
10513                                     /* Ignore the trailing zero bits
10514                                      * of the last non-zero xdigit.
10515                                      *
10516                                      * The assumption here is that if
10517                                      * one has input of e.g. the xdigit
10518                                      * eight (0x8), there is only one
10519                                      * bit being input, not the full
10520                                      * four bits.  Conversely, if one
10521                                      * specifies a zero xdigit, the
10522                                      * assumption is that one really
10523                                      * wants all those bits to be zero. */
10524                                     if (b) {
10525                                         if ((b & 0x1) == 0x0) {
10526                                             significant_bits--;
10527                                             if ((b & 0x2) == 0x0) {
10528                                                 significant_bits--;
10529                                                 if ((b & 0x4) == 0x0) {
10530                                                     significant_bits--;
10531                                                 }
10532                                             }
10533                                         }
10534                                     }
10535
10536                                     accumulate = FALSE;
10537                                 }
10538                             } else {
10539                                 /* Keep skipping the xdigits, and
10540                                  * accumulating the significant bits,
10541                                  * but do not shift the uquad
10542                                  * (which would catastrophically drop
10543                                  * high-order bits) or accumulate the
10544                                  * xdigits anymore. */
10545                             }
10546 #else /* HEXFP_NV */
10547                             if (accumulate) {
10548                                 nv_mult /= 16.0;
10549                                 if (nv_mult > 0.0)
10550                                     hexfp_nv += b * nv_mult;
10551                                 else
10552                                     accumulate = FALSE;
10553                             }
10554 #endif
10555                         }
10556                         if (significant_bits >= NV_MANT_DIG)
10557                             accumulate = FALSE;
10558                     }
10559                 }
10560
10561                 if ((total_bits > 0 || significant_bits > 0) &&
10562                     isALPHA_FOLD_EQ(*h, 'p')) {
10563                     bool negexp = FALSE;
10564                     h++;
10565                     if (*h == '+')
10566                         h++;
10567                     else if (*h == '-') {
10568                         negexp = TRUE;
10569                         h++;
10570                     }
10571                     if (isDIGIT(*h)) {
10572                         I32 hexfp_exp = 0;
10573                         while (isDIGIT(*h) || *h == '_') {
10574                             if (isDIGIT(*h)) {
10575                                 hexfp_exp *= 10;
10576                                 hexfp_exp += *h - '0';
10577 #ifdef NV_MIN_EXP
10578                                 if (negexp
10579                                     && -hexfp_exp < NV_MIN_EXP - 1) {
10580                                     /* NOTE: this means that the exponent
10581                                      * underflow warning happens for
10582                                      * the IEEE 754 subnormals (denormals),
10583                                      * because DBL_MIN_EXP etc are the lowest
10584                                      * possible binary (or, rather, DBL_RADIX-base)
10585                                      * exponent for normals, not subnormals.
10586                                      *
10587                                      * This may or may not be a good thing. */
10588                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
10589                                                    "Hexadecimal float: exponent underflow");
10590                                     break;
10591                                 }
10592 #endif
10593 #ifdef NV_MAX_EXP
10594                                 if (!negexp
10595                                     && hexfp_exp > NV_MAX_EXP - 1) {
10596                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
10597                                                    "Hexadecimal float: exponent overflow");
10598                                     break;
10599                                 }
10600 #endif
10601                             }
10602                             h++;
10603                         }
10604                         if (negexp)
10605                             hexfp_exp = -hexfp_exp;
10606 #ifdef HEXFP_UQUAD
10607                         hexfp_exp -= hexfp_frac_bits;
10608 #endif
10609                         hexfp_mult = Perl_pow(2.0, hexfp_exp);
10610                         hexfp = TRUE;
10611                         goto decimal;
10612                     }
10613                 }
10614             }
10615
10616             if (overflowed) {
10617                 if (n > 4294967295.0)
10618                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
10619                                    "%s number > %s non-portable",
10620                                    Base, max);
10621                 sv = newSVnv(n);
10622             }
10623             else {
10624 #if UVSIZE > 4
10625                 if (u > 0xffffffff)
10626                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
10627                                    "%s number > %s non-portable",
10628                                    Base, max);
10629 #endif
10630                 sv = newSVuv(u);
10631             }
10632             if (just_zero && (PL_hints & HINT_NEW_INTEGER))
10633                 sv = new_constant(start, s - start, "integer",
10634                                   sv, NULL, NULL, 0);
10635             else if (PL_hints & HINT_NEW_BINARY)
10636                 sv = new_constant(start, s - start, "binary", sv, NULL, NULL, 0);
10637         }
10638         break;
10639
10640     /*
10641       handle decimal numbers.
10642       we're also sent here when we read a 0 as the first digit
10643     */
10644     case '1': case '2': case '3': case '4': case '5':
10645     case '6': case '7': case '8': case '9': case '.':
10646       decimal:
10647         d = PL_tokenbuf;
10648         e = PL_tokenbuf + sizeof PL_tokenbuf - 6; /* room for various punctuation */
10649         floatit = FALSE;
10650         if (hexfp) {
10651             floatit = TRUE;
10652             *d++ = '0';
10653             *d++ = 'x';
10654             s = start + 2;
10655         }
10656
10657         /* read next group of digits and _ and copy into d */
10658         while (isDIGIT(*s)
10659                || *s == '_'
10660                || UNLIKELY(hexfp && isXDIGIT(*s)))
10661         {
10662             /* skip underscores, checking for misplaced ones
10663                if -w is on
10664             */
10665             if (*s == '_') {
10666                 if (lastub && s == lastub + 1)
10667                     Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10668                                    "Misplaced _ in number");
10669                 lastub = s++;
10670             }
10671             else {
10672                 /* check for end of fixed-length buffer */
10673                 if (d >= e)
10674                     Perl_croak(aTHX_ "%s", number_too_long);
10675                 /* if we're ok, copy the character */
10676                 *d++ = *s++;
10677             }
10678         }
10679
10680         /* final misplaced underbar check */
10681         if (lastub && s == lastub + 1) {
10682             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "Misplaced _ in number");
10683         }
10684
10685         /* read a decimal portion if there is one.  avoid
10686            3..5 being interpreted as the number 3. followed
10687            by .5
10688         */
10689         if (*s == '.' && s[1] != '.') {
10690             floatit = TRUE;
10691             *d++ = *s++;
10692
10693             if (*s == '_') {
10694                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10695                                "Misplaced _ in number");
10696                 lastub = s;
10697             }
10698
10699             /* copy, ignoring underbars, until we run out of digits.
10700             */
10701             for (; isDIGIT(*s)
10702                    || *s == '_'
10703                    || UNLIKELY(hexfp && isXDIGIT(*s));
10704                  s++)
10705             {
10706                 /* fixed length buffer check */
10707                 if (d >= e)
10708                     Perl_croak(aTHX_ "%s", number_too_long);
10709                 if (*s == '_') {
10710                    if (lastub && s == lastub + 1)
10711                        Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10712                                       "Misplaced _ in number");
10713                    lastub = s;
10714                 }
10715                 else
10716                     *d++ = *s;
10717             }
10718             /* fractional part ending in underbar? */
10719             if (s[-1] == '_') {
10720                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10721                                "Misplaced _ in number");
10722             }
10723             if (*s == '.' && isDIGIT(s[1])) {
10724                 /* oops, it's really a v-string, but without the "v" */
10725                 s = start;
10726                 goto vstring;
10727             }
10728         }
10729
10730         /* read exponent part, if present */
10731         if ((isALPHA_FOLD_EQ(*s, 'e')
10732               || UNLIKELY(hexfp && isALPHA_FOLD_EQ(*s, 'p')))
10733             && strchr("+-0123456789_", s[1]))
10734         {
10735             floatit = TRUE;
10736
10737             /* regardless of whether user said 3E5 or 3e5, use lower 'e',
10738                ditto for p (hexfloats) */
10739             if ((isALPHA_FOLD_EQ(*s, 'e'))) {
10740                 /* At least some Mach atof()s don't grok 'E' */
10741                 *d++ = 'e';
10742             }
10743             else if (UNLIKELY(hexfp && (isALPHA_FOLD_EQ(*s, 'p')))) {
10744                 *d++ = 'p';
10745             }
10746
10747             s++;
10748
10749
10750             /* stray preinitial _ */
10751             if (*s == '_') {
10752                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10753                                "Misplaced _ in number");
10754                 lastub = s++;
10755             }
10756
10757             /* allow positive or negative exponent */
10758             if (*s == '+' || *s == '-')
10759                 *d++ = *s++;
10760
10761             /* stray initial _ */
10762             if (*s == '_') {
10763                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10764                                "Misplaced _ in number");
10765                 lastub = s++;
10766             }
10767
10768             /* read digits of exponent */
10769             while (isDIGIT(*s) || *s == '_') {
10770                 if (isDIGIT(*s)) {
10771                     if (d >= e)
10772                         Perl_croak(aTHX_ "%s", number_too_long);
10773                     *d++ = *s++;
10774                 }
10775                 else {
10776                    if (((lastub && s == lastub + 1)
10777                         || (!isDIGIT(s[1]) && s[1] != '_')))
10778                        Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),
10779                                       "Misplaced _ in number");
10780                    lastub = s++;
10781                 }
10782             }
10783         }
10784
10785
10786         /*
10787            We try to do an integer conversion first if no characters
10788            indicating "float" have been found.
10789          */
10790
10791         if (!floatit) {
10792             UV uv;
10793             const int flags = grok_number (PL_tokenbuf, d - PL_tokenbuf, &uv);
10794
10795             if (flags == IS_NUMBER_IN_UV) {
10796               if (uv <= IV_MAX)
10797                 sv = newSViv(uv); /* Prefer IVs over UVs. */
10798               else
10799                 sv = newSVuv(uv);
10800             } else if (flags == (IS_NUMBER_IN_UV | IS_NUMBER_NEG)) {
10801               if (uv <= (UV) IV_MIN)
10802                 sv = newSViv(-(IV)uv);
10803               else
10804                 floatit = TRUE;
10805             } else
10806               floatit = TRUE;
10807         }
10808         if (floatit) {
10809             STORE_LC_NUMERIC_UNDERLYING_SET_STANDARD();
10810             /* terminate the string */
10811             *d = '\0';
10812             if (UNLIKELY(hexfp)) {
10813 #  ifdef NV_MANT_DIG
10814                 if (significant_bits > NV_MANT_DIG)
10815                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
10816                                    "Hexadecimal float: mantissa overflow");
10817 #  endif
10818 #ifdef HEXFP_UQUAD
10819                 nv = hexfp_uquad * hexfp_mult;
10820 #else /* HEXFP_NV */
10821                 nv = hexfp_nv * hexfp_mult;
10822 #endif
10823             } else {
10824                 nv = Atof(PL_tokenbuf);
10825             }
10826             RESTORE_LC_NUMERIC_UNDERLYING();
10827             sv = newSVnv(nv);
10828         }
10829
10830         if ( floatit
10831              ? (PL_hints & HINT_NEW_FLOAT) : (PL_hints & HINT_NEW_INTEGER) ) {
10832             const char *const key = floatit ? "float" : "integer";
10833             const STRLEN keylen = floatit ? 5 : 7;
10834             sv = S_new_constant(aTHX_ PL_tokenbuf, d - PL_tokenbuf,
10835                                 key, keylen, sv, NULL, NULL, 0);
10836         }
10837         break;
10838
10839     /* if it starts with a v, it could be a v-string */
10840     case 'v':
10841     vstring:
10842                 sv = newSV(5); /* preallocate storage space */
10843                 ENTER_with_name("scan_vstring");
10844                 SAVEFREESV(sv);
10845                 s = scan_vstring(s, PL_bufend, sv);
10846                 SvREFCNT_inc_simple_void_NN(sv);
10847                 LEAVE_with_name("scan_vstring");
10848         break;
10849     }
10850
10851     /* make the op for the constant and return */
10852
10853     if (sv)
10854         lvalp->opval = newSVOP(OP_CONST, 0, sv);
10855     else
10856         lvalp->opval = NULL;
10857
10858     return (char *)s;
10859 }
10860
10861 STATIC char *
10862 S_scan_formline(pTHX_ char *s)
10863 {
10864     char *eol;
10865     char *t;
10866     SV * const stuff = newSVpvs("");
10867     bool needargs = FALSE;
10868     bool eofmt = FALSE;
10869
10870     PERL_ARGS_ASSERT_SCAN_FORMLINE;
10871
10872     while (!needargs) {
10873         if (*s == '.') {
10874             t = s+1;
10875 #ifdef PERL_STRICT_CR
10876             while (SPACE_OR_TAB(*t))
10877                 t++;
10878 #else
10879             while (SPACE_OR_TAB(*t) || *t == '\r')
10880                 t++;
10881 #endif
10882             if (*t == '\n' || t == PL_bufend) {
10883                 eofmt = TRUE;
10884                 break;
10885             }
10886         }
10887         eol = (char *) memchr(s,'\n',PL_bufend-s);
10888         if (!eol++)
10889                 eol = PL_bufend;
10890         if (*s != '#') {
10891             for (t = s; t < eol; t++) {
10892                 if (*t == '~' && t[1] == '~' && SvCUR(stuff)) {
10893                     needargs = FALSE;
10894                     goto enough;        /* ~~ must be first line in formline */
10895                 }
10896                 if (*t == '@' || *t == '^')
10897                     needargs = TRUE;
10898             }
10899             if (eol > s) {
10900                 sv_catpvn(stuff, s, eol-s);
10901 #ifndef PERL_STRICT_CR
10902                 if (eol-s > 1 && eol[-2] == '\r' && eol[-1] == '\n') {
10903                     char *end = SvPVX(stuff) + SvCUR(stuff);
10904                     end[-2] = '\n';
10905                     end[-1] = '\0';
10906                     SvCUR_set(stuff, SvCUR(stuff) - 1);
10907                 }
10908 #endif
10909             }
10910             else
10911               break;
10912         }
10913         s = (char*)eol;
10914         if ((PL_rsfp || PL_parser->filtered)
10915          && PL_parser->form_lex_state == LEX_NORMAL) {
10916             bool got_some;
10917             PL_bufptr = PL_bufend;
10918             COPLINE_INC_WITH_HERELINES;
10919             got_some = lex_next_chunk(0);
10920             CopLINE_dec(PL_curcop);
10921             s = PL_bufptr;
10922             if (!got_some)
10923                 break;
10924         }
10925         incline(s);
10926     }
10927   enough:
10928     if (!SvCUR(stuff) || needargs)
10929         PL_lex_state = PL_parser->form_lex_state;
10930     if (SvCUR(stuff)) {
10931         PL_expect = XSTATE;
10932         if (needargs) {
10933             const char *s2 = s;
10934             while (*s2 == '\r' || *s2 == ' ' || *s2 == '\t' || *s2 == '\f'
10935                 || *s2 == '\v')
10936                 s2++;
10937             if (*s2 == '{') {
10938                 PL_expect = XTERMBLOCK;
10939                 NEXTVAL_NEXTTOKE.ival = 0;
10940                 force_next(DO);
10941             }
10942             NEXTVAL_NEXTTOKE.ival = 0;
10943             force_next(FORMLBRACK);
10944         }
10945         if (!IN_BYTES) {
10946             if (UTF && is_utf8_string((U8*)SvPVX_const(stuff), SvCUR(stuff)))
10947                 SvUTF8_on(stuff);
10948         }
10949         NEXTVAL_NEXTTOKE.opval = (OP*)newSVOP(OP_CONST, 0, stuff);
10950         force_next(THING);
10951     }
10952     else {
10953         SvREFCNT_dec(stuff);
10954         if (eofmt)
10955             PL_lex_formbrack = 0;
10956     }
10957     return s;
10958 }
10959
10960 I32
10961 Perl_start_subparse(pTHX_ I32 is_format, U32 flags)
10962 {
10963     const I32 oldsavestack_ix = PL_savestack_ix;
10964     CV* const outsidecv = PL_compcv;
10965
10966     SAVEI32(PL_subline);
10967     save_item(PL_subname);
10968     SAVESPTR(PL_compcv);
10969
10970     PL_compcv = MUTABLE_CV(newSV_type(is_format ? SVt_PVFM : SVt_PVCV));
10971     CvFLAGS(PL_compcv) |= flags;
10972
10973     PL_subline = CopLINE(PL_curcop);
10974     CvPADLIST(PL_compcv) = pad_new(padnew_SAVE|padnew_SAVESUB);
10975     CvOUTSIDE(PL_compcv) = MUTABLE_CV(SvREFCNT_inc_simple(outsidecv));
10976     CvOUTSIDE_SEQ(PL_compcv) = PL_cop_seqmax;
10977     if (outsidecv && CvPADLIST(outsidecv))
10978         CvPADLIST(PL_compcv)->xpadl_outid = CvPADLIST(outsidecv)->xpadl_id;
10979
10980     return oldsavestack_ix;
10981 }
10982
10983 static int
10984 S_yywarn(pTHX_ const char *const s, U32 flags)
10985 {
10986     PERL_ARGS_ASSERT_YYWARN;
10987
10988     PL_in_eval |= EVAL_WARNONLY;
10989     yyerror_pv(s, flags);
10990     return 0;
10991 }
10992
10993 int
10994 Perl_yyerror(pTHX_ const char *const s)
10995 {
10996     PERL_ARGS_ASSERT_YYERROR;
10997     return yyerror_pvn(s, strlen(s), 0);
10998 }
10999
11000 int
11001 Perl_yyerror_pv(pTHX_ const char *const s, U32 flags)
11002 {
11003     PERL_ARGS_ASSERT_YYERROR_PV;
11004     return yyerror_pvn(s, strlen(s), flags);
11005 }
11006
11007 int
11008 Perl_yyerror_pvn(pTHX_ const char *const s, STRLEN len, U32 flags)
11009 {
11010     const char *context = NULL;
11011     int contlen = -1;
11012     SV *msg;
11013     SV * const where_sv = newSVpvs_flags("", SVs_TEMP);
11014     int yychar  = PL_parser->yychar;
11015
11016     PERL_ARGS_ASSERT_YYERROR_PVN;
11017
11018     if (!yychar || (yychar == ';' && !PL_rsfp))
11019         sv_catpvs(where_sv, "at EOF");
11020     else if (   PL_oldoldbufptr
11021              && PL_bufptr > PL_oldoldbufptr
11022              && PL_bufptr - PL_oldoldbufptr < 200
11023              && PL_oldoldbufptr != PL_oldbufptr
11024              && PL_oldbufptr != PL_bufptr)
11025     {
11026         /*
11027                 Only for NetWare:
11028                 The code below is removed for NetWare because it abends/crashes on NetWare
11029                 when the script has error such as not having the closing quotes like:
11030                     if ($var eq "value)
11031                 Checking of white spaces is anyway done in NetWare code.
11032         */
11033 #ifndef NETWARE
11034         while (isSPACE(*PL_oldoldbufptr))
11035             PL_oldoldbufptr++;
11036 #endif
11037         context = PL_oldoldbufptr;
11038         contlen = PL_bufptr - PL_oldoldbufptr;
11039     }
11040     else if (  PL_oldbufptr
11041             && PL_bufptr > PL_oldbufptr
11042             && PL_bufptr - PL_oldbufptr < 200
11043             && PL_oldbufptr != PL_bufptr) {
11044         /*
11045                 Only for NetWare:
11046                 The code below is removed for NetWare because it abends/crashes on NetWare
11047                 when the script has error such as not having the closing quotes like:
11048                     if ($var eq "value)
11049                 Checking of white spaces is anyway done in NetWare code.
11050         */
11051 #ifndef NETWARE
11052         while (isSPACE(*PL_oldbufptr))
11053             PL_oldbufptr++;
11054 #endif
11055         context = PL_oldbufptr;
11056         contlen = PL_bufptr - PL_oldbufptr;
11057     }
11058     else if (yychar > 255)
11059         sv_catpvs(where_sv, "next token ???");
11060     else if (yychar == YYEMPTY) {
11061         if (PL_lex_state == LEX_NORMAL)
11062             sv_catpvs(where_sv, "at end of line");
11063         else if (PL_lex_inpat)
11064             sv_catpvs(where_sv, "within pattern");
11065         else
11066             sv_catpvs(where_sv, "within string");
11067     }
11068     else {
11069         sv_catpvs(where_sv, "next char ");
11070         if (yychar < 32)
11071             Perl_sv_catpvf(aTHX_ where_sv, "^%c", toCTRL(yychar));
11072         else if (isPRINT_LC(yychar)) {
11073             const char string = yychar;
11074             sv_catpvn(where_sv, &string, 1);
11075         }
11076         else
11077             Perl_sv_catpvf(aTHX_ where_sv, "\\%03o", yychar & 255);
11078     }
11079     msg = newSVpvn_flags(s, len, (flags & SVf_UTF8) | SVs_TEMP);
11080     Perl_sv_catpvf(aTHX_ msg, " at %s line %"IVdf", ",
11081         OutCopFILE(PL_curcop),
11082         (IV)(PL_parser->preambling == NOLINE
11083                ? CopLINE(PL_curcop)
11084                : PL_parser->preambling));
11085     if (context)
11086         Perl_sv_catpvf(aTHX_ msg, "near \"%"UTF8f"\"\n",
11087                              UTF8fARG(UTF, contlen, context));
11088     else
11089         Perl_sv_catpvf(aTHX_ msg, "%"SVf"\n", SVfARG(where_sv));
11090     if (PL_multi_start < PL_multi_end && (U32)(CopLINE(PL_curcop) - PL_multi_end) <= 1) {
11091         Perl_sv_catpvf(aTHX_ msg,
11092         "  (Might be a runaway multi-line %c%c string starting on line %"IVdf")\n",
11093                 (int)PL_multi_open,(int)PL_multi_close,(IV)PL_multi_start);
11094         PL_multi_end = 0;
11095     }
11096     if (PL_in_eval & EVAL_WARNONLY) {
11097         PL_in_eval &= ~EVAL_WARNONLY;
11098         Perl_ck_warner_d(aTHX_ packWARN(WARN_SYNTAX), "%"SVf, SVfARG(msg));
11099     }
11100     else
11101         qerror(msg);
11102     if (PL_error_count >= 10) {
11103         SV * errsv;
11104         if (PL_in_eval && ((errsv = ERRSV), SvCUR(errsv)))
11105             Perl_croak(aTHX_ "%"SVf"%s has too many errors.\n",
11106                        SVfARG(errsv), OutCopFILE(PL_curcop));
11107         else
11108             Perl_croak(aTHX_ "%s has too many errors.\n",
11109             OutCopFILE(PL_curcop));
11110     }
11111     PL_in_my = 0;
11112     PL_in_my_stash = NULL;
11113     return 0;
11114 }
11115
11116 STATIC char*
11117 S_swallow_bom(pTHX_ U8 *s)
11118 {
11119     const STRLEN slen = SvCUR(PL_linestr);
11120
11121     PERL_ARGS_ASSERT_SWALLOW_BOM;
11122
11123     switch (s[0]) {
11124     case 0xFF:
11125         if (s[1] == 0xFE) {
11126             /* UTF-16 little-endian? (or UTF-32LE?) */
11127             if (s[2] == 0 && s[3] == 0)  /* UTF-32 little-endian */
11128                 /* diag_listed_as: Unsupported script encoding %s */
11129                 Perl_croak(aTHX_ "Unsupported script encoding UTF-32LE");
11130 #ifndef PERL_NO_UTF16_FILTER
11131             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (BOM)\n");
11132             s += 2;
11133             if (PL_bufend > (char*)s) {
11134                 s = add_utf16_textfilter(s, TRUE);
11135             }
11136 #else
11137             /* diag_listed_as: Unsupported script encoding %s */
11138             Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
11139 #endif
11140         }
11141         break;
11142     case 0xFE:
11143         if (s[1] == 0xFF) {   /* UTF-16 big-endian? */
11144 #ifndef PERL_NO_UTF16_FILTER
11145             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (BOM)\n");
11146             s += 2;
11147             if (PL_bufend > (char *)s) {
11148                 s = add_utf16_textfilter(s, FALSE);
11149             }
11150 #else
11151             /* diag_listed_as: Unsupported script encoding %s */
11152             Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
11153 #endif
11154         }
11155         break;
11156     case BOM_UTF8_FIRST_BYTE: {
11157         const STRLEN len = sizeof(BOM_UTF8_TAIL) - 1; /* Exclude trailing NUL */
11158         if (slen > len && memEQ(s+1, BOM_UTF8_TAIL, len)) {
11159             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-8 script encoding (BOM)\n");
11160             s += len + 1;                      /* UTF-8 */
11161         }
11162         break;
11163     }
11164     case 0:
11165         if (slen > 3) {
11166              if (s[1] == 0) {
11167                   if (s[2] == 0xFE && s[3] == 0xFF) {
11168                        /* UTF-32 big-endian */
11169                        /* diag_listed_as: Unsupported script encoding %s */
11170                        Perl_croak(aTHX_ "Unsupported script encoding UTF-32BE");
11171                   }
11172              }
11173              else if (s[2] == 0 && s[3] != 0) {
11174                   /* Leading bytes
11175                    * 00 xx 00 xx
11176                    * are a good indicator of UTF-16BE. */
11177 #ifndef PERL_NO_UTF16_FILTER
11178                   if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (no BOM)\n");
11179                   s = add_utf16_textfilter(s, FALSE);
11180 #else
11181                   /* diag_listed_as: Unsupported script encoding %s */
11182                   Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
11183 #endif
11184              }
11185         }
11186         break;
11187
11188     default:
11189          if (slen > 3 && s[1] == 0 && s[2] != 0 && s[3] == 0) {
11190                   /* Leading bytes
11191                    * xx 00 xx 00
11192                    * are a good indicator of UTF-16LE. */
11193 #ifndef PERL_NO_UTF16_FILTER
11194               if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (no BOM)\n");
11195               s = add_utf16_textfilter(s, TRUE);
11196 #else
11197               /* diag_listed_as: Unsupported script encoding %s */
11198               Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
11199 #endif
11200          }
11201     }
11202     return (char*)s;
11203 }
11204
11205
11206 #ifndef PERL_NO_UTF16_FILTER
11207 static I32
11208 S_utf16_textfilter(pTHX_ int idx, SV *sv, int maxlen)
11209 {
11210     SV *const filter = FILTER_DATA(idx);
11211     /* We re-use this each time round, throwing the contents away before we
11212        return.  */
11213     SV *const utf16_buffer = MUTABLE_SV(IoTOP_GV(filter));
11214     SV *const utf8_buffer = filter;
11215     IV status = IoPAGE(filter);
11216     const bool reverse = cBOOL(IoLINES(filter));
11217     I32 retval;
11218
11219     PERL_ARGS_ASSERT_UTF16_TEXTFILTER;
11220
11221     /* As we're automatically added, at the lowest level, and hence only called
11222        from this file, we can be sure that we're not called in block mode. Hence
11223        don't bother writing code to deal with block mode.  */
11224     if (maxlen) {
11225         Perl_croak(aTHX_ "panic: utf16_textfilter called in block mode (for %d characters)", maxlen);
11226     }
11227     if (status < 0) {
11228         Perl_croak(aTHX_ "panic: utf16_textfilter called after error (status=%"IVdf")", status);
11229     }
11230     DEBUG_P(PerlIO_printf(Perl_debug_log,
11231                           "utf16_textfilter(%p,%ce): idx=%d maxlen=%d status=%"IVdf" utf16=%"UVuf" utf8=%"UVuf"\n",
11232                           FPTR2DPTR(void *, S_utf16_textfilter),
11233                           reverse ? 'l' : 'b', idx, maxlen, status,
11234                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
11235
11236     while (1) {
11237         STRLEN chars;
11238         STRLEN have;
11239         I32 newlen;
11240         U8 *end;
11241         /* First, look in our buffer of existing UTF-8 data:  */
11242         char *nl = (char *)memchr(SvPVX(utf8_buffer), '\n', SvCUR(utf8_buffer));
11243
11244         if (nl) {
11245             ++nl;
11246         } else if (status == 0) {
11247             /* EOF */
11248             IoPAGE(filter) = 0;
11249             nl = SvEND(utf8_buffer);
11250         }
11251         if (nl) {
11252             STRLEN got = nl - SvPVX(utf8_buffer);
11253             /* Did we have anything to append?  */
11254             retval = got != 0;
11255             sv_catpvn(sv, SvPVX(utf8_buffer), got);
11256             /* Everything else in this code works just fine if SVp_POK isn't
11257                set.  This, however, needs it, and we need it to work, else
11258                we loop infinitely because the buffer is never consumed.  */
11259             sv_chop(utf8_buffer, nl);
11260             break;
11261         }
11262
11263         /* OK, not a complete line there, so need to read some more UTF-16.
11264            Read an extra octect if the buffer currently has an odd number. */
11265         while (1) {
11266             if (status <= 0)
11267                 break;
11268             if (SvCUR(utf16_buffer) >= 2) {
11269                 /* Location of the high octet of the last complete code point.
11270                    Gosh, UTF-16 is a pain. All the benefits of variable length,
11271                    *coupled* with all the benefits of partial reads and
11272                    endianness.  */
11273                 const U8 *const last_hi = (U8*)SvPVX(utf16_buffer)
11274                     + ((SvCUR(utf16_buffer) & ~1) - (reverse ? 1 : 2));
11275
11276                 if (*last_hi < 0xd8 || *last_hi > 0xdb) {
11277                     break;
11278                 }
11279
11280                 /* We have the first half of a surrogate. Read more.  */
11281                 DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter partial surrogate detected at %p\n", last_hi));
11282             }
11283
11284             status = FILTER_READ(idx + 1, utf16_buffer,
11285                                  160 + (SvCUR(utf16_buffer) & 1));
11286             DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter status=%"IVdf" SvCUR(sv)=%"UVuf"\n", status, (UV)SvCUR(utf16_buffer)));
11287             DEBUG_P({ sv_dump(utf16_buffer); sv_dump(utf8_buffer);});
11288             if (status < 0) {
11289                 /* Error */
11290                 IoPAGE(filter) = status;
11291                 return status;
11292             }
11293         }
11294
11295         chars = SvCUR(utf16_buffer) >> 1;
11296         have = SvCUR(utf8_buffer);
11297         SvGROW(utf8_buffer, have + chars * 3 + 1);
11298
11299         if (reverse) {
11300             end = utf16_to_utf8_reversed((U8*)SvPVX(utf16_buffer),
11301                                          (U8*)SvPVX_const(utf8_buffer) + have,
11302                                          chars * 2, &newlen);
11303         } else {
11304             end = utf16_to_utf8((U8*)SvPVX(utf16_buffer),
11305                                 (U8*)SvPVX_const(utf8_buffer) + have,
11306                                 chars * 2, &newlen);
11307         }
11308         SvCUR_set(utf8_buffer, have + newlen);
11309         *end = '\0';
11310
11311         /* No need to keep this SV "well-formed" with a '\0' after the end, as
11312            it's private to us, and utf16_to_utf8{,reversed} take a
11313            (pointer,length) pair, rather than a NUL-terminated string.  */
11314         if(SvCUR(utf16_buffer) & 1) {
11315             *SvPVX(utf16_buffer) = SvEND(utf16_buffer)[-1];
11316             SvCUR_set(utf16_buffer, 1);
11317         } else {
11318             SvCUR_set(utf16_buffer, 0);
11319         }
11320     }
11321     DEBUG_P(PerlIO_printf(Perl_debug_log,
11322                           "utf16_textfilter: returns, status=%"IVdf" utf16=%"UVuf" utf8=%"UVuf"\n",
11323                           status,
11324                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
11325     DEBUG_P({ sv_dump(utf8_buffer); sv_dump(sv);});
11326     return retval;
11327 }
11328
11329 static U8 *
11330 S_add_utf16_textfilter(pTHX_ U8 *const s, bool reversed)
11331 {
11332     SV *filter = filter_add(S_utf16_textfilter, NULL);
11333
11334     PERL_ARGS_ASSERT_ADD_UTF16_TEXTFILTER;
11335
11336     IoTOP_GV(filter) = MUTABLE_GV(newSVpvn((char *)s, PL_bufend - (char*)s));
11337     SvPVCLEAR(filter);
11338     IoLINES(filter) = reversed;
11339     IoPAGE(filter) = 1; /* Not EOF */
11340
11341     /* Sadly, we have to return a valid pointer, come what may, so we have to
11342        ignore any error return from this.  */
11343     SvCUR_set(PL_linestr, 0);
11344     if (FILTER_READ(0, PL_linestr, 0)) {
11345         SvUTF8_on(PL_linestr);
11346     } else {
11347         SvUTF8_on(PL_linestr);
11348     }
11349     PL_bufend = SvEND(PL_linestr);
11350     return (U8*)SvPVX(PL_linestr);
11351 }
11352 #endif
11353
11354 /*
11355 Returns a pointer to the next character after the parsed
11356 vstring, as well as updating the passed in sv.
11357
11358 Function must be called like
11359
11360         sv = sv_2mortal(newSV(5));
11361         s = scan_vstring(s,e,sv);
11362
11363 where s and e are the start and end of the string.
11364 The sv should already be large enough to store the vstring
11365 passed in, for performance reasons.
11366
11367 This function may croak if fatal warnings are enabled in the
11368 calling scope, hence the sv_2mortal in the example (to prevent
11369 a leak).  Make sure to do SvREFCNT_inc afterwards if you use
11370 sv_2mortal.
11371
11372 */
11373
11374 char *
11375 Perl_scan_vstring(pTHX_ const char *s, const char *const e, SV *sv)
11376 {
11377     const char *pos = s;
11378     const char *start = s;
11379
11380     PERL_ARGS_ASSERT_SCAN_VSTRING;
11381
11382     if (*pos == 'v') pos++;  /* get past 'v' */
11383     while (pos < e && (isDIGIT(*pos) || *pos == '_'))
11384         pos++;
11385     if ( *pos != '.') {
11386         /* this may not be a v-string if followed by => */
11387         const char *next = pos;
11388         while (next < e && isSPACE(*next))
11389             ++next;
11390         if ((e - next) >= 2 && *next == '=' && next[1] == '>' ) {
11391             /* return string not v-string */
11392             sv_setpvn(sv,(char *)s,pos-s);
11393             return (char *)pos;
11394         }
11395     }
11396
11397     if (!isALPHA(*pos)) {
11398         U8 tmpbuf[UTF8_MAXBYTES+1];
11399
11400         if (*s == 'v')
11401             s++;  /* get past 'v' */
11402
11403         SvPVCLEAR(sv);
11404
11405         for (;;) {
11406             /* this is atoi() that tolerates underscores */
11407             U8 *tmpend;
11408             UV rev = 0;
11409             const char *end = pos;
11410             UV mult = 1;
11411             while (--end >= s) {
11412                 if (*end != '_') {
11413                     const UV orev = rev;
11414                     rev += (*end - '0') * mult;
11415                     mult *= 10;
11416                     if (orev > rev)
11417                         /* diag_listed_as: Integer overflow in %s number */
11418                         Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
11419                                          "Integer overflow in decimal number");
11420                 }
11421             }
11422
11423             /* Append native character for the rev point */
11424             tmpend = uvchr_to_utf8(tmpbuf, rev);
11425             sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
11426             if (!UVCHR_IS_INVARIANT(rev))
11427                  SvUTF8_on(sv);
11428             if (pos + 1 < e && *pos == '.' && isDIGIT(pos[1]))
11429                  s = ++pos;
11430             else {
11431                  s = pos;
11432                  break;
11433             }
11434             while (pos < e && (isDIGIT(*pos) || *pos == '_'))
11435                  pos++;
11436         }
11437         SvPOK_on(sv);
11438         sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
11439         SvRMAGICAL_on(sv);
11440     }
11441     return (char *)s;
11442 }
11443
11444 int
11445 Perl_keyword_plugin_standard(pTHX_
11446         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
11447 {
11448     PERL_ARGS_ASSERT_KEYWORD_PLUGIN_STANDARD;
11449     PERL_UNUSED_CONTEXT;
11450     PERL_UNUSED_ARG(keyword_ptr);
11451     PERL_UNUSED_ARG(keyword_len);
11452     PERL_UNUSED_ARG(op_ptr);
11453     return KEYWORD_PLUGIN_DECLINE;
11454 }
11455
11456 #define parse_recdescent(g,p) S_parse_recdescent(aTHX_ g,p)
11457 static void
11458 S_parse_recdescent(pTHX_ int gramtype, I32 fakeeof)
11459 {
11460     SAVEI32(PL_lex_brackets);
11461     if (PL_lex_brackets > 100)
11462         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
11463     PL_lex_brackstack[PL_lex_brackets++] = XFAKEEOF;
11464     SAVEI32(PL_lex_allbrackets);
11465     PL_lex_allbrackets = 0;
11466     SAVEI8(PL_lex_fakeeof);
11467     PL_lex_fakeeof = (U8)fakeeof;
11468     if(yyparse(gramtype) && !PL_parser->error_count)
11469         qerror(Perl_mess(aTHX_ "Parse error"));
11470 }
11471
11472 #define parse_recdescent_for_op(g,p) S_parse_recdescent_for_op(aTHX_ g,p)
11473 static OP *
11474 S_parse_recdescent_for_op(pTHX_ int gramtype, I32 fakeeof)
11475 {
11476     OP *o;
11477     ENTER;
11478     SAVEVPTR(PL_eval_root);
11479     PL_eval_root = NULL;
11480     parse_recdescent(gramtype, fakeeof);
11481     o = PL_eval_root;
11482     LEAVE;
11483     return o;
11484 }
11485
11486 #define parse_expr(p,f) S_parse_expr(aTHX_ p,f)
11487 static OP *
11488 S_parse_expr(pTHX_ I32 fakeeof, U32 flags)
11489 {
11490     OP *exprop;
11491     if (flags & ~PARSE_OPTIONAL)
11492         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_expr");
11493     exprop = parse_recdescent_for_op(GRAMEXPR, fakeeof);
11494     if (!exprop && !(flags & PARSE_OPTIONAL)) {
11495         if (!PL_parser->error_count)
11496             qerror(Perl_mess(aTHX_ "Parse error"));
11497         exprop = newOP(OP_NULL, 0);
11498     }
11499     return exprop;
11500 }
11501
11502 /*
11503 =for apidoc Amx|OP *|parse_arithexpr|U32 flags
11504
11505 Parse a Perl arithmetic expression.  This may contain operators of precedence
11506 down to the bit shift operators.  The expression must be followed (and thus
11507 terminated) either by a comparison or lower-precedence operator or by
11508 something that would normally terminate an expression such as semicolon.
11509 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
11510 otherwise it is mandatory.  It is up to the caller to ensure that the
11511 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
11512 the source of the code to be parsed and the lexical context for the
11513 expression.
11514
11515 The op tree representing the expression is returned.  If an optional
11516 expression is absent, a null pointer is returned, otherwise the pointer
11517 will be non-null.
11518
11519 If an error occurs in parsing or compilation, in most cases a valid op
11520 tree is returned anyway.  The error is reflected in the parser state,
11521 normally resulting in a single exception at the top level of parsing
11522 which covers all the compilation errors that occurred.  Some compilation
11523 errors, however, will throw an exception immediately.
11524
11525 =cut
11526 */
11527
11528 OP *
11529 Perl_parse_arithexpr(pTHX_ U32 flags)
11530 {
11531     return parse_expr(LEX_FAKEEOF_COMPARE, flags);
11532 }
11533
11534 /*
11535 =for apidoc Amx|OP *|parse_termexpr|U32 flags
11536
11537 Parse a Perl term expression.  This may contain operators of precedence
11538 down to the assignment operators.  The expression must be followed (and thus
11539 terminated) either by a comma or lower-precedence operator or by
11540 something that would normally terminate an expression such as semicolon.
11541 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
11542 otherwise it is mandatory.  It is up to the caller to ensure that the
11543 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
11544 the source of the code to be parsed and the lexical context for the
11545 expression.
11546
11547 The op tree representing the expression is returned.  If an optional
11548 expression is absent, a null pointer is returned, otherwise the pointer
11549 will be non-null.
11550
11551 If an error occurs in parsing or compilation, in most cases a valid op
11552 tree is returned anyway.  The error is reflected in the parser state,
11553 normally resulting in a single exception at the top level of parsing
11554 which covers all the compilation errors that occurred.  Some compilation
11555 errors, however, will throw an exception immediately.
11556
11557 =cut
11558 */
11559
11560 OP *
11561 Perl_parse_termexpr(pTHX_ U32 flags)
11562 {
11563     return parse_expr(LEX_FAKEEOF_COMMA, flags);
11564 }
11565
11566 /*
11567 =for apidoc Amx|OP *|parse_listexpr|U32 flags
11568
11569 Parse a Perl list expression.  This may contain operators of precedence
11570 down to the comma operator.  The expression must be followed (and thus
11571 terminated) either by a low-precedence logic operator such as C<or> or by
11572 something that would normally terminate an expression such as semicolon.
11573 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
11574 otherwise it is mandatory.  It is up to the caller to ensure that the
11575 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
11576 the source of the code to be parsed and the lexical context for the
11577 expression.
11578
11579 The op tree representing the expression is returned.  If an optional
11580 expression is absent, a null pointer is returned, otherwise the pointer
11581 will be non-null.
11582
11583 If an error occurs in parsing or compilation, in most cases a valid op
11584 tree is returned anyway.  The error is reflected in the parser state,
11585 normally resulting in a single exception at the top level of parsing
11586 which covers all the compilation errors that occurred.  Some compilation
11587 errors, however, will throw an exception immediately.
11588
11589 =cut
11590 */
11591
11592 OP *
11593 Perl_parse_listexpr(pTHX_ U32 flags)
11594 {
11595     return parse_expr(LEX_FAKEEOF_LOWLOGIC, flags);
11596 }
11597
11598 /*
11599 =for apidoc Amx|OP *|parse_fullexpr|U32 flags
11600
11601 Parse a single complete Perl expression.  This allows the full
11602 expression grammar, including the lowest-precedence operators such
11603 as C<or>.  The expression must be followed (and thus terminated) by a
11604 token that an expression would normally be terminated by: end-of-file,
11605 closing bracketing punctuation, semicolon, or one of the keywords that
11606 signals a postfix expression-statement modifier.  If C<flags> has the
11607 C<PARSE_OPTIONAL> bit set, then the expression is optional, otherwise it is
11608 mandatory.  It is up to the caller to ensure that the dynamic parser
11609 state (L</PL_parser> et al) is correctly set to reflect the source of
11610 the code to be parsed and the lexical context for the expression.
11611
11612 The op tree representing the expression is returned.  If an optional
11613 expression is absent, a null pointer is returned, otherwise the pointer
11614 will be non-null.
11615
11616 If an error occurs in parsing or compilation, in most cases a valid op
11617 tree is returned anyway.  The error is reflected in the parser state,
11618 normally resulting in a single exception at the top level of parsing
11619 which covers all the compilation errors that occurred.  Some compilation
11620 errors, however, will throw an exception immediately.
11621
11622 =cut
11623 */
11624
11625 OP *
11626 Perl_parse_fullexpr(pTHX_ U32 flags)
11627 {
11628     return parse_expr(LEX_FAKEEOF_NONEXPR, flags);
11629 }
11630
11631 /*
11632 =for apidoc Amx|OP *|parse_block|U32 flags
11633
11634 Parse a single complete Perl code block.  This consists of an opening
11635 brace, a sequence of statements, and a closing brace.  The block
11636 constitutes a lexical scope, so C<my> variables and various compile-time
11637 effects can be contained within it.  It is up to the caller to ensure
11638 that the dynamic parser state (L</PL_parser> et al) is correctly set to
11639 reflect the source of the code to be parsed and the lexical context for
11640 the statement.
11641
11642 The op tree representing the code block is returned.  This is always a
11643 real op, never a null pointer.  It will normally be a C<lineseq> list,
11644 including C<nextstate> or equivalent ops.  No ops to construct any kind
11645 of runtime scope are included by virtue of it being a block.
11646
11647 If an error occurs in parsing or compilation, in most cases a valid op
11648 tree (most likely null) is returned anyway.  The error is reflected in
11649 the parser state, normally resulting in a single exception at the top
11650 level of parsing which covers all the compilation errors that occurred.
11651 Some compilation errors, however, will throw an exception immediately.
11652
11653 The C<flags> parameter is reserved for future use, and must always
11654 be zero.
11655
11656 =cut
11657 */
11658
11659 OP *
11660 Perl_parse_block(pTHX_ U32 flags)
11661 {
11662     if (flags)
11663         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_block");
11664     return parse_recdescent_for_op(GRAMBLOCK, LEX_FAKEEOF_NEVER);
11665 }
11666
11667 /*
11668 =for apidoc Amx|OP *|parse_barestmt|U32 flags
11669
11670 Parse a single unadorned Perl statement.  This may be a normal imperative
11671 statement or a declaration that has compile-time effect.  It does not
11672 include any label or other affixture.  It is up to the caller to ensure
11673 that the dynamic parser state (L</PL_parser> et al) is correctly set to
11674 reflect the source of the code to be parsed and the lexical context for
11675 the statement.
11676
11677 The op tree representing the statement is returned.  This may be a
11678 null pointer if the statement is null, for example if it was actually
11679 a subroutine definition (which has compile-time side effects).  If not
11680 null, it will be ops directly implementing the statement, suitable to
11681 pass to L</newSTATEOP>.  It will not normally include a C<nextstate> or
11682 equivalent op (except for those embedded in a scope contained entirely
11683 within the statement).
11684
11685 If an error occurs in parsing or compilation, in most cases a valid op
11686 tree (most likely null) is returned anyway.  The error is reflected in
11687 the parser state, normally resulting in a single exception at the top
11688 level of parsing which covers all the compilation errors that occurred.
11689 Some compilation errors, however, will throw an exception immediately.
11690
11691 The C<flags> parameter is reserved for future use, and must always
11692 be zero.
11693
11694 =cut
11695 */
11696
11697 OP *
11698 Perl_parse_barestmt(pTHX_ U32 flags)
11699 {
11700     if (flags)
11701         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_barestmt");
11702     return parse_recdescent_for_op(GRAMBARESTMT, LEX_FAKEEOF_NEVER);
11703 }
11704
11705 /*
11706 =for apidoc Amx|SV *|parse_label|U32 flags
11707
11708 Parse a single label, possibly optional, of the type that may prefix a
11709 Perl statement.  It is up to the caller to ensure that the dynamic parser
11710 state (L</PL_parser> et al) is correctly set to reflect the source of
11711 the code to be parsed.  If C<flags> has the C<PARSE_OPTIONAL> bit set, then the
11712 label is optional, otherwise it is mandatory.
11713
11714 The name of the label is returned in the form of a fresh scalar.  If an
11715 optional label is absent, a null pointer is returned.
11716
11717 If an error occurs in parsing, which can only occur if the label is
11718 mandatory, a valid label is returned anyway.  The error is reflected in
11719 the parser state, normally resulting in a single exception at the top
11720 level of parsing which covers all the compilation errors that occurred.
11721
11722 =cut
11723 */
11724
11725 SV *
11726 Perl_parse_label(pTHX_ U32 flags)
11727 {
11728     if (flags & ~PARSE_OPTIONAL)
11729         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_label");
11730     if (PL_nexttoke) {
11731         PL_parser->yychar = yylex();
11732         if (PL_parser->yychar == LABEL) {
11733             char * const lpv = pl_yylval.pval;
11734             STRLEN llen = strlen(lpv);
11735             PL_parser->yychar = YYEMPTY;
11736             return newSVpvn_flags(lpv, llen, lpv[llen+1] ? SVf_UTF8 : 0);
11737         } else {
11738             yyunlex();
11739             goto no_label;
11740         }
11741     } else {
11742         char *s, *t;
11743         STRLEN wlen, bufptr_pos;
11744         lex_read_space(0);
11745         t = s = PL_bufptr;
11746         if (!isIDFIRST_lazy_if(s, UTF))
11747             goto no_label;
11748         t = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &wlen);
11749         if (word_takes_any_delimiter(s, wlen))
11750             goto no_label;
11751         bufptr_pos = s - SvPVX(PL_linestr);
11752         PL_bufptr = t;
11753         lex_read_space(LEX_KEEP_PREVIOUS);
11754         t = PL_bufptr;
11755         s = SvPVX(PL_linestr) + bufptr_pos;
11756         if (t[0] == ':' && t[1] != ':') {
11757             PL_oldoldbufptr = PL_oldbufptr;
11758             PL_oldbufptr = s;
11759             PL_bufptr = t+1;
11760             return newSVpvn_flags(s, wlen, UTF ? SVf_UTF8 : 0);
11761         } else {
11762             PL_bufptr = s;
11763             no_label:
11764             if (flags & PARSE_OPTIONAL) {
11765                 return NULL;
11766             } else {
11767                 qerror(Perl_mess(aTHX_ "Parse error"));
11768                 return newSVpvs("x");
11769             }
11770         }
11771     }
11772 }
11773
11774 /*
11775 =for apidoc Amx|OP *|parse_fullstmt|U32 flags
11776
11777 Parse a single complete Perl statement.  This may be a normal imperative
11778 statement or a declaration that has compile-time effect, and may include
11779 optional labels.  It is up to the caller to ensure that the dynamic
11780 parser state (L</PL_parser> et al) is correctly set to reflect the source
11781 of the code to be parsed and the lexical context for the statement.
11782
11783 The op tree representing the statement is returned.  This may be a
11784 null pointer if the statement is null, for example if it was actually
11785 a subroutine definition (which has compile-time side effects).  If not
11786 null, it will be the result of a L</newSTATEOP> call, normally including
11787 a C<nextstate> or equivalent op.
11788
11789 If an error occurs in parsing or compilation, in most cases a valid op
11790 tree (most likely null) is returned anyway.  The error is reflected in
11791 the parser state, normally resulting in a single exception at the top
11792 level of parsing which covers all the compilation errors that occurred.
11793 Some compilation errors, however, will throw an exception immediately.
11794
11795 The C<flags> parameter is reserved for future use, and must always
11796 be zero.
11797
11798 =cut
11799 */
11800
11801 OP *
11802 Perl_parse_fullstmt(pTHX_ U32 flags)
11803 {
11804     if (flags)
11805         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_fullstmt");
11806     return parse_recdescent_for_op(GRAMFULLSTMT, LEX_FAKEEOF_NEVER);
11807 }
11808
11809 /*
11810 =for apidoc Amx|OP *|parse_stmtseq|U32 flags
11811
11812 Parse a sequence of zero or more Perl statements.  These may be normal
11813 imperative statements, including optional labels, or declarations
11814 that have compile-time effect, or any mixture thereof.  The statement
11815 sequence ends when a closing brace or end-of-file is encountered in a
11816 place where a new statement could have validly started.  It is up to
11817 the caller to ensure that the dynamic parser state (L</PL_parser> et al)
11818 is correctly set to reflect the source of the code to be parsed and the
11819 lexical context for the statements.
11820
11821 The op tree representing the statement sequence is returned.  This may
11822 be a null pointer if the statements were all null, for example if there
11823 were no statements or if there were only subroutine definitions (which
11824 have compile-time side effects).  If not null, it will be a C<lineseq>
11825 list, normally including C<nextstate> or equivalent ops.
11826
11827 If an error occurs in parsing or compilation, in most cases a valid op
11828 tree is returned anyway.  The error is reflected in the parser state,
11829 normally resulting in a single exception at the top level of parsing
11830 which covers all the compilation errors that occurred.  Some compilation
11831 errors, however, will throw an exception immediately.
11832
11833 The C<flags> parameter is reserved for future use, and must always
11834 be zero.
11835
11836 =cut
11837 */
11838
11839 OP *
11840 Perl_parse_stmtseq(pTHX_ U32 flags)
11841 {
11842     OP *stmtseqop;
11843     I32 c;
11844     if (flags)
11845         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_stmtseq");
11846     stmtseqop = parse_recdescent_for_op(GRAMSTMTSEQ, LEX_FAKEEOF_CLOSING);
11847     c = lex_peek_unichar(0);
11848     if (c != -1 && c != /*{*/'}')
11849         qerror(Perl_mess(aTHX_ "Parse error"));
11850     return stmtseqop;
11851 }
11852
11853 /*
11854  * ex: set ts=8 sts=4 sw=4 et:
11855  */