This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
perldelta for stat(CLOSED) fix
[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
92 #define SvEVALED(sv) \
93     (SvTYPE(sv) >= SVt_PVNV \
94     && ((XPVIV*)SvANY(sv))->xiv_u.xivu_eval_seen)
95
96 static const char* const ident_too_long = "Identifier too long";
97
98 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
99
100 #define XENUMMASK  0x3f
101 #define XFAKEEOF   0x40
102 #define XFAKEBRACK 0x80
103
104 #ifdef USE_UTF8_SCRIPTS
105 #   define UTF cBOOL(!IN_BYTES)
106 #else
107 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
108 #endif
109
110 /* The maximum number of characters preceding the unrecognized one to display */
111 #define UNRECOGNIZED_PRECEDE_COUNT 10
112
113 /* In variables named $^X, these are the legal values for X.
114  * 1999-02-27 mjd-perl-patch@plover.com */
115 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
116
117 #define SPACE_OR_TAB(c) isBLANK_A(c)
118
119 #define HEXFP_PEEK(s)     \
120     (((s[0] == '.') && \
121       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
122      isALPHA_FOLD_EQ(s[0], 'p'))
123
124 /* LEX_* are values for PL_lex_state, the state of the lexer.
125  * They are arranged oddly so that the guard on the switch statement
126  * can get by with a single comparison (if the compiler is smart enough).
127  *
128  * These values refer to the various states within a sublex parse,
129  * i.e. within a double quotish string
130  */
131
132 /* #define LEX_NOTPARSING               11 is done in perl.h. */
133
134 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
135 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
136 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
137 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
138 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
139
140                                    /* at end of code, eg "$x" followed by:  */
141 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
142 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
143
144 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
145                                         string or after \E, $foo, etc       */
146 #define LEX_INTERPCONST          2 /* NOT USED */
147 #define LEX_FORMLINE             1 /* expecting a format line               */
148
149
150 #ifdef DEBUGGING
151 static const char* const lex_state_names[] = {
152     "KNOWNEXT",
153     "FORMLINE",
154     "INTERPCONST",
155     "INTERPCONCAT",
156     "INTERPENDMAYBE",
157     "INTERPEND",
158     "INTERPSTART",
159     "INTERPPUSH",
160     "INTERPCASEMOD",
161     "INTERPNORMAL",
162     "NORMAL"
163 };
164 #endif
165
166 #include "keywords.h"
167
168 /* CLINE is a macro that ensures PL_copline has a sane value */
169
170 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
171
172 /*
173  * Convenience functions to return different tokens and prime the
174  * lexer for the next token.  They all take an argument.
175  *
176  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
177  * OPERATOR     : generic operator
178  * AOPERATOR    : assignment operator
179  * PREBLOCK     : beginning the block after an if, while, foreach, ...
180  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
181  * PREREF       : *EXPR where EXPR is not a simple identifier
182  * TERM         : expression term
183  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
184  * LOOPX        : loop exiting command (goto, last, dump, etc)
185  * FTST         : file test operator
186  * FUN0         : zero-argument function
187  * FUN0OP       : zero-argument function, with its op created in this file
188  * FUN1         : not used, except for not, which isn't a UNIOP
189  * BOop         : bitwise or or xor
190  * BAop         : bitwise and
191  * BCop         : bitwise complement
192  * SHop         : shift operator
193  * PWop         : power operator
194  * PMop         : pattern-matching operator
195  * Aop          : addition-level operator
196  * AopNOASSIGN  : addition-level operator that is never part of .=
197  * Mop          : multiplication-level operator
198  * Eop          : equality-testing operator
199  * Rop          : relational operator <= != gt
200  *
201  * Also see LOP and lop() below.
202  */
203
204 #ifdef DEBUGGING /* Serve -DT. */
205 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
206 #else
207 #   define REPORT(retval) (retval)
208 #endif
209
210 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
211 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
212 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
213 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
214 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
215 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
216 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
217 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
218 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
219                          pl_yylval.ival=f, \
220                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
221                          REPORT((int)LOOPEX))
222 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
223 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
224 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
225 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
226 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
227 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
228 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
229                        REPORT('~')
230 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
231 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
232 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
233 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
234 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
235 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
236 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
237 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
238
239 /* This bit of chicanery makes a unary function followed by
240  * a parenthesis into a function with one argument, highest precedence.
241  * The UNIDOR macro is for unary functions that can be followed by the //
242  * operator (such as C<shift // 0>).
243  */
244 #define UNI3(f,x,have_x) { \
245         pl_yylval.ival = f; \
246         if (have_x) PL_expect = x; \
247         PL_bufptr = s; \
248         PL_last_uni = PL_oldbufptr; \
249         PL_last_lop_op = (f) < 0 ? -(f) : (f); \
250         if (*s == '(') \
251             return REPORT( (int)FUNC1 ); \
252         s = skipspace(s); \
253         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
254         }
255 #define UNI(f)    UNI3(f,XTERM,1)
256 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
257 #define UNIPROTO(f,optional) { \
258         if (optional) PL_last_uni = PL_oldbufptr; \
259         OPERATOR(f); \
260         }
261
262 #define UNIBRACK(f) UNI3(f,0,0)
263
264 /* grandfather return to old style */
265 #define OLDLOP(f) \
266         do { \
267             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
268                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
269             pl_yylval.ival = (f); \
270             PL_expect = XTERM; \
271             PL_bufptr = s; \
272             return (int)LSTOP; \
273         } while(0)
274
275 #define COPLINE_INC_WITH_HERELINES                  \
276     STMT_START {                                     \
277         CopLINE_inc(PL_curcop);                       \
278         if (PL_parser->herelines)                      \
279             CopLINE(PL_curcop) += PL_parser->herelines, \
280             PL_parser->herelines = 0;                    \
281     } STMT_END
282 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
283  * is no sublex_push to follow. */
284 #define COPLINE_SET_FROM_MULTI_END            \
285     STMT_START {                               \
286         CopLINE_set(PL_curcop, PL_multi_end);   \
287         if (PL_multi_end != PL_multi_start)      \
288             PL_parser->herelines = 0;             \
289     } STMT_END
290
291
292 #ifdef DEBUGGING
293
294 /* how to interpret the pl_yylval associated with the token */
295 enum token_type {
296     TOKENTYPE_NONE,
297     TOKENTYPE_IVAL,
298     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
299     TOKENTYPE_PVAL,
300     TOKENTYPE_OPVAL
301 };
302
303 static struct debug_tokens {
304     const int token;
305     enum token_type type;
306     const char *name;
307 } const debug_tokens[] =
308 {
309     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
310     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
311     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
312     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
313     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
314     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
315     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
316     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
317     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
318     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
319     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
320     { DO,               TOKENTYPE_NONE,         "DO" },
321     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
322     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
323     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
324     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
325     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
326     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
327     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
328     { FOR,              TOKENTYPE_IVAL,         "FOR" },
329     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
330     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
331     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
332     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
333     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
334     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
335     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
336     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
337     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
338     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
339     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
340     { IF,               TOKENTYPE_IVAL,         "IF" },
341     { LABEL,            TOKENTYPE_PVAL,         "LABEL" },
342     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
343     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
344     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
345     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
346     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
347     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
348     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
349     { MY,               TOKENTYPE_IVAL,         "MY" },
350     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
351     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
352     { OROP,             TOKENTYPE_IVAL,         "OROP" },
353     { OROR,             TOKENTYPE_NONE,         "OROR" },
354     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
355     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
356     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
357     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
358     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
359     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
360     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
361     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
362     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
363     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
364     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
365     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
366     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
367     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
368     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
369     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
370     { SUB,              TOKENTYPE_NONE,         "SUB" },
371     { THING,            TOKENTYPE_OPVAL,        "THING" },
372     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
373     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
374     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
375     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
376     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
377     { USE,              TOKENTYPE_IVAL,         "USE" },
378     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
379     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
380     { BAREWORD,         TOKENTYPE_OPVAL,        "BAREWORD" },
381     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
382     { 0,                TOKENTYPE_NONE,         NULL }
383 };
384
385 /* dump the returned token in rv, plus any optional arg in pl_yylval */
386
387 STATIC int
388 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
389 {
390     PERL_ARGS_ASSERT_TOKEREPORT;
391
392     if (DEBUG_T_TEST) {
393         const char *name = NULL;
394         enum token_type type = TOKENTYPE_NONE;
395         const struct debug_tokens *p;
396         SV* const report = newSVpvs("<== ");
397
398         for (p = debug_tokens; p->token; p++) {
399             if (p->token == (int)rv) {
400                 name = p->name;
401                 type = p->type;
402                 break;
403             }
404         }
405         if (name)
406             Perl_sv_catpv(aTHX_ report, name);
407         else if (isGRAPH(rv))
408         {
409             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
410             if ((char)rv == 'p')
411                 sv_catpvs(report, " (pending identifier)");
412         }
413         else if (!rv)
414             sv_catpvs(report, "EOF");
415         else
416             Perl_sv_catpvf(aTHX_ report, "?? %" IVdf, (IV)rv);
417         switch (type) {
418         case TOKENTYPE_NONE:
419             break;
420         case TOKENTYPE_IVAL:
421             Perl_sv_catpvf(aTHX_ report, "(ival=%" IVdf ")", (IV)lvalp->ival);
422             break;
423         case TOKENTYPE_OPNUM:
424             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
425                                     PL_op_name[lvalp->ival]);
426             break;
427         case TOKENTYPE_PVAL:
428             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
429             break;
430         case TOKENTYPE_OPVAL:
431             if (lvalp->opval) {
432                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
433                                     PL_op_name[lvalp->opval->op_type]);
434                 if (lvalp->opval->op_type == OP_CONST) {
435                     Perl_sv_catpvf(aTHX_ report, " %s",
436                         SvPEEK(cSVOPx_sv(lvalp->opval)));
437                 }
438
439             }
440             else
441                 sv_catpvs(report, "(opval=null)");
442             break;
443         }
444         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
445     };
446     return (int)rv;
447 }
448
449
450 /* print the buffer with suitable escapes */
451
452 STATIC void
453 S_printbuf(pTHX_ const char *const fmt, const char *const s)
454 {
455     SV* const tmp = newSVpvs("");
456
457     PERL_ARGS_ASSERT_PRINTBUF;
458
459     GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
460     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
461     GCC_DIAG_RESTORE;
462     SvREFCNT_dec(tmp);
463 }
464
465 #endif
466
467 /*
468  * S_ao
469  *
470  * This subroutine looks for an '=' next to the operator that has just been
471  * parsed and turns it into an ASSIGNOP if it finds one.
472  */
473
474 STATIC int
475 S_ao(pTHX_ int toketype)
476 {
477     if (*PL_bufptr == '=') {
478         PL_bufptr++;
479         if (toketype == ANDAND)
480             pl_yylval.ival = OP_ANDASSIGN;
481         else if (toketype == OROR)
482             pl_yylval.ival = OP_ORASSIGN;
483         else if (toketype == DORDOR)
484             pl_yylval.ival = OP_DORASSIGN;
485         toketype = ASSIGNOP;
486     }
487     return REPORT(toketype);
488 }
489
490 /*
491  * S_no_op
492  * When Perl expects an operator and finds something else, no_op
493  * prints the warning.  It always prints "<something> found where
494  * operator expected.  It prints "Missing semicolon on previous line?"
495  * if the surprise occurs at the start of the line.  "do you need to
496  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
497  * where the compiler doesn't know if foo is a method call or a function.
498  * It prints "Missing operator before end of line" if there's nothing
499  * after the missing operator, or "... before <...>" if there is something
500  * after the missing operator.
501  *
502  * PL_bufptr is expected to point to the start of the thing that was found,
503  * and s after the next token or partial token.
504  */
505
506 STATIC void
507 S_no_op(pTHX_ const char *const what, char *s)
508 {
509     char * const oldbp = PL_bufptr;
510     const bool is_first = (PL_oldbufptr == PL_linestart);
511
512     PERL_ARGS_ASSERT_NO_OP;
513
514     if (!s)
515         s = oldbp;
516     else
517         PL_bufptr = s;
518     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
519     if (ckWARN_d(WARN_SYNTAX)) {
520         if (is_first)
521             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
522                     "\t(Missing semicolon on previous line?)\n");
523         else if (PL_oldoldbufptr && isIDFIRST_lazy_if_safe(PL_oldoldbufptr,
524                                                            PL_bufend,
525                                                            UTF))
526         {
527             const char *t;
528             for (t = PL_oldoldbufptr;
529                  (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF) || *t == ':');
530                  t += UTF ? UTF8SKIP(t) : 1)
531             {
532                 NOOP;
533             }
534             if (t < PL_bufptr && isSPACE(*t))
535                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
536                         "\t(Do you need to predeclare %" UTF8f "?)\n",
537                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
538         }
539         else {
540             assert(s >= oldbp);
541             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
542                     "\t(Missing operator before %" UTF8f "?)\n",
543                      UTF8fARG(UTF, s - oldbp, oldbp));
544         }
545     }
546     PL_bufptr = oldbp;
547 }
548
549 /*
550  * S_missingterm
551  * Complain about missing quote/regexp/heredoc terminator.
552  * If it's called with NULL then it cauterizes the line buffer.
553  * If we're in a delimited string and the delimiter is a control
554  * character, it's reformatted into a two-char sequence like ^C.
555  * This is fatal.
556  */
557
558 STATIC void
559 S_missingterm(pTHX_ char *s, STRLEN len)
560 {
561     char tmpbuf[UTF8_MAXBYTES + 1];
562     char q;
563     bool uni = FALSE;
564     SV *sv;
565     if (s) {
566         char * const nl = (char *) my_memrchr(s, '\n', len);
567         if (nl) {
568             *nl = '\0';
569             len = nl - s;
570         }
571         uni = UTF;
572     }
573     else if (PL_multi_close < 32) {
574         *tmpbuf = '^';
575         tmpbuf[1] = (char)toCTRL(PL_multi_close);
576         tmpbuf[2] = '\0';
577         s = tmpbuf;
578         len = 2;
579     }
580     else {
581         if (LIKELY(PL_multi_close < 256)) {
582             *tmpbuf = (char)PL_multi_close;
583             tmpbuf[1] = '\0';
584             len = 1;
585         }
586         else {
587             char *end = (char *)uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close);
588             *end = '\0';
589             len = end - tmpbuf;
590             uni = TRUE;
591         }
592         s = tmpbuf;
593     }
594     q = memchr(s, '"', len) ? '\'' : '"';
595     sv = sv_2mortal(newSVpvn(s, len));
596     if (uni)
597         SvUTF8_on(sv);
598     Perl_croak(aTHX_ "Can't find string terminator %c%" SVf "%c"
599                      " anywhere before EOF", q, SVfARG(sv), q);
600 }
601
602 #include "feature.h"
603
604 /*
605  * Check whether the named feature is enabled.
606  */
607 bool
608 Perl_feature_is_enabled(pTHX_ const char *const name, STRLEN namelen)
609 {
610     char he_name[8 + MAX_FEATURE_LEN] = "feature_";
611
612     PERL_ARGS_ASSERT_FEATURE_IS_ENABLED;
613
614     assert(CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM);
615
616     if (namelen > MAX_FEATURE_LEN)
617         return FALSE;
618     memcpy(&he_name[8], name, namelen);
619
620     return cBOOL(cop_hints_fetch_pvn(PL_curcop, he_name, 8 + namelen, 0,
621                                      REFCOUNTED_HE_EXISTS));
622 }
623
624 /*
625  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
626  * utf16-to-utf8-reversed.
627  */
628
629 #ifdef PERL_CR_FILTER
630 static void
631 strip_return(SV *sv)
632 {
633     const char *s = SvPVX_const(sv);
634     const char * const e = s + SvCUR(sv);
635
636     PERL_ARGS_ASSERT_STRIP_RETURN;
637
638     /* outer loop optimized to do nothing if there are no CR-LFs */
639     while (s < e) {
640         if (*s++ == '\r' && *s == '\n') {
641             /* hit a CR-LF, need to copy the rest */
642             char *d = s - 1;
643             *d++ = *s++;
644             while (s < e) {
645                 if (*s == '\r' && s[1] == '\n')
646                     s++;
647                 *d++ = *s++;
648             }
649             SvCUR(sv) -= s - d;
650             return;
651         }
652     }
653 }
654
655 STATIC I32
656 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
657 {
658     const I32 count = FILTER_READ(idx+1, sv, maxlen);
659     if (count > 0 && !maxlen)
660         strip_return(sv);
661     return count;
662 }
663 #endif
664
665 /*
666 =for apidoc Amx|void|lex_start|SV *line|PerlIO *rsfp|U32 flags
667
668 Creates and initialises a new lexer/parser state object, supplying
669 a context in which to lex and parse from a new source of Perl code.
670 A pointer to the new state object is placed in L</PL_parser>.  An entry
671 is made on the save stack so that upon unwinding, the new state object
672 will be destroyed and the former value of L</PL_parser> will be restored.
673 Nothing else need be done to clean up the parsing context.
674
675 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
676 non-null, provides a string (in SV form) containing code to be parsed.
677 A copy of the string is made, so subsequent modification of C<line>
678 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
679 from which code will be read to be parsed.  If both are non-null, the
680 code in C<line> comes first and must consist of complete lines of input,
681 and C<rsfp> supplies the remainder of the source.
682
683 The C<flags> parameter is reserved for future use.  Currently it is only
684 used by perl internally, so extensions should always pass zero.
685
686 =cut
687 */
688
689 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
690    can share filters with the current parser.
691    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
692    caller, hence isn't owned by the parser, so shouldn't be closed on parser
693    destruction. This is used to handle the case of defaulting to reading the
694    script from the standard input because no filename was given on the command
695    line (without getting confused by situation where STDIN has been closed, so
696    the script handle is opened on fd 0)  */
697
698 void
699 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
700 {
701     const char *s = NULL;
702     yy_parser *parser, *oparser;
703
704     if (flags && flags & ~LEX_START_FLAGS)
705         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
706
707     /* create and initialise a parser */
708
709     Newxz(parser, 1, yy_parser);
710     parser->old_parser = oparser = PL_parser;
711     PL_parser = parser;
712
713     parser->stack = NULL;
714     parser->stack_max1 = NULL;
715     parser->ps = NULL;
716
717     /* on scope exit, free this parser and restore any outer one */
718     SAVEPARSER(parser);
719     parser->saved_curcop = PL_curcop;
720
721     /* initialise lexer state */
722
723     parser->nexttoke = 0;
724     parser->error_count = oparser ? oparser->error_count : 0;
725     parser->copline = parser->preambling = NOLINE;
726     parser->lex_state = LEX_NORMAL;
727     parser->expect = XSTATE;
728     parser->rsfp = rsfp;
729     parser->recheck_utf8_validity = FALSE;
730     parser->rsfp_filters =
731       !(flags & LEX_START_SAME_FILTER) || !oparser
732         ? NULL
733         : MUTABLE_AV(SvREFCNT_inc(
734             oparser->rsfp_filters
735              ? oparser->rsfp_filters
736              : (oparser->rsfp_filters = newAV())
737           ));
738
739     Newx(parser->lex_brackstack, 120, char);
740     Newx(parser->lex_casestack, 12, char);
741     *parser->lex_casestack = '\0';
742     Newxz(parser->lex_shared, 1, LEXSHARED);
743
744     if (line) {
745         STRLEN len;
746         const U8* first_bad_char_loc;
747
748         s = SvPV_const(line, len);
749
750         if (   SvUTF8(line)
751             && UNLIKELY(! is_utf8_string_loc((U8 *) s,
752                                              SvCUR(line),
753                                              &first_bad_char_loc)))
754         {
755             _force_out_malformed_utf8_message(first_bad_char_loc,
756                                               (U8 *) s + SvCUR(line),
757                                               0,
758                                               1 /* 1 means die */ );
759             NOT_REACHED; /* NOTREACHED */
760         }
761
762         parser->linestr = flags & LEX_START_COPIED
763                             ? SvREFCNT_inc_simple_NN(line)
764                             : newSVpvn_flags(s, len, SvUTF8(line));
765         if (!rsfp)
766             sv_catpvs(parser->linestr, "\n;");
767     } else {
768         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
769     }
770
771     parser->oldoldbufptr =
772         parser->oldbufptr =
773         parser->bufptr =
774         parser->linestart = SvPVX(parser->linestr);
775     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
776     parser->last_lop = parser->last_uni = NULL;
777
778     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
779                                                         |LEX_DONT_CLOSE_RSFP));
780     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
781                                                         |LEX_DONT_CLOSE_RSFP));
782
783     parser->in_pod = parser->filtered = 0;
784 }
785
786
787 /* delete a parser object */
788
789 void
790 Perl_parser_free(pTHX_  const yy_parser *parser)
791 {
792     PERL_ARGS_ASSERT_PARSER_FREE;
793
794     PL_curcop = parser->saved_curcop;
795     SvREFCNT_dec(parser->linestr);
796
797     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
798         PerlIO_clearerr(parser->rsfp);
799     else if (parser->rsfp && (!parser->old_parser
800           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
801         PerlIO_close(parser->rsfp);
802     SvREFCNT_dec(parser->rsfp_filters);
803     SvREFCNT_dec(parser->lex_stuff);
804     SvREFCNT_dec(parser->lex_sub_repl);
805
806     Safefree(parser->lex_brackstack);
807     Safefree(parser->lex_casestack);
808     Safefree(parser->lex_shared);
809     PL_parser = parser->old_parser;
810     Safefree(parser);
811 }
812
813 void
814 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
815 {
816     I32 nexttoke = parser->nexttoke;
817     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
818     while (nexttoke--) {
819         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
820          && parser->nextval[nexttoke].opval
821          && parser->nextval[nexttoke].opval->op_slabbed
822          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
823             op_free(parser->nextval[nexttoke].opval);
824             parser->nextval[nexttoke].opval = NULL;
825         }
826     }
827 }
828
829
830 /*
831 =for apidoc AmxU|SV *|PL_parser-E<gt>linestr
832
833 Buffer scalar containing the chunk currently under consideration of the
834 text currently being lexed.  This is always a plain string scalar (for
835 which C<SvPOK> is true).  It is not intended to be used as a scalar by
836 normal scalar means; instead refer to the buffer directly by the pointer
837 variables described below.
838
839 The lexer maintains various C<char*> pointers to things in the
840 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
841 reallocated, all of these pointers must be updated.  Don't attempt to
842 do this manually, but rather use L</lex_grow_linestr> if you need to
843 reallocate the buffer.
844
845 The content of the text chunk in the buffer is commonly exactly one
846 complete line of input, up to and including a newline terminator,
847 but there are situations where it is otherwise.  The octets of the
848 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
849 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
850 flag on this scalar, which may disagree with it.
851
852 For direct examination of the buffer, the variable
853 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
854 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
855 of these pointers is usually preferable to examination of the scalar
856 through normal scalar means.
857
858 =for apidoc AmxU|char *|PL_parser-E<gt>bufend
859
860 Direct pointer to the end of the chunk of text currently being lexed, the
861 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
862 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
863 always located at the end of the buffer, and does not count as part of
864 the buffer's contents.
865
866 =for apidoc AmxU|char *|PL_parser-E<gt>bufptr
867
868 Points to the current position of lexing inside the lexer buffer.
869 Characters around this point may be freely examined, within
870 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
871 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
872 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
873
874 Lexing code (whether in the Perl core or not) moves this pointer past
875 the characters that it consumes.  It is also expected to perform some
876 bookkeeping whenever a newline character is consumed.  This movement
877 can be more conveniently performed by the function L</lex_read_to>,
878 which handles newlines appropriately.
879
880 Interpretation of the buffer's octets can be abstracted out by
881 using the slightly higher-level functions L</lex_peek_unichar> and
882 L</lex_read_unichar>.
883
884 =for apidoc AmxU|char *|PL_parser-E<gt>linestart
885
886 Points to the start of the current line inside the lexer buffer.
887 This is useful for indicating at which column an error occurred, and
888 not much else.  This must be updated by any lexing code that consumes
889 a newline; the function L</lex_read_to> handles this detail.
890
891 =cut
892 */
893
894 /*
895 =for apidoc Amx|bool|lex_bufutf8
896
897 Indicates whether the octets in the lexer buffer
898 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
899 of Unicode characters.  If not, they should be interpreted as Latin-1
900 characters.  This is analogous to the C<SvUTF8> flag for scalars.
901
902 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
903 contains valid UTF-8.  Lexing code must be robust in the face of invalid
904 encoding.
905
906 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
907 is significant, but not the whole story regarding the input character
908 encoding.  Normally, when a file is being read, the scalar contains octets
909 and its C<SvUTF8> flag is off, but the octets should be interpreted as
910 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
911 however, the scalar may have the C<SvUTF8> flag on, and in this case its
912 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
913 is in effect.  This logic may change in the future; use this function
914 instead of implementing the logic yourself.
915
916 =cut
917 */
918
919 bool
920 Perl_lex_bufutf8(pTHX)
921 {
922     return UTF;
923 }
924
925 /*
926 =for apidoc Amx|char *|lex_grow_linestr|STRLEN len
927
928 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
929 at least C<len> octets (including terminating C<NUL>).  Returns a
930 pointer to the reallocated buffer.  This is necessary before making
931 any direct modification of the buffer that would increase its length.
932 L</lex_stuff_pvn> provides a more convenient way to insert text into
933 the buffer.
934
935 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
936 this function updates all of the lexer's variables that point directly
937 into the buffer.
938
939 =cut
940 */
941
942 char *
943 Perl_lex_grow_linestr(pTHX_ STRLEN len)
944 {
945     SV *linestr;
946     char *buf;
947     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
948     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
949     bool current;
950
951     linestr = PL_parser->linestr;
952     buf = SvPVX(linestr);
953     if (len <= SvLEN(linestr))
954         return buf;
955
956     /* Is the lex_shared linestr SV the same as the current linestr SV?
957      * Only in this case does re_eval_start need adjusting, since it
958      * points within lex_shared->ls_linestr's buffer */
959     current = (   !PL_parser->lex_shared->ls_linestr
960                || linestr == PL_parser->lex_shared->ls_linestr);
961
962     bufend_pos = PL_parser->bufend - buf;
963     bufptr_pos = PL_parser->bufptr - buf;
964     oldbufptr_pos = PL_parser->oldbufptr - buf;
965     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
966     linestart_pos = PL_parser->linestart - buf;
967     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
968     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
969     re_eval_start_pos = (current && PL_parser->lex_shared->re_eval_start) ?
970                             PL_parser->lex_shared->re_eval_start - buf : 0;
971
972     buf = sv_grow(linestr, len);
973
974     PL_parser->bufend = buf + bufend_pos;
975     PL_parser->bufptr = buf + bufptr_pos;
976     PL_parser->oldbufptr = buf + oldbufptr_pos;
977     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
978     PL_parser->linestart = buf + linestart_pos;
979     if (PL_parser->last_uni)
980         PL_parser->last_uni = buf + last_uni_pos;
981     if (PL_parser->last_lop)
982         PL_parser->last_lop = buf + last_lop_pos;
983     if (current && PL_parser->lex_shared->re_eval_start)
984         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
985     return buf;
986 }
987
988 /*
989 =for apidoc Amx|void|lex_stuff_pvn|const char *pv|STRLEN len|U32 flags
990
991 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
992 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
993 reallocating the buffer if necessary.  This means that lexing code that
994 runs later will see the characters as if they had appeared in the input.
995 It is not recommended to do this as part of normal parsing, and most
996 uses of this facility run the risk of the inserted characters being
997 interpreted in an unintended manner.
998
999 The string to be inserted is represented by C<len> octets starting
1000 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
1001 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
1002 The characters are recoded for the lexer buffer, according to how the
1003 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
1004 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
1005 function is more convenient.
1006
1007 =cut
1008 */
1009
1010 void
1011 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
1012 {
1013     dVAR;
1014     char *bufptr;
1015     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
1016     if (flags & ~(LEX_STUFF_UTF8))
1017         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
1018     if (UTF) {
1019         if (flags & LEX_STUFF_UTF8) {
1020             goto plain_copy;
1021         } else {
1022             STRLEN highhalf = 0;    /* Count of variants */
1023             const char *p, *e = pv+len;
1024             for (p = pv; p != e; p++) {
1025                 if (! UTF8_IS_INVARIANT(*p)) {
1026                     highhalf++;
1027                 }
1028             }
1029             if (!highhalf)
1030                 goto plain_copy;
1031             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
1032             bufptr = PL_parser->bufptr;
1033             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
1034             SvCUR_set(PL_parser->linestr,
1035                 SvCUR(PL_parser->linestr) + len+highhalf);
1036             PL_parser->bufend += len+highhalf;
1037             for (p = pv; p != e; p++) {
1038                 U8 c = (U8)*p;
1039                 if (! UTF8_IS_INVARIANT(c)) {
1040                     *bufptr++ = UTF8_TWO_BYTE_HI(c);
1041                     *bufptr++ = UTF8_TWO_BYTE_LO(c);
1042                 } else {
1043                     *bufptr++ = (char)c;
1044                 }
1045             }
1046         }
1047     } else {
1048         if (flags & LEX_STUFF_UTF8) {
1049             STRLEN highhalf = 0;
1050             const char *p, *e = pv+len;
1051             for (p = pv; p != e; p++) {
1052                 U8 c = (U8)*p;
1053                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1054                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1055                                 "non-Latin-1 character into Latin-1 input");
1056                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1057                     p++;
1058                     highhalf++;
1059                 } else assert(UTF8_IS_INVARIANT(c));
1060             }
1061             if (!highhalf)
1062                 goto plain_copy;
1063             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1064             bufptr = PL_parser->bufptr;
1065             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1066             SvCUR_set(PL_parser->linestr,
1067                 SvCUR(PL_parser->linestr) + len-highhalf);
1068             PL_parser->bufend += len-highhalf;
1069             p = pv;
1070             while (p < e) {
1071                 if (UTF8_IS_INVARIANT(*p)) {
1072                     *bufptr++ = *p;
1073                     p++;
1074                 }
1075                 else {
1076                     assert(p < e -1 );
1077                     *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1078                     p += 2;
1079                 }
1080             }
1081         } else {
1082           plain_copy:
1083             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1084             bufptr = PL_parser->bufptr;
1085             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1086             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1087             PL_parser->bufend += len;
1088             Copy(pv, bufptr, len, char);
1089         }
1090     }
1091 }
1092
1093 /*
1094 =for apidoc Amx|void|lex_stuff_pv|const char *pv|U32 flags
1095
1096 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1097 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1098 reallocating the buffer if necessary.  This means that lexing code that
1099 runs later will see the characters as if they had appeared in the input.
1100 It is not recommended to do this as part of normal parsing, and most
1101 uses of this facility run the risk of the inserted characters being
1102 interpreted in an unintended manner.
1103
1104 The string to be inserted is represented by octets starting at C<pv>
1105 and continuing to the first nul.  These octets are interpreted as either
1106 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1107 in C<flags>.  The characters are recoded for the lexer buffer, according
1108 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1109 If it is not convenient to nul-terminate a string to be inserted, the
1110 L</lex_stuff_pvn> function is more appropriate.
1111
1112 =cut
1113 */
1114
1115 void
1116 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1117 {
1118     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1119     lex_stuff_pvn(pv, strlen(pv), flags);
1120 }
1121
1122 /*
1123 =for apidoc Amx|void|lex_stuff_sv|SV *sv|U32 flags
1124
1125 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1126 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1127 reallocating the buffer if necessary.  This means that lexing code that
1128 runs later will see the characters as if they had appeared in the input.
1129 It is not recommended to do this as part of normal parsing, and most
1130 uses of this facility run the risk of the inserted characters being
1131 interpreted in an unintended manner.
1132
1133 The string to be inserted is the string value of C<sv>.  The characters
1134 are recoded for the lexer buffer, according to how the buffer is currently
1135 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1136 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1137 need to construct a scalar.
1138
1139 =cut
1140 */
1141
1142 void
1143 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1144 {
1145     char *pv;
1146     STRLEN len;
1147     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1148     if (flags)
1149         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1150     pv = SvPV(sv, len);
1151     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1152 }
1153
1154 /*
1155 =for apidoc Amx|void|lex_unstuff|char *ptr
1156
1157 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1158 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1159 This hides the discarded text from any lexing code that runs later,
1160 as if the text had never appeared.
1161
1162 This is not the normal way to consume lexed text.  For that, use
1163 L</lex_read_to>.
1164
1165 =cut
1166 */
1167
1168 void
1169 Perl_lex_unstuff(pTHX_ char *ptr)
1170 {
1171     char *buf, *bufend;
1172     STRLEN unstuff_len;
1173     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1174     buf = PL_parser->bufptr;
1175     if (ptr < buf)
1176         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1177     if (ptr == buf)
1178         return;
1179     bufend = PL_parser->bufend;
1180     if (ptr > bufend)
1181         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1182     unstuff_len = ptr - buf;
1183     Move(ptr, buf, bufend+1-ptr, char);
1184     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1185     PL_parser->bufend = bufend - unstuff_len;
1186 }
1187
1188 /*
1189 =for apidoc Amx|void|lex_read_to|char *ptr
1190
1191 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1192 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1193 performing the correct bookkeeping whenever a newline character is passed.
1194 This is the normal way to consume lexed text.
1195
1196 Interpretation of the buffer's octets can be abstracted out by
1197 using the slightly higher-level functions L</lex_peek_unichar> and
1198 L</lex_read_unichar>.
1199
1200 =cut
1201 */
1202
1203 void
1204 Perl_lex_read_to(pTHX_ char *ptr)
1205 {
1206     char *s;
1207     PERL_ARGS_ASSERT_LEX_READ_TO;
1208     s = PL_parser->bufptr;
1209     if (ptr < s || ptr > PL_parser->bufend)
1210         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1211     for (; s != ptr; s++)
1212         if (*s == '\n') {
1213             COPLINE_INC_WITH_HERELINES;
1214             PL_parser->linestart = s+1;
1215         }
1216     PL_parser->bufptr = ptr;
1217 }
1218
1219 /*
1220 =for apidoc Amx|void|lex_discard_to|char *ptr
1221
1222 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1223 up to C<ptr>.  The remaining content of the buffer will be moved, and
1224 all pointers into the buffer updated appropriately.  C<ptr> must not
1225 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1226 it is not permitted to discard text that has yet to be lexed.
1227
1228 Normally it is not necessarily to do this directly, because it suffices to
1229 use the implicit discarding behaviour of L</lex_next_chunk> and things
1230 based on it.  However, if a token stretches across multiple lines,
1231 and the lexing code has kept multiple lines of text in the buffer for
1232 that purpose, then after completion of the token it would be wise to
1233 explicitly discard the now-unneeded earlier lines, to avoid future
1234 multi-line tokens growing the buffer without bound.
1235
1236 =cut
1237 */
1238
1239 void
1240 Perl_lex_discard_to(pTHX_ char *ptr)
1241 {
1242     char *buf;
1243     STRLEN discard_len;
1244     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1245     buf = SvPVX(PL_parser->linestr);
1246     if (ptr < buf)
1247         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1248     if (ptr == buf)
1249         return;
1250     if (ptr > PL_parser->bufptr)
1251         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1252     discard_len = ptr - buf;
1253     if (PL_parser->oldbufptr < ptr)
1254         PL_parser->oldbufptr = ptr;
1255     if (PL_parser->oldoldbufptr < ptr)
1256         PL_parser->oldoldbufptr = ptr;
1257     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1258         PL_parser->last_uni = NULL;
1259     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1260         PL_parser->last_lop = NULL;
1261     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1262     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1263     PL_parser->bufend -= discard_len;
1264     PL_parser->bufptr -= discard_len;
1265     PL_parser->oldbufptr -= discard_len;
1266     PL_parser->oldoldbufptr -= discard_len;
1267     if (PL_parser->last_uni)
1268         PL_parser->last_uni -= discard_len;
1269     if (PL_parser->last_lop)
1270         PL_parser->last_lop -= discard_len;
1271 }
1272
1273 void
1274 Perl_notify_parser_that_changed_to_utf8(pTHX)
1275 {
1276     /* Called when $^H is changed to indicate that HINT_UTF8 has changed from
1277      * off to on.  At compile time, this has the effect of entering a 'use
1278      * utf8' section.  This means that any input was not previously checked for
1279      * UTF-8 (because it was off), but now we do need to check it, or our
1280      * assumptions about the input being sane could be wrong, and we could
1281      * segfault.  This routine just sets a flag so that the next time we look
1282      * at the input we do the well-formed UTF-8 check.  If we aren't in the
1283      * proper phase, there may not be a parser object, but if there is, setting
1284      * the flag is harmless */
1285
1286     if (PL_parser) {
1287         PL_parser->recheck_utf8_validity = TRUE;
1288     }
1289 }
1290
1291 /*
1292 =for apidoc Amx|bool|lex_next_chunk|U32 flags
1293
1294 Reads in the next chunk of text to be lexed, appending it to
1295 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1296 looked to the end of the current chunk and wants to know more.  It is
1297 usual, but not necessary, for lexing to have consumed the entirety of
1298 the current chunk at this time.
1299
1300 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1301 chunk (i.e., the current chunk has been entirely consumed), normally the
1302 current chunk will be discarded at the same time that the new chunk is
1303 read in.  If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1304 will not be discarded.  If the current chunk has not been entirely
1305 consumed, then it will not be discarded regardless of the flag.
1306
1307 Returns true if some new text was added to the buffer, or false if the
1308 buffer has reached the end of the input text.
1309
1310 =cut
1311 */
1312
1313 #define LEX_FAKE_EOF 0x80000000
1314 #define LEX_NO_TERM  0x40000000 /* here-doc */
1315
1316 bool
1317 Perl_lex_next_chunk(pTHX_ U32 flags)
1318 {
1319     SV *linestr;
1320     char *buf;
1321     STRLEN old_bufend_pos, new_bufend_pos;
1322     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1323     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1324     bool got_some_for_debugger = 0;
1325     bool got_some;
1326
1327     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1328         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1329     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1330         return FALSE;
1331     linestr = PL_parser->linestr;
1332     buf = SvPVX(linestr);
1333     if (!(flags & LEX_KEEP_PREVIOUS)
1334           && PL_parser->bufptr == PL_parser->bufend)
1335     {
1336         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1337         linestart_pos = 0;
1338         if (PL_parser->last_uni != PL_parser->bufend)
1339             PL_parser->last_uni = NULL;
1340         if (PL_parser->last_lop != PL_parser->bufend)
1341             PL_parser->last_lop = NULL;
1342         last_uni_pos = last_lop_pos = 0;
1343         *buf = 0;
1344         SvCUR(linestr) = 0;
1345     } else {
1346         old_bufend_pos = PL_parser->bufend - buf;
1347         bufptr_pos = PL_parser->bufptr - buf;
1348         oldbufptr_pos = PL_parser->oldbufptr - buf;
1349         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1350         linestart_pos = PL_parser->linestart - buf;
1351         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1352         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1353     }
1354     if (flags & LEX_FAKE_EOF) {
1355         goto eof;
1356     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1357         got_some = 0;
1358     } else if (filter_gets(linestr, old_bufend_pos)) {
1359         got_some = 1;
1360         got_some_for_debugger = 1;
1361     } else if (flags & LEX_NO_TERM) {
1362         got_some = 0;
1363     } else {
1364         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1365             SvPVCLEAR(linestr);
1366         eof:
1367         /* End of real input.  Close filehandle (unless it was STDIN),
1368          * then add implicit termination.
1369          */
1370         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1371             PerlIO_clearerr(PL_parser->rsfp);
1372         else if (PL_parser->rsfp)
1373             (void)PerlIO_close(PL_parser->rsfp);
1374         PL_parser->rsfp = NULL;
1375         PL_parser->in_pod = PL_parser->filtered = 0;
1376         if (!PL_in_eval && PL_minus_p) {
1377             sv_catpvs(linestr,
1378                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1379             PL_minus_n = PL_minus_p = 0;
1380         } else if (!PL_in_eval && PL_minus_n) {
1381             sv_catpvs(linestr, /*{*/";}");
1382             PL_minus_n = 0;
1383         } else
1384             sv_catpvs(linestr, ";");
1385         got_some = 1;
1386     }
1387     buf = SvPVX(linestr);
1388     new_bufend_pos = SvCUR(linestr);
1389     PL_parser->bufend = buf + new_bufend_pos;
1390     PL_parser->bufptr = buf + bufptr_pos;
1391
1392     if (UTF) {
1393         const U8* first_bad_char_loc;
1394         if (UNLIKELY(! is_utf8_string_loc(
1395                             (U8 *) PL_parser->bufptr,
1396                                    PL_parser->bufend - PL_parser->bufptr,
1397                                    &first_bad_char_loc)))
1398         {
1399             _force_out_malformed_utf8_message(first_bad_char_loc,
1400                                               (U8 *) PL_parser->bufend,
1401                                               0,
1402                                               1 /* 1 means die */ );
1403             NOT_REACHED; /* NOTREACHED */
1404         }
1405     }
1406
1407     PL_parser->oldbufptr = buf + oldbufptr_pos;
1408     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1409     PL_parser->linestart = buf + linestart_pos;
1410     if (PL_parser->last_uni)
1411         PL_parser->last_uni = buf + last_uni_pos;
1412     if (PL_parser->last_lop)
1413         PL_parser->last_lop = buf + last_lop_pos;
1414     if (PL_parser->preambling != NOLINE) {
1415         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1416         PL_parser->preambling = NOLINE;
1417     }
1418     if (   got_some_for_debugger
1419         && PERLDB_LINE_OR_SAVESRC
1420         && PL_curstash != PL_debstash)
1421     {
1422         /* debugger active and we're not compiling the debugger code,
1423          * so store the line into the debugger's array of lines
1424          */
1425         update_debugger_info(NULL, buf+old_bufend_pos,
1426             new_bufend_pos-old_bufend_pos);
1427     }
1428     return got_some;
1429 }
1430
1431 /*
1432 =for apidoc Amx|I32|lex_peek_unichar|U32 flags
1433
1434 Looks ahead one (Unicode) character in the text currently being lexed.
1435 Returns the codepoint (unsigned integer value) of the next character,
1436 or -1 if lexing has reached the end of the input text.  To consume the
1437 peeked character, use L</lex_read_unichar>.
1438
1439 If the next character is in (or extends into) the next chunk of input
1440 text, the next chunk will be read in.  Normally the current chunk will be
1441 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1442 bit set, then the current chunk will not be discarded.
1443
1444 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1445 is encountered, an exception is generated.
1446
1447 =cut
1448 */
1449
1450 I32
1451 Perl_lex_peek_unichar(pTHX_ U32 flags)
1452 {
1453     dVAR;
1454     char *s, *bufend;
1455     if (flags & ~(LEX_KEEP_PREVIOUS))
1456         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1457     s = PL_parser->bufptr;
1458     bufend = PL_parser->bufend;
1459     if (UTF) {
1460         U8 head;
1461         I32 unichar;
1462         STRLEN len, retlen;
1463         if (s == bufend) {
1464             if (!lex_next_chunk(flags))
1465                 return -1;
1466             s = PL_parser->bufptr;
1467             bufend = PL_parser->bufend;
1468         }
1469         head = (U8)*s;
1470         if (UTF8_IS_INVARIANT(head))
1471             return head;
1472         if (UTF8_IS_START(head)) {
1473             len = UTF8SKIP(&head);
1474             while ((STRLEN)(bufend-s) < len) {
1475                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1476                     break;
1477                 s = PL_parser->bufptr;
1478                 bufend = PL_parser->bufend;
1479             }
1480         }
1481         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1482         if (retlen == (STRLEN)-1) {
1483             _force_out_malformed_utf8_message((U8 *) s,
1484                                               (U8 *) bufend,
1485                                               0,
1486                                               1 /* 1 means die */ );
1487             NOT_REACHED; /* NOTREACHED */
1488         }
1489         return unichar;
1490     } else {
1491         if (s == bufend) {
1492             if (!lex_next_chunk(flags))
1493                 return -1;
1494             s = PL_parser->bufptr;
1495         }
1496         return (U8)*s;
1497     }
1498 }
1499
1500 /*
1501 =for apidoc Amx|I32|lex_read_unichar|U32 flags
1502
1503 Reads the next (Unicode) character in the text currently being lexed.
1504 Returns the codepoint (unsigned integer value) of the character read,
1505 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1506 if lexing has reached the end of the input text.  To non-destructively
1507 examine the next character, use L</lex_peek_unichar> instead.
1508
1509 If the next character is in (or extends into) the next chunk of input
1510 text, the next chunk will be read in.  Normally the current chunk will be
1511 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1512 bit set, then the current chunk will not be discarded.
1513
1514 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1515 is encountered, an exception is generated.
1516
1517 =cut
1518 */
1519
1520 I32
1521 Perl_lex_read_unichar(pTHX_ U32 flags)
1522 {
1523     I32 c;
1524     if (flags & ~(LEX_KEEP_PREVIOUS))
1525         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1526     c = lex_peek_unichar(flags);
1527     if (c != -1) {
1528         if (c == '\n')
1529             COPLINE_INC_WITH_HERELINES;
1530         if (UTF)
1531             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1532         else
1533             ++(PL_parser->bufptr);
1534     }
1535     return c;
1536 }
1537
1538 /*
1539 =for apidoc Amx|void|lex_read_space|U32 flags
1540
1541 Reads optional spaces, in Perl style, in the text currently being
1542 lexed.  The spaces may include ordinary whitespace characters and
1543 Perl-style comments.  C<#line> directives are processed if encountered.
1544 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1545 at a non-space character (or the end of the input text).
1546
1547 If spaces extend into the next chunk of input text, the next chunk will
1548 be read in.  Normally the current chunk will be discarded at the same
1549 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1550 chunk will not be discarded.
1551
1552 =cut
1553 */
1554
1555 #define LEX_NO_INCLINE    0x40000000
1556 #define LEX_NO_NEXT_CHUNK 0x80000000
1557
1558 void
1559 Perl_lex_read_space(pTHX_ U32 flags)
1560 {
1561     char *s, *bufend;
1562     const bool can_incline = !(flags & LEX_NO_INCLINE);
1563     bool need_incline = 0;
1564     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1565         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1566     s = PL_parser->bufptr;
1567     bufend = PL_parser->bufend;
1568     while (1) {
1569         char c = *s;
1570         if (c == '#') {
1571             do {
1572                 c = *++s;
1573             } while (!(c == '\n' || (c == 0 && s == bufend)));
1574         } else if (c == '\n') {
1575             s++;
1576             if (can_incline) {
1577                 PL_parser->linestart = s;
1578                 if (s == bufend)
1579                     need_incline = 1;
1580                 else
1581                     incline(s, bufend);
1582             }
1583         } else if (isSPACE(c)) {
1584             s++;
1585         } else if (c == 0 && s == bufend) {
1586             bool got_more;
1587             line_t l;
1588             if (flags & LEX_NO_NEXT_CHUNK)
1589                 break;
1590             PL_parser->bufptr = s;
1591             l = CopLINE(PL_curcop);
1592             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1593             got_more = lex_next_chunk(flags);
1594             CopLINE_set(PL_curcop, l);
1595             s = PL_parser->bufptr;
1596             bufend = PL_parser->bufend;
1597             if (!got_more)
1598                 break;
1599             if (can_incline && need_incline && PL_parser->rsfp) {
1600                 incline(s, bufend);
1601                 need_incline = 0;
1602             }
1603         } else if (!c) {
1604             s++;
1605         } else {
1606             break;
1607         }
1608     }
1609     PL_parser->bufptr = s;
1610 }
1611
1612 /*
1613
1614 =for apidoc EXMp|bool|validate_proto|SV *name|SV *proto|bool warn
1615
1616 This function performs syntax checking on a prototype, C<proto>.
1617 If C<warn> is true, any illegal characters or mismatched brackets
1618 will trigger illegalproto warnings, declaring that they were
1619 detected in the prototype for C<name>.
1620
1621 The return value is C<true> if this is a valid prototype, and
1622 C<false> if it is not, regardless of whether C<warn> was C<true> or
1623 C<false>.
1624
1625 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1626
1627 =cut
1628
1629  */
1630
1631 bool
1632 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn, bool curstash)
1633 {
1634     STRLEN len, origlen;
1635     char *p;
1636     bool bad_proto = FALSE;
1637     bool in_brackets = FALSE;
1638     bool after_slash = FALSE;
1639     char greedy_proto = ' ';
1640     bool proto_after_greedy_proto = FALSE;
1641     bool must_be_last = FALSE;
1642     bool underscore = FALSE;
1643     bool bad_proto_after_underscore = FALSE;
1644
1645     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1646
1647     if (!proto)
1648         return TRUE;
1649
1650     p = SvPV(proto, len);
1651     origlen = len;
1652     for (; len--; p++) {
1653         if (!isSPACE(*p)) {
1654             if (must_be_last)
1655                 proto_after_greedy_proto = TRUE;
1656             if (underscore) {
1657                 if (!strchr(";@%", *p))
1658                     bad_proto_after_underscore = TRUE;
1659                 underscore = FALSE;
1660             }
1661             if (!strchr("$@%*;[]&\\_+", *p) || *p == '\0') {
1662                 bad_proto = TRUE;
1663             }
1664             else {
1665                 if (*p == '[')
1666                     in_brackets = TRUE;
1667                 else if (*p == ']')
1668                     in_brackets = FALSE;
1669                 else if ((*p == '@' || *p == '%')
1670                          && !after_slash
1671                          && !in_brackets )
1672                 {
1673                     must_be_last = TRUE;
1674                     greedy_proto = *p;
1675                 }
1676                 else if (*p == '_')
1677                     underscore = TRUE;
1678             }
1679             if (*p == '\\')
1680                 after_slash = TRUE;
1681             else
1682                 after_slash = FALSE;
1683         }
1684     }
1685
1686     if (warn) {
1687         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1688         p -= origlen;
1689         p = SvUTF8(proto)
1690             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1691                              origlen, UNI_DISPLAY_ISPRINT)
1692             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1693
1694         if (curstash && !memchr(SvPVX(name), ':', SvCUR(name))) {
1695             SV *name2 = sv_2mortal(newSVsv(PL_curstname));
1696             sv_catpvs(name2, "::");
1697             sv_catsv(name2, (SV *)name);
1698             name = name2;
1699         }
1700
1701         if (proto_after_greedy_proto)
1702             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1703                         "Prototype after '%c' for %" SVf " : %s",
1704                         greedy_proto, SVfARG(name), p);
1705         if (in_brackets)
1706             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1707                         "Missing ']' in prototype for %" SVf " : %s",
1708                         SVfARG(name), p);
1709         if (bad_proto)
1710             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1711                         "Illegal character in prototype for %" SVf " : %s",
1712                         SVfARG(name), p);
1713         if (bad_proto_after_underscore)
1714             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1715                         "Illegal character after '_' in prototype for %" SVf " : %s",
1716                         SVfARG(name), p);
1717     }
1718
1719     return (! (proto_after_greedy_proto || bad_proto) );
1720 }
1721
1722 /*
1723  * S_incline
1724  * This subroutine has nothing to do with tilting, whether at windmills
1725  * or pinball tables.  Its name is short for "increment line".  It
1726  * increments the current line number in CopLINE(PL_curcop) and checks
1727  * to see whether the line starts with a comment of the form
1728  *    # line 500 "foo.pm"
1729  * If so, it sets the current line number and file to the values in the comment.
1730  */
1731
1732 STATIC void
1733 S_incline(pTHX_ const char *s, const char *end)
1734 {
1735     const char *t;
1736     const char *n;
1737     const char *e;
1738     line_t line_num;
1739     UV uv;
1740
1741     PERL_ARGS_ASSERT_INCLINE;
1742
1743     assert(end >= s);
1744
1745     COPLINE_INC_WITH_HERELINES;
1746     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1747      && s+1 == PL_bufend && *s == ';') {
1748         /* fake newline in string eval */
1749         CopLINE_dec(PL_curcop);
1750         return;
1751     }
1752     if (*s++ != '#')
1753         return;
1754     while (SPACE_OR_TAB(*s))
1755         s++;
1756     if (memBEGINs(s, (STRLEN) (end - s), "line"))
1757         s += sizeof("line") - 1;
1758     else
1759         return;
1760     if (SPACE_OR_TAB(*s))
1761         s++;
1762     else
1763         return;
1764     while (SPACE_OR_TAB(*s))
1765         s++;
1766     if (!isDIGIT(*s))
1767         return;
1768
1769     n = s;
1770     while (isDIGIT(*s))
1771         s++;
1772     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1773         return;
1774     while (SPACE_OR_TAB(*s))
1775         s++;
1776     if (*s == '"' && (t = (char *) memchr(s+1, '"', end - s))) {
1777         s++;
1778         e = t + 1;
1779     }
1780     else {
1781         t = s;
1782         while (*t && !isSPACE(*t))
1783             t++;
1784         e = t;
1785     }
1786     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1787         e++;
1788     if (*e != '\n' && *e != '\0')
1789         return;         /* false alarm */
1790
1791     if (!grok_atoUV(n, &uv, &e))
1792         return;
1793     line_num = ((line_t)uv) - 1;
1794
1795     if (t - s > 0) {
1796         const STRLEN len = t - s;
1797
1798         if (!PL_rsfp && !PL_parser->filtered) {
1799             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1800              * to *{"::_<newfilename"} */
1801             /* However, the long form of evals is only turned on by the
1802                debugger - usually they're "(eval %lu)" */
1803             GV * const cfgv = CopFILEGV(PL_curcop);
1804             if (cfgv) {
1805                 char smallbuf[128];
1806                 STRLEN tmplen2 = len;
1807                 char *tmpbuf2;
1808                 GV *gv2;
1809
1810                 if (tmplen2 + 2 <= sizeof smallbuf)
1811                     tmpbuf2 = smallbuf;
1812                 else
1813                     Newx(tmpbuf2, tmplen2 + 2, char);
1814
1815                 tmpbuf2[0] = '_';
1816                 tmpbuf2[1] = '<';
1817
1818                 memcpy(tmpbuf2 + 2, s, tmplen2);
1819                 tmplen2 += 2;
1820
1821                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1822                 if (!isGV(gv2)) {
1823                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1824                     /* adjust ${"::_<newfilename"} to store the new file name */
1825                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1826                     /* The line number may differ. If that is the case,
1827                        alias the saved lines that are in the array.
1828                        Otherwise alias the whole array. */
1829                     if (CopLINE(PL_curcop) == line_num) {
1830                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1831                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1832                     }
1833                     else if (GvAV(cfgv)) {
1834                         AV * const av = GvAV(cfgv);
1835                         const I32 start = CopLINE(PL_curcop)+1;
1836                         I32 items = AvFILLp(av) - start;
1837                         if (items > 0) {
1838                             AV * const av2 = GvAVn(gv2);
1839                             SV **svp = AvARRAY(av) + start;
1840                             I32 l = (I32)line_num+1;
1841                             while (items--)
1842                                 av_store(av2, l++, SvREFCNT_inc(*svp++));
1843                         }
1844                     }
1845                 }
1846
1847                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1848             }
1849         }
1850         CopFILE_free(PL_curcop);
1851         CopFILE_setn(PL_curcop, s, len);
1852     }
1853     CopLINE_set(PL_curcop, line_num);
1854 }
1855
1856 STATIC void
1857 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1858 {
1859     AV *av = CopFILEAVx(PL_curcop);
1860     if (av) {
1861         SV * sv;
1862         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1863         else {
1864             sv = *av_fetch(av, 0, 1);
1865             SvUPGRADE(sv, SVt_PVMG);
1866         }
1867         if (!SvPOK(sv)) SvPVCLEAR(sv);
1868         if (orig_sv)
1869             sv_catsv(sv, orig_sv);
1870         else
1871             sv_catpvn(sv, buf, len);
1872         if (!SvIOK(sv)) {
1873             (void)SvIOK_on(sv);
1874             SvIV_set(sv, 0);
1875         }
1876         if (PL_parser->preambling == NOLINE)
1877             av_store(av, CopLINE(PL_curcop), sv);
1878     }
1879 }
1880
1881 /*
1882  * skipspace
1883  * Called to gobble the appropriate amount and type of whitespace.
1884  * Skips comments as well.
1885  * Returns the next character after the whitespace that is skipped.
1886  *
1887  * peekspace
1888  * Same thing, but look ahead without incrementing line numbers or
1889  * adjusting PL_linestart.
1890  */
1891
1892 #define skipspace(s) skipspace_flags(s, 0)
1893 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1894
1895 STATIC char *
1896 S_skipspace_flags(pTHX_ char *s, U32 flags)
1897 {
1898     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1899     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1900         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1901             s++;
1902     } else {
1903         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1904         PL_bufptr = s;
1905         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1906                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1907                     LEX_NO_NEXT_CHUNK : 0));
1908         s = PL_bufptr;
1909         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1910         if (PL_linestart > PL_bufptr)
1911             PL_bufptr = PL_linestart;
1912         return s;
1913     }
1914     return s;
1915 }
1916
1917 /*
1918  * S_check_uni
1919  * Check the unary operators to ensure there's no ambiguity in how they're
1920  * used.  An ambiguous piece of code would be:
1921  *     rand + 5
1922  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1923  * the +5 is its argument.
1924  */
1925
1926 STATIC void
1927 S_check_uni(pTHX)
1928 {
1929     const char *s;
1930
1931     if (PL_oldoldbufptr != PL_last_uni)
1932         return;
1933     while (isSPACE(*PL_last_uni))
1934         PL_last_uni++;
1935     s = PL_last_uni;
1936     while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF) || *s == '-')
1937         s += UTF ? UTF8SKIP(s) : 1;
1938     if (s < PL_bufptr && memchr(s, '(', PL_bufptr - s))
1939         return;
1940
1941     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1942                      "Warning: Use of \"%" UTF8f "\" without parentheses is ambiguous",
1943                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1944 }
1945
1946 /*
1947  * LOP : macro to build a list operator.  Its behaviour has been replaced
1948  * with a subroutine, S_lop() for which LOP is just another name.
1949  */
1950
1951 #define LOP(f,x) return lop(f,x,s)
1952
1953 /*
1954  * S_lop
1955  * Build a list operator (or something that might be one).  The rules:
1956  *  - if we have a next token, then it's a list operator (no parens) for
1957  *    which the next token has already been parsed; e.g.,
1958  *       sort foo @args
1959  *       sort foo (@args)
1960  *  - if the next thing is an opening paren, then it's a function
1961  *  - else it's a list operator
1962  */
1963
1964 STATIC I32
1965 S_lop(pTHX_ I32 f, U8 x, char *s)
1966 {
1967     PERL_ARGS_ASSERT_LOP;
1968
1969     pl_yylval.ival = f;
1970     CLINE;
1971     PL_bufptr = s;
1972     PL_last_lop = PL_oldbufptr;
1973     PL_last_lop_op = (OPCODE)f;
1974     if (PL_nexttoke)
1975         goto lstop;
1976     PL_expect = x;
1977     if (*s == '(')
1978         return REPORT(FUNC);
1979     s = skipspace(s);
1980     if (*s == '(')
1981         return REPORT(FUNC);
1982     else {
1983         lstop:
1984         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1985             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1986         return REPORT(LSTOP);
1987     }
1988 }
1989
1990 /*
1991  * S_force_next
1992  * When the lexer realizes it knows the next token (for instance,
1993  * it is reordering tokens for the parser) then it can call S_force_next
1994  * to know what token to return the next time the lexer is called.  Caller
1995  * will need to set PL_nextval[] and possibly PL_expect to ensure
1996  * the lexer handles the token correctly.
1997  */
1998
1999 STATIC void
2000 S_force_next(pTHX_ I32 type)
2001 {
2002 #ifdef DEBUGGING
2003     if (DEBUG_T_TEST) {
2004         PerlIO_printf(Perl_debug_log, "### forced token:\n");
2005         tokereport(type, &NEXTVAL_NEXTTOKE);
2006     }
2007 #endif
2008     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
2009     PL_nexttype[PL_nexttoke] = type;
2010     PL_nexttoke++;
2011 }
2012
2013 /*
2014  * S_postderef
2015  *
2016  * This subroutine handles postfix deref syntax after the arrow has already
2017  * been emitted.  @* $* etc. are emitted as two separate token right here.
2018  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
2019  * only the first, leaving yylex to find the next.
2020  */
2021
2022 static int
2023 S_postderef(pTHX_ int const funny, char const next)
2024 {
2025     assert(funny == DOLSHARP || strchr("$@%&*", funny));
2026     if (next == '*') {
2027         PL_expect = XOPERATOR;
2028         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
2029             assert('@' == funny || '$' == funny || DOLSHARP == funny);
2030             PL_lex_state = LEX_INTERPEND;
2031             if ('@' == funny)
2032                 force_next(POSTJOIN);
2033         }
2034         force_next(next);
2035         PL_bufptr+=2;
2036     }
2037     else {
2038         if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
2039          && !PL_lex_brackets)
2040             PL_lex_dojoin = 2;
2041         PL_expect = XOPERATOR;
2042         PL_bufptr++;
2043     }
2044     return funny;
2045 }
2046
2047 void
2048 Perl_yyunlex(pTHX)
2049 {
2050     int yyc = PL_parser->yychar;
2051     if (yyc != YYEMPTY) {
2052         if (yyc) {
2053             NEXTVAL_NEXTTOKE = PL_parser->yylval;
2054             if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
2055                 PL_lex_allbrackets--;
2056                 PL_lex_brackets--;
2057                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
2058             } else if (yyc == '('/*)*/) {
2059                 PL_lex_allbrackets--;
2060                 yyc |= (2<<24);
2061             }
2062             force_next(yyc);
2063         }
2064         PL_parser->yychar = YYEMPTY;
2065     }
2066 }
2067
2068 STATIC SV *
2069 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
2070 {
2071     SV * const sv = newSVpvn_utf8(start, len,
2072                           !IN_BYTES
2073                           && UTF
2074                           && !is_utf8_invariant_string((const U8*)start, len)
2075                           && is_utf8_string((const U8*)start, len));
2076     return sv;
2077 }
2078
2079 /*
2080  * S_force_word
2081  * When the lexer knows the next thing is a word (for instance, it has
2082  * just seen -> and it knows that the next char is a word char, then
2083  * it calls S_force_word to stick the next word into the PL_nexttoke/val
2084  * lookahead.
2085  *
2086  * Arguments:
2087  *   char *start : buffer position (must be within PL_linestr)
2088  *   int token   : PL_next* will be this type of bare word
2089  *                 (e.g., METHOD,BAREWORD)
2090  *   int check_keyword : if true, Perl checks to make sure the word isn't
2091  *       a keyword (do this if the word is a label, e.g. goto FOO)
2092  *   int allow_pack : if true, : characters will also be allowed (require,
2093  *       use, etc. do this)
2094  */
2095
2096 STATIC char *
2097 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2098 {
2099     char *s;
2100     STRLEN len;
2101
2102     PERL_ARGS_ASSERT_FORCE_WORD;
2103
2104     start = skipspace(start);
2105     s = start;
2106     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
2107         || (allow_pack && *s == ':' && s[1] == ':') )
2108     {
2109         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2110         if (check_keyword) {
2111           char *s2 = PL_tokenbuf;
2112           STRLEN len2 = len;
2113           if (allow_pack && memBEGINPs(s2, len, "CORE::")) {
2114             s2 += sizeof("CORE::") - 1;
2115             len2 -= sizeof("CORE::") - 1;
2116           }
2117           if (keyword(s2, len2, 0))
2118             return start;
2119         }
2120         if (token == METHOD) {
2121             s = skipspace(s);
2122             if (*s == '(')
2123                 PL_expect = XTERM;
2124             else {
2125                 PL_expect = XOPERATOR;
2126             }
2127         }
2128         NEXTVAL_NEXTTOKE.opval
2129             = newSVOP(OP_CONST,0,
2130                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2131         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2132         force_next(token);
2133     }
2134     return s;
2135 }
2136
2137 /*
2138  * S_force_ident
2139  * Called when the lexer wants $foo *foo &foo etc, but the program
2140  * text only contains the "foo" portion.  The first argument is a pointer
2141  * to the "foo", and the second argument is the type symbol to prefix.
2142  * Forces the next token to be a "BAREWORD".
2143  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2144  */
2145
2146 STATIC void
2147 S_force_ident(pTHX_ const char *s, int kind)
2148 {
2149     PERL_ARGS_ASSERT_FORCE_IDENT;
2150
2151     if (s[0]) {
2152         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2153         OP* const o = newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2154                                                                 UTF ? SVf_UTF8 : 0));
2155         NEXTVAL_NEXTTOKE.opval = o;
2156         force_next(BAREWORD);
2157         if (kind) {
2158             o->op_private = OPpCONST_ENTERED;
2159             /* XXX see note in pp_entereval() for why we forgo typo
2160                warnings if the symbol must be introduced in an eval.
2161                GSAR 96-10-12 */
2162             gv_fetchpvn_flags(s, len,
2163                               (PL_in_eval ? GV_ADDMULTI
2164                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2165                               kind == '$' ? SVt_PV :
2166                               kind == '@' ? SVt_PVAV :
2167                               kind == '%' ? SVt_PVHV :
2168                               SVt_PVGV
2169                               );
2170         }
2171     }
2172 }
2173
2174 static void
2175 S_force_ident_maybe_lex(pTHX_ char pit)
2176 {
2177     NEXTVAL_NEXTTOKE.ival = pit;
2178     force_next('p');
2179 }
2180
2181 NV
2182 Perl_str_to_version(pTHX_ SV *sv)
2183 {
2184     NV retval = 0.0;
2185     NV nshift = 1.0;
2186     STRLEN len;
2187     const char *start = SvPV_const(sv,len);
2188     const char * const end = start + len;
2189     const bool utf = cBOOL(SvUTF8(sv));
2190
2191     PERL_ARGS_ASSERT_STR_TO_VERSION;
2192
2193     while (start < end) {
2194         STRLEN skip;
2195         UV n;
2196         if (utf)
2197             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2198         else {
2199             n = *(U8*)start;
2200             skip = 1;
2201         }
2202         retval += ((NV)n)/nshift;
2203         start += skip;
2204         nshift *= 1000;
2205     }
2206     return retval;
2207 }
2208
2209 /*
2210  * S_force_version
2211  * Forces the next token to be a version number.
2212  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2213  * and if "guessing" is TRUE, then no new token is created (and the caller
2214  * must use an alternative parsing method).
2215  */
2216
2217 STATIC char *
2218 S_force_version(pTHX_ char *s, int guessing)
2219 {
2220     OP *version = NULL;
2221     char *d;
2222
2223     PERL_ARGS_ASSERT_FORCE_VERSION;
2224
2225     s = skipspace(s);
2226
2227     d = s;
2228     if (*d == 'v')
2229         d++;
2230     if (isDIGIT(*d)) {
2231         while (isDIGIT(*d) || *d == '_' || *d == '.')
2232             d++;
2233         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2234             SV *ver;
2235             s = scan_num(s, &pl_yylval);
2236             version = pl_yylval.opval;
2237             ver = cSVOPx(version)->op_sv;
2238             if (SvPOK(ver) && !SvNIOK(ver)) {
2239                 SvUPGRADE(ver, SVt_PVNV);
2240                 SvNV_set(ver, str_to_version(ver));
2241                 SvNOK_on(ver);          /* hint that it is a version */
2242             }
2243         }
2244         else if (guessing) {
2245             return s;
2246         }
2247     }
2248
2249     /* NOTE: The parser sees the package name and the VERSION swapped */
2250     NEXTVAL_NEXTTOKE.opval = version;
2251     force_next(BAREWORD);
2252
2253     return s;
2254 }
2255
2256 /*
2257  * S_force_strict_version
2258  * Forces the next token to be a version number using strict syntax rules.
2259  */
2260
2261 STATIC char *
2262 S_force_strict_version(pTHX_ char *s)
2263 {
2264     OP *version = NULL;
2265     const char *errstr = NULL;
2266
2267     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2268
2269     while (isSPACE(*s)) /* leading whitespace */
2270         s++;
2271
2272     if (is_STRICT_VERSION(s,&errstr)) {
2273         SV *ver = newSV(0);
2274         s = (char *)scan_version(s, ver, 0);
2275         version = newSVOP(OP_CONST, 0, ver);
2276     }
2277     else if ((*s != ';' && *s != '{' && *s != '}' )
2278              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2279     {
2280         PL_bufptr = s;
2281         if (errstr)
2282             yyerror(errstr); /* version required */
2283         return s;
2284     }
2285
2286     /* NOTE: The parser sees the package name and the VERSION swapped */
2287     NEXTVAL_NEXTTOKE.opval = version;
2288     force_next(BAREWORD);
2289
2290     return s;
2291 }
2292
2293 /*
2294  * S_tokeq
2295  * Turns any \\ into \ in a quoted string passed in in 'sv', returning 'sv',
2296  * modified as necessary.  However, if HINT_NEW_STRING is on, 'sv' is
2297  * unchanged, and a new SV containing the modified input is returned.
2298  */
2299
2300 STATIC SV *
2301 S_tokeq(pTHX_ SV *sv)
2302 {
2303     char *s;
2304     char *send;
2305     char *d;
2306     SV *pv = sv;
2307
2308     PERL_ARGS_ASSERT_TOKEQ;
2309
2310     assert (SvPOK(sv));
2311     assert (SvLEN(sv));
2312     assert (!SvIsCOW(sv));
2313     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2314         goto finish;
2315     s = SvPVX(sv);
2316     send = SvEND(sv);
2317     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2318     while (s < send && !(*s == '\\' && s[1] == '\\'))
2319         s++;
2320     if (s == send)
2321         goto finish;
2322     d = s;
2323     if ( PL_hints & HINT_NEW_STRING ) {
2324         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2325                             SVs_TEMP | SvUTF8(sv));
2326     }
2327     while (s < send) {
2328         if (*s == '\\') {
2329             if (s + 1 < send && (s[1] == '\\'))
2330                 s++;            /* all that, just for this */
2331         }
2332         *d++ = *s++;
2333     }
2334     *d = '\0';
2335     SvCUR_set(sv, d - SvPVX_const(sv));
2336   finish:
2337     if ( PL_hints & HINT_NEW_STRING )
2338        return new_constant(NULL, 0, "q", sv, pv, "q", 1);
2339     return sv;
2340 }
2341
2342 /*
2343  * Now come three functions related to double-quote context,
2344  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2345  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2346  * interact with PL_lex_state, and create fake ( ... ) argument lists
2347  * to handle functions and concatenation.
2348  * For example,
2349  *   "foo\lbar"
2350  * is tokenised as
2351  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2352  */
2353
2354 /*
2355  * S_sublex_start
2356  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2357  *
2358  * Pattern matching will set PL_lex_op to the pattern-matching op to
2359  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2360  *
2361  * OP_CONST is easy--just make the new op and return.
2362  *
2363  * Everything else becomes a FUNC.
2364  *
2365  * Sets PL_lex_state to LEX_INTERPPUSH unless ival was OP_NULL or we
2366  * had an OP_CONST.  This just sets us up for a
2367  * call to S_sublex_push().
2368  */
2369
2370 STATIC I32
2371 S_sublex_start(pTHX)
2372 {
2373     const I32 op_type = pl_yylval.ival;
2374
2375     if (op_type == OP_NULL) {
2376         pl_yylval.opval = PL_lex_op;
2377         PL_lex_op = NULL;
2378         return THING;
2379     }
2380     if (op_type == OP_CONST) {
2381         SV *sv = PL_lex_stuff;
2382         PL_lex_stuff = NULL;
2383         sv = tokeq(sv);
2384
2385         if (SvTYPE(sv) == SVt_PVIV) {
2386             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2387             STRLEN len;
2388             const char * const p = SvPV_const(sv, len);
2389             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2390             SvREFCNT_dec(sv);
2391             sv = nsv;
2392         }
2393         pl_yylval.opval = newSVOP(op_type, 0, sv);
2394         return THING;
2395     }
2396
2397     PL_parser->lex_super_state = PL_lex_state;
2398     PL_parser->lex_sub_inwhat = (U16)op_type;
2399     PL_parser->lex_sub_op = PL_lex_op;
2400     PL_lex_state = LEX_INTERPPUSH;
2401
2402     PL_expect = XTERM;
2403     if (PL_lex_op) {
2404         pl_yylval.opval = PL_lex_op;
2405         PL_lex_op = NULL;
2406         return PMFUNC;
2407     }
2408     else
2409         return FUNC;
2410 }
2411
2412 /*
2413  * S_sublex_push
2414  * Create a new scope to save the lexing state.  The scope will be
2415  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2416  * to the uc, lc, etc. found before.
2417  * Sets PL_lex_state to LEX_INTERPCONCAT.
2418  */
2419
2420 STATIC I32
2421 S_sublex_push(pTHX)
2422 {
2423     LEXSHARED *shared;
2424     const bool is_heredoc = PL_multi_close == '<';
2425     ENTER;
2426
2427     PL_lex_state = PL_parser->lex_super_state;
2428     SAVEI8(PL_lex_dojoin);
2429     SAVEI32(PL_lex_brackets);
2430     SAVEI32(PL_lex_allbrackets);
2431     SAVEI32(PL_lex_formbrack);
2432     SAVEI8(PL_lex_fakeeof);
2433     SAVEI32(PL_lex_casemods);
2434     SAVEI32(PL_lex_starts);
2435     SAVEI8(PL_lex_state);
2436     SAVESPTR(PL_lex_repl);
2437     SAVEVPTR(PL_lex_inpat);
2438     SAVEI16(PL_lex_inwhat);
2439     if (is_heredoc)
2440     {
2441         SAVECOPLINE(PL_curcop);
2442         SAVEI32(PL_multi_end);
2443         SAVEI32(PL_parser->herelines);
2444         PL_parser->herelines = 0;
2445     }
2446     SAVEIV(PL_multi_close);
2447     SAVEPPTR(PL_bufptr);
2448     SAVEPPTR(PL_bufend);
2449     SAVEPPTR(PL_oldbufptr);
2450     SAVEPPTR(PL_oldoldbufptr);
2451     SAVEPPTR(PL_last_lop);
2452     SAVEPPTR(PL_last_uni);
2453     SAVEPPTR(PL_linestart);
2454     SAVESPTR(PL_linestr);
2455     SAVEGENERICPV(PL_lex_brackstack);
2456     SAVEGENERICPV(PL_lex_casestack);
2457     SAVEGENERICPV(PL_parser->lex_shared);
2458     SAVEBOOL(PL_parser->lex_re_reparsing);
2459     SAVEI32(PL_copline);
2460
2461     /* The here-doc parser needs to be able to peek into outer lexing
2462        scopes to find the body of the here-doc.  So we put PL_linestr and
2463        PL_bufptr into lex_shared, to â€˜share’ those values.
2464      */
2465     PL_parser->lex_shared->ls_linestr = PL_linestr;
2466     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2467
2468     PL_linestr = PL_lex_stuff;
2469     PL_lex_repl = PL_parser->lex_sub_repl;
2470     PL_lex_stuff = NULL;
2471     PL_parser->lex_sub_repl = NULL;
2472
2473     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2474        set for an inner quote-like operator and then an error causes scope-
2475        popping.  We must not have a PL_lex_stuff value left dangling, as
2476        that breaks assumptions elsewhere.  See bug #123617.  */
2477     SAVEGENERICSV(PL_lex_stuff);
2478     SAVEGENERICSV(PL_parser->lex_sub_repl);
2479
2480     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2481         = SvPVX(PL_linestr);
2482     PL_bufend += SvCUR(PL_linestr);
2483     PL_last_lop = PL_last_uni = NULL;
2484     SAVEFREESV(PL_linestr);
2485     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2486
2487     PL_lex_dojoin = FALSE;
2488     PL_lex_brackets = PL_lex_formbrack = 0;
2489     PL_lex_allbrackets = 0;
2490     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2491     Newx(PL_lex_brackstack, 120, char);
2492     Newx(PL_lex_casestack, 12, char);
2493     PL_lex_casemods = 0;
2494     *PL_lex_casestack = '\0';
2495     PL_lex_starts = 0;
2496     PL_lex_state = LEX_INTERPCONCAT;
2497     if (is_heredoc)
2498         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2499     PL_copline = NOLINE;
2500
2501     Newxz(shared, 1, LEXSHARED);
2502     shared->ls_prev = PL_parser->lex_shared;
2503     PL_parser->lex_shared = shared;
2504
2505     PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2506     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2507     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2508         PL_lex_inpat = PL_parser->lex_sub_op;
2509     else
2510         PL_lex_inpat = NULL;
2511
2512     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2513     PL_in_eval &= ~EVAL_RE_REPARSING;
2514
2515     return '(';
2516 }
2517
2518 /*
2519  * S_sublex_done
2520  * Restores lexer state after a S_sublex_push.
2521  */
2522
2523 STATIC I32
2524 S_sublex_done(pTHX)
2525 {
2526     if (!PL_lex_starts++) {
2527         SV * const sv = newSVpvs("");
2528         if (SvUTF8(PL_linestr))
2529             SvUTF8_on(sv);
2530         PL_expect = XOPERATOR;
2531         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
2532         return THING;
2533     }
2534
2535     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2536         PL_lex_state = LEX_INTERPCASEMOD;
2537         return yylex();
2538     }
2539
2540     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2541     assert(PL_lex_inwhat != OP_TRANSR);
2542     if (PL_lex_repl) {
2543         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2544         PL_linestr = PL_lex_repl;
2545         PL_lex_inpat = 0;
2546         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2547         PL_bufend += SvCUR(PL_linestr);
2548         PL_last_lop = PL_last_uni = NULL;
2549         PL_lex_dojoin = FALSE;
2550         PL_lex_brackets = 0;
2551         PL_lex_allbrackets = 0;
2552         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2553         PL_lex_casemods = 0;
2554         *PL_lex_casestack = '\0';
2555         PL_lex_starts = 0;
2556         if (SvEVALED(PL_lex_repl)) {
2557             PL_lex_state = LEX_INTERPNORMAL;
2558             PL_lex_starts++;
2559             /*  we don't clear PL_lex_repl here, so that we can check later
2560                 whether this is an evalled subst; that means we rely on the
2561                 logic to ensure sublex_done() is called again only via the
2562                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2563         }
2564         else {
2565             PL_lex_state = LEX_INTERPCONCAT;
2566             PL_lex_repl = NULL;
2567         }
2568         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2569             CopLINE(PL_curcop) +=
2570                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2571                  + PL_parser->herelines;
2572             PL_parser->herelines = 0;
2573         }
2574         return '/';
2575     }
2576     else {
2577         const line_t l = CopLINE(PL_curcop);
2578         LEAVE;
2579         if (PL_multi_close == '<')
2580             PL_parser->herelines += l - PL_multi_end;
2581         PL_bufend = SvPVX(PL_linestr);
2582         PL_bufend += SvCUR(PL_linestr);
2583         PL_expect = XOPERATOR;
2584         return ')';
2585     }
2586 }
2587
2588 STATIC SV*
2589 S_get_and_check_backslash_N_name(pTHX_ const char* s, const char* const e)
2590 {
2591     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2592      * interior, hence to the "}".  Finds what the name resolves to, returning
2593      * an SV* containing it; NULL if no valid one found */
2594
2595     SV* res = newSVpvn_flags(s, e - s, UTF ? SVf_UTF8 : 0);
2596
2597     HV * table;
2598     SV **cvp;
2599     SV *cv;
2600     SV *rv;
2601     HV *stash;
2602     const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2603
2604     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2605
2606     if (!SvCUR(res)) {
2607         SvREFCNT_dec_NN(res);
2608         /* diag_listed_as: Unknown charname '%s' */
2609         yyerror("Unknown charname ''");
2610         return NULL;
2611     }
2612
2613     res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2614                         /* include the <}> */
2615                         e - backslash_ptr + 1);
2616     if (! SvPOK(res)) {
2617         SvREFCNT_dec_NN(res);
2618         return NULL;
2619     }
2620
2621     /* See if the charnames handler is the Perl core's, and if so, we can skip
2622      * the validation needed for a user-supplied one, as Perl's does its own
2623      * validation. */
2624     table = GvHV(PL_hintgv);             /* ^H */
2625     cvp = hv_fetchs(table, "charnames", FALSE);
2626     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2627         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2628     {
2629         const char * const name = HvNAME(stash);
2630          if (memEQs(name, HvNAMELEN(stash), "_charnames")) {
2631            return res;
2632        }
2633     }
2634
2635     /* Here, it isn't Perl's charname handler.  We can't rely on a
2636      * user-supplied handler to validate the input name.  For non-ut8 input,
2637      * look to see that the first character is legal.  Then loop through the
2638      * rest checking that each is a continuation */
2639
2640     /* This code makes the reasonable assumption that the only Latin1-range
2641      * characters that begin a character name alias are alphabetic, otherwise
2642      * would have to create a isCHARNAME_BEGIN macro */
2643
2644     if (! UTF) {
2645         if (! isALPHAU(*s)) {
2646             goto bad_charname;
2647         }
2648         s++;
2649         while (s < e) {
2650             if (! isCHARNAME_CONT(*s)) {
2651                 goto bad_charname;
2652             }
2653             if (*s == ' ' && *(s-1) == ' ') {
2654                 goto multi_spaces;
2655             }
2656             s++;
2657         }
2658     }
2659     else {
2660         /* Similarly for utf8.  For invariants can check directly; for other
2661          * Latin1, can calculate their code point and check; otherwise  use a
2662          * swash */
2663         if (UTF8_IS_INVARIANT(*s)) {
2664             if (! isALPHAU(*s)) {
2665                 goto bad_charname;
2666             }
2667             s++;
2668         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2669             if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2670                 goto bad_charname;
2671             }
2672             s += 2;
2673         }
2674         else {
2675             if (! PL_utf8_charname_begin) {
2676                 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2677                 PL_utf8_charname_begin = _core_swash_init("utf8",
2678                                                         "_Perl_Charname_Begin",
2679                                                         &PL_sv_undef,
2680                                                         1, 0, NULL, &flags);
2681             }
2682             if (! swash_fetch(PL_utf8_charname_begin, (U8 *) s, TRUE)) {
2683                 goto bad_charname;
2684             }
2685             s += UTF8SKIP(s);
2686         }
2687
2688         while (s < e) {
2689             if (UTF8_IS_INVARIANT(*s)) {
2690                 if (! isCHARNAME_CONT(*s)) {
2691                     goto bad_charname;
2692                 }
2693                 if (*s == ' ' && *(s-1) == ' ') {
2694                     goto multi_spaces;
2695                 }
2696                 s++;
2697             }
2698             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2699                 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2700                 {
2701                     goto bad_charname;
2702                 }
2703                 s += 2;
2704             }
2705             else {
2706                 if (! PL_utf8_charname_continue) {
2707                     U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2708                     PL_utf8_charname_continue = _core_swash_init("utf8",
2709                                                 "_Perl_Charname_Continue",
2710                                                 &PL_sv_undef,
2711                                                 1, 0, NULL, &flags);
2712                 }
2713                 if (! swash_fetch(PL_utf8_charname_continue, (U8 *) s, TRUE)) {
2714                     goto bad_charname;
2715                 }
2716                 s += UTF8SKIP(s);
2717             }
2718         }
2719     }
2720     if (*(s-1) == ' ') {
2721         /* diag_listed_as: charnames alias definitions may not contain
2722                            trailing white-space; marked by <-- HERE in %s
2723          */
2724         yyerror_pv(
2725             Perl_form(aTHX_
2726             "charnames alias definitions may not contain trailing "
2727             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2728             (int)(s - backslash_ptr + 1), backslash_ptr,
2729             (int)(e - s + 1), s + 1
2730             ),
2731         UTF ? SVf_UTF8 : 0);
2732         return NULL;
2733     }
2734
2735     if (SvUTF8(res)) { /* Don't accept malformed input */
2736         const U8* first_bad_char_loc;
2737         STRLEN len;
2738         const char* const str = SvPV_const(res, len);
2739         if (UNLIKELY(! is_utf8_string_loc((U8 *) str, len,
2740                                           &first_bad_char_loc)))
2741         {
2742             _force_out_malformed_utf8_message(first_bad_char_loc,
2743                                               (U8 *) PL_parser->bufend,
2744                                               0,
2745                                               0 /* 0 means don't die */ );
2746             /* diag_listed_as: Malformed UTF-8 returned by \N{%s}
2747                                immediately after '%s' */
2748             yyerror_pv(
2749               Perl_form(aTHX_
2750                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2751                  (int) (e - backslash_ptr + 1), backslash_ptr,
2752                  (int) ((char *) first_bad_char_loc - str), str
2753               ),
2754               SVf_UTF8);
2755             return NULL;
2756         }
2757     }
2758
2759     return res;
2760
2761   bad_charname: {
2762
2763         /* The final %.*s makes sure that should the trailing NUL be missing
2764          * that this print won't run off the end of the string */
2765         /* diag_listed_as: Invalid character in \N{...}; marked by <-- HERE
2766                            in \N{%s} */
2767         yyerror_pv(
2768           Perl_form(aTHX_
2769             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2770             (int)(s - backslash_ptr + 1), backslash_ptr,
2771             (int)(e - s + 1), s + 1
2772           ),
2773           UTF ? SVf_UTF8 : 0);
2774         return NULL;
2775     }
2776
2777   multi_spaces:
2778         /* diag_listed_as: charnames alias definitions may not contain a
2779                            sequence of multiple spaces; marked by <-- HERE
2780                            in %s */
2781         yyerror_pv(
2782           Perl_form(aTHX_
2783             "charnames alias definitions may not contain a sequence of "
2784             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2785             (int)(s - backslash_ptr + 1), backslash_ptr,
2786             (int)(e - s + 1), s + 1
2787           ),
2788           UTF ? SVf_UTF8 : 0);
2789         return NULL;
2790 }
2791
2792 /*
2793   scan_const
2794
2795   Extracts the next constant part of a pattern, double-quoted string,
2796   or transliteration.  This is terrifying code.
2797
2798   For example, in parsing the double-quoted string "ab\x63$d", it would
2799   stop at the '$' and return an OP_CONST containing 'abc'.
2800
2801   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2802   processing a pattern (PL_lex_inpat is true), a transliteration
2803   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2804
2805   Returns a pointer to the character scanned up to. If this is
2806   advanced from the start pointer supplied (i.e. if anything was
2807   successfully parsed), will leave an OP_CONST for the substring scanned
2808   in pl_yylval. Caller must intuit reason for not parsing further
2809   by looking at the next characters herself.
2810
2811   In patterns:
2812     expand:
2813       \N{FOO}  => \N{U+hex_for_character_FOO}
2814       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2815
2816     pass through:
2817         all other \-char, including \N and \N{ apart from \N{ABC}
2818
2819     stops on:
2820         @ and $ where it appears to be a var, but not for $ as tail anchor
2821         \l \L \u \U \Q \E
2822         (?{  or  (??{
2823
2824   In transliterations:
2825     characters are VERY literal, except for - not at the start or end
2826     of the string, which indicates a range.  However some backslash sequences
2827     are recognized: \r, \n, and the like
2828                     \007 \o{}, \x{}, \N{}
2829     If all elements in the transliteration are below 256,
2830     scan_const expands the range to the full set of intermediate
2831     characters. If the range is in utf8, the hyphen is replaced with
2832     a certain range mark which will be handled by pmtrans() in op.c.
2833
2834   In double-quoted strings:
2835     backslashes:
2836       all those recognized in transliterations
2837       deprecated backrefs: \1 (in substitution replacements)
2838       case and quoting: \U \Q \E
2839     stops on @ and $
2840
2841   scan_const does *not* construct ops to handle interpolated strings.
2842   It stops processing as soon as it finds an embedded $ or @ variable
2843   and leaves it to the caller to work out what's going on.
2844
2845   embedded arrays (whether in pattern or not) could be:
2846       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2847
2848   $ in double-quoted strings must be the symbol of an embedded scalar.
2849
2850   $ in pattern could be $foo or could be tail anchor.  Assumption:
2851   it's a tail anchor if $ is the last thing in the string, or if it's
2852   followed by one of "()| \r\n\t"
2853
2854   \1 (backreferences) are turned into $1 in substitutions
2855
2856   The structure of the code is
2857       while (there's a character to process) {
2858           handle transliteration ranges
2859           skip regexp comments /(?#comment)/ and codes /(?{code})/
2860           skip #-initiated comments in //x patterns
2861           check for embedded arrays
2862           check for embedded scalars
2863           if (backslash) {
2864               deprecate \1 in substitution replacements
2865               handle string-changing backslashes \l \U \Q \E, etc.
2866               switch (what was escaped) {
2867                   handle \- in a transliteration (becomes a literal -)
2868                   if a pattern and not \N{, go treat as regular character
2869                   handle \132 (octal characters)
2870                   handle \x15 and \x{1234} (hex characters)
2871                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2872                   handle \cV (control characters)
2873                   handle printf-style backslashes (\f, \r, \n, etc)
2874               } (end switch)
2875               continue
2876           } (end if backslash)
2877           handle regular character
2878     } (end while character to read)
2879
2880 */
2881
2882 STATIC char *
2883 S_scan_const(pTHX_ char *start)
2884 {
2885     char *send = PL_bufend;             /* end of the constant */
2886     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
2887                                            on sizing. */
2888     char *s = start;                    /* start of the constant */
2889     char *d = SvPVX(sv);                /* destination for copies */
2890     bool dorange = FALSE;               /* are we in a translit range? */
2891     bool didrange = FALSE;              /* did we just finish a range? */
2892     bool in_charclass = FALSE;          /* within /[...]/ */
2893     bool has_utf8 = FALSE;              /* Output constant is UTF8 */
2894     bool  this_utf8 = cBOOL(UTF);       /* Is the source string assumed to be
2895                                            UTF8?  But, this can show as true
2896                                            when the source isn't utf8, as for
2897                                            example when it is entirely composed
2898                                            of hex constants */
2899     STRLEN utf8_variant_count = 0;      /* When not in UTF-8, this counts the
2900                                            number of characters found so far
2901                                            that will expand (into 2 bytes)
2902                                            should we have to convert to
2903                                            UTF-8) */
2904     SV *res;                            /* result from charnames */
2905     STRLEN offset_to_max;   /* The offset in the output to where the range
2906                                high-end character is temporarily placed */
2907
2908     /* Does something require special handling in tr/// ?  This avoids extra
2909      * work in a less likely case.  As such, khw didn't feel it was worth
2910      * adding any branches to the more mainline code to handle this, which
2911      * means that this doesn't get set in some circumstances when things like
2912      * \x{100} get expanded out.  As a result there needs to be extra testing
2913      * done in the tr code */
2914     bool has_above_latin1 = FALSE;
2915
2916     /* Note on sizing:  The scanned constant is placed into sv, which is
2917      * initialized by newSV() assuming one byte of output for every byte of
2918      * input.  This routine expects newSV() to allocate an extra byte for a
2919      * trailing NUL, which this routine will append if it gets to the end of
2920      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2921      * CAPITAL LETTER A}), or more output than input if the constant ends up
2922      * recoded to utf8, but each time a construct is found that might increase
2923      * the needed size, SvGROW() is called.  Its size parameter each time is
2924      * based on the best guess estimate at the time, namely the length used so
2925      * far, plus the length the current construct will occupy, plus room for
2926      * the trailing NUL, plus one byte for every input byte still unscanned */
2927
2928     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2929                        before set */
2930 #ifdef EBCDIC
2931     int backslash_N = 0;            /* ? was the character from \N{} */
2932     int non_portable_endpoint = 0;  /* ? In a range is an endpoint
2933                                        platform-specific like \x65 */
2934 #endif
2935
2936     PERL_ARGS_ASSERT_SCAN_CONST;
2937
2938     assert(PL_lex_inwhat != OP_TRANSR);
2939     if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
2940         /* If we are doing a trans and we know we want UTF8 set expectation */
2941         has_utf8   = PL_parser->lex_sub_op->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF);
2942         this_utf8  = PL_parser->lex_sub_op->op_private & (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
2943     }
2944
2945     /* Protect sv from errors and fatal warnings. */
2946     ENTER_with_name("scan_const");
2947     SAVEFREESV(sv);
2948
2949     while (s < send
2950            || dorange   /* Handle tr/// range at right edge of input */
2951     ) {
2952
2953         /* get transliterations out of the way (they're most literal) */
2954         if (PL_lex_inwhat == OP_TRANS) {
2955
2956             /* But there isn't any special handling necessary unless there is a
2957              * range, so for most cases we just drop down and handle the value
2958              * as any other.  There are two exceptions.
2959              *
2960              * 1.  A hyphen indicates that we are actually going to have a
2961              *     range.  In this case, skip the '-', set a flag, then drop
2962              *     down to handle what should be the end range value.
2963              * 2.  After we've handled that value, the next time through, that
2964              *     flag is set and we fix up the range.
2965              *
2966              * Ranges entirely within Latin1 are expanded out entirely, in
2967              * order to make the transliteration a simple table look-up.
2968              * Ranges that extend above Latin1 have to be done differently, so
2969              * there is no advantage to expanding them here, so they are
2970              * stored here as Min, ILLEGAL_UTF8_BYTE, Max.  The illegal byte
2971              * signifies a hyphen without any possible ambiguity.  On EBCDIC
2972              * machines, if the range is expressed as Unicode, the Latin1
2973              * portion is expanded out even if the range extends above
2974              * Latin1.  This is because each code point in it has to be
2975              * processed here individually to get its native translation */
2976
2977             if (! dorange) {
2978
2979                 /* Here, we don't think we're in a range.  If the new character
2980                  * is not a hyphen; or if it is a hyphen, but it's too close to
2981                  * either edge to indicate a range, or if we haven't output any
2982                  * characters yet then it's a regular character. */
2983                 if (*s != '-' || s >= send - 1 || s == start || d == SvPVX(sv)) {
2984
2985                     /* A regular character.  Process like any other, but first
2986                      * clear any flags */
2987                     didrange = FALSE;
2988                     dorange = FALSE;
2989 #ifdef EBCDIC
2990                     non_portable_endpoint = 0;
2991                     backslash_N = 0;
2992 #endif
2993                     /* The tests here for being above Latin1 and similar ones
2994                      * in the following 'else' suffice to find all such
2995                      * occurences in the constant, except those added by a
2996                      * backslash escape sequence, like \x{100}.  Mostly, those
2997                      * set 'has_above_latin1' as appropriate */
2998                     if (this_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
2999                         has_above_latin1 = TRUE;
3000                     }
3001
3002                     /* Drops down to generic code to process current byte */
3003                 }
3004                 else {  /* Is a '-' in the context where it means a range */
3005                     if (didrange) { /* Something like y/A-C-Z// */
3006                         Perl_croak(aTHX_ "Ambiguous range in transliteration"
3007                                          " operator");
3008                     }
3009
3010                     dorange = TRUE;
3011
3012                     s++;    /* Skip past the hyphen */
3013
3014                     /* d now points to where the end-range character will be
3015                      * placed.  Save it so won't have to go finding it later,
3016                      * and drop down to get that character.  (Actually we
3017                      * instead save the offset, to handle the case where a
3018                      * realloc in the meantime could change the actual
3019                      * pointer).  We'll finish processing the range the next
3020                      * time through the loop */
3021                     offset_to_max = d - SvPVX_const(sv);
3022
3023                     if (this_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3024                         has_above_latin1 = TRUE;
3025                     }
3026
3027                     /* Drops down to generic code to process current byte */
3028                 }
3029             }  /* End of not a range */
3030             else {
3031                 /* Here we have parsed a range.  Now must handle it.  At this
3032                  * point:
3033                  * 'sv' is a SV* that contains the output string we are
3034                  *      constructing.  The final two characters in that string
3035                  *      are the range start and range end, in order.
3036                  * 'd'  points to just beyond the range end in the 'sv' string,
3037                  *      where we would next place something
3038                  * 'offset_to_max' is the offset in 'sv' at which the character
3039                  *      (the range's maximum end point) before 'd'  begins.
3040                  */
3041                 char * max_ptr = SvPVX(sv) + offset_to_max;
3042                 char * min_ptr;
3043                 IV range_min;
3044                 IV range_max;   /* last character in range */
3045                 STRLEN grow;
3046                 Size_t offset_to_min = 0;
3047                 Size_t extras = 0;
3048 #ifdef EBCDIC
3049                 bool convert_unicode;
3050                 IV real_range_max = 0;
3051 #endif
3052                 /* Get the code point values of the range ends. */
3053                 if (has_utf8) {
3054                     /* We know the utf8 is valid, because we just constructed
3055                      * it ourselves in previous loop iterations */
3056                     min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
3057                     range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
3058                     range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
3059
3060                     /* This compensates for not all code setting
3061                      * 'has_above_latin1', so that we don't skip stuff that
3062                      * should be executed */
3063                     if (range_max > 255) {
3064                         has_above_latin1 = TRUE;
3065                     }
3066                 }
3067                 else {
3068                     min_ptr = max_ptr - 1;
3069                     range_min = * (U8*) min_ptr;
3070                     range_max = * (U8*) max_ptr;
3071                 }
3072
3073                 /* If the range is just a single code point, like tr/a-a/.../,
3074                  * that code point is already in the output, twice.  We can
3075                  * just back up over the second instance and avoid all the rest
3076                  * of the work.  But if it is a variant character, it's been
3077                  * counted twice, so decrement.  (This unlikely scenario is
3078                  * special cased, like the one for a range of 2 code points
3079                  * below, only because the main-line code below needs a range
3080                  * of 3 or more to work without special casing.  Might as well
3081                  * get it out of the way now.) */
3082                 if (UNLIKELY(range_max == range_min)) {
3083                     d = max_ptr;
3084                     if (! has_utf8 && ! UVCHR_IS_INVARIANT(range_max)) {
3085                         utf8_variant_count--;
3086                     }
3087                     goto range_done;
3088                 }
3089
3090 #ifdef EBCDIC
3091                 /* On EBCDIC platforms, we may have to deal with portable
3092                  * ranges.  These happen if at least one range endpoint is a
3093                  * Unicode value (\N{...}), or if the range is a subset of
3094                  * [A-Z] or [a-z], and both ends are literal characters,
3095                  * like 'A', and not like \x{C1} */
3096                 convert_unicode =
3097                                cBOOL(backslash_N)   /* \N{} forces Unicode,
3098                                                        hence portable range */
3099                     || (     ! non_portable_endpoint
3100                         && ((  isLOWER_A(range_min) && isLOWER_A(range_max))
3101                            || (isUPPER_A(range_min) && isUPPER_A(range_max))));
3102                 if (convert_unicode) {
3103
3104                     /* Special handling is needed for these portable ranges.
3105                      * They are defined to be in Unicode terms, which includes
3106                      * all the Unicode code points between the end points.
3107                      * Convert to Unicode to get the Unicode range.  Later we
3108                      * will convert each code point in the range back to
3109                      * native.  */
3110                     range_min = NATIVE_TO_UNI(range_min);
3111                     range_max = NATIVE_TO_UNI(range_max);
3112                 }
3113 #endif
3114
3115                 if (range_min > range_max) {
3116 #ifdef EBCDIC
3117                     if (convert_unicode) {
3118                         /* Need to convert back to native for meaningful
3119                          * messages for this platform */
3120                         range_min = UNI_TO_NATIVE(range_min);
3121                         range_max = UNI_TO_NATIVE(range_max);
3122                     }
3123 #endif
3124                     /* Use the characters themselves for the error message if
3125                      * ASCII printables; otherwise some visible representation
3126                      * of them */
3127                     if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3128                         Perl_croak(aTHX_
3129                          "Invalid range \"%c-%c\" in transliteration operator",
3130                          (char)range_min, (char)range_max);
3131                     }
3132 #ifdef EBCDIC
3133                     else if (convert_unicode) {
3134         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3135                         Perl_croak(aTHX_
3136                            "Invalid range \"\\N{U+%04" UVXf "}-\\N{U+%04"
3137                            UVXf "}\" in transliteration operator",
3138                            range_min, range_max);
3139                     }
3140 #endif
3141                     else {
3142         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3143                         Perl_croak(aTHX_
3144                            "Invalid range \"\\x{%04" UVXf "}-\\x{%04" UVXf "}\""
3145                            " in transliteration operator",
3146                            range_min, range_max);
3147                     }
3148                 }
3149
3150                 /* If the range is exactly two code points long, they are
3151                  * already both in the output */
3152                 if (UNLIKELY(range_min + 1 == range_max)) {
3153                     goto range_done;
3154                 }
3155
3156                 /* Here the range contains at least 3 code points */
3157
3158                 if (has_utf8) {
3159
3160                     /* If everything in the transliteration is below 256, we
3161                      * can avoid special handling later.  A translation table
3162                      * for each of those bytes is created by op.c.  So we
3163                      * expand out all ranges to their constituent code points.
3164                      * But if we've encountered something above 255, the
3165                      * expanding won't help, so skip doing that.  But if it's
3166                      * EBCDIC, we may have to look at each character below 256
3167                      * if we have to convert to/from Unicode values */
3168                     if (   has_above_latin1
3169 #ifdef EBCDIC
3170                         && (range_min > 255 || ! convert_unicode)
3171 #endif
3172                     ) {
3173                         /* Move the high character one byte to the right; then
3174                          * insert between it and the range begin, an illegal
3175                          * byte which serves to indicate this is a range (using
3176                          * a '-' would be ambiguous). */
3177                         char *e = d++;
3178                         while (e-- > max_ptr) {
3179                             *(e + 1) = *e;
3180                         }
3181                         *(e + 1) = (char) ILLEGAL_UTF8_BYTE;
3182                         goto range_done;
3183                     }
3184
3185                     /* Here, we're going to expand out the range.  For EBCDIC
3186                      * the range can extend above 255 (not so in ASCII), so
3187                      * for EBCDIC, split it into the parts above and below
3188                      * 255/256 */
3189 #ifdef EBCDIC
3190                     if (range_max > 255) {
3191                         real_range_max = range_max;
3192                         range_max = 255;
3193                     }
3194 #endif
3195                 }
3196
3197                 /* Here we need to expand out the string to contain each
3198                  * character in the range.  Grow the output to handle this.
3199                  * For non-UTF8, we need a byte for each code point in the
3200                  * range, minus the three that we've already allocated for: the
3201                  * hyphen, the min, and the max.  For UTF-8, we need this
3202                  * plus an extra byte for each code point that occupies two
3203                  * bytes (is variant) when in UTF-8 (except we've already
3204                  * allocated for the end points, including if they are
3205                  * variants).  For ASCII platforms and Unicode ranges on EBCDIC
3206                  * platforms, it's easy to calculate a precise number.  To
3207                  * start, we count the variants in the range, which we need
3208                  * elsewhere in this function anyway.  (For the case where it
3209                  * isn't easy to calculate, 'extras' has been initialized to 0,
3210                  * and the calculation is done in a loop further down.) */
3211 #ifdef EBCDIC
3212                 if (convert_unicode)
3213 #endif
3214                 {
3215                     /* This is executed unconditionally on ASCII, and for
3216                      * Unicode ranges on EBCDIC.  Under these conditions, all
3217                      * code points above a certain value are variant; and none
3218                      * under that value are.  We just need to find out how much
3219                      * of the range is above that value.  We don't count the
3220                      * end points here, as they will already have been counted
3221                      * as they were parsed. */
3222                     if (range_min >= UTF_CONTINUATION_MARK) {
3223
3224                         /* The whole range is made up of variants */
3225                         extras = (range_max - 1) - (range_min + 1) + 1;
3226                     }
3227                     else if (range_max >= UTF_CONTINUATION_MARK) {
3228
3229                         /* Only the higher portion of the range is variants */
3230                         extras = (range_max - 1) - UTF_CONTINUATION_MARK + 1;
3231                     }
3232
3233                     utf8_variant_count += extras;
3234                 }
3235
3236                 /* The base growth is the number of code points in the range,
3237                  * not including the endpoints, which have already been sized
3238                  * for (and output).  We don't subtract for the hyphen, as it
3239                  * has been parsed but not output, and the SvGROW below is
3240                  * based only on what's been output plus what's left to parse.
3241                  * */
3242                 grow = (range_max - 1) - (range_min + 1) + 1;
3243
3244                 if (has_utf8) {
3245 #ifdef EBCDIC
3246                     /* In some cases in EBCDIC, we haven't yet calculated a
3247                      * precise amount needed for the UTF-8 variants.  Just
3248                      * assume the worst case, that everything will expand by a
3249                      * byte */
3250                     if (! convert_unicode) {
3251                         grow *= 2;
3252                     }
3253                     else
3254 #endif
3255                     {
3256                         /* Otherwise we know exactly how many variants there
3257                          * are in the range. */
3258                         grow += extras;
3259                     }
3260                 }
3261
3262                 /* Grow, but position the output to overwrite the range min end
3263                  * point, because in some cases we overwrite that */
3264                 SvCUR_set(sv, d - SvPVX_const(sv));
3265                 offset_to_min = min_ptr - SvPVX_const(sv);
3266
3267                 /* See Note on sizing above. */
3268                 d = offset_to_min + SvGROW(sv, SvCUR(sv)
3269                                              + (send - s)
3270                                              + grow
3271                                              + 1 /* Trailing NUL */ );
3272
3273                 /* Now, we can expand out the range. */
3274 #ifdef EBCDIC
3275                 if (convert_unicode) {
3276                     SSize_t i;
3277
3278                     /* Recall that the min and max are now in Unicode terms, so
3279                      * we have to convert each character to its native
3280                      * equivalent */
3281                     if (has_utf8) {
3282                         for (i = range_min; i <= range_max; i++) {
3283                             append_utf8_from_native_byte(
3284                                                     LATIN1_TO_NATIVE((U8) i),
3285                                                     (U8 **) &d);
3286                         }
3287                     }
3288                     else {
3289                         for (i = range_min; i <= range_max; i++) {
3290                             *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3291                         }
3292                     }
3293                 }
3294                 else
3295 #endif
3296                 /* Always gets run for ASCII, and sometimes for EBCDIC. */
3297                 {
3298                     /* Here, no conversions are necessary, which means that the
3299                      * first character in the range is already in 'd' and
3300                      * valid, so we can skip overwriting it */
3301                     if (has_utf8) {
3302                         SSize_t i;
3303                         d += UTF8SKIP(d);
3304                         for (i = range_min + 1; i <= range_max; i++) {
3305                             append_utf8_from_native_byte((U8) i, (U8 **) &d);
3306                         }
3307                     }
3308                     else {
3309                         SSize_t i;
3310                         d++;
3311                         assert(range_min + 1 <= range_max);
3312                         for (i = range_min + 1; i < range_max; i++) {
3313 #ifdef EBCDIC
3314                             /* In this case on EBCDIC, we haven't calculated
3315                              * the variants.  Do it here, as we go along */
3316                             if (! UVCHR_IS_INVARIANT(i)) {
3317                                 utf8_variant_count++;
3318                             }
3319 #endif
3320                             *d++ = (char)i;
3321                         }
3322
3323                         /* The range_max is done outside the loop so as to
3324                          * avoid having to special case not incrementing
3325                          * 'utf8_variant_count' on EBCDIC (it's already been
3326                          * counted when originally parsed) */
3327                         *d++ = (char) range_max;
3328                     }
3329                 }
3330
3331 #ifdef EBCDIC
3332                 /* If the original range extended above 255, add in that
3333                  * portion. */
3334                 if (real_range_max) {
3335                     *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3336                     *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3337                     if (real_range_max > 0x100) {
3338                         if (real_range_max > 0x101) {
3339                             *d++ = (char) ILLEGAL_UTF8_BYTE;
3340                         }
3341                         d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3342                     }
3343                 }
3344 #endif
3345
3346               range_done:
3347                 /* mark the range as done, and continue */
3348                 didrange = TRUE;
3349                 dorange = FALSE;
3350 #ifdef EBCDIC
3351                 non_portable_endpoint = 0;
3352                 backslash_N = 0;
3353 #endif
3354                 continue;
3355             } /* End of is a range */
3356         } /* End of transliteration.  Joins main code after these else's */
3357         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3358             char *s1 = s-1;
3359             int esc = 0;
3360             while (s1 >= start && *s1-- == '\\')
3361                 esc = !esc;
3362             if (!esc)
3363                 in_charclass = TRUE;
3364         }
3365         else if (*s == ']' && PL_lex_inpat && in_charclass) {
3366             char *s1 = s-1;
3367             int esc = 0;
3368             while (s1 >= start && *s1-- == '\\')
3369                 esc = !esc;
3370             if (!esc)
3371                 in_charclass = FALSE;
3372         }
3373             /* skip for regexp comments /(?#comment)/, except for the last
3374              * char, which will be done separately.  Stop on (?{..}) and
3375              * friends */
3376         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3377             if (s[2] == '#') {
3378                 while (s+1 < send && *s != ')')
3379                     *d++ = *s++;
3380             }
3381             else if (!PL_lex_casemods
3382                      && (    s[2] == '{' /* This should match regcomp.c */
3383                          || (s[2] == '?' && s[3] == '{')))
3384             {
3385                 break;
3386             }
3387         }
3388             /* likewise skip #-initiated comments in //x patterns */
3389         else if (*s == '#'
3390                  && PL_lex_inpat
3391                  && !in_charclass
3392                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3393         {
3394             while (s < send && *s != '\n')
3395                 *d++ = *s++;
3396         }
3397             /* no further processing of single-quoted regex */
3398         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3399             goto default_action;
3400
3401             /* check for embedded arrays
3402              * (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3403              */
3404         else if (*s == '@' && s[1]) {
3405             if (UTF
3406                ? isIDFIRST_utf8_safe(s+1, send)
3407                : isWORDCHAR_A(s[1]))
3408             {
3409                 break;
3410             }
3411             if (strchr(":'{$", s[1]))
3412                 break;
3413             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3414                 break; /* in regexp, neither @+ nor @- are interpolated */
3415         }
3416             /* check for embedded scalars.  only stop if we're sure it's a
3417              * variable.  */
3418         else if (*s == '$') {
3419             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3420                 break;
3421             if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
3422                 if (s[1] == '\\') {
3423                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3424                                    "Possible unintended interpolation of $\\ in regex");
3425                 }
3426                 break;          /* in regexp, $ might be tail anchor */
3427             }
3428         }
3429
3430         /* End of else if chain - OP_TRANS rejoin rest */
3431
3432         if (UNLIKELY(s >= send)) {
3433             assert(s == send);
3434             break;
3435         }
3436
3437         /* backslashes */
3438         if (*s == '\\' && s+1 < send) {
3439             char* e;    /* Can be used for ending '}', etc. */
3440
3441             s++;
3442
3443             /* warn on \1 - \9 in substitution replacements, but note that \11
3444              * is an octal; and \19 is \1 followed by '9' */
3445             if (PL_lex_inwhat == OP_SUBST
3446                 && !PL_lex_inpat
3447                 && isDIGIT(*s)
3448                 && *s != '0'
3449                 && !isDIGIT(s[1]))
3450             {
3451                 /* diag_listed_as: \%d better written as $%d */
3452                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3453                 *--s = '$';
3454                 break;
3455             }
3456
3457             /* string-change backslash escapes */
3458             if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQF", *s)) {
3459                 --s;
3460                 break;
3461             }
3462             /* In a pattern, process \N, but skip any other backslash escapes.
3463              * This is because we don't want to translate an escape sequence
3464              * into a meta symbol and have the regex compiler use the meta
3465              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3466              * in spite of this, we do have to process \N here while the proper
3467              * charnames handler is in scope.  See bugs #56444 and #62056.
3468              *
3469              * There is a complication because \N in a pattern may also stand
3470              * for 'match a non-nl', and not mean a charname, in which case its
3471              * processing should be deferred to the regex compiler.  To be a
3472              * charname it must be followed immediately by a '{', and not look
3473              * like \N followed by a curly quantifier, i.e., not something like
3474              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3475              * quantifier */
3476             else if (PL_lex_inpat
3477                     && (*s != 'N'
3478                         || s[1] != '{'
3479                         || regcurly(s + 1)))
3480             {
3481                 *d++ = '\\';
3482                 goto default_action;
3483             }
3484
3485             switch (*s) {
3486             default:
3487                 {
3488                     if ((isALPHANUMERIC(*s)))
3489                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3490                                        "Unrecognized escape \\%c passed through",
3491                                        *s);
3492                     /* default action is to copy the quoted character */
3493                     goto default_action;
3494                 }
3495
3496             /* eg. \132 indicates the octal constant 0132 */
3497             case '0': case '1': case '2': case '3':
3498             case '4': case '5': case '6': case '7':
3499                 {
3500                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
3501                     STRLEN len = 3;
3502                     uv = grok_oct(s, &len, &flags, NULL);
3503                     s += len;
3504                     if (len < 3 && s < send && isDIGIT(*s)
3505                         && ckWARN(WARN_MISC))
3506                     {
3507                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3508                                     "%s", form_short_octal_warning(s, len));
3509                     }
3510                 }
3511                 goto NUM_ESCAPE_INSERT;
3512
3513             /* eg. \o{24} indicates the octal constant \024 */
3514             case 'o':
3515                 {
3516                     const char* error;
3517
3518                     bool valid = grok_bslash_o(&s, PL_bufend,
3519                                                &uv, &error,
3520                                                TRUE, /* Output warning */
3521                                                FALSE, /* Not strict */
3522                                                TRUE, /* Output warnings for
3523                                                          non-portables */
3524                                                UTF);
3525                     if (! valid) {
3526                         yyerror(error);
3527                         uv = 0; /* drop through to ensure range ends are set */
3528                     }
3529                     goto NUM_ESCAPE_INSERT;
3530                 }
3531
3532             /* eg. \x24 indicates the hex constant 0x24 */
3533             case 'x':
3534                 {
3535                     const char* error;
3536
3537                     bool valid = grok_bslash_x(&s, PL_bufend,
3538                                                &uv, &error,
3539                                                TRUE, /* Output warning */
3540                                                FALSE, /* Not strict */
3541                                                TRUE,  /* Output warnings for
3542                                                          non-portables */
3543                                                UTF);
3544                     if (! valid) {
3545                         yyerror(error);
3546                         uv = 0; /* drop through to ensure range ends are set */
3547                     }
3548                 }
3549
3550               NUM_ESCAPE_INSERT:
3551                 /* Insert oct or hex escaped character. */
3552
3553                 /* Here uv is the ordinal of the next character being added */
3554                 if (UVCHR_IS_INVARIANT(uv)) {
3555                     *d++ = (char) uv;
3556                 }
3557                 else {
3558                     if (!has_utf8 && uv > 255) {
3559
3560                         /* Here, 'uv' won't fit unless we convert to UTF-8.
3561                          * If we've only seen invariants so far, all we have to
3562                          * do is turn on the flag */
3563                         if (utf8_variant_count == 0) {
3564                             SvUTF8_on(sv);
3565                         }
3566                         else {
3567                             SvCUR_set(sv, d - SvPVX_const(sv));
3568                             SvPOK_on(sv);
3569                             *d = '\0';
3570
3571                             sv_utf8_upgrade_flags_grow(
3572                                            sv,
3573                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3574
3575                                            /* Since we're having to grow here,
3576                                             * make sure we have enough room for
3577                                             * this escape and a NUL, so the
3578                                             * code immediately below won't have
3579                                             * to actually grow again */
3580                                           UVCHR_SKIP(uv)
3581                                         + (STRLEN)(send - s) + 1);
3582                             d = SvPVX(sv) + SvCUR(sv);
3583                         }
3584
3585                         has_above_latin1 = TRUE;
3586                         has_utf8 = TRUE;
3587                     }
3588
3589                     if (! has_utf8) {
3590                         *d++ = (char)uv;
3591                         utf8_variant_count++;
3592                     }
3593                     else {
3594                        /* Usually, there will already be enough room in 'sv'
3595                         * since such escapes are likely longer than any UTF-8
3596                         * sequence they can end up as.  This isn't the case on
3597                         * EBCDIC where \x{40000000} contains 12 bytes, and the
3598                         * UTF-8 for it contains 14.  And, we have to allow for
3599                         * a trailing NUL.  It probably can't happen on ASCII
3600                         * platforms, but be safe.  See Note on sizing above. */
3601                         const STRLEN needed = d - SvPVX(sv)
3602                                             + UVCHR_SKIP(uv)
3603                                             + (send - s)
3604                                             + 1;
3605                         if (UNLIKELY(needed > SvLEN(sv))) {
3606                             SvCUR_set(sv, d - SvPVX_const(sv));
3607                             d = SvCUR(sv) + SvGROW(sv, needed);
3608                         }
3609
3610                         d = (char*)uvchr_to_utf8((U8*)d, uv);
3611                         if (PL_lex_inwhat == OP_TRANS
3612                             && PL_parser->lex_sub_op)
3613                         {
3614                             PL_parser->lex_sub_op->op_private |=
3615                                 (PL_lex_repl ? OPpTRANS_FROM_UTF
3616                                              : OPpTRANS_TO_UTF);
3617                         }
3618                     }
3619                 }
3620 #ifdef EBCDIC
3621                 non_portable_endpoint++;
3622 #endif
3623                 continue;
3624
3625             case 'N':
3626                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3627                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3628                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3629                  * GRAVE} (except y/// can't handle the latter, croaking).  For
3630                  * convenience all three forms are referred to as "named
3631                  * characters" below.
3632                  *
3633                  * For patterns, \N also can mean to match a non-newline.  Code
3634                  * before this 'switch' statement should already have handled
3635                  * this situation, and hence this code only has to deal with
3636                  * the named character cases.
3637                  *
3638                  * For non-patterns, the named characters are converted to
3639                  * their string equivalents.  In patterns, named characters are
3640                  * not converted to their ultimate forms for the same reasons
3641                  * that other escapes aren't (mainly that the ultimate
3642                  * character could be considered a meta-symbol by the regex
3643                  * compiler).  Instead, they are converted to the \N{U+...}
3644                  * form to get the value from the charnames that is in effect
3645                  * right now, while preserving the fact that it was a named
3646                  * character, so that the regex compiler knows this.
3647                  *
3648                  * The structure of this section of code (besides checking for
3649                  * errors and upgrading to utf8) is:
3650                  *    If the named character is of the form \N{U+...}, pass it
3651                  *      through if a pattern; otherwise convert the code point
3652                  *      to utf8
3653                  *    Otherwise must be some \N{NAME}: convert to
3654                  *      \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3655                  *
3656                  * Transliteration is an exception.  The conversion to utf8 is
3657                  * only done if the code point requires it to be representable.
3658                  *
3659                  * Here, 's' points to the 'N'; the test below is guaranteed to
3660                  * succeed if we are being called on a pattern, as we already
3661                  * know from a test above that the next character is a '{'.  A
3662                  * non-pattern \N must mean 'named character', which requires
3663                  * braces */
3664                 s++;
3665                 if (*s != '{') {
3666                     yyerror("Missing braces on \\N{}");
3667                     *d++ = '\0';
3668                     continue;
3669                 }
3670                 s++;
3671
3672                 /* If there is no matching '}', it is an error. */
3673                 if (! (e = (char *) memchr(s, '}', send - s))) {
3674                     if (! PL_lex_inpat) {
3675                         yyerror("Missing right brace on \\N{}");
3676                     } else {
3677                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3678                     }
3679                     yyquit(); /* Have exhausted the input. */
3680                 }
3681
3682                 /* Here it looks like a named character */
3683
3684                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3685                     s += 2;         /* Skip to next char after the 'U+' */
3686                     if (PL_lex_inpat) {
3687
3688                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3689                         /* Check the syntax.  */
3690                         const char *orig_s;
3691                         orig_s = s - 5;
3692                         if (!isXDIGIT(*s)) {
3693                           bad_NU:
3694                             yyerror(
3695                                 "Invalid hexadecimal number in \\N{U+...}"
3696                             );
3697                             s = e + 1;
3698                             *d++ = '\0';
3699                             continue;
3700                         }
3701                         while (++s < e) {
3702                             if (isXDIGIT(*s))
3703                                 continue;
3704                             else if ((*s == '.' || *s == '_')
3705                                   && isXDIGIT(s[1]))
3706                                 continue;
3707                             goto bad_NU;
3708                         }
3709
3710                         /* Pass everything through unchanged.
3711                          * +1 is for the '}' */
3712                         Copy(orig_s, d, e - orig_s + 1, char);
3713                         d += e - orig_s + 1;
3714                     }
3715                     else {  /* Not a pattern: convert the hex to string */
3716                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3717                                 | PERL_SCAN_SILENT_ILLDIGIT
3718                                 | PERL_SCAN_DISALLOW_PREFIX;
3719                         STRLEN len = e - s;
3720                         uv = grok_hex(s, &len, &flags, NULL);
3721                         if (len == 0 || (len != (STRLEN)(e - s)))
3722                             goto bad_NU;
3723
3724                          /* For non-tr///, if the destination is not in utf8,
3725                           * unconditionally recode it to be so.  This is
3726                           * because \N{} implies Unicode semantics, and scalars
3727                           * have to be in utf8 to guarantee those semantics.
3728                           * tr/// doesn't care about Unicode rules, so no need
3729                           * there to upgrade to UTF-8 for small enough code
3730                           * points */
3731                         if (! has_utf8 && (   uv > 0xFF
3732                                            || PL_lex_inwhat != OP_TRANS))
3733                         {
3734                             /* See Note on sizing above.  */
3735                             const STRLEN extra = OFFUNISKIP(uv) + (send - e) + 1;
3736
3737                             SvCUR_set(sv, d - SvPVX_const(sv));
3738                             SvPOK_on(sv);
3739                             *d = '\0';
3740
3741                             if (utf8_variant_count == 0) {
3742                                 SvUTF8_on(sv);
3743                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3744                             }
3745                             else {
3746                                 sv_utf8_upgrade_flags_grow(
3747                                                sv,
3748                                                SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3749                                                extra);
3750                                 d = SvPVX(sv) + SvCUR(sv);
3751                             }
3752
3753                             has_utf8 = TRUE;
3754                             has_above_latin1 = TRUE;
3755                         }
3756
3757                         /* Add the (Unicode) code point to the output. */
3758                         if (! has_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3759                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3760                         }
3761                         else {
3762                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv, 0);
3763                         }
3764                     }
3765                 }
3766                 else /* Here is \N{NAME} but not \N{U+...}. */
3767                      if ((res = get_and_check_backslash_N_name(s, e)))
3768                 {
3769                     STRLEN len;
3770                     const char *str = SvPV_const(res, len);
3771                     if (PL_lex_inpat) {
3772
3773                         if (! len) { /* The name resolved to an empty string */
3774                             Copy("\\N{}", d, 4, char);
3775                             d += 4;
3776                         }
3777                         else {
3778                             /* In order to not lose information for the regex
3779                             * compiler, pass the result in the specially made
3780                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3781                             * the code points in hex of each character
3782                             * returned by charnames */
3783
3784                             const char *str_end = str + len;
3785                             const STRLEN off = d - SvPVX_const(sv);
3786
3787                             if (! SvUTF8(res)) {
3788                                 /* For the non-UTF-8 case, we can determine the
3789                                  * exact length needed without having to parse
3790                                  * through the string.  Each character takes up
3791                                  * 2 hex digits plus either a trailing dot or
3792                                  * the "}" */
3793                                 const char initial_text[] = "\\N{U+";
3794                                 const STRLEN initial_len = sizeof(initial_text)
3795                                                            - 1;
3796                                 d = off + SvGROW(sv, off
3797                                                     + 3 * len
3798
3799                                                     /* +1 for trailing NUL */
3800                                                     + initial_len + 1
3801
3802                                                     + (STRLEN)(send - e));
3803                                 Copy(initial_text, d, initial_len, char);
3804                                 d += initial_len;
3805                                 while (str < str_end) {
3806                                     char hex_string[4];
3807                                     int len =
3808                                         my_snprintf(hex_string,
3809                                                   sizeof(hex_string),
3810                                                   "%02X.",
3811
3812                                                   /* The regex compiler is
3813                                                    * expecting Unicode, not
3814                                                    * native */
3815                                                   NATIVE_TO_LATIN1(*str));
3816                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3817                                                            sizeof(hex_string));
3818                                     Copy(hex_string, d, 3, char);
3819                                     d += 3;
3820                                     str++;
3821                                 }
3822                                 d--;    /* Below, we will overwrite the final
3823                                            dot with a right brace */
3824                             }
3825                             else {
3826                                 STRLEN char_length; /* cur char's byte length */
3827
3828                                 /* and the number of bytes after this is
3829                                  * translated into hex digits */
3830                                 STRLEN output_length;
3831
3832                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3833                                  * for max('U+', '.'); and 1 for NUL */
3834                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3835
3836                                 /* Get the first character of the result. */
3837                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3838                                                         len,
3839                                                         &char_length,
3840                                                         UTF8_ALLOW_ANYUV);
3841                                 /* Convert first code point to Unicode hex,
3842                                  * including the boiler plate before it. */
3843                                 output_length =
3844                                     my_snprintf(hex_string, sizeof(hex_string),
3845                                              "\\N{U+%X",
3846                                              (unsigned int) NATIVE_TO_UNI(uv));
3847
3848                                 /* Make sure there is enough space to hold it */
3849                                 d = off + SvGROW(sv, off
3850                                                     + output_length
3851                                                     + (STRLEN)(send - e)
3852                                                     + 2);       /* '}' + NUL */
3853                                 /* And output it */
3854                                 Copy(hex_string, d, output_length, char);
3855                                 d += output_length;
3856
3857                                 /* For each subsequent character, append dot and
3858                                 * its Unicode code point in hex */
3859                                 while ((str += char_length) < str_end) {
3860                                     const STRLEN off = d - SvPVX_const(sv);
3861                                     U32 uv = utf8n_to_uvchr((U8 *) str,
3862                                                             str_end - str,
3863                                                             &char_length,
3864                                                             UTF8_ALLOW_ANYUV);
3865                                     output_length =
3866                                         my_snprintf(hex_string,
3867                                              sizeof(hex_string),
3868                                              ".%X",
3869                                              (unsigned int) NATIVE_TO_UNI(uv));
3870
3871                                     d = off + SvGROW(sv, off
3872                                                         + output_length
3873                                                         + (STRLEN)(send - e)
3874                                                         + 2);   /* '}' +  NUL */
3875                                     Copy(hex_string, d, output_length, char);
3876                                     d += output_length;
3877                                 }
3878                             }
3879
3880                             *d++ = '}'; /* Done.  Add the trailing brace */
3881                         }
3882                     }
3883                     else { /* Here, not in a pattern.  Convert the name to a
3884                             * string. */
3885
3886                         if (PL_lex_inwhat == OP_TRANS) {
3887                             str = SvPV_const(res, len);
3888                             if (len > ((SvUTF8(res))
3889                                        ? UTF8SKIP(str)
3890                                        : 1U))
3891                             {
3892                                 yyerror(Perl_form(aTHX_
3893                                     "%.*s must not be a named sequence"
3894                                     " in transliteration operator",
3895                                         /*  +1 to include the "}" */
3896                                     (int) (e + 1 - start), start));
3897                                 *d++ = '\0';
3898                                 goto end_backslash_N;
3899                             }
3900
3901                             if (SvUTF8(res) && UTF8_IS_ABOVE_LATIN1(*str)) {
3902                                 has_above_latin1 = TRUE;
3903                             }
3904
3905                         }
3906                         else if (! SvUTF8(res)) {
3907                             /* Make sure \N{} return is UTF-8.  This is because
3908                              * \N{} implies Unicode semantics, and scalars have
3909                              * to be in utf8 to guarantee those semantics; but
3910                              * not needed in tr/// */
3911                             sv_utf8_upgrade_flags(res, 0);
3912                             str = SvPV_const(res, len);
3913                         }
3914
3915                          /* Upgrade destination to be utf8 if this new
3916                           * component is */
3917                         if (! has_utf8 && SvUTF8(res)) {
3918                             /* See Note on sizing above.  */
3919                             const STRLEN extra = len + (send - s) + 1;
3920
3921                             SvCUR_set(sv, d - SvPVX_const(sv));
3922                             SvPOK_on(sv);
3923                             *d = '\0';
3924
3925                             if (utf8_variant_count == 0) {
3926                                 SvUTF8_on(sv);
3927                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3928                             }
3929                             else {
3930                                 sv_utf8_upgrade_flags_grow(sv,
3931                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3932                                                 extra);
3933                                 d = SvPVX(sv) + SvCUR(sv);
3934                             }
3935                             has_utf8 = TRUE;
3936                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3937
3938                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3939                              * set correctly here). */
3940                             const STRLEN extra = len + (send - e) + 1;
3941                             const STRLEN off = d - SvPVX_const(sv);
3942                             d = off + SvGROW(sv, off + extra);
3943                         }
3944                         Copy(str, d, len, char);
3945                         d += len;
3946                     }
3947
3948                     SvREFCNT_dec(res);
3949
3950                 } /* End \N{NAME} */
3951
3952               end_backslash_N:
3953 #ifdef EBCDIC
3954                 backslash_N++; /* \N{} is defined to be Unicode */
3955 #endif
3956                 s = e + 1;  /* Point to just after the '}' */
3957                 continue;
3958
3959             /* \c is a control character */
3960             case 'c':
3961                 s++;
3962                 if (s < send) {
3963                     *d++ = grok_bslash_c(*s, 1);
3964                 }
3965                 else {
3966                     yyerror("Missing control char name in \\c");
3967                     yyquit();   /* Are at end of input, no sense continuing */
3968                 }
3969 #ifdef EBCDIC
3970                 non_portable_endpoint++;
3971 #endif
3972                 break;
3973
3974             /* printf-style backslashes, formfeeds, newlines, etc */
3975             case 'b':
3976                 *d++ = '\b';
3977                 break;
3978             case 'n':
3979                 *d++ = '\n';
3980                 break;
3981             case 'r':
3982                 *d++ = '\r';
3983                 break;
3984             case 'f':
3985                 *d++ = '\f';
3986                 break;
3987             case 't':
3988                 *d++ = '\t';
3989                 break;
3990             case 'e':
3991                 *d++ = ESC_NATIVE;
3992                 break;
3993             case 'a':
3994                 *d++ = '\a';
3995                 break;
3996             } /* end switch */
3997
3998             s++;
3999             continue;
4000         } /* end if (backslash) */
4001
4002     default_action:
4003         /* Just copy the input to the output, though we may have to convert
4004          * to/from UTF-8.
4005          *
4006          * If the input has the same representation in UTF-8 as not, it will be
4007          * a single byte, and we don't care about UTF8ness; just copy the byte */
4008         if (NATIVE_BYTE_IS_INVARIANT((U8)(*s))) {
4009             *d++ = *s++;
4010         }
4011         else if (! this_utf8 && ! has_utf8) {
4012             /* If neither source nor output is UTF-8, is also a single byte,
4013              * just copy it; but this byte counts should we later have to
4014              * convert to UTF-8 */
4015             *d++ = *s++;
4016             utf8_variant_count++;
4017         }
4018         else if (this_utf8 && has_utf8) {   /* Both UTF-8, can just copy */
4019             const STRLEN len = UTF8SKIP(s);
4020
4021             /* We expect the source to have already been checked for
4022              * malformedness */
4023             assert(isUTF8_CHAR((U8 *) s, (U8 *) send));
4024
4025             Copy(s, d, len, U8);
4026             d += len;
4027             s += len;
4028         }
4029         else { /* UTF8ness matters and doesn't match, need to convert */
4030             STRLEN len = 1;
4031             const UV nextuv   = (this_utf8)
4032                                 ? utf8n_to_uvchr((U8*)s, send - s, &len, 0)
4033                                 : (UV) ((U8) *s);
4034             STRLEN need = UVCHR_SKIP(nextuv);
4035
4036             if (!has_utf8) {
4037                 SvCUR_set(sv, d - SvPVX_const(sv));
4038                 SvPOK_on(sv);
4039                 *d = '\0';
4040
4041                 /* See Note on sizing above. */
4042                 need += (STRLEN)(send - s) + 1;
4043
4044                 if (utf8_variant_count == 0) {
4045                     SvUTF8_on(sv);
4046                     d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + need);
4047                 }
4048                 else {
4049                     sv_utf8_upgrade_flags_grow(sv,
4050                                                SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4051                                                need);
4052                     d = SvPVX(sv) + SvCUR(sv);
4053                 }
4054                 has_utf8 = TRUE;
4055             } else if (need > len) {
4056                 /* encoded value larger than old, may need extra space (NOTE:
4057                  * SvCUR() is not set correctly here).   See Note on sizing
4058                  * above.  */
4059                 const STRLEN extra = need + (send - s) + 1;
4060                 const STRLEN off = d - SvPVX_const(sv);
4061                 d = off + SvGROW(sv, off + extra);
4062             }
4063             s += len;
4064
4065             d = (char*)uvchr_to_utf8((U8*)d, nextuv);
4066         }
4067     } /* while loop to process each character */
4068
4069     /* terminate the string and set up the sv */
4070     *d = '\0';
4071     SvCUR_set(sv, d - SvPVX_const(sv));
4072     if (SvCUR(sv) >= SvLEN(sv))
4073         Perl_croak(aTHX_ "panic: constant overflowed allocated space, %" UVuf
4074                    " >= %" UVuf, (UV)SvCUR(sv), (UV)SvLEN(sv));
4075
4076     SvPOK_on(sv);
4077     if (has_utf8) {
4078         SvUTF8_on(sv);
4079         if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
4080             PL_parser->lex_sub_op->op_private |=
4081                     (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
4082         }
4083     }
4084
4085     /* shrink the sv if we allocated more than we used */
4086     if (SvCUR(sv) + 5 < SvLEN(sv)) {
4087         SvPV_shrink_to_cur(sv);
4088     }
4089
4090     /* return the substring (via pl_yylval) only if we parsed anything */
4091     if (s > start) {
4092         char *s2 = start;
4093         for (; s2 < s; s2++) {
4094             if (*s2 == '\n')
4095                 COPLINE_INC_WITH_HERELINES;
4096         }
4097         SvREFCNT_inc_simple_void_NN(sv);
4098         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
4099             && ! PL_parser->lex_re_reparsing)
4100         {
4101             const char *const key = PL_lex_inpat ? "qr" : "q";
4102             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
4103             const char *type;
4104             STRLEN typelen;
4105
4106             if (PL_lex_inwhat == OP_TRANS) {
4107                 type = "tr";
4108                 typelen = 2;
4109             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
4110                 type = "s";
4111                 typelen = 1;
4112             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
4113                 type = "q";
4114                 typelen = 1;
4115             } else  {
4116                 type = "qq";
4117                 typelen = 2;
4118             }
4119
4120             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
4121                                 type, typelen);
4122         }
4123         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
4124     }
4125     LEAVE_with_name("scan_const");
4126     return s;
4127 }
4128
4129 /* S_intuit_more
4130  * Returns TRUE if there's more to the expression (e.g., a subscript),
4131  * FALSE otherwise.
4132  *
4133  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
4134  *
4135  * ->[ and ->{ return TRUE
4136  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
4137  * { and [ outside a pattern are always subscripts, so return TRUE
4138  * if we're outside a pattern and it's not { or [, then return FALSE
4139  * if we're in a pattern and the first char is a {
4140  *   {4,5} (any digits around the comma) returns FALSE
4141  * if we're in a pattern and the first char is a [
4142  *   [] returns FALSE
4143  *   [SOMETHING] has a funky algorithm to decide whether it's a
4144  *      character class or not.  It has to deal with things like
4145  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
4146  * anything else returns TRUE
4147  */
4148
4149 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
4150
4151 STATIC int
4152 S_intuit_more(pTHX_ char *s, char *e)
4153 {
4154     PERL_ARGS_ASSERT_INTUIT_MORE;
4155
4156     if (PL_lex_brackets)
4157         return TRUE;
4158     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
4159         return TRUE;
4160     if (*s == '-' && s[1] == '>'
4161      && FEATURE_POSTDEREF_QQ_IS_ENABLED
4162      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
4163         ||(s[2] == '@' && strchr("*[{",s[3])) ))
4164         return TRUE;
4165     if (*s != '{' && *s != '[')
4166         return FALSE;
4167     if (!PL_lex_inpat)
4168         return TRUE;
4169
4170     /* In a pattern, so maybe we have {n,m}. */
4171     if (*s == '{') {
4172         if (regcurly(s)) {
4173             return FALSE;
4174         }
4175         return TRUE;
4176     }
4177
4178     /* On the other hand, maybe we have a character class */
4179
4180     s++;
4181     if (*s == ']' || *s == '^')
4182         return FALSE;
4183     else {
4184         /* this is terrifying, and it works */
4185         int weight;
4186         char seen[256];
4187         const char * const send = (char *) memchr(s, ']', e - s);
4188         unsigned char un_char, last_un_char;
4189         char tmpbuf[sizeof PL_tokenbuf * 4];
4190
4191         if (!send)              /* has to be an expression */
4192             return TRUE;
4193         weight = 2;             /* let's weigh the evidence */
4194
4195         if (*s == '$')
4196             weight -= 3;
4197         else if (isDIGIT(*s)) {
4198             if (s[1] != ']') {
4199                 if (isDIGIT(s[1]) && s[2] == ']')
4200                     weight -= 10;
4201             }
4202             else
4203                 weight -= 100;
4204         }
4205         Zero(seen,256,char);
4206         un_char = 255;
4207         for (; s < send; s++) {
4208             last_un_char = un_char;
4209             un_char = (unsigned char)*s;
4210             switch (*s) {
4211             case '@':
4212             case '&':
4213             case '$':
4214                 weight -= seen[un_char] * 10;
4215                 if (isWORDCHAR_lazy_if_safe(s+1, PL_bufend, UTF)) {
4216                     int len;
4217                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
4218                     len = (int)strlen(tmpbuf);
4219                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
4220                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
4221                         weight -= 100;
4222                     else
4223                         weight -= 10;
4224                 }
4225                 else if (*s == '$'
4226                          && s[1]
4227                          && strchr("[#!%*<>()-=",s[1]))
4228                 {
4229                     if (/*{*/ strchr("])} =",s[2]))
4230                         weight -= 10;
4231                     else
4232                         weight -= 1;
4233                 }
4234                 break;
4235             case '\\':
4236                 un_char = 254;
4237                 if (s[1]) {
4238                     if (strchr("wds]",s[1]))
4239                         weight += 100;
4240                     else if (seen[(U8)'\''] || seen[(U8)'"'])
4241                         weight += 1;
4242                     else if (strchr("rnftbxcav",s[1]))
4243                         weight += 40;
4244                     else if (isDIGIT(s[1])) {
4245                         weight += 40;
4246                         while (s[1] && isDIGIT(s[1]))
4247                             s++;
4248                     }
4249                 }
4250                 else
4251                     weight += 100;
4252                 break;
4253             case '-':
4254                 if (s[1] == '\\')
4255                     weight += 50;
4256                 if (strchr("aA01! ",last_un_char))
4257                     weight += 30;
4258                 if (strchr("zZ79~",s[1]))
4259                     weight += 30;
4260                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4261                     weight -= 5;        /* cope with negative subscript */
4262                 break;
4263             default:
4264                 if (!isWORDCHAR(last_un_char)
4265                     && !(last_un_char == '$' || last_un_char == '@'
4266                          || last_un_char == '&')
4267                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4268                     char *d = s;
4269                     while (isALPHA(*s))
4270                         s++;
4271                     if (keyword(d, s - d, 0))
4272                         weight -= 150;
4273                 }
4274                 if (un_char == last_un_char + 1)
4275                     weight += 5;
4276                 weight -= seen[un_char];
4277                 break;
4278             }
4279             seen[un_char]++;
4280         }
4281         if (weight >= 0)        /* probably a character class */
4282             return FALSE;
4283     }
4284
4285     return TRUE;
4286 }
4287
4288 /*
4289  * S_intuit_method
4290  *
4291  * Does all the checking to disambiguate
4292  *   foo bar
4293  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
4294  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4295  *
4296  * First argument is the stuff after the first token, e.g. "bar".
4297  *
4298  * Not a method if foo is a filehandle.
4299  * Not a method if foo is a subroutine prototyped to take a filehandle.
4300  * Not a method if it's really "Foo $bar"
4301  * Method if it's "foo $bar"
4302  * Not a method if it's really "print foo $bar"
4303  * Method if it's really "foo package::" (interpreted as package->foo)
4304  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4305  * Not a method if bar is a filehandle or package, but is quoted with
4306  *   =>
4307  */
4308
4309 STATIC int
4310 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4311 {
4312     char *s = start + (*start == '$');
4313     char tmpbuf[sizeof PL_tokenbuf];
4314     STRLEN len;
4315     GV* indirgv;
4316         /* Mustn't actually add anything to a symbol table.
4317            But also don't want to "initialise" any placeholder
4318            constants that might already be there into full
4319            blown PVGVs with attached PVCV.  */
4320     GV * const gv =
4321         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4322
4323     PERL_ARGS_ASSERT_INTUIT_METHOD;
4324
4325     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4326             return 0;
4327     if (cv && SvPOK(cv)) {
4328         const char *proto = CvPROTO(cv);
4329         if (proto) {
4330             while (*proto && (isSPACE(*proto) || *proto == ';'))
4331                 proto++;
4332             if (*proto == '*')
4333                 return 0;
4334         }
4335     }
4336
4337     if (*start == '$') {
4338         SSize_t start_off = start - SvPVX(PL_linestr);
4339         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4340             || isUPPER(*PL_tokenbuf))
4341             return 0;
4342         /* this could be $# */
4343         if (isSPACE(*s))
4344             s = skipspace(s);
4345         PL_bufptr = SvPVX(PL_linestr) + start_off;
4346         PL_expect = XREF;
4347         return *s == '(' ? FUNCMETH : METHOD;
4348     }
4349
4350     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4351     /* start is the beginning of the possible filehandle/object,
4352      * and s is the end of it
4353      * tmpbuf is a copy of it (but with single quotes as double colons)
4354      */
4355
4356     if (!keyword(tmpbuf, len, 0)) {
4357         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4358             len -= 2;
4359             tmpbuf[len] = '\0';
4360             goto bare_package;
4361         }
4362         indirgv = gv_fetchpvn_flags(tmpbuf, len,
4363                                     GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4364                                     SVt_PVCV);
4365         if (indirgv && SvTYPE(indirgv) != SVt_NULL
4366          && (!isGV(indirgv) || GvCVu(indirgv)))
4367             return 0;
4368         /* filehandle or package name makes it a method */
4369         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4370             s = skipspace(s);
4371             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4372                 return 0;       /* no assumptions -- "=>" quotes bareword */
4373       bare_package:
4374             NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0,
4375                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4376             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4377             PL_expect = XTERM;
4378             force_next(BAREWORD);
4379             PL_bufptr = s;
4380             return *s == '(' ? FUNCMETH : METHOD;
4381         }
4382     }
4383     return 0;
4384 }
4385
4386 /* Encoded script support. filter_add() effectively inserts a
4387  * 'pre-processing' function into the current source input stream.
4388  * Note that the filter function only applies to the current source file
4389  * (e.g., it will not affect files 'require'd or 'use'd by this one).
4390  *
4391  * The datasv parameter (which may be NULL) can be used to pass
4392  * private data to this instance of the filter. The filter function
4393  * can recover the SV using the FILTER_DATA macro and use it to
4394  * store private buffers and state information.
4395  *
4396  * The supplied datasv parameter is upgraded to a PVIO type
4397  * and the IoDIRP/IoANY field is used to store the function pointer,
4398  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4399  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4400  * private use must be set using malloc'd pointers.
4401  */
4402
4403 SV *
4404 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4405 {
4406     if (!funcp)
4407         return NULL;
4408
4409     if (!PL_parser)
4410         return NULL;
4411
4412     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4413         Perl_croak(aTHX_ "Source filters apply only to byte streams");
4414
4415     if (!PL_rsfp_filters)
4416         PL_rsfp_filters = newAV();
4417     if (!datasv)
4418         datasv = newSV(0);
4419     SvUPGRADE(datasv, SVt_PVIO);
4420     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4421     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4422     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4423                           FPTR2DPTR(void *, IoANY(datasv)),
4424                           SvPV_nolen(datasv)));
4425     av_unshift(PL_rsfp_filters, 1);
4426     av_store(PL_rsfp_filters, 0, datasv) ;
4427     if (
4428         !PL_parser->filtered
4429      && PL_parser->lex_flags & LEX_EVALBYTES
4430      && PL_bufptr < PL_bufend
4431     ) {
4432         const char *s = PL_bufptr;
4433         while (s < PL_bufend) {
4434             if (*s == '\n') {
4435                 SV *linestr = PL_parser->linestr;
4436                 char *buf = SvPVX(linestr);
4437                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4438                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4439                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4440                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4441                 STRLEN const last_uni_pos =
4442                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4443                 STRLEN const last_lop_pos =
4444                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4445                 av_push(PL_rsfp_filters, linestr);
4446                 PL_parser->linestr =
4447                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4448                 buf = SvPVX(PL_parser->linestr);
4449                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4450                 PL_parser->bufptr = buf + bufptr_pos;
4451                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4452                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4453                 PL_parser->linestart = buf + linestart_pos;
4454                 if (PL_parser->last_uni)
4455                     PL_parser->last_uni = buf + last_uni_pos;
4456                 if (PL_parser->last_lop)
4457                     PL_parser->last_lop = buf + last_lop_pos;
4458                 SvLEN_set(linestr, SvCUR(linestr));
4459                 SvCUR_set(linestr, s - SvPVX(linestr));
4460                 PL_parser->filtered = 1;
4461                 break;
4462             }
4463             s++;
4464         }
4465     }
4466     return(datasv);
4467 }
4468
4469
4470 /* Delete most recently added instance of this filter function. */
4471 void
4472 Perl_filter_del(pTHX_ filter_t funcp)
4473 {
4474     SV *datasv;
4475
4476     PERL_ARGS_ASSERT_FILTER_DEL;
4477
4478 #ifdef DEBUGGING
4479     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4480                           FPTR2DPTR(void*, funcp)));
4481 #endif
4482     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4483         return;
4484     /* if filter is on top of stack (usual case) just pop it off */
4485     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4486     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4487         sv_free(av_pop(PL_rsfp_filters));
4488
4489         return;
4490     }
4491     /* we need to search for the correct entry and clear it     */
4492     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4493 }
4494
4495
4496 /* Invoke the idxth filter function for the current rsfp.        */
4497 /* maxlen 0 = read one text line */
4498 I32
4499 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4500 {
4501     filter_t funcp;
4502     I32 ret;
4503     SV *datasv = NULL;
4504     /* This API is bad. It should have been using unsigned int for maxlen.
4505        Not sure if we want to change the API, but if not we should sanity
4506        check the value here.  */
4507     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4508
4509     PERL_ARGS_ASSERT_FILTER_READ;
4510
4511     if (!PL_parser || !PL_rsfp_filters)
4512         return -1;
4513     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4514         /* Provide a default input filter to make life easy.    */
4515         /* Note that we append to the line. This is handy.      */
4516         DEBUG_P(PerlIO_printf(Perl_debug_log,
4517                               "filter_read %d: from rsfp\n", idx));
4518         if (correct_length) {
4519             /* Want a block */
4520             int len ;
4521             const int old_len = SvCUR(buf_sv);
4522
4523             /* ensure buf_sv is large enough */
4524             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4525             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4526                                    correct_length)) <= 0) {
4527                 if (PerlIO_error(PL_rsfp))
4528                     return -1;          /* error */
4529                 else
4530                     return 0 ;          /* end of file */
4531             }
4532             SvCUR_set(buf_sv, old_len + len) ;
4533             SvPVX(buf_sv)[old_len + len] = '\0';
4534         } else {
4535             /* Want a line */
4536             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4537                 if (PerlIO_error(PL_rsfp))
4538                     return -1;          /* error */
4539                 else
4540                     return 0 ;          /* end of file */
4541             }
4542         }
4543         return SvCUR(buf_sv);
4544     }
4545     /* Skip this filter slot if filter has been deleted */
4546     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4547         DEBUG_P(PerlIO_printf(Perl_debug_log,
4548                               "filter_read %d: skipped (filter deleted)\n",
4549                               idx));
4550         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4551     }
4552     if (SvTYPE(datasv) != SVt_PVIO) {
4553         if (correct_length) {
4554             /* Want a block */
4555             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4556             if (!remainder) return 0; /* eof */
4557             if (correct_length > remainder) correct_length = remainder;
4558             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4559             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4560         } else {
4561             /* Want a line */
4562             const char *s = SvEND(datasv);
4563             const char *send = SvPVX(datasv) + SvLEN(datasv);
4564             while (s < send) {
4565                 if (*s == '\n') {
4566                     s++;
4567                     break;
4568                 }
4569                 s++;
4570             }
4571             if (s == send) return 0; /* eof */
4572             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4573             SvCUR_set(datasv, s-SvPVX(datasv));
4574         }
4575         return SvCUR(buf_sv);
4576     }
4577     /* Get function pointer hidden within datasv        */
4578     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4579     DEBUG_P(PerlIO_printf(Perl_debug_log,
4580                           "filter_read %d: via function %p (%s)\n",
4581                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4582     /* Call function. The function is expected to       */
4583     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4584     /* Return: <0:error, =0:eof, >0:not eof             */
4585     ENTER;
4586     save_scalar(PL_errgv);
4587     ret = (*funcp)(aTHX_ idx, buf_sv, correct_length);
4588     LEAVE;
4589     return ret;
4590 }
4591
4592 STATIC char *
4593 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4594 {
4595     PERL_ARGS_ASSERT_FILTER_GETS;
4596
4597 #ifdef PERL_CR_FILTER
4598     if (!PL_rsfp_filters) {
4599         filter_add(S_cr_textfilter,NULL);
4600     }
4601 #endif
4602     if (PL_rsfp_filters) {
4603         if (!append)
4604             SvCUR_set(sv, 0);   /* start with empty line        */
4605         if (FILTER_READ(0, sv, 0) > 0)
4606             return ( SvPVX(sv) ) ;
4607         else
4608             return NULL ;
4609     }
4610     else
4611         return (sv_gets(sv, PL_rsfp, append));
4612 }
4613
4614 STATIC HV *
4615 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4616 {
4617     GV *gv;
4618
4619     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4620
4621     if (memEQs(pkgname, len, "__PACKAGE__"))
4622         return PL_curstash;
4623
4624     if (len > 2
4625         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4626         && (gv = gv_fetchpvn_flags(pkgname,
4627                                    len,
4628                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4629     {
4630         return GvHV(gv);                        /* Foo:: */
4631     }
4632
4633     /* use constant CLASS => 'MyClass' */
4634     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4635     if (gv && GvCV(gv)) {
4636         SV * const sv = cv_const_sv(GvCV(gv));
4637         if (sv)
4638             return gv_stashsv(sv, 0);
4639     }
4640
4641     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4642 }
4643
4644
4645 STATIC char *
4646 S_tokenize_use(pTHX_ int is_use, char *s) {
4647     PERL_ARGS_ASSERT_TOKENIZE_USE;
4648
4649     if (PL_expect != XSTATE)
4650         /* diag_listed_as: "use" not allowed in expression */
4651         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4652                     is_use ? "use" : "no"));
4653     PL_expect = XTERM;
4654     s = skipspace(s);
4655     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4656         s = force_version(s, TRUE);
4657         if (*s == ';' || *s == '}'
4658                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4659             NEXTVAL_NEXTTOKE.opval = NULL;
4660             force_next(BAREWORD);
4661         }
4662         else if (*s == 'v') {
4663             s = force_word(s,BAREWORD,FALSE,TRUE);
4664             s = force_version(s, FALSE);
4665         }
4666     }
4667     else {
4668         s = force_word(s,BAREWORD,FALSE,TRUE);
4669         s = force_version(s, FALSE);
4670     }
4671     pl_yylval.ival = is_use;
4672     return s;
4673 }
4674 #ifdef DEBUGGING
4675     static const char* const exp_name[] =
4676         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4677           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4678           "SIGVAR", "TERMORDORDOR"
4679         };
4680 #endif
4681
4682 #define word_takes_any_delimiter(p,l) S_word_takes_any_delimiter(p,l)
4683 STATIC bool
4684 S_word_takes_any_delimiter(char *p, STRLEN len)
4685 {
4686     return (len == 1 && strchr("msyq", p[0]))
4687             || (len == 2
4688                 && ((p[0] == 't' && p[1] == 'r')
4689                     || (p[0] == 'q' && strchr("qwxr", p[1]))));
4690 }
4691
4692 static void
4693 S_check_scalar_slice(pTHX_ char *s)
4694 {
4695     s++;
4696     while (SPACE_OR_TAB(*s)) s++;
4697     if (*s == 'q' && s[1] == 'w' && !isWORDCHAR_lazy_if_safe(s+2,
4698                                                              PL_bufend,
4699                                                              UTF))
4700     {
4701         return;
4702     }
4703     while (    isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF)
4704            || (*s && strchr(" \t$#+-'\"", *s)))
4705     {
4706         s += UTF ? UTF8SKIP(s) : 1;
4707     }
4708     if (*s == '}' || *s == ']')
4709         pl_yylval.ival = OPpSLICEWARNING;
4710 }
4711
4712 #define lex_token_boundary() S_lex_token_boundary(aTHX)
4713 static void
4714 S_lex_token_boundary(pTHX)
4715 {
4716     PL_oldoldbufptr = PL_oldbufptr;
4717     PL_oldbufptr = PL_bufptr;
4718 }
4719
4720 #define vcs_conflict_marker(s) S_vcs_conflict_marker(aTHX_ s)
4721 static char *
4722 S_vcs_conflict_marker(pTHX_ char *s)
4723 {
4724     lex_token_boundary();
4725     PL_bufptr = s;
4726     yyerror("Version control conflict marker");
4727     while (s < PL_bufend && *s != '\n')
4728         s++;
4729     return s;
4730 }
4731
4732 /*
4733   yylex
4734
4735   Works out what to call the token just pulled out of the input
4736   stream.  The yacc parser takes care of taking the ops we return and
4737   stitching them into a tree.
4738
4739   Returns:
4740     The type of the next token
4741
4742   Structure:
4743       Check if we have already built the token; if so, use it.
4744       Switch based on the current state:
4745           - if we have a case modifier in a string, deal with that
4746           - handle other cases of interpolation inside a string
4747           - scan the next line if we are inside a format
4748       In the normal state, switch on the next character:
4749           - default:
4750             if alphabetic, go to key lookup
4751             unrecognized character - croak
4752           - 0/4/26: handle end-of-line or EOF
4753           - cases for whitespace
4754           - \n and #: handle comments and line numbers
4755           - various operators, brackets and sigils
4756           - numbers
4757           - quotes
4758           - 'v': vstrings (or go to key lookup)
4759           - 'x' repetition operator (or go to key lookup)
4760           - other ASCII alphanumerics (key lookup begins here):
4761               word before => ?
4762               keyword plugin
4763               scan built-in keyword (but do nothing with it yet)
4764               check for statement label
4765               check for lexical subs
4766                   goto just_a_word if there is one
4767               see whether built-in keyword is overridden
4768               switch on keyword number:
4769                   - default: just_a_word:
4770                       not a built-in keyword; handle bareword lookup
4771                       disambiguate between method and sub call
4772                       fall back to bareword
4773                   - cases for built-in keywords
4774 */
4775
4776
4777 int
4778 Perl_yylex(pTHX)
4779 {
4780     dVAR;
4781     char *s = PL_bufptr;
4782     char *d;
4783     STRLEN len;
4784     bool bof = FALSE;
4785     const bool saw_infix_sigil = cBOOL(PL_parser->saw_infix_sigil);
4786     U8 formbrack = 0;
4787     U32 fake_eof = 0;
4788
4789     /* orig_keyword, gvp, and gv are initialized here because
4790      * jump to the label just_a_word_zero can bypass their
4791      * initialization later. */
4792     I32 orig_keyword = 0;
4793     GV *gv = NULL;
4794     GV **gvp = NULL;
4795
4796     if (UNLIKELY(PL_parser->recheck_utf8_validity)) {
4797         const U8* first_bad_char_loc;
4798         if (UTF && UNLIKELY(! is_utf8_string_loc((U8 *) PL_bufptr,
4799                                                         PL_bufend - PL_bufptr,
4800                                                         &first_bad_char_loc)))
4801         {
4802             _force_out_malformed_utf8_message(first_bad_char_loc,
4803                                               (U8 *) PL_bufend,
4804                                               0,
4805                                               1 /* 1 means die */ );
4806             NOT_REACHED; /* NOTREACHED */
4807         }
4808         PL_parser->recheck_utf8_validity = FALSE;
4809     }
4810     DEBUG_T( {
4811         SV* tmp = newSVpvs("");
4812         PerlIO_printf(Perl_debug_log, "### %" IVdf ":LEX_%s/X%s %s\n",
4813             (IV)CopLINE(PL_curcop),
4814             lex_state_names[PL_lex_state],
4815             exp_name[PL_expect],
4816             pv_display(tmp, s, strlen(s), 0, 60));
4817         SvREFCNT_dec(tmp);
4818     } );
4819
4820     /* when we've already built the next token, just pull it out of the queue */
4821     if (PL_nexttoke) {
4822         PL_nexttoke--;
4823         pl_yylval = PL_nextval[PL_nexttoke];
4824         {
4825             I32 next_type;
4826             next_type = PL_nexttype[PL_nexttoke];
4827             if (next_type & (7<<24)) {
4828                 if (next_type & (1<<24)) {
4829                     if (PL_lex_brackets > 100)
4830                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
4831                     PL_lex_brackstack[PL_lex_brackets++] =
4832                         (char) ((next_type >> 16) & 0xff);
4833                 }
4834                 if (next_type & (2<<24))
4835                     PL_lex_allbrackets++;
4836                 if (next_type & (4<<24))
4837                     PL_lex_allbrackets--;
4838                 next_type &= 0xffff;
4839             }
4840             return REPORT(next_type == 'p' ? pending_ident() : next_type);
4841         }
4842     }
4843
4844     switch (PL_lex_state) {
4845     case LEX_NORMAL:
4846     case LEX_INTERPNORMAL:
4847         break;
4848
4849     /* interpolated case modifiers like \L \U, including \Q and \E.
4850        when we get here, PL_bufptr is at the \
4851     */
4852     case LEX_INTERPCASEMOD:
4853 #ifdef DEBUGGING
4854         if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
4855             Perl_croak(aTHX_
4856                        "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
4857                        PL_bufptr, PL_bufend, *PL_bufptr);
4858 #endif
4859         /* handle \E or end of string */
4860         if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
4861             /* if at a \E */
4862             if (PL_lex_casemods) {
4863                 const char oldmod = PL_lex_casestack[--PL_lex_casemods];
4864                 PL_lex_casestack[PL_lex_casemods] = '\0';
4865
4866                 if (PL_bufptr != PL_bufend
4867                     && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
4868                         || oldmod == 'F')) {
4869                     PL_bufptr += 2;
4870                     PL_lex_state = LEX_INTERPCONCAT;
4871                 }
4872                 PL_lex_allbrackets--;
4873                 return REPORT(')');
4874             }
4875             else if ( PL_bufptr != PL_bufend && PL_bufptr[1] == 'E' ) {
4876                /* Got an unpaired \E */
4877                Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
4878                         "Useless use of \\E");
4879             }
4880             if (PL_bufptr != PL_bufend)
4881                 PL_bufptr += 2;
4882             PL_lex_state = LEX_INTERPCONCAT;
4883             return yylex();
4884         }
4885         else {
4886             DEBUG_T({ PerlIO_printf(Perl_debug_log,
4887               "### Saw case modifier\n"); });
4888             s = PL_bufptr + 1;
4889             if (s[1] == '\\' && s[2] == 'E') {
4890                 PL_bufptr = s + 3;
4891                 PL_lex_state = LEX_INTERPCONCAT;
4892                 return yylex();
4893             }
4894             else {
4895                 I32 tmp;
4896                 if (   memBEGINs(s, (STRLEN) (PL_bufend - s), "L\\u")
4897                     || memBEGINs(s, (STRLEN) (PL_bufend - s), "U\\l"))
4898                 {
4899                     tmp = *s, *s = s[2], s[2] = (char)tmp;      /* misordered... */
4900                 }
4901                 if ((*s == 'L' || *s == 'U' || *s == 'F')
4902                     && (strpbrk(PL_lex_casestack, "LUF")))
4903                 {
4904                     PL_lex_casestack[--PL_lex_casemods] = '\0';
4905                     PL_lex_allbrackets--;
4906                     return REPORT(')');
4907                 }
4908                 if (PL_lex_casemods > 10)
4909                     Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
4910                 PL_lex_casestack[PL_lex_casemods++] = *s;
4911                 PL_lex_casestack[PL_lex_casemods] = '\0';
4912                 PL_lex_state = LEX_INTERPCONCAT;
4913                 NEXTVAL_NEXTTOKE.ival = 0;
4914                 force_next((2<<24)|'(');
4915                 if (*s == 'l')
4916                     NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
4917                 else if (*s == 'u')
4918                     NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
4919                 else if (*s == 'L')
4920                     NEXTVAL_NEXTTOKE.ival = OP_LC;
4921                 else if (*s == 'U')
4922                     NEXTVAL_NEXTTOKE.ival = OP_UC;
4923                 else if (*s == 'Q')
4924                     NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
4925                 else if (*s == 'F')
4926                     NEXTVAL_NEXTTOKE.ival = OP_FC;
4927                 else
4928                     Perl_croak(aTHX_ "panic: yylex, *s=%u", *s);
4929                 PL_bufptr = s + 1;
4930             }
4931             force_next(FUNC);
4932             if (PL_lex_starts) {
4933                 s = PL_bufptr;
4934                 PL_lex_starts = 0;
4935                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4936                 if (PL_lex_casemods == 1 && PL_lex_inpat)
4937                     TOKEN(',');
4938                 else
4939                     AopNOASSIGN(OP_CONCAT);
4940             }
4941             else
4942                 return yylex();
4943         }
4944
4945     case LEX_INTERPPUSH:
4946         return REPORT(sublex_push());
4947
4948     case LEX_INTERPSTART:
4949         if (PL_bufptr == PL_bufend)
4950             return REPORT(sublex_done());
4951         DEBUG_T({ if(*PL_bufptr != '(') PerlIO_printf(Perl_debug_log,
4952               "### Interpolated variable\n"); });
4953         PL_expect = XTERM;
4954         /* for /@a/, we leave the joining for the regex engine to do
4955          * (unless we're within \Q etc) */
4956         PL_lex_dojoin = (*PL_bufptr == '@'
4957                             && (!PL_lex_inpat || PL_lex_casemods));
4958         PL_lex_state = LEX_INTERPNORMAL;
4959         if (PL_lex_dojoin) {
4960             NEXTVAL_NEXTTOKE.ival = 0;
4961             force_next(',');
4962             force_ident("\"", '$');
4963             NEXTVAL_NEXTTOKE.ival = 0;
4964             force_next('$');
4965             NEXTVAL_NEXTTOKE.ival = 0;
4966             force_next((2<<24)|'(');
4967             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
4968             force_next(FUNC);
4969         }
4970         /* Convert (?{...}) and friends to 'do {...}' */
4971         if (PL_lex_inpat && *PL_bufptr == '(') {
4972             PL_parser->lex_shared->re_eval_start = PL_bufptr;
4973             PL_bufptr += 2;
4974             if (*PL_bufptr != '{')
4975                 PL_bufptr++;
4976             PL_expect = XTERMBLOCK;
4977             force_next(DO);
4978         }
4979
4980         if (PL_lex_starts++) {
4981             s = PL_bufptr;
4982             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
4983             if (!PL_lex_casemods && PL_lex_inpat)
4984                 TOKEN(',');
4985             else
4986                 AopNOASSIGN(OP_CONCAT);
4987         }
4988         return yylex();
4989
4990     case LEX_INTERPENDMAYBE:
4991         if (intuit_more(PL_bufptr, PL_bufend)) {
4992             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
4993             break;
4994         }
4995         /* FALLTHROUGH */
4996
4997     case LEX_INTERPEND:
4998         if (PL_lex_dojoin) {
4999             const U8 dojoin_was = PL_lex_dojoin;
5000             PL_lex_dojoin = FALSE;
5001             PL_lex_state = LEX_INTERPCONCAT;
5002             PL_lex_allbrackets--;
5003             return REPORT(dojoin_was == 1 ? (int)')' : (int)POSTJOIN);
5004         }
5005         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
5006             && SvEVALED(PL_lex_repl))
5007         {
5008             if (PL_bufptr != PL_bufend)
5009                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
5010             PL_lex_repl = NULL;
5011         }
5012         /* Paranoia.  re_eval_start is adjusted when S_scan_heredoc sets
5013            re_eval_str.  If the here-doc body’s length equals the previous
5014            value of re_eval_start, re_eval_start will now be null.  So
5015            check re_eval_str as well. */
5016         if (PL_parser->lex_shared->re_eval_start
5017          || PL_parser->lex_shared->re_eval_str) {
5018             SV *sv;
5019             if (*PL_bufptr != ')')
5020                 Perl_croak(aTHX_ "Sequence (?{...}) not terminated with ')'");
5021             PL_bufptr++;
5022             /* having compiled a (?{..}) expression, return the original
5023              * text too, as a const */
5024             if (PL_parser->lex_shared->re_eval_str) {
5025                 sv = PL_parser->lex_shared->re_eval_str;
5026                 PL_parser->lex_shared->re_eval_str = NULL;
5027                 SvCUR_set(sv,
5028                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
5029                 SvPV_shrink_to_cur(sv);
5030             }
5031             else sv = newSVpvn(PL_parser->lex_shared->re_eval_start,
5032                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
5033             NEXTVAL_NEXTTOKE.opval =
5034                     newSVOP(OP_CONST, 0,
5035                                  sv);
5036             force_next(THING);
5037             PL_parser->lex_shared->re_eval_start = NULL;
5038             PL_expect = XTERM;
5039             return REPORT(',');
5040         }
5041
5042         /* FALLTHROUGH */
5043     case LEX_INTERPCONCAT:
5044 #ifdef DEBUGGING
5045         if (PL_lex_brackets)
5046             Perl_croak(aTHX_ "panic: INTERPCONCAT, lex_brackets=%ld",
5047                        (long) PL_lex_brackets);
5048 #endif
5049         if (PL_bufptr == PL_bufend)
5050             return REPORT(sublex_done());
5051
5052         /* m'foo' still needs to be parsed for possible (?{...}) */
5053         if (SvIVX(PL_linestr) == '\'' && !PL_lex_inpat) {
5054             SV *sv = newSVsv(PL_linestr);
5055             sv = tokeq(sv);
5056             pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
5057             s = PL_bufend;
5058         }
5059         else {
5060             int save_error_count = PL_error_count;
5061
5062             s = scan_const(PL_bufptr);
5063
5064             /* Set flag if this was a pattern and there were errors.  op.c will
5065              * refuse to compile a pattern with this flag set.  Otherwise, we
5066              * could get segfaults, etc. */
5067             if (PL_lex_inpat && PL_error_count > save_error_count) {
5068                 ((PMOP*)PL_lex_inpat)->op_pmflags |= PMf_HAS_ERROR;
5069             }
5070             if (*s == '\\')
5071                 PL_lex_state = LEX_INTERPCASEMOD;
5072             else
5073                 PL_lex_state = LEX_INTERPSTART;
5074         }
5075
5076         if (s != PL_bufptr) {
5077             NEXTVAL_NEXTTOKE = pl_yylval;
5078             PL_expect = XTERM;
5079             force_next(THING);
5080             if (PL_lex_starts++) {
5081                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
5082                 if (!PL_lex_casemods && PL_lex_inpat)
5083                     TOKEN(',');
5084                 else
5085                     AopNOASSIGN(OP_CONCAT);
5086             }
5087             else {
5088                 PL_bufptr = s;
5089                 return yylex();
5090             }
5091         }
5092
5093         return yylex();
5094     case LEX_FORMLINE:
5095         assert(PL_lex_formbrack);
5096         s = scan_formline(PL_bufptr);
5097         if (!PL_lex_formbrack)
5098         {
5099             formbrack = 1;
5100             goto rightbracket;
5101         }
5102         PL_bufptr = s;
5103         return yylex();
5104     }
5105
5106     /* We really do *not* want PL_linestr ever becoming a COW. */
5107     assert (!SvIsCOW(PL_linestr));
5108     s = PL_bufptr;
5109     PL_oldoldbufptr = PL_oldbufptr;
5110     PL_oldbufptr = s;
5111     PL_parser->saw_infix_sigil = 0;
5112
5113     if (PL_in_my == KEY_sigvar) {
5114         /* we expect the sigil and optional var name part of a
5115          * signature element here. Since a '$' is not necessarily
5116          * followed by a var name, handle it specially here; the general
5117          * yylex code would otherwise try to interpret whatever follows
5118          * as a var; e.g. ($, ...) would be seen as the var '$,'
5119          */
5120
5121         U8 sigil;
5122
5123         s = skipspace(s);
5124         sigil = *s++;
5125         PL_bufptr = s; /* for error reporting */
5126         switch (sigil) {
5127         case '$':
5128         case '@':
5129         case '%':
5130             /* spot stuff that looks like an prototype */
5131             if (strchr("$:@%&*;\\[]", *s)) {
5132                 yyerror("Illegal character following sigil in a subroutine signature");
5133                 break;
5134             }
5135             /* '$#' is banned, while '$ # comment' isn't */
5136             if (*s == '#') {
5137                 yyerror("'#' not allowed immediately following a sigil in a subroutine signature");
5138                 break;
5139             }
5140             s = skipspace(s);
5141             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5142                 char *dest = PL_tokenbuf + 1;
5143                 /* read var name, including sigil, into PL_tokenbuf */
5144                 PL_tokenbuf[0] = sigil;
5145                 parse_ident(&s, &dest, dest + sizeof(PL_tokenbuf) - 1,
5146                     0, cBOOL(UTF), FALSE);
5147                 *dest = '\0';
5148                 assert(PL_tokenbuf[1]); /* we have a variable name */
5149             }
5150             else {
5151                 *PL_tokenbuf = 0;
5152                 PL_in_my = 0;
5153             }
5154
5155             s = skipspace(s);
5156             /* parse the = for the default ourselves to avoid '+=' etc being accepted here
5157              * as the ASSIGNOP, and exclude other tokens that start with =
5158              */
5159             if (*s == '=' && (!s[1] || strchr("=~>", s[1]) == 0)) {
5160                 /* save now to report with the same context as we did when
5161                  * all ASSIGNOPS were accepted */
5162                 PL_oldbufptr = s;
5163
5164                 ++s;
5165                 NEXTVAL_NEXTTOKE.ival = 0;
5166                 force_next(ASSIGNOP);
5167                 PL_expect = XTERM;
5168             }
5169             else if (*s == ',' || *s == ')') {
5170                 PL_expect = XOPERATOR;
5171             }
5172             else {
5173                 /* make sure the context shows the unexpected character and
5174                  * hopefully a bit more */
5175                 if (*s) ++s;
5176                 while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
5177                     s++;
5178                 PL_bufptr = s; /* for error reporting */
5179                 yyerror("Illegal operator following parameter in a subroutine signature");
5180                 PL_in_my = 0;
5181             }
5182             if (*PL_tokenbuf) {
5183                 NEXTVAL_NEXTTOKE.ival = sigil;
5184                 force_next('p'); /* force a signature pending identifier */
5185             }
5186             break;
5187
5188         case ')':
5189             PL_expect = XBLOCK;
5190             break;
5191         case ',': /* handle ($a,,$b) */
5192             break;
5193
5194         default:
5195             PL_in_my = 0;
5196             yyerror("A signature parameter must start with '$', '@' or '%'");
5197             /* very crude error recovery: skip to likely next signature
5198              * element */
5199             while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
5200                 s++;
5201             break;
5202         }
5203         TOKEN(sigil);
5204     }
5205
5206   retry:
5207     switch (*s) {
5208     default:
5209         if (UTF) {
5210             if (isIDFIRST_utf8_safe(s, PL_bufend)) {
5211                 goto keylookup;
5212             }
5213         }
5214         else if (isALNUMC(*s)) {
5215             goto keylookup;
5216         }
5217     {
5218         SV *dsv = newSVpvs_flags("", SVs_TEMP);
5219         const char *c;
5220         if (UTF) {
5221             STRLEN skiplen = UTF8SKIP(s);
5222             STRLEN stravail = PL_bufend - s;
5223             c = sv_uni_display(dsv, newSVpvn_flags(s,
5224                                                    skiplen > stravail ? stravail : skiplen,
5225                                                    SVs_TEMP | SVf_UTF8),
5226                                10, UNI_DISPLAY_ISPRINT);
5227         }
5228         else {
5229             c = Perl_form(aTHX_ "\\x%02X", (unsigned char)*s);
5230         }
5231
5232         if (s >= PL_linestart) {
5233             d = PL_linestart;
5234         }
5235         else {
5236             /* somehow (probably due to a parse failure), PL_linestart has advanced
5237              * pass PL_bufptr, get a reasonable beginning of line
5238              */
5239             d = s;
5240             while (d > SvPVX(PL_linestr) && d[-1] && d[-1] != '\n')
5241                 --d;
5242         }
5243         len = UTF ? Perl_utf8_length(aTHX_ (U8 *) d, (U8 *) s) : (STRLEN) (s - d);
5244         if (len > UNRECOGNIZED_PRECEDE_COUNT) {
5245             d = UTF ? (char *) utf8_hop_back((U8 *) s, -UNRECOGNIZED_PRECEDE_COUNT, (U8 *)d) : s - UNRECOGNIZED_PRECEDE_COUNT;
5246         }
5247
5248         Perl_croak(aTHX_  "Unrecognized character %s; marked by <-- HERE after %" UTF8f "<-- HERE near column %d", c,
5249                           UTF8fARG(UTF, (s - d), d),
5250                          (int) len + 1);
5251     }
5252     case 4:
5253     case 26:
5254         goto fake_eof;                  /* emulate EOF on ^D or ^Z */
5255     case 0:
5256         if ((!PL_rsfp || PL_lex_inwhat)
5257          && (!PL_parser->filtered || s+1 < PL_bufend)) {
5258             PL_last_uni = 0;
5259             PL_last_lop = 0;
5260             if (PL_lex_brackets
5261                 && PL_lex_brackstack[PL_lex_brackets-1] != XFAKEEOF)
5262             {
5263                 yyerror((const char *)
5264                         (PL_lex_formbrack
5265                          ? "Format not terminated"
5266                          : "Missing right curly or square bracket"));
5267             }
5268             DEBUG_T( { PerlIO_printf(Perl_debug_log,
5269                         "### Tokener got EOF\n");
5270             } );
5271             TOKEN(0);
5272         }
5273         if (s++ < PL_bufend)
5274             goto retry;                 /* ignore stray nulls */
5275         PL_last_uni = 0;
5276         PL_last_lop = 0;
5277         if (!PL_in_eval && !PL_preambled) {
5278             PL_preambled = TRUE;
5279             if (PL_perldb) {
5280                 /* Generate a string of Perl code to load the debugger.
5281                  * If PERL5DB is set, it will return the contents of that,
5282                  * otherwise a compile-time require of perl5db.pl.  */
5283
5284                 const char * const pdb = PerlEnv_getenv("PERL5DB");
5285
5286                 if (pdb) {
5287                     sv_setpv(PL_linestr, pdb);
5288                     sv_catpvs(PL_linestr,";");
5289                 } else {
5290                     SETERRNO(0,SS_NORMAL);
5291                     sv_setpvs(PL_linestr, "BEGIN { require 'perl5db.pl' };");
5292                 }
5293                 PL_parser->preambling = CopLINE(PL_curcop);
5294             } else
5295                 SvPVCLEAR(PL_linestr);
5296             if (PL_preambleav) {
5297                 SV **svp = AvARRAY(PL_preambleav);
5298                 SV **const end = svp + AvFILLp(PL_preambleav);
5299                 while(svp <= end) {
5300                     sv_catsv(PL_linestr, *svp);
5301                     ++svp;
5302                     sv_catpvs(PL_linestr, ";");
5303                 }
5304                 sv_free(MUTABLE_SV(PL_preambleav));
5305                 PL_preambleav = NULL;
5306             }
5307             if (PL_minus_E)
5308                 sv_catpvs(PL_linestr,
5309                           "use feature ':5." STRINGIFY(PERL_VERSION) "';");
5310             if (PL_minus_n || PL_minus_p) {
5311                 sv_catpvs(PL_linestr, "LINE: while (<>) {"/*}*/);
5312                 if (PL_minus_l)
5313                     sv_catpvs(PL_linestr,"chomp;");
5314                 if (PL_minus_a) {
5315                     if (PL_minus_F) {
5316                         if (   (   *PL_splitstr == '/'
5317                                 || *PL_splitstr == '\''
5318                                 || *PL_splitstr == '"')
5319                             && strchr(PL_splitstr + 1, *PL_splitstr))
5320                         {
5321                             /* strchr is ok, because -F pattern can't contain
5322                              * embeddded NULs */
5323                             Perl_sv_catpvf(aTHX_ PL_linestr, "our @F=split(%s);", PL_splitstr);
5324                         }
5325                         else {
5326                             /* "q\0${splitstr}\0" is legal perl. Yes, even NUL
5327                                bytes can be used as quoting characters.  :-) */
5328                             const char *splits = PL_splitstr;
5329                             sv_catpvs(PL_linestr, "our @F=split(q\0");
5330                             do {
5331                                 /* Need to \ \s  */
5332                                 if (*splits == '\\')
5333                                     sv_catpvn(PL_linestr, splits, 1);
5334                                 sv_catpvn(PL_linestr, splits, 1);
5335                             } while (*splits++);
5336                             /* This loop will embed the trailing NUL of
5337                                PL_linestr as the last thing it does before
5338                                terminating.  */
5339                             sv_catpvs(PL_linestr, ");");
5340                         }
5341                     }
5342                     else
5343                         sv_catpvs(PL_linestr,"our @F=split(' ');");
5344                 }
5345             }
5346             sv_catpvs(PL_linestr, "\n");
5347             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5348             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5349             PL_last_lop = PL_last_uni = NULL;
5350             if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
5351                 update_debugger_info(PL_linestr, NULL, 0);
5352             goto retry;
5353         }
5354         do {
5355             fake_eof = 0;
5356             bof = cBOOL(PL_rsfp);
5357             if (0) {
5358               fake_eof:
5359                 fake_eof = LEX_FAKE_EOF;
5360             }
5361             PL_bufptr = PL_bufend;
5362             COPLINE_INC_WITH_HERELINES;
5363             if (!lex_next_chunk(fake_eof)) {
5364                 CopLINE_dec(PL_curcop);
5365                 s = PL_bufptr;
5366                 TOKEN(';');     /* not infinite loop because rsfp is NULL now */
5367             }
5368             CopLINE_dec(PL_curcop);
5369             s = PL_bufptr;
5370             /* If it looks like the start of a BOM or raw UTF-16,
5371              * check if it in fact is. */
5372             if (bof && PL_rsfp
5373                 && (   *s == 0
5374                     || *(U8*)s == BOM_UTF8_FIRST_BYTE
5375                     || *(U8*)s >= 0xFE
5376                     || s[1] == 0))
5377             {
5378                 Off_t offset = (IV)PerlIO_tell(PL_rsfp);
5379                 bof = (offset == (Off_t)SvCUR(PL_linestr));
5380 #if defined(PERLIO_USING_CRLF) && defined(PERL_TEXTMODE_SCRIPTS)
5381                 /* offset may include swallowed CR */
5382                 if (!bof)
5383                     bof = (offset == (Off_t)SvCUR(PL_linestr)+1);
5384 #endif
5385                 if (bof) {
5386                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5387                     s = swallow_bom((U8*)s);
5388                 }
5389             }
5390             if (PL_parser->in_pod) {
5391                 /* Incest with pod. */
5392                 if (    memBEGINPs(s, (STRLEN) (PL_bufend - s), "=cut")
5393                     && !isALPHA(s[4]))
5394                 {
5395                     SvPVCLEAR(PL_linestr);
5396                     PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5397                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5398                     PL_last_lop = PL_last_uni = NULL;
5399                     PL_parser->in_pod = 0;
5400                 }
5401             }
5402             if (PL_rsfp || PL_parser->filtered)
5403                 incline(s, PL_bufend);
5404         } while (PL_parser->in_pod);
5405         PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = PL_linestart = s;
5406         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5407         PL_last_lop = PL_last_uni = NULL;
5408         if (CopLINE(PL_curcop) == 1) {
5409             while (s < PL_bufend && isSPACE(*s))
5410                 s++;
5411             if (*s == ':' && s[1] != ':') /* for csh execing sh scripts */
5412                 s++;
5413             d = NULL;
5414             if (!PL_in_eval) {
5415                 if (*s == '#' && *(s+1) == '!')
5416                     d = s + 2;
5417 #ifdef ALTERNATE_SHEBANG
5418                 else {
5419                     static char const as[] = ALTERNATE_SHEBANG;
5420                     if (*s == as[0] && strnEQ(s, as, sizeof(as) - 1))
5421                         d = s + (sizeof(as) - 1);
5422                 }
5423 #endif /* ALTERNATE_SHEBANG */
5424             }
5425             if (d) {
5426                 char *ipath;
5427                 char *ipathend;
5428
5429                 while (isSPACE(*d))
5430                     d++;
5431                 ipath = d;
5432                 while (*d && !isSPACE(*d))
5433                     d++;
5434                 ipathend = d;
5435
5436 #ifdef ARG_ZERO_IS_SCRIPT
5437                 if (ipathend > ipath) {
5438                     /*
5439                      * HP-UX (at least) sets argv[0] to the script name,
5440                      * which makes $^X incorrect.  And Digital UNIX and Linux,
5441                      * at least, set argv[0] to the basename of the Perl
5442                      * interpreter. So, having found "#!", we'll set it right.
5443                      */
5444                     SV* copfilesv = CopFILESV(PL_curcop);
5445                     if (copfilesv) {
5446                         SV * const x =
5447                             GvSV(gv_fetchpvs("\030", GV_ADD|GV_NOTQUAL,
5448                                              SVt_PV)); /* $^X */
5449                         assert(SvPOK(x) || SvGMAGICAL(x));
5450                         if (sv_eq(x, copfilesv)) {
5451                             sv_setpvn(x, ipath, ipathend - ipath);
5452                             SvSETMAGIC(x);
5453                         }
5454                         else {
5455                             STRLEN blen;
5456                             STRLEN llen;
5457                             const char *bstart = SvPV_const(copfilesv, blen);
5458                             const char * const lstart = SvPV_const(x, llen);
5459                             if (llen < blen) {
5460                                 bstart += blen - llen;
5461                                 if (strnEQ(bstart, lstart, llen) &&     bstart[-1] == '/') {
5462                                     sv_setpvn(x, ipath, ipathend - ipath);
5463                                     SvSETMAGIC(x);
5464                                 }
5465                             }
5466                         }
5467                     }
5468                     else {
5469                         /* Anything to do if no copfilesv? */
5470                     }
5471                     TAINT_NOT;  /* $^X is always tainted, but that's OK */
5472                 }
5473 #endif /* ARG_ZERO_IS_SCRIPT */
5474
5475                 /*
5476                  * Look for options.
5477                  */
5478                 d = instr(s,"perl -");
5479                 if (!d) {
5480                     d = instr(s,"perl");
5481 #if defined(DOSISH)
5482                     /* avoid getting into infinite loops when shebang
5483                      * line contains "Perl" rather than "perl" */
5484                     if (!d) {
5485                         for (d = ipathend-4; d >= ipath; --d) {
5486                             if (isALPHA_FOLD_EQ(*d, 'p')
5487                                 && !ibcmp(d, "perl", 4))
5488                             {
5489                                 break;
5490                             }
5491                         }
5492                         if (d < ipath)
5493                             d = NULL;
5494                     }
5495 #endif
5496                 }
5497 #ifdef ALTERNATE_SHEBANG
5498                 /*
5499                  * If the ALTERNATE_SHEBANG on this system starts with a
5500                  * character that can be part of a Perl expression, then if
5501                  * we see it but not "perl", we're probably looking at the
5502                  * start of Perl code, not a request to hand off to some
5503                  * other interpreter.  Similarly, if "perl" is there, but
5504                  * not in the first 'word' of the line, we assume the line
5505                  * contains the start of the Perl program.
5506                  */
5507                 if (d && *s != '#') {
5508                     const char *c = ipath;
5509                     while (*c && !strchr("; \t\r\n\f\v#", *c))
5510                         c++;
5511                     if (c < d)
5512                         d = NULL;       /* "perl" not in first word; ignore */
5513                     else
5514                         *s = '#';       /* Don't try to parse shebang line */
5515                 }
5516 #endif /* ALTERNATE_SHEBANG */
5517                 if (!d
5518                     && *s == '#'
5519                     && ipathend > ipath
5520                     && !PL_minus_c
5521                     && !instr(s,"indir")
5522                     && instr(PL_origargv[0],"perl"))
5523                 {
5524                     dVAR;
5525                     char **newargv;
5526
5527                     *ipathend = '\0';
5528                     s = ipathend + 1;
5529                     while (s < PL_bufend && isSPACE(*s))
5530                         s++;
5531                     if (s < PL_bufend) {
5532                         Newx(newargv,PL_origargc+3,char*);
5533                         newargv[1] = s;
5534                         while (s < PL_bufend && !isSPACE(*s))
5535                             s++;
5536                         *s = '\0';
5537                         Copy(PL_origargv+1, newargv+2, PL_origargc+1, char*);
5538                     }
5539                     else
5540                         newargv = PL_origargv;
5541                     newargv[0] = ipath;
5542                     PERL_FPU_PRE_EXEC
5543                     PerlProc_execv(ipath, EXEC_ARGV_CAST(newargv));
5544                     PERL_FPU_POST_EXEC
5545                     Perl_croak(aTHX_ "Can't exec %s", ipath);
5546                 }
5547                 if (d) {
5548                     while (*d && !isSPACE(*d))
5549                         d++;
5550                     while (SPACE_OR_TAB(*d))
5551                         d++;
5552
5553                     if (*d++ == '-') {
5554                         const bool switches_done = PL_doswitches;
5555                         const U32 oldpdb = PL_perldb;
5556                         const bool oldn = PL_minus_n;
5557                         const bool oldp = PL_minus_p;
5558                         const char *d1 = d;
5559
5560                         do {
5561                             bool baduni = FALSE;
5562                             if (*d1 == 'C') {
5563                                 const char *d2 = d1 + 1;
5564                                 if (parse_unicode_opts((const char **)&d2)
5565                                     != PL_unicode)
5566                                     baduni = TRUE;
5567                             }
5568                             if (baduni || isALPHA_FOLD_EQ(*d1, 'M')) {
5569                                 const char * const m = d1;
5570                                 while (*d1 && !isSPACE(*d1))
5571                                     d1++;
5572                                 Perl_croak(aTHX_ "Too late for \"-%.*s\" option",
5573                                       (int)(d1 - m), m);
5574                             }
5575                             d1 = moreswitches(d1);
5576                         } while (d1);
5577                         if (PL_doswitches && !switches_done) {
5578                             int argc = PL_origargc;
5579                             char **argv = PL_origargv;
5580                             do {
5581                                 argc--,argv++;
5582                             } while (argc && argv[0][0] == '-' && argv[0][1]);
5583                             init_argv_symbols(argc,argv);
5584                         }
5585                         if (   (PERLDB_LINE_OR_SAVESRC && !oldpdb)
5586                             || ((PL_minus_n || PL_minus_p) && !(oldn || oldp)))
5587                               /* if we have already added "LINE: while (<>) {",
5588                                  we must not do it again */
5589                         {
5590                             SvPVCLEAR(PL_linestr);
5591                             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
5592                             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
5593                             PL_last_lop = PL_last_uni = NULL;
5594                             PL_preambled = FALSE;
5595                             if (PERLDB_LINE_OR_SAVESRC)
5596                                 (void)gv_fetchfile(PL_origfilename);
5597                             goto retry;
5598                         }
5599                     }
5600                 }
5601             }
5602         }
5603         if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
5604             PL_lex_state = LEX_FORMLINE;
5605             force_next(FORMRBRACK);
5606             TOKEN(';');
5607         }
5608         goto retry;
5609     case '\r':
5610 #ifdef PERL_STRICT_CR
5611         Perl_warn(aTHX_ "Illegal character \\%03o (carriage return)", '\r');
5612         Perl_croak(aTHX_
5613       "\t(Maybe you didn't strip carriage returns after a network transfer?)\n");
5614 #endif
5615     case ' ': case '\t': case '\f': case '\v':
5616         s++;
5617         goto retry;
5618     case '#':
5619     case '\n':
5620         if (PL_lex_state != LEX_NORMAL
5621             || (PL_in_eval && !PL_rsfp && !PL_parser->filtered))
5622         {
5623             const bool in_comment = *s == '#';
5624             if (*s == '#' && s == PL_linestart && PL_in_eval
5625              && !PL_rsfp && !PL_parser->filtered) {
5626                 /* handle eval qq[#line 1 "foo"\n ...] */
5627                 CopLINE_dec(PL_curcop);
5628                 incline(s, PL_bufend);
5629             }
5630             d = s;
5631             while (d < PL_bufend && *d != '\n')
5632                 d++;
5633             if (d < PL_bufend)
5634                 d++;
5635             s = d;
5636             if (in_comment && d == PL_bufend
5637                 && PL_lex_state == LEX_INTERPNORMAL
5638                 && PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
5639                 && SvEVALED(PL_lex_repl) && d[-1] == '}') s--;
5640             else
5641                 incline(s, PL_bufend);
5642             if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
5643                 PL_lex_state = LEX_FORMLINE;
5644                 force_next(FORMRBRACK);
5645                 TOKEN(';');
5646             }
5647         }
5648         else {
5649             while (s < PL_bufend && *s != '\n')
5650                 s++;
5651             if (s < PL_bufend)
5652                 {
5653                     s++;
5654                     if (s < PL_bufend)
5655                         incline(s, PL_bufend);
5656                 }
5657         }
5658         goto retry;
5659     case '-':
5660         if (s[1] && isALPHA(s[1]) && !isWORDCHAR(s[2])) {
5661             I32 ftst = 0;
5662             char tmp;
5663
5664             s++;
5665             PL_bufptr = s;
5666             tmp = *s++;
5667
5668             while (s < PL_bufend && SPACE_OR_TAB(*s))
5669                 s++;
5670
5671             if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=>")) {
5672                 s = force_word(PL_bufptr,BAREWORD,FALSE,FALSE);
5673                 DEBUG_T( { printbuf("### Saw unary minus before =>, forcing word %s\n", s); } );
5674                 OPERATOR('-');          /* unary minus */
5675             }
5676             switch (tmp) {
5677             case 'r': ftst = OP_FTEREAD;        break;
5678             case 'w': ftst = OP_FTEWRITE;       break;
5679             case 'x': ftst = OP_FTEEXEC;        break;
5680             case 'o': ftst = OP_FTEOWNED;       break;
5681             case 'R': ftst = OP_FTRREAD;        break;
5682             case 'W': ftst = OP_FTRWRITE;       break;
5683             case 'X': ftst = OP_FTREXEC;        break;
5684             case 'O': ftst = OP_FTROWNED;       break;
5685             case 'e': ftst = OP_FTIS;           break;
5686             case 'z': ftst = OP_FTZERO;         break;
5687             case 's': ftst = OP_FTSIZE;         break;
5688             case 'f': ftst = OP_FTFILE;         break;
5689             case 'd': ftst = OP_FTDIR;          break;
5690             case 'l': ftst = OP_FTLINK;         break;
5691             case 'p': ftst = OP_FTPIPE;         break;
5692             case 'S': ftst = OP_FTSOCK;         break;
5693             case 'u': ftst = OP_FTSUID;         break;
5694             case 'g': ftst = OP_FTSGID;         break;
5695             case 'k': ftst = OP_FTSVTX;         break;
5696             case 'b': ftst = OP_FTBLK;          break;
5697             case 'c': ftst = OP_FTCHR;          break;
5698             case 't': ftst = OP_FTTTY;          break;
5699             case 'T': ftst = OP_FTTEXT;         break;
5700             case 'B': ftst = OP_FTBINARY;       break;
5701             case 'M': case 'A': case 'C':
5702                 gv_fetchpvs("\024", GV_ADD|GV_NOTQUAL, SVt_PV);
5703                 switch (tmp) {
5704                 case 'M': ftst = OP_FTMTIME;    break;
5705                 case 'A': ftst = OP_FTATIME;    break;
5706                 case 'C': ftst = OP_FTCTIME;    break;
5707                 default:                        break;
5708                 }
5709                 break;
5710             default:
5711                 break;
5712             }
5713             if (ftst) {
5714                 PL_last_uni = PL_oldbufptr;
5715                 PL_last_lop_op = (OPCODE)ftst;
5716                 DEBUG_T( { PerlIO_printf(Perl_debug_log,
5717                         "### Saw file test %c\n", (int)tmp);
5718                 } );
5719                 FTST(ftst);
5720             }
5721             else {
5722                 /* Assume it was a minus followed by a one-letter named
5723                  * subroutine call (or a -bareword), then. */
5724                 DEBUG_T( { PerlIO_printf(Perl_debug_log,
5725                         "### '-%c' looked like a file test but was not\n",
5726                         (int) tmp);
5727                 } );
5728                 s = --PL_bufptr;
5729             }
5730         }
5731         {
5732             const char tmp = *s++;
5733             if (*s == tmp) {
5734                 s++;
5735                 if (PL_expect == XOPERATOR)
5736                     TERM(POSTDEC);
5737                 else
5738                     OPERATOR(PREDEC);
5739             }
5740             else if (*s == '>') {
5741                 s++;
5742                 s = skipspace(s);
5743                 if (((*s == '$' || *s == '&') && s[1] == '*')
5744                   ||(*s == '$' && s[1] == '#' && s[2] == '*')
5745                   ||((*s == '@' || *s == '%') && strchr("*[{", s[1]))
5746                   ||(*s == '*' && (s[1] == '*' || s[1] == '{'))
5747                  )
5748                 {
5749                     PL_expect = XPOSTDEREF;
5750                     TOKEN(ARROW);
5751                 }
5752                 if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5753                     s = force_word(s,METHOD,FALSE,TRUE);
5754                     TOKEN(ARROW);
5755                 }
5756                 else if (*s == '$')
5757                     OPERATOR(ARROW);
5758                 else
5759                     TERM(ARROW);
5760             }
5761             if (PL_expect == XOPERATOR) {
5762                 if (*s == '='
5763                     && !PL_lex_allbrackets
5764                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5765                 {
5766                     s--;
5767                     TOKEN(0);
5768                 }
5769                 Aop(OP_SUBTRACT);
5770             }
5771             else {
5772                 if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5773                     check_uni();
5774                 OPERATOR('-');          /* unary minus */
5775             }
5776         }
5777
5778     case '+':
5779         {
5780             const char tmp = *s++;
5781             if (*s == tmp) {
5782                 s++;
5783                 if (PL_expect == XOPERATOR)
5784                     TERM(POSTINC);
5785                 else
5786                     OPERATOR(PREINC);
5787             }
5788             if (PL_expect == XOPERATOR) {
5789                 if (*s == '='
5790                     && !PL_lex_allbrackets
5791                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5792                 {
5793                     s--;
5794                     TOKEN(0);
5795                 }
5796                 Aop(OP_ADD);
5797             }
5798             else {
5799                 if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5800                     check_uni();
5801                 OPERATOR('+');
5802             }
5803         }
5804
5805     case '*':
5806         if (PL_expect == XPOSTDEREF) POSTDEREF('*');
5807         if (PL_expect != XOPERATOR) {
5808             s = scan_ident(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE);
5809             PL_expect = XOPERATOR;
5810             force_ident(PL_tokenbuf, '*');
5811             if (!*PL_tokenbuf)
5812                 PREREF('*');
5813             TERM('*');
5814         }
5815         s++;
5816         if (*s == '*') {
5817             s++;
5818             if (*s == '=' && !PL_lex_allbrackets
5819                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5820             {
5821                 s -= 2;
5822                 TOKEN(0);
5823             }
5824             PWop(OP_POW);
5825         }
5826         if (*s == '='
5827             && !PL_lex_allbrackets
5828             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5829         {
5830             s--;
5831             TOKEN(0);
5832         }
5833         PL_parser->saw_infix_sigil = 1;
5834         Mop(OP_MULTIPLY);
5835
5836     case '%':
5837     {
5838         if (PL_expect == XOPERATOR) {
5839             if (s[1] == '='
5840                 && !PL_lex_allbrackets
5841                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5842             {
5843                 TOKEN(0);
5844             }
5845             ++s;
5846             PL_parser->saw_infix_sigil = 1;
5847             Mop(OP_MODULO);
5848         }
5849         else if (PL_expect == XPOSTDEREF) POSTDEREF('%');
5850         PL_tokenbuf[0] = '%';
5851         s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
5852         pl_yylval.ival = 0;
5853         if (!PL_tokenbuf[1]) {
5854             PREREF('%');
5855         }
5856         if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
5857             && intuit_more(s, PL_bufend)) {
5858             if (*s == '[')
5859                 PL_tokenbuf[0] = '@';
5860         }
5861         PL_expect = XOPERATOR;
5862         force_ident_maybe_lex('%');
5863         TERM('%');
5864     }
5865     case '^':
5866         d = s;
5867         bof = FEATURE_BITWISE_IS_ENABLED;
5868         if (bof && s[1] == '.')
5869             s++;
5870         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
5871                 (s[1] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE))
5872         {
5873             s = d;
5874             TOKEN(0);
5875         }
5876         s++;
5877         BOop(bof ? d == s-2 ? OP_SBIT_XOR : OP_NBIT_XOR : OP_BIT_XOR);
5878     case '[':
5879         if (PL_lex_brackets > 100)
5880             Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
5881         PL_lex_brackstack[PL_lex_brackets++] = 0;
5882         PL_lex_allbrackets++;
5883         {
5884             const char tmp = *s++;
5885             OPERATOR(tmp);
5886         }
5887     case '~':
5888         if (s[1] == '~'
5889             && (PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR))
5890         {
5891             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
5892                 TOKEN(0);
5893             s += 2;
5894             Perl_ck_warner_d(aTHX_
5895                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
5896                 "Smartmatch is experimental");
5897             Eop(OP_SMARTMATCH);
5898         }
5899         s++;
5900         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.') {
5901             s++;
5902             BCop(OP_SCOMPLEMENT);
5903         }
5904         BCop(bof ? OP_NCOMPLEMENT : OP_COMPLEMENT);
5905     case ',':
5906         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
5907             TOKEN(0);
5908         s++;
5909         OPERATOR(',');
5910     case ':':
5911         if (s[1] == ':') {
5912             len = 0;
5913             goto just_a_word_zero_gv;
5914         }
5915         s++;
5916         {
5917         OP *attrs;
5918
5919         switch (PL_expect) {
5920         case XOPERATOR:
5921             if (!PL_in_my || PL_lex_state != LEX_NORMAL)
5922                 break;
5923             PL_bufptr = s;      /* update in case we back off */
5924             if (*s == '=') {
5925                 Perl_croak(aTHX_
5926                            "Use of := for an empty attribute list is not allowed");
5927             }
5928             goto grabattrs;
5929         case XATTRBLOCK:
5930             PL_expect = XBLOCK;
5931             goto grabattrs;
5932         case XATTRTERM:
5933             PL_expect = XTERMBLOCK;
5934          grabattrs:
5935             s = skipspace(s);
5936             attrs = NULL;
5937             while (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5938                 I32 tmp;
5939                 SV *sv;
5940                 d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
5941                 if (isLOWER(*s) && (tmp = keyword(PL_tokenbuf, len, 0))) {
5942                     if (tmp < 0) tmp = -tmp;
5943                     switch (tmp) {
5944                     case KEY_or:
5945                     case KEY_and:
5946                     case KEY_for:
5947                     case KEY_foreach:
5948                     case KEY_unless:
5949                     case KEY_if:
5950                     case KEY_while:
5951                     case KEY_until:
5952                         goto got_attrs;
5953                     default:
5954                         break;
5955                     }
5956                 }
5957                 sv = newSVpvn_flags(s, len, UTF ? SVf_UTF8 : 0);
5958                 if (*d == '(') {
5959                     d = scan_str(d,TRUE,TRUE,FALSE,NULL);
5960                     if (!d) {
5961                         if (attrs)
5962                             op_free(attrs);
5963                         sv_free(sv);
5964                         Perl_croak(aTHX_ "Unterminated attribute parameter in attribute list");
5965                     }
5966                     COPLINE_SET_FROM_MULTI_END;
5967                 }
5968                 if (PL_lex_stuff) {
5969                     sv_catsv(sv, PL_lex_stuff);
5970                     attrs = op_append_elem(OP_LIST, attrs,
5971                                         newSVOP(OP_CONST, 0, sv));
5972                     SvREFCNT_dec_NN(PL_lex_stuff);
5973                     PL_lex_stuff = NULL;
5974                 }
5975                 else {
5976                     /* NOTE: any CV attrs applied here need to be part of
5977                        the CVf_BUILTIN_ATTRS define in cv.h! */
5978                     if (!PL_in_my && memEQs(SvPVX(sv), len, "lvalue")) {
5979                         sv_free(sv);
5980                         CvLVALUE_on(PL_compcv);
5981                     }
5982                     else if (!PL_in_my && memEQs(SvPVX(sv), len, "method")) {
5983                         sv_free(sv);
5984                         CvMETHOD_on(PL_compcv);
5985                     }
5986                     else if (!PL_in_my && memEQs(SvPVX(sv), len, "const"))
5987                     {
5988                         sv_free(sv);
5989                         Perl_ck_warner_d(aTHX_
5990                             packWARN(WARN_EXPERIMENTAL__CONST_ATTR),
5991                            ":const is experimental"
5992                         );
5993                         CvANONCONST_on(PL_compcv);
5994                         if (!CvANON(PL_compcv))
5995                             yyerror(":const is not permitted on named "
5996                                     "subroutines");
5997                     }
5998                     /* After we've set the flags, it could be argued that
5999                        we don't need to do the attributes.pm-based setting
6000                        process, and shouldn't bother appending recognized
6001                        flags.  To experiment with that, uncomment the
6002                        following "else".  (Note that's already been
6003                        uncommented.  That keeps the above-applied built-in
6004                        attributes from being intercepted (and possibly
6005                        rejected) by a package's attribute routines, but is
6006                        justified by the performance win for the common case
6007                        of applying only built-in attributes.) */
6008                     else
6009                         attrs = op_append_elem(OP_LIST, attrs,
6010                                             newSVOP(OP_CONST, 0,
6011                                                     sv));
6012                 }
6013                 s = skipspace(d);
6014                 if (*s == ':' && s[1] != ':')
6015                     s = skipspace(s+1);
6016                 else if (s == d)
6017                     break;      /* require real whitespace or :'s */
6018                 /* XXX losing whitespace on sequential attributes here */
6019             }
6020             {
6021                 if (*s != ';'
6022                     && *s != '}'
6023                     && !(PL_expect == XOPERATOR
6024                          ? (*s == '=' ||  *s == ')')
6025                          : (*s == '{' ||  *s == '(')))
6026                 {
6027                     const char q = ((*s == '\'') ? '"' : '\'');
6028                     /* If here for an expression, and parsed no attrs, back
6029                        off. */
6030                     if (PL_expect == XOPERATOR && !attrs) {
6031                         s = PL_bufptr;
6032                         break;
6033                     }
6034                     /* MUST advance bufptr here to avoid bogus "at end of line"
6035                        context messages from yyerror().
6036                     */
6037                     PL_bufptr = s;
6038                     yyerror( (const char *)
6039                              (*s
6040                               ? Perl_form(aTHX_ "Invalid separator character "
6041                                           "%c%c%c in attribute list", q, *s, q)
6042                               : "Unterminated attribute list" ) );
6043                     if (attrs)
6044                         op_free(attrs);
6045                     OPERATOR(':');
6046                 }
6047             }
6048         got_attrs:
6049             if (attrs) {
6050                 NEXTVAL_NEXTTOKE.opval = attrs;
6051                 force_next(THING);
6052             }
6053             TOKEN(COLONATTR);
6054         }
6055         }
6056         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING) {
6057             s--;
6058             TOKEN(0);
6059         }
6060         PL_lex_allbrackets--;
6061         OPERATOR(':');
6062     case '(':
6063         s++;
6064         if (PL_last_lop == PL_oldoldbufptr || PL_last_uni == PL_oldoldbufptr)
6065             PL_oldbufptr = PL_oldoldbufptr;             /* allow print(STDOUT 123) */
6066         else
6067             PL_expect = XTERM;
6068         s = skipspace(s);
6069         PL_lex_allbrackets++;
6070         TOKEN('(');
6071     case ';':
6072         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
6073             TOKEN(0);
6074         CLINE;
6075         s++;
6076         PL_expect = XSTATE;
6077         TOKEN(';');
6078     case ')':
6079         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING)
6080             TOKEN(0);
6081         s++;
6082         PL_lex_allbrackets--;
6083         s = skipspace(s);
6084         if (*s == '{')
6085             PREBLOCK(')');
6086         TERM(')');
6087     case ']':
6088         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
6089             TOKEN(0);
6090         s++;
6091         if (PL_lex_brackets <= 0)
6092             /* diag_listed_as: Unmatched right %s bracket */
6093             yyerror("Unmatched right square bracket");
6094         else
6095             --PL_lex_brackets;
6096         PL_lex_allbrackets--;
6097         if (PL_lex_state == LEX_INTERPNORMAL) {
6098             if (PL_lex_brackets == 0) {
6099                 if (*s == '-' && s[1] == '>')
6100                     PL_lex_state = LEX_INTERPENDMAYBE;
6101                 else if (*s != '[' && *s != '{')
6102                     PL_lex_state = LEX_INTERPEND;
6103             }
6104         }
6105         TERM(']');
6106     case '{':
6107         s++;
6108       leftbracket:
6109         if (PL_lex_brackets > 100) {
6110             Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
6111         }
6112         switch (PL_expect) {
6113         case XTERM:
6114         case XTERMORDORDOR:
6115             PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6116             PL_lex_allbrackets++;
6117             OPERATOR(HASHBRACK);
6118         case XOPERATOR:
6119             while (s < PL_bufend && SPACE_OR_TAB(*s))
6120                 s++;
6121             d = s;
6122             PL_tokenbuf[0] = '\0';
6123             if (d < PL_bufend && *d == '-') {
6124                 PL_tokenbuf[0] = '-';
6125                 d++;
6126                 while (d < PL_bufend && SPACE_OR_TAB(*d))
6127                     d++;
6128             }
6129             if (d < PL_bufend && isIDFIRST_lazy_if_safe(d, PL_bufend, UTF)) {
6130                 d = scan_word(d, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
6131                               FALSE, &len);
6132                 while (d < PL_bufend && SPACE_OR_TAB(*d))
6133                     d++;
6134                 if (*d == '}') {
6135                     const char minus = (PL_tokenbuf[0] == '-');
6136                     s = force_word(s + minus, BAREWORD, FALSE, TRUE);
6137                     if (minus)
6138                         force_next('-');
6139                 }
6140             }
6141             /* FALLTHROUGH */
6142         case XATTRTERM:
6143         case XTERMBLOCK:
6144             PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6145             PL_lex_allbrackets++;
6146             PL_expect = XSTATE;
6147             break;
6148         case XATTRBLOCK:
6149         case XBLOCK:
6150             PL_lex_brackstack[PL_lex_brackets++] = XSTATE;
6151             PL_lex_allbrackets++;
6152             PL_expect = XSTATE;
6153             break;
6154         case XBLOCKTERM:
6155             PL_lex_brackstack[PL_lex_brackets++] = XTERM;
6156             PL_lex_allbrackets++;
6157             PL_expect = XSTATE;
6158             break;
6159         default: {
6160                 const char *t;
6161                 if (PL_oldoldbufptr == PL_last_lop)
6162                     PL_lex_brackstack[PL_lex_brackets++] = XTERM;
6163                 else
6164                     PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6165                 PL_lex_allbrackets++;
6166                 s = skipspace(s);
6167                 if (*s == '}') {
6168                     if (PL_expect == XREF && PL_lex_state == LEX_INTERPNORMAL) {
6169                         PL_expect = XTERM;
6170                         /* This hack is to get the ${} in the message. */
6171                         PL_bufptr = s+1;
6172                         yyerror("syntax error");
6173                         break;
6174                     }
6175                     OPERATOR(HASHBRACK);
6176                 }
6177                 if (PL_expect == XREF && PL_oldoldbufptr != PL_last_lop) {
6178                     /* ${...} or @{...} etc., but not print {...}
6179                      * Skip the disambiguation and treat this as a block.
6180                      */
6181                     goto block_expectation;
6182                 }
6183                 /* This hack serves to disambiguate a pair of curlies
6184                  * as being a block or an anon hash.  Normally, expectation
6185                  * determines that, but in cases where we're not in a
6186                  * position to expect anything in particular (like inside
6187                  * eval"") we have to resolve the ambiguity.  This code
6188                  * covers the case where the first term in the curlies is a
6189                  * quoted string.  Most other cases need to be explicitly
6190                  * disambiguated by prepending a "+" before the opening
6191                  * curly in order to force resolution as an anon hash.
6192                  *
6193                  * XXX should probably propagate the outer expectation
6194                  * into eval"" to rely less on this hack, but that could
6195                  * potentially break current behavior of eval"".
6196                  * GSAR 97-07-21
6197                  */
6198                 t = s;
6199                 if (*s == '\'' || *s == '"' || *s == '`') {
6200                     /* common case: get past first string, handling escapes */
6201                     for (t++; t < PL_bufend && *t != *s;)
6202                         if (*t++ == '\\')
6203                             t++;
6204                     t++;
6205                 }
6206                 else if (*s == 'q') {
6207                     if (++t < PL_bufend
6208                         && (!isWORDCHAR(*t)
6209                             || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
6210                                 && !isWORDCHAR(*t))))
6211                     {
6212                         /* skip q//-like construct */
6213                         const char *tmps;
6214                         char open, close, term;
6215                         I32 brackets = 1;
6216
6217                         while (t < PL_bufend && isSPACE(*t))
6218                             t++;
6219                         /* check for q => */
6220                         if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
6221                             OPERATOR(HASHBRACK);
6222                         }
6223                         term = *t;
6224                         open = term;
6225                         if (term && (tmps = strchr("([{< )]}> )]}>",term)))
6226                             term = tmps[5];
6227                         close = term;
6228                         if (open == close)
6229                             for (t++; t < PL_bufend; t++) {
6230                                 if (*t == '\\' && t+1 < PL_bufend && open != '\\')
6231                                     t++;
6232                                 else if (*t == open)
6233                                     break;
6234                             }
6235                         else {
6236                             for (t++; t < PL_bufend; t++) {
6237                                 if (*t == '\\' && t+1 < PL_bufend)
6238                                     t++;
6239                                 else if (*t == close && --brackets <= 0)
6240                                     break;
6241                                 else if (*t == open)
6242                                     brackets++;
6243                             }
6244                         }
6245                         t++;
6246                     }
6247                     else
6248                         /* skip plain q word */
6249                         while (   t < PL_bufend
6250                                && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6251                         {
6252                             t += UTF ? UTF8SKIP(t) : 1;
6253                         }
6254                 }
6255                 else if (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)) {
6256                     t += UTF ? UTF8SKIP(t) : 1;
6257                     while (   t < PL_bufend
6258                            && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6259                     {
6260                         t += UTF ? UTF8SKIP(t) : 1;
6261                     }
6262                 }
6263                 while (t < PL_bufend && isSPACE(*t))
6264                     t++;
6265                 /* if comma follows first term, call it an anon hash */
6266                 /* XXX it could be a comma expression with loop modifiers */
6267                 if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
6268                                    || (*t == '=' && t[1] == '>')))
6269                     OPERATOR(HASHBRACK);
6270                 if (PL_expect == XREF)
6271                 {
6272                   block_expectation:
6273                     /* If there is an opening brace or 'sub:', treat it
6274                        as a term to make ${{...}}{k} and &{sub:attr...}
6275                        dwim.  Otherwise, treat it as a statement, so
6276                        map {no strict; ...} works.
6277                      */
6278                     s = skipspace(s);
6279                     if (*s == '{') {
6280                         PL_expect = XTERM;
6281                         break;
6282                     }
6283                     if (memBEGINs(s, (STRLEN) (PL_bufend - s), "sub")) {
6284                         PL_bufptr = s;
6285                         d = s + 3;
6286                         d = skipspace(d);
6287                         s = PL_bufptr;
6288                         if (*d == ':') {
6289                             PL_expect = XTERM;
6290                             break;
6291                         }
6292                     }
6293                     PL_expect = XSTATE;
6294                 }
6295                 else {
6296                     PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
6297                     PL_expect = XSTATE;
6298                 }
6299             }
6300             break;
6301         }
6302         pl_yylval.ival = CopLINE(PL_curcop);
6303         PL_copline = NOLINE;   /* invalidate current command line number */
6304         TOKEN(formbrack ? '=' : '{');
6305     case '}':
6306         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
6307             TOKEN(0);
6308       rightbracket:
6309         assert(s != PL_bufend);
6310         s++;
6311         if (PL_lex_brackets <= 0)
6312             /* diag_listed_as: Unmatched right %s bracket */
6313             yyerror("Unmatched right curly bracket");
6314         else
6315             PL_expect = (expectation)PL_lex_brackstack[--PL_lex_brackets];
6316         PL_lex_allbrackets--;
6317         if (PL_lex_state == LEX_INTERPNORMAL) {
6318             if (PL_lex_brackets == 0) {
6319                 if (PL_expect & XFAKEBRACK) {
6320                     PL_expect &= XENUMMASK;
6321                     PL_lex_state = LEX_INTERPEND;
6322                     PL_bufptr = s;
6323                     return yylex();     /* ignore fake brackets */
6324                 }
6325                 if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6326                  && SvEVALED(PL_lex_repl))
6327                     PL_lex_state = LEX_INTERPEND;
6328                 else if (*s == '-' && s[1] == '>')
6329                     PL_lex_state = LEX_INTERPENDMAYBE;
6330                 else if (*s != '[' && *s != '{')
6331                     PL_lex_state = LEX_INTERPEND;
6332             }
6333         }
6334         if (PL_expect & XFAKEBRACK) {
6335             PL_expect &= XENUMMASK;
6336             PL_bufptr = s;
6337             return yylex();             /* ignore fake brackets */
6338         }
6339         force_next(formbrack ? '.' : '}');
6340         if (formbrack) LEAVE_with_name("lex_format");
6341         if (formbrack == 2) { /* means . where arguments were expected */
6342             force_next(';');
6343             TOKEN(FORMRBRACK);
6344         }
6345         TOKEN(';');
6346     case '&':
6347         if (PL_expect == XPOSTDEREF) POSTDEREF('&');
6348         s++;
6349         if (*s++ == '&') {
6350             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6351                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6352                 s -= 2;
6353                 TOKEN(0);
6354             }
6355             AOPERATOR(ANDAND);
6356         }
6357         s--;
6358         if (PL_expect == XOPERATOR) {
6359             if (   PL_bufptr == PL_linestart
6360                 && ckWARN(WARN_SEMICOLON)
6361                 && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
6362             {
6363                 CopLINE_dec(PL_curcop);
6364                 Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6365                 CopLINE_inc(PL_curcop);
6366             }
6367             d = s;
6368             if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6369                 s++;
6370             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6371                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6372                 s = d;
6373                 s--;
6374                 TOKEN(0);
6375             }
6376             if (d == s) {
6377                 PL_parser->saw_infix_sigil = 1;
6378                 BAop(bof ? OP_NBIT_AND : OP_BIT_AND);
6379             }
6380             else
6381                 BAop(OP_SBIT_AND);
6382         }
6383
6384         PL_tokenbuf[0] = '&';
6385         s = scan_ident(s - 1, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, TRUE);
6386         pl_yylval.ival = (OPpENTERSUB_AMPER<<8);
6387         if (PL_tokenbuf[1]) {
6388             force_ident_maybe_lex('&');
6389         }
6390         else
6391             PREREF('&');
6392         TERM('&');
6393
6394     case '|':
6395         s++;
6396         if (*s++ == '|') {
6397             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6398                     (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6399                 s -= 2;
6400                 TOKEN(0);
6401             }
6402             AOPERATOR(OROR);
6403         }
6404         s--;
6405         d = s;
6406         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6407             s++;
6408         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6409                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6410             s = d - 1;
6411             TOKEN(0);
6412         }
6413         BOop(bof ? s == d ? OP_NBIT_OR : OP_SBIT_OR : OP_BIT_OR);
6414     case '=':
6415         s++;
6416         {
6417             const char tmp = *s++;
6418             if (tmp == '=') {
6419                 if (   (s == PL_linestart+2 || s[-3] == '\n')
6420                     && memBEGINs(s, (STRLEN) (PL_bufend - s), "====="))
6421                 {
6422                     s = vcs_conflict_marker(s + 5);
6423                     goto retry;
6424                 }
6425                 if (!PL_lex_allbrackets
6426                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6427                 {
6428                     s -= 2;
6429                     TOKEN(0);
6430                 }
6431                 Eop(OP_EQ);
6432             }
6433             if (tmp == '>') {
6434                 if (!PL_lex_allbrackets
6435                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
6436                 {
6437                     s -= 2;
6438                     TOKEN(0);
6439                 }
6440                 OPERATOR(',');
6441             }
6442             if (tmp == '~')
6443                 PMop(OP_MATCH);
6444             if (tmp && isSPACE(*s) && ckWARN(WARN_SYNTAX)
6445                 && strchr("+-*/%.^&|<",tmp))
6446                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6447                             "Reversed %c= operator",(int)tmp);
6448             s--;
6449             if (PL_expect == XSTATE
6450                 && isALPHA(tmp)
6451                 && (s == PL_linestart+1 || s[-2] == '\n') )
6452             {
6453                 if (   (PL_in_eval && !PL_rsfp && !PL_parser->filtered)
6454                     || PL_lex_state != LEX_NORMAL)
6455                 {
6456                     d = PL_bufend;
6457                     while (s < d) {
6458                         if (*s++ == '\n') {
6459                             incline(s, PL_bufend);
6460                             if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=cut"))
6461                             {
6462                                 s = (char *) memchr(s,'\n', d - s);
6463                                 if (s)
6464                                     s++;
6465                                 else
6466                                     s = d;
6467                                 incline(s, PL_bufend);
6468                                 goto retry;
6469                             }
6470                         }
6471                     }
6472                     goto retry;
6473                 }
6474                 s = PL_bufend;
6475                 PL_parser->in_pod = 1;
6476                 goto retry;
6477             }
6478         }
6479         if (PL_expect == XBLOCK) {
6480             const char *t = s;
6481 #ifdef PERL_STRICT_CR
6482             while (SPACE_OR_TAB(*t))
6483 #else
6484             while (SPACE_OR_TAB(*t) || *t == '\r')
6485 #endif
6486                 t++;
6487             if (*t == '\n' || *t == '#') {
6488                 formbrack = 1;
6489                 ENTER_with_name("lex_format");
6490                 SAVEI8(PL_parser->form_lex_state);
6491                 SAVEI32(PL_lex_formbrack);
6492                 PL_parser->form_lex_state = PL_lex_state;
6493                 PL_lex_formbrack = PL_lex_brackets + 1;
6494                 goto leftbracket;
6495             }
6496         }
6497         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6498             s--;
6499             TOKEN(0);
6500         }
6501         pl_yylval.ival = 0;
6502         OPERATOR(ASSIGNOP);
6503     case '!':
6504         s++;
6505         {
6506             const char tmp = *s++;
6507             if (tmp == '=') {
6508                 /* was this !=~ where !~ was meant?
6509                  * warn on m:!=~\s+([/?]|[msy]\W|tr\W): */
6510
6511                 if (*s == '~' && ckWARN(WARN_SYNTAX)) {
6512                     const char *t = s+1;
6513
6514                     while (t < PL_bufend && isSPACE(*t))
6515                         ++t;
6516
6517                     if (*t == '/' || *t == '?'
6518                         || ((*t == 'm' || *t == 's' || *t == 'y')
6519                             && !isWORDCHAR(t[1]))
6520                         || (*t == 't' && t[1] == 'r' && !isWORDCHAR(t[2])))
6521                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6522                                     "!=~ should be !~");
6523                 }
6524                 if (!PL_lex_allbrackets
6525                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6526                 {
6527                     s -= 2;
6528                     TOKEN(0);
6529                 }
6530                 Eop(OP_NE);
6531             }
6532             if (tmp == '~')
6533                 PMop(OP_NOT);
6534         }
6535         s--;
6536         OPERATOR('!');
6537     case '<':
6538         if (PL_expect != XOPERATOR) {
6539             if (s[1] != '<' && !memchr(s,'>', PL_bufend - s))
6540                 check_uni();
6541             if (s[1] == '<' && s[2] != '>') {
6542                 if (   (s == PL_linestart || s[-1] == '\n')
6543                     && memBEGINs(s+2, (STRLEN) (PL_bufend - (s+2)), "<<<<<"))
6544                 {
6545                     s = vcs_conflict_marker(s + 7);
6546                     goto retry;
6547                 }
6548                 s = scan_heredoc(s);
6549             }
6550             else
6551                 s = scan_inputsymbol(s);
6552             PL_expect = XOPERATOR;
6553             TOKEN(sublex_start());
6554         }
6555         s++;
6556         {
6557             char tmp = *s++;
6558             if (tmp == '<') {
6559                 if (   (s == PL_linestart+2 || s[-3] == '\n')
6560                     && memBEGINs(s, (STRLEN) (PL_bufend - s), "<<<<<"))
6561                 {
6562                     s = vcs_conflict_marker(s + 5);
6563                     goto retry;
6564                 }
6565                 if (*s == '=' && !PL_lex_allbrackets
6566                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6567                 {
6568                     s -= 2;
6569                     TOKEN(0);
6570                 }
6571                 SHop(OP_LEFT_SHIFT);
6572             }
6573             if (tmp == '=') {
6574                 tmp = *s++;
6575                 if (tmp == '>') {
6576                     if (!PL_lex_allbrackets
6577                         && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6578                     {
6579                         s -= 3;
6580                         TOKEN(0);
6581                     }
6582                     Eop(OP_NCMP);
6583                 }
6584                 s--;
6585                 if (!PL_lex_allbrackets
6586                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6587                 {
6588                     s -= 2;
6589                     TOKEN(0);
6590                 }
6591                 Rop(OP_LE);
6592             }
6593         }
6594         s--;
6595         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6596             s--;
6597             TOKEN(0);
6598         }
6599         Rop(OP_LT);
6600     case '>':
6601         s++;
6602         {
6603             const char tmp = *s++;
6604             if (tmp == '>') {
6605                 if (   (s == PL_linestart+2 || s[-3] == '\n')
6606                     && memBEGINs(s, (STRLEN) (PL_bufend - s), ">>>>>"))
6607                 {
6608                     s = vcs_conflict_marker(s + 5);
6609                     goto retry;
6610                 }
6611                 if (*s == '=' && !PL_lex_allbrackets
6612                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6613                 {
6614                     s -= 2;
6615                     TOKEN(0);
6616                 }
6617                 SHop(OP_RIGHT_SHIFT);
6618             }
6619             else if (tmp == '=') {
6620                 if (!PL_lex_allbrackets
6621                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6622                 {
6623                     s -= 2;
6624                     TOKEN(0);
6625                 }
6626                 Rop(OP_GE);
6627             }
6628         }
6629         s--;
6630         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6631             s--;
6632             TOKEN(0);
6633         }
6634         Rop(OP_GT);
6635
6636     case '$':
6637         CLINE;
6638
6639         if (PL_expect == XPOSTDEREF) {
6640             if (s[1] == '#') {
6641                 s++;
6642                 POSTDEREF(DOLSHARP);
6643             }
6644             POSTDEREF('$');
6645         }
6646
6647         if (   s[1] == '#'
6648             && (   isIDFIRST_lazy_if_safe(s+2, PL_bufend, UTF)
6649                 || strchr("{$:+-@", s[2])))
6650         {
6651             PL_tokenbuf[0] = '@';
6652             s = scan_ident(s + 1, PL_tokenbuf + 1,
6653                            sizeof PL_tokenbuf - 1, FALSE);
6654             if (PL_expect == XOPERATOR) {
6655                 d = s;
6656                 if (PL_bufptr > s) {
6657                     d = PL_bufptr-1;
6658                     PL_bufptr = PL_oldbufptr;
6659                 }
6660                 no_op("Array length", d);
6661             }
6662             if (!PL_tokenbuf[1])
6663                 PREREF(DOLSHARP);
6664             PL_expect = XOPERATOR;
6665             force_ident_maybe_lex('#');
6666             TOKEN(DOLSHARP);
6667         }
6668
6669         PL_tokenbuf[0] = '$';
6670         s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6671         if (PL_expect == XOPERATOR) {
6672             d = s;
6673             if (PL_bufptr > s) {
6674                 d = PL_bufptr-1;
6675                 PL_bufptr = PL_oldbufptr;
6676             }
6677             no_op("Scalar", d);
6678         }
6679         if (!PL_tokenbuf[1]) {
6680             if (s == PL_bufend)
6681                 yyerror("Final $ should be \\$ or $name");
6682             PREREF('$');
6683         }
6684
6685         d = s;
6686         {
6687             const char tmp = *s;
6688             if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
6689                 s = skipspace(s);
6690
6691             if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6692                 && intuit_more(s, PL_bufend)) {
6693                 if (*s == '[') {
6694                     PL_tokenbuf[0] = '@';
6695                     if (ckWARN(WARN_SYNTAX)) {
6696                         char *t = s+1;
6697
6698                         while (   isSPACE(*t)
6699                                || isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)
6700                                || *t == '$')
6701                         {
6702                             t += UTF ? UTF8SKIP(t) : 1;
6703                         }
6704                         if (*t++ == ',') {
6705                             PL_bufptr = skipspace(PL_bufptr); /* XXX can realloc */
6706                             while (t < PL_bufend && *t != ']')
6707                                 t++;
6708                             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6709                                         "Multidimensional syntax %" UTF8f " not supported",
6710                                         UTF8fARG(UTF,(int)((t - PL_bufptr) + 1), PL_bufptr));
6711                         }
6712                     }
6713                 }
6714                 else if (*s == '{') {
6715                     char *t;
6716                     PL_tokenbuf[0] = '%';
6717                     if (    strEQ(PL_tokenbuf+1, "SIG")
6718                         && ckWARN(WARN_SYNTAX)
6719                         && (t = (char *) memchr(s, '}', PL_bufend - s))
6720                         && (t = (char *) memchr(t, '=', PL_bufend - t)))
6721                     {
6722                         char tmpbuf[sizeof PL_tokenbuf];
6723                         do {
6724                             t++;
6725                         } while (isSPACE(*t));
6726                         if (isIDFIRST_lazy_if_safe(t, PL_bufend, UTF)) {
6727                             STRLEN len;
6728                             t = scan_word(t, tmpbuf, sizeof tmpbuf, TRUE,
6729                                             &len);
6730                             while (isSPACE(*t))
6731                                 t++;
6732                             if (  *t == ';'
6733                                 && get_cvn_flags(tmpbuf, len, UTF
6734                                                                 ? SVf_UTF8
6735                                                                 : 0))
6736                             {
6737                                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6738                                     "You need to quote \"%" UTF8f "\"",
6739                                         UTF8fARG(UTF, len, tmpbuf));
6740                             }
6741                         }
6742                     }
6743                 }
6744             }
6745
6746             PL_expect = XOPERATOR;
6747             if (PL_lex_state == LEX_NORMAL && isSPACE((char)tmp)) {
6748                 const bool islop = (PL_last_lop == PL_oldoldbufptr);
6749                 if (!islop || PL_last_lop_op == OP_GREPSTART)
6750                     PL_expect = XOPERATOR;
6751                 else if (strchr("$@\"'`q", *s))
6752                     PL_expect = XTERM;          /* e.g. print $fh "foo" */
6753                 else if (   strchr("&*<%", *s)
6754                          && isIDFIRST_lazy_if_safe(s+1, PL_bufend, UTF))
6755                 {
6756                     PL_expect = XTERM;          /* e.g. print $fh &sub */
6757                 }
6758                 else if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6759                     char tmpbuf[sizeof PL_tokenbuf];
6760                     int t2;
6761                     scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
6762                     if ((t2 = keyword(tmpbuf, len, 0))) {
6763                         /* binary operators exclude handle interpretations */
6764                         switch (t2) {
6765                         case -KEY_x:
6766                         case -KEY_eq:
6767                         case -KEY_ne:
6768                         case -KEY_gt:
6769                         case -KEY_lt:
6770                         case -KEY_ge:
6771                         case -KEY_le:
6772                         case -KEY_cmp:
6773                             break;
6774                         default:
6775                             PL_expect = XTERM;  /* e.g. print $fh length() */
6776                             break;
6777                         }
6778                     }
6779                     else {
6780                         PL_expect = XTERM;      /* e.g. print $fh subr() */
6781                     }
6782                 }
6783                 else if (isDIGIT(*s))
6784                     PL_expect = XTERM;          /* e.g. print $fh 3 */
6785                 else if (*s == '.' && isDIGIT(s[1]))
6786                     PL_expect = XTERM;          /* e.g. print $fh .3 */
6787                 else if ((*s == '?' || *s == '-' || *s == '+')
6788                          && !isSPACE(s[1]) && s[1] != '=')
6789                     PL_expect = XTERM;          /* e.g. print $fh -1 */
6790                 else if (*s == '/' && !isSPACE(s[1]) && s[1] != '='
6791                          && s[1] != '/')
6792                     PL_expect = XTERM;          /* e.g. print $fh /.../
6793                                                    XXX except DORDOR operator
6794                                                 */
6795                 else if (*s == '<' && s[1] == '<' && !isSPACE(s[2])
6796                          && s[2] != '=')
6797                     PL_expect = XTERM;          /* print $fh <<"EOF" */
6798             }
6799         }
6800         force_ident_maybe_lex('$');
6801         TOKEN('$');
6802
6803     case '@':
6804         if (PL_expect == XPOSTDEREF)
6805             POSTDEREF('@');
6806         PL_tokenbuf[0] = '@';
6807         s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6808         if (PL_expect == XOPERATOR) {
6809             d = s;
6810             if (PL_bufptr > s) {
6811                 d = PL_bufptr-1;
6812                 PL_bufptr = PL_oldbufptr;
6813             }
6814             no_op("Array", d);
6815         }
6816         pl_yylval.ival = 0;
6817         if (!PL_tokenbuf[1]) {
6818             PREREF('@');
6819         }
6820         if (PL_lex_state == LEX_NORMAL)
6821             s = skipspace(s);
6822         if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6823             && intuit_more(s, PL_bufend))
6824         {
6825             if (*s == '{')
6826                 PL_tokenbuf[0] = '%';
6827
6828             /* Warn about @ where they meant $. */
6829             if (*s == '[' || *s == '{') {
6830                 if (ckWARN(WARN_SYNTAX)) {
6831                     S_check_scalar_slice(aTHX_ s);
6832                 }
6833             }
6834         }
6835         PL_expect = XOPERATOR;
6836         force_ident_maybe_lex('@');
6837         TERM('@');
6838
6839      case '/':                  /* may be division, defined-or, or pattern */
6840         if ((PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR) && s[1] == '/') {
6841             if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6842                     (s[2] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC))
6843                 TOKEN(0);
6844             s += 2;
6845             AOPERATOR(DORDOR);
6846         }
6847         else if (PL_expect == XOPERATOR) {
6848             s++;
6849             if (*s == '=' && !PL_lex_allbrackets
6850                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6851             {
6852                 s--;
6853                 TOKEN(0);
6854             }
6855             Mop(OP_DIVIDE);
6856         }
6857         else {
6858             /* Disable warning on "study /blah/" */
6859             if (    PL_oldoldbufptr == PL_last_uni
6860                 && (   *PL_last_uni != 's' || s - PL_last_uni < 5
6861                     || memNE(PL_last_uni, "study", 5)
6862                     || isWORDCHAR_lazy_if_safe(PL_last_uni+5, PL_bufend, UTF)
6863              ))
6864                 check_uni();
6865             s = scan_pat(s,OP_MATCH);
6866             TERM(sublex_start());
6867         }
6868
6869      case '?':                  /* conditional */
6870         s++;
6871         if (!PL_lex_allbrackets
6872             && PL_lex_fakeeof >= LEX_FAKEEOF_IFELSE)
6873         {
6874             s--;
6875             TOKEN(0);
6876         }
6877         PL_lex_allbrackets++;
6878         OPERATOR('?');
6879
6880     case '.':
6881         if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack
6882 #ifdef PERL_STRICT_CR
6883             && s[1] == '\n'
6884 #else
6885             && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n'))
6886 #endif
6887             && (s == PL_linestart || s[-1] == '\n') )
6888         {
6889             PL_expect = XSTATE;
6890             formbrack = 2; /* dot seen where arguments expected */
6891             goto rightbracket;
6892         }
6893         if (PL_expect == XSTATE && s[1] == '.' && s[2] == '.') {
6894             s += 3;
6895             OPERATOR(YADAYADA);
6896         }
6897         if (PL_expect == XOPERATOR || !isDIGIT(s[1])) {
6898             char tmp = *s++;
6899             if (*s == tmp) {
6900                 if (!PL_lex_allbrackets
6901                     && PL_lex_fakeeof >= LEX_FAKEEOF_RANGE)
6902                 {
6903                     s--;
6904                     TOKEN(0);
6905                 }
6906                 s++;
6907                 if (*s == tmp) {
6908                     s++;
6909                     pl_yylval.ival = OPf_SPECIAL;
6910                 }
6911                 else
6912                     pl_yylval.ival = 0;
6913                 OPERATOR(DOTDOT);
6914             }
6915             if (*s == '=' && !PL_lex_allbrackets
6916                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6917             {
6918                 s--;
6919                 TOKEN(0);
6920             }
6921             Aop(OP_CONCAT);
6922         }
6923         /* FALLTHROUGH */
6924     case '0': case '1': case '2': case '3': case '4':
6925     case '5': case '6': case '7': case '8': case '9':
6926         s = scan_num(s, &pl_yylval);
6927         DEBUG_T( { printbuf("### Saw number in %s\n", s); } );
6928         if (PL_expect == XOPERATOR)
6929             no_op("Number",s);
6930         TERM(THING);
6931
6932     case '\'':
6933         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6934         if (!s)
6935             missingterm(NULL, 0);
6936         COPLINE_SET_FROM_MULTI_END;
6937         DEBUG_T( { printbuf("### Saw string before %s\n", s); } );
6938         if (PL_expect == XOPERATOR) {
6939             no_op("String",s);
6940         }
6941         pl_yylval.ival = OP_CONST;
6942         TERM(sublex_start());
6943
6944     case '"':
6945         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6946         DEBUG_T( {
6947             if (s)
6948                 printbuf("### Saw string before %s\n", s);
6949             else
6950                 PerlIO_printf(Perl_debug_log,
6951                              "### Saw unterminated string\n");
6952         } );
6953         if (PL_expect == XOPERATOR) {
6954                 no_op("String",s);
6955         }
6956         if (!s)
6957             missingterm(NULL, 0);
6958         pl_yylval.ival = OP_CONST;
6959         /* FIXME. I think that this can be const if char *d is replaced by
6960            more localised variables.  */
6961         for (d = SvPV(PL_lex_stuff, len); len; len--, d++) {
6962             if (*d == '$' || *d == '@' || *d == '\\' || !UTF8_IS_INVARIANT((U8)*d)) {
6963                 pl_yylval.ival = OP_STRINGIFY;
6964                 break;
6965             }
6966         }
6967         if (pl_yylval.ival == OP_CONST)
6968             COPLINE_SET_FROM_MULTI_END;
6969         TERM(sublex_start());
6970
6971     case '`':
6972         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6973         DEBUG_T( {
6974             if (s)
6975                 printbuf("### Saw backtick string before %s\n", s);
6976             else
6977                 PerlIO_printf(Perl_debug_log,
6978                              "### Saw unterminated backtick string\n");
6979         } );
6980         if (PL_expect == XOPERATOR)
6981             no_op("Backticks",s);
6982         if (!s)
6983             missingterm(NULL, 0);
6984         pl_yylval.ival = OP_BACKTICK;
6985         TERM(sublex_start());
6986
6987     case '\\':
6988         s++;
6989         if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6990          && isDIGIT(*s))
6991             Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),"Can't use \\%c to mean $%c in expression",
6992                            *s, *s);
6993         if (PL_expect == XOPERATOR)
6994             no_op("Backslash",s);
6995         OPERATOR(REFGEN);
6996
6997     case 'v':
6998         if (isDIGIT(s[1]) && PL_expect != XOPERATOR) {
6999             char *start = s + 2;
7000             while (isDIGIT(*start) || *start == '_')
7001                 start++;
7002             if (*start == '.' && isDIGIT(start[1])) {
7003                 s = scan_num(s, &pl_yylval);
7004                 TERM(THING);
7005             }
7006             else if ((*start == ':' && start[1] == ':')
7007                   || (PL_expect == XSTATE && *start == ':'))
7008                 goto keylookup;
7009             else if (PL_expect == XSTATE) {
7010                 d = start;
7011                 while (d < PL_bufend && isSPACE(*d)) d++;
7012                 if (*d == ':') goto keylookup;
7013             }
7014             /* avoid v123abc() or $h{v1}, allow C<print v10;> */
7015             if (!isALPHA(*start) && (PL_expect == XTERM
7016                         || PL_expect == XREF || PL_expect == XSTATE
7017                         || PL_expect == XTERMORDORDOR)) {
7018                 GV *const gv = gv_fetchpvn_flags(s, start - s,
7019                                                     UTF ? SVf_UTF8 : 0, SVt_PVCV);
7020                 if (!gv) {
7021                     s = scan_num(s, &pl_yylval);
7022                     TERM(THING);
7023                 }
7024             }
7025         }
7026         goto keylookup;
7027     case 'x':
7028         if (isDIGIT(s[1]) && PL_expect == XOPERATOR) {
7029             s++;
7030             Mop(OP_REPEAT);
7031         }
7032         goto keylookup;
7033
7034     case '_':
7035     case 'a': case 'A':
7036     case 'b': case 'B':
7037     case 'c': case 'C':
7038     case 'd': case 'D':
7039     case 'e': case 'E':
7040     case 'f': case 'F':
7041     case 'g': case 'G':
7042     case 'h': case 'H':
7043     case 'i': case 'I':
7044     case 'j': case 'J':
7045     case 'k': case 'K':
7046     case 'l': case 'L':
7047     case 'm': case 'M':
7048     case 'n': case 'N':
7049     case 'o': case 'O':
7050     case 'p': case 'P':
7051     case 'q': case 'Q':
7052     case 'r': case 'R':
7053     case 's': case 'S':
7054     case 't': case 'T':
7055     case 'u': case 'U':
7056               case 'V':
7057     case 'w': case 'W':
7058               case 'X':
7059     case 'y': case 'Y':
7060     case 'z': case 'Z':
7061
7062       keylookup: {
7063         bool anydelim;
7064         bool lex;
7065         I32 tmp;
7066         SV *sv;
7067         CV *cv;
7068         PADOFFSET off;
7069         OP *rv2cv_op;
7070
7071         lex = FALSE;
7072         orig_keyword = 0;
7073         off = 0;
7074         sv = NULL;
7075         cv = NULL;
7076         gv = NULL;
7077         gvp = NULL;
7078         rv2cv_op = NULL;
7079
7080         PL_bufptr = s;
7081         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
7082
7083         /* Some keywords can be followed by any delimiter, including ':' */
7084         anydelim = word_takes_any_delimiter(PL_tokenbuf, len);
7085
7086         /* x::* is just a word, unless x is "CORE" */
7087         if (!anydelim && *s == ':' && s[1] == ':') {
7088             if (memEQs(PL_tokenbuf, len, "CORE")) goto case_KEY_CORE;
7089             goto just_a_word;
7090         }
7091
7092         d = s;
7093         while (d < PL_bufend && isSPACE(*d))
7094                 d++;    /* no comments skipped here, or s### is misparsed */
7095
7096         /* Is this a word before a => operator? */
7097         if (*d == '=' && d[1] == '>') {
7098           fat_arrow:
7099             CLINE;
7100             pl_yylval.opval
7101                 = newSVOP(OP_CONST, 0,
7102                                S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
7103             pl_yylval.opval->op_private = OPpCONST_BARE;
7104             TERM(BAREWORD);
7105         }
7106
7107         /* Check for plugged-in keyword */
7108         {
7109             OP *o;
7110             int result;
7111             char *saved_bufptr = PL_bufptr;
7112             PL_bufptr = s;
7113             result = PL_keyword_plugin(aTHX_ PL_tokenbuf, len, &o);
7114             s = PL_bufptr;
7115             if (result == KEYWORD_PLUGIN_DECLINE) {
7116                 /* not a plugged-in keyword */
7117                 PL_bufptr = saved_bufptr;
7118             } else if (result == KEYWORD_PLUGIN_STMT) {
7119                 pl_yylval.opval = o;
7120                 CLINE;
7121                 if (!PL_nexttoke) PL_expect = XSTATE;
7122                 return REPORT(PLUGSTMT);
7123             } else if (result == KEYWORD_PLUGIN_EXPR) {
7124                 pl_yylval.opval = o;
7125                 CLINE;
7126                 if (!PL_nexttoke) PL_expect = XOPERATOR;
7127                 return REPORT(PLUGEXPR);
7128             } else {
7129                 Perl_croak(aTHX_ "Bad plugin affecting keyword '%s'",
7130                                         PL_tokenbuf);
7131             }
7132         }
7133
7134         /* Check for built-in keyword */
7135         tmp = keyword(PL_tokenbuf, len, 0);
7136
7137         /* Is this a label? */
7138         if (!anydelim && PL_expect == XSTATE
7139               && d < PL_bufend && *d == ':' && *(d + 1) != ':') {
7140             s = d + 1;
7141             pl_yylval.pval = savepvn(PL_tokenbuf, len+1);
7142             pl_yylval.pval[len] = '\0';
7143             pl_yylval.pval[len+1] = UTF ? 1 : 0;
7144             CLINE;
7145             TOKEN(LABEL);
7146         }
7147
7148         /* Check for lexical sub */
7149         if (PL_expect != XOPERATOR) {
7150             char tmpbuf[sizeof PL_tokenbuf + 1];
7151             *tmpbuf = '&';
7152             Copy(PL_tokenbuf, tmpbuf+1, len, char);
7153             off = pad_findmy_pvn(tmpbuf, len+1, 0);
7154             if (off != NOT_IN_PAD) {
7155                 assert(off); /* we assume this is boolean-true below */
7156                 if (PAD_COMPNAME_FLAGS_isOUR(off)) {
7157                     HV *  const stash = PAD_COMPNAME_OURSTASH(off);
7158                     HEK * const stashname = HvNAME_HEK(stash);
7159                     sv = newSVhek(stashname);
7160                     sv_catpvs(sv, "::");
7161                     sv_catpvn_flags(sv, PL_tokenbuf, len,
7162                                     (UTF ? SV_CATUTF8 : SV_CATBYTES));
7163                     gv = gv_fetchsv(sv, GV_NOADD_NOINIT | SvUTF8(sv),
7164                                     SVt_PVCV);
7165                     off = 0;
7166                     if (!gv) {
7167                         sv_free(sv);
7168                         sv = NULL;
7169                         goto just_a_word;
7170                     }
7171                 }
7172                 else {
7173                     rv2cv_op = newOP(OP_PADANY, 0);
7174                     rv2cv_op->op_targ = off;
7175                     cv = find_lexical_cv(off);
7176                 }
7177                 lex = TRUE;
7178                 goto just_a_word;
7179             }
7180             off = 0;
7181         }
7182
7183         if (tmp < 0) {                  /* second-class keyword? */
7184             GV *ogv = NULL;     /* override (winner) */
7185             GV *hgv = NULL;     /* hidden (loser) */
7186             if (PL_expect != XOPERATOR && (*s != ':' || s[1] != ':')) {
7187                 CV *cv;
7188                 if ((gv = gv_fetchpvn_flags(PL_tokenbuf, len,
7189                                             (UTF ? SVf_UTF8 : 0)|GV_NOTQUAL,
7190                                             SVt_PVCV))
7191                     && (cv = GvCVu(gv)))
7192                 {
7193                     if (GvIMPORTED_CV(gv))
7194                         ogv = gv;
7195                     else if (! CvMETHOD(cv))
7196                         hgv = gv;
7197                 }
7198                 if (!ogv
7199                     && (gvp = (GV**)hv_fetch(PL_globalstash, PL_tokenbuf,
7200                                                               len, FALSE))
7201                     && (gv = *gvp)
7202                     && (isGV_with_GP(gv)
7203                         ? GvCVu(gv) && GvIMPORTED_CV(gv)
7204                         :   SvPCS_IMPORTED(gv)
7205                         && (gv_init(gv, PL_globalstash, PL_tokenbuf,
7206                                                                  len, 0), 1)))
7207                 {
7208                     ogv = gv;
7209                 }
7210             }
7211             if (ogv) {
7212                 orig_keyword = tmp;
7213                 tmp = 0;                /* overridden by import or by GLOBAL */
7214             }
7215             else if (gv && !gvp
7216                      && -tmp==KEY_lock  /* XXX generalizable kludge */
7217                      && GvCVu(gv))
7218             {
7219                 tmp = 0;                /* any sub overrides "weak" keyword */
7220             }
7221             else {                      /* no override */
7222                 tmp = -tmp;
7223                 if (tmp == KEY_dump) {
7224                     Perl_ck_warner_d(aTHX_ packWARN2(WARN_MISC,WARN_DEPRECATED),
7225                                      "dump() better written as CORE::dump(). "
7226                                      "dump() will no longer be available "
7227                                      "in Perl 5.30");
7228                 }
7229                 gv = NULL;
7230                 gvp = 0;
7231                 if (hgv && tmp != KEY_x)        /* never ambiguous */
7232                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
7233                                    "Ambiguous call resolved as CORE::%s(), "
7234                                    "qualify as such or use &",
7235                                    GvENAME(hgv));
7236             }
7237         }
7238
7239         if (tmp && tmp != KEY___DATA__ && tmp != KEY___END__
7240          && (!anydelim || *s != '#')) {
7241             /* no override, and not s### either; skipspace is safe here
7242              * check for => on following line */
7243             bool arrow;
7244             STRLEN bufoff = PL_bufptr - SvPVX(PL_linestr);
7245             STRLEN   soff = s         - SvPVX(PL_linestr);
7246             s = peekspace(s);
7247             arrow = *s == '=' && s[1] == '>';
7248             PL_bufptr = SvPVX(PL_linestr) + bufoff;
7249             s         = SvPVX(PL_linestr) +   soff;
7250             if (arrow)
7251                 goto fat_arrow;
7252         }
7253
7254       reserved_word:
7255         switch (tmp) {
7256
7257             /* Trade off - by using this evil construction we can pull the
7258                variable gv into the block labelled keylookup. If not, then
7259                we have to give it function scope so that the goto from the
7260                earlier ':' case doesn't bypass the initialisation.  */
7261             just_a_word_zero_gv:
7262                 sv = NULL;
7263                 cv = NULL;
7264                 gv = NULL;
7265                 gvp = NULL;
7266                 rv2cv_op = NULL;
7267                 orig_keyword = 0;
7268                 lex = 0;
7269                 off = 0;
7270             /* FALLTHROUGH */
7271         default:                        /* not a keyword */
7272           just_a_word: {
7273                 int pkgname = 0;
7274                 const char lastchar = (PL_bufptr == PL_oldoldbufptr ? 0 : PL_bufptr[-1]);
7275                 bool safebw;
7276
7277
7278                 /* Get the rest if it looks like a package qualifier */
7279
7280                 if (*s == '\'' || (*s == ':' && s[1] == ':')) {
7281                     STRLEN morelen;
7282                     s = scan_word(s, PL_tokenbuf + len, sizeof PL_tokenbuf - len,
7283                                   TRUE, &morelen);
7284                     if (!morelen)
7285                         Perl_croak(aTHX_ "Bad name after %" UTF8f "%s",
7286                                 UTF8fARG(UTF, len, PL_tokenbuf),
7287                                 *s == '\'' ? "'" : "::");
7288                     len += morelen;
7289                     pkgname = 1;
7290                 }
7291
7292                 if (PL_expect == XOPERATOR) {
7293                     if (PL_bufptr == PL_linestart) {
7294                         CopLINE_dec(PL_curcop);
7295                         Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
7296                         CopLINE_inc(PL_curcop);
7297                     }
7298                     else
7299                         no_op("Bareword",s);
7300                 }
7301
7302                 /* See if the name is "Foo::",
7303                    in which case Foo is a bareword
7304                    (and a package name). */
7305
7306                 if (len > 2
7307                     && PL_tokenbuf[len - 2] == ':'
7308                     && PL_tokenbuf[len - 1] == ':')
7309                 {
7310                     if (ckWARN(WARN_BAREWORD)
7311                         && ! gv_fetchpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0, SVt_PVHV))
7312                         Perl_warner(aTHX_ packWARN(WARN_BAREWORD),
7313                                     "Bareword \"%" UTF8f
7314                                     "\" refers to nonexistent package",
7315                                     UTF8fARG(UTF, len, PL_tokenbuf));
7316                     len -= 2;
7317                     PL_tokenbuf[len] = '\0';
7318                     gv = NULL;
7319                     gvp = 0;
7320                     safebw = TRUE;
7321                 }
7322                 else {
7323                     safebw = FALSE;
7324                 }
7325
7326                 /* if we saw a global override before, get the right name */
7327
7328                 if (!sv)
7329                   sv = S_newSV_maybe_utf8(aTHX_ PL_tokenbuf,
7330                                                 len);
7331                 if (gvp) {
7332                     SV * const tmp_sv = sv;
7333                     sv = newSVpvs("CORE::GLOBAL::");
7334                     sv_catsv(sv, tmp_sv);
7335                     SvREFCNT_dec(tmp_sv);
7336                 }
7337
7338
7339                 /* Presume this is going to be a bareword of some sort. */
7340                 CLINE;
7341                 pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
7342                 pl_yylval.opval->op_private = OPpCONST_BARE;
7343
7344                 /* And if "Foo::", then that's what it certainly is. */
7345                 if (safebw)
7346                     goto safe_bareword;
7347
7348                 if (!off)
7349                 {
7350                     OP *const_op = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(sv));
7351                     const_op->op_private = OPpCONST_BARE;
7352                     rv2cv_op =
7353                         newCVREF(OPpMAY_RETURN_CONSTANT<<8, const_op);
7354                     cv = lex
7355                         ? isGV(gv)
7356                             ? GvCV(gv)
7357                             : SvROK(gv) && SvTYPE(SvRV(gv)) == SVt_PVCV
7358                                 ? (CV *)SvRV(gv)
7359                                 : ((CV *)gv)
7360                         : rv2cv_op_cv(rv2cv_op, RV2CVOPCV_RETURN_STUB);
7361                 }
7362
7363                 /* Use this var to track whether intuit_method has been
7364                    called.  intuit_method returns 0 or > 255.  */
7365                 tmp = 1;
7366
7367                 /* See if it's the indirect object for a list operator. */
7368
7369                 if (PL_oldoldbufptr
7370                     && PL_oldoldbufptr < PL_bufptr
7371                     && (PL_oldoldbufptr == PL_last_lop
7372                         || PL_oldoldbufptr == PL_last_uni)
7373                     && /* NO SKIPSPACE BEFORE HERE! */
7374                        (PL_expect == XREF
7375                         || ((PL_opargs[PL_last_lop_op] >> OASHIFT)& 7)
7376                                                                == OA_FILEREF))
7377                 {
7378                     bool immediate_paren = *s == '(';
7379                     SSize_t s_off;
7380
7381                     /* (Now we can afford to cross potential line boundary.) */
7382                     s = skipspace(s);
7383
7384                     /* intuit_method() can indirectly call lex_next_chunk(),
7385                      * invalidating s
7386                      */
7387                     s_off = s - SvPVX(PL_linestr);
7388                     /* Two barewords in a row may indicate method call. */
7389                     if (   (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
7390                             || *s == '$')
7391                         && (tmp = intuit_method(s, lex ? NULL : sv, cv)))
7392                     {
7393                         /* the code at method: doesn't use s */
7394                         goto method;
7395                     }
7396                     s = SvPVX(PL_linestr) + s_off;
7397
7398                     /* If not a declared subroutine, it's an indirect object. */
7399                     /* (But it's an indir obj regardless for sort.) */
7400                     /* Also, if "_" follows a filetest operator, it's a bareword */
7401
7402                     if (
7403                         ( !immediate_paren && (PL_last_lop_op == OP_SORT
7404                          || (!cv
7405                              && (PL_last_lop_op != OP_MAPSTART
7406                                  && PL_last_lop_op != OP_GREPSTART))))
7407                        || (PL_tokenbuf[0] == '_' && PL_tokenbuf[1] == '\0'
7408                             && ((PL_opargs[PL_last_lop_op] & OA_CLASS_MASK)
7409                                                             == OA_FILESTATOP))
7410                        )
7411                     {
7412                         PL_expect = (PL_last_lop == PL_oldoldbufptr) ? XTERM : XOPERATOR;
7413                         goto bareword;
7414                     }
7415                 }
7416
7417                 PL_expect = XOPERATOR;
7418                 s = skipspace(s);
7419
7420                 /* Is this a word before a => operator? */
7421                 if (*s == '=' && s[1] == '>' && !pkgname) {
7422                     op_free(rv2cv_op);
7423                     CLINE;
7424                     if (gvp || (lex && !off)) {
7425                         assert (cSVOPx(pl_yylval.opval)->op_sv == sv);
7426                         /* This is our own scalar, created a few lines
7427                            above, so this is safe. */
7428                         SvREADONLY_off(sv);
7429                         sv_setpv(sv, PL_tokenbuf);
7430                         if (UTF && !IN_BYTES
7431                          && is_utf8_string((U8*)PL_tokenbuf, len))
7432                               SvUTF8_on(sv);
7433                         SvREADONLY_on(sv);
7434                     }
7435                     TERM(BAREWORD);
7436                 }
7437
7438                 /* If followed by a paren, it's certainly a subroutine. */
7439                 if (*s == '(') {
7440                     CLINE;
7441                     if (cv) {
7442                         d = s + 1;
7443                         while (SPACE_OR_TAB(*d))
7444                             d++;
7445                         if (*d == ')' && (sv = cv_const_sv_or_av(cv))) {
7446                             s = d + 1;
7447                             goto its_constant;
7448                         }
7449                     }
7450                     NEXTVAL_NEXTTOKE.opval =
7451                         off ? rv2cv_op : pl_yylval.opval;
7452                     if (off)
7453                          op_free(pl_yylval.opval), force_next(PRIVATEREF);
7454                     else op_free(rv2cv_op),        force_next(BAREWORD);
7455                     pl_yylval.ival = 0;
7456                     TOKEN('&');
7457                 }
7458
7459                 /* If followed by var or block, call it a method (unless sub) */
7460
7461                 if ((*s == '$' || *s == '{') && !cv) {
7462                     op_free(rv2cv_op);
7463                     PL_last_lop = PL_oldbufptr;
7464                     PL_last_lop_op = OP_METHOD;
7465                     if (!PL_lex_allbrackets
7466                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7467                     {
7468                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7469                     }
7470                     PL_expect = XBLOCKTERM;
7471                     PL_bufptr = s;
7472                     return REPORT(METHOD);
7473                 }
7474
7475                 /* If followed by a bareword, see if it looks like indir obj. */
7476
7477                 if (   tmp == 1
7478                     && !orig_keyword
7479                     && (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF) || *s == '$')
7480                     && (tmp = intuit_method(s, lex ? NULL : sv, cv)))
7481                 {
7482                   method:
7483                     if (lex && !off) {
7484                         assert(cSVOPx(pl_yylval.opval)->op_sv == sv);
7485                         SvREADONLY_off(sv);
7486                         sv_setpvn(sv, PL_tokenbuf, len);
7487                         if (UTF && !IN_BYTES
7488                          && is_utf8_string((U8*)PL_tokenbuf, len))
7489                             SvUTF8_on (sv);
7490                         else SvUTF8_off(sv);
7491                     }
7492                     op_free(rv2cv_op);
7493                     if (tmp == METHOD && !PL_lex_allbrackets
7494                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7495                     {
7496                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7497                     }
7498                     return REPORT(tmp);
7499                 }
7500
7501                 /* Not a method, so call it a subroutine (if defined) */
7502
7503                 if (cv) {
7504                     /* Check for a constant sub */
7505                     if ((sv = cv_const_sv_or_av(cv))) {
7506                   its_constant:
7507                         op_free(rv2cv_op);
7508                         SvREFCNT_dec(((SVOP*)pl_yylval.opval)->op_sv);
7509                         ((SVOP*)pl_yylval.opval)->op_sv = SvREFCNT_inc_simple(sv);
7510                         if (SvTYPE(sv) == SVt_PVAV)
7511                             pl_yylval.opval = newUNOP(OP_RV2AV, OPf_PARENS,
7512                                                       pl_yylval.opval);
7513                         else {
7514                             pl_yylval.opval->op_private = 0;
7515                             pl_yylval.opval->op_folded = 1;
7516                             pl_yylval.opval->op_flags |= OPf_SPECIAL;
7517                         }
7518                         TOKEN(BAREWORD);
7519                     }
7520
7521                     op_free(pl_yylval.opval);
7522                     pl_yylval.opval =
7523                         off ? newCVREF(0, rv2cv_op) : rv2cv_op;
7524                     pl_yylval.opval->op_private |= OPpENTERSUB_NOPAREN;
7525                     PL_last_lop = PL_oldbufptr;
7526                     PL_last_lop_op = OP_ENTERSUB;
7527                     /* Is there a prototype? */
7528                     if (
7529                         SvPOK(cv))
7530                     {
7531                         STRLEN protolen = CvPROTOLEN(cv);
7532                         const char *proto = CvPROTO(cv);
7533                         bool optional;
7534                         proto = S_strip_spaces(aTHX_ proto, &protolen);
7535                         if (!protolen)
7536                             TERM(FUNC0SUB);
7537                         if ((optional = *proto == ';'))
7538                           do
7539                             proto++;
7540                           while (*proto == ';');
7541                         if (
7542                             (
7543                                 (
7544                                     *proto == '$' || *proto == '_'
7545                                  || *proto == '*' || *proto == '+'
7546                                 )
7547                              && proto[1] == '\0'
7548                             )
7549                          || (
7550                              *proto == '\\' && proto[1] && proto[2] == '\0'
7551                             )
7552                         )
7553                             UNIPROTO(UNIOPSUB,optional);
7554                         if (*proto == '\\' && proto[1] == '[') {
7555                             const char *p = proto + 2;
7556                             while(*p && *p != ']')
7557                                 ++p;
7558                             if(*p == ']' && !p[1])
7559                                 UNIPROTO(UNIOPSUB,optional);
7560                         }
7561                         if (*proto == '&' && *s == '{') {
7562                             if (PL_curstash)
7563                                 sv_setpvs(PL_subname, "__ANON__");
7564                             else
7565                                 sv_setpvs(PL_subname, "__ANON__::__ANON__");
7566                             if (!PL_lex_allbrackets
7567                                 && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7568                             {
7569                                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7570                             }
7571                             PREBLOCK(LSTOPSUB);
7572                         }
7573                     }
7574                     NEXTVAL_NEXTTOKE.opval = pl_yylval.opval;
7575                     PL_expect = XTERM;
7576                     force_next(off ? PRIVATEREF : BAREWORD);
7577                     if (!PL_lex_allbrackets
7578                         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7579                     {
7580                         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7581                     }
7582                     TOKEN(NOAMP);
7583                 }
7584
7585                 /* Call it a bare word */
7586
7587                 if (PL_hints & HINT_STRICT_SUBS)
7588                     pl_yylval.opval->op_private |= OPpCONST_STRICT;
7589                 else {
7590                 bareword:
7591                     /* after "print" and similar functions (corresponding to
7592                      * "F? L" in opcode.pl), whatever wasn't already parsed as
7593                      * a filehandle should be subject to "strict subs".
7594                      * Likewise for the optional indirect-object argument to system
7595                      * or exec, which can't be a bareword */
7596                     if ((PL_last_lop_op == OP_PRINT
7597                             || PL_last_lop_op == OP_PRTF
7598                             || PL_last_lop_op == OP_SAY
7599                             || PL_last_lop_op == OP_SYSTEM
7600                             || PL_last_lop_op == OP_EXEC)
7601                             && (PL_hints & HINT_STRICT_SUBS))
7602                         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7603                     if (lastchar != '-') {
7604                         if (ckWARN(WARN_RESERVED)) {
7605                             d = PL_tokenbuf;
7606                             while (isLOWER(*d))
7607                                 d++;
7608                             if (!*d && !gv_stashpv(PL_tokenbuf, UTF ? SVf_UTF8 : 0))
7609                             {
7610                                 /* PL_warn_reserved is constant */
7611                                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
7612                                 Perl_warner(aTHX_ packWARN(WARN_RESERVED), PL_warn_reserved,
7613                                        PL_tokenbuf);
7614                                 GCC_DIAG_RESTORE;
7615                             }
7616                         }
7617                     }
7618                 }
7619                 op_free(rv2cv_op);
7620
7621             safe_bareword:
7622                 if ((lastchar == '*' || lastchar == '%' || lastchar == '&')
7623                  && saw_infix_sigil) {
7624                     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7625                                      "Operator or semicolon missing before %c%" UTF8f,
7626                                      lastchar,
7627                                      UTF8fARG(UTF, strlen(PL_tokenbuf),
7628                                               PL_tokenbuf));
7629                     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7630                                      "Ambiguous use of %c resolved as operator %c",
7631                                      lastchar, lastchar);
7632                 }
7633                 TOKEN(BAREWORD);
7634             }
7635
7636         case KEY___FILE__:
7637             FUN0OP(
7638                 newSVOP(OP_CONST, 0, newSVpv(CopFILE(PL_curcop),0))
7639             );
7640
7641         case KEY___LINE__:
7642             FUN0OP(
7643                 newSVOP(OP_CONST, 0,
7644                     Perl_newSVpvf(aTHX_ "%" IVdf, (IV)CopLINE(PL_curcop)))
7645             );
7646
7647         case KEY___PACKAGE__:
7648             FUN0OP(
7649                 newSVOP(OP_CONST, 0,
7650                                         (PL_curstash
7651                                          ? newSVhek(HvNAME_HEK(PL_curstash))
7652                                          : &PL_sv_undef))
7653             );
7654
7655         case KEY___DATA__:
7656         case KEY___END__: {
7657             GV *gv;
7658             if (PL_rsfp && (!PL_in_eval || PL_tokenbuf[2] == 'D')) {
7659                 HV * const stash = PL_tokenbuf[2] == 'D' && PL_curstash
7660                                         ? PL_curstash
7661                                         : PL_defstash;
7662                 gv = (GV *)*hv_fetchs(stash, "DATA", 1);
7663                 if (!isGV(gv))
7664                     gv_init(gv,stash,"DATA",4,0);
7665                 GvMULTI_on(gv);
7666                 if (!GvIO(gv))
7667                     GvIOp(gv) = newIO();
7668                 IoIFP(GvIOp(gv)) = PL_rsfp;
7669 #if defined(HAS_FCNTL) && defined(F_SETFD) && defined(FD_CLOEXEC)
7670                 {
7671                     const int fd = PerlIO_fileno(PL_rsfp);
7672                     if (fd >= 3) {
7673                         fcntl(fd,F_SETFD, FD_CLOEXEC);
7674                     }
7675                 }
7676 #endif
7677                 /* Mark this internal pseudo-handle as clean */
7678                 IoFLAGS(GvIOp(gv)) |= IOf_UNTAINT;
7679                 if ((PerlIO*)PL_rsfp == PerlIO_stdin())
7680                     IoTYPE(GvIOp(gv)) = IoTYPE_STD;
7681                 else
7682                     IoTYPE(GvIOp(gv)) = IoTYPE_RDONLY;
7683 #if defined(WIN32) && !defined(PERL_TEXTMODE_SCRIPTS)
7684                 /* if the script was opened in binmode, we need to revert
7685                  * it to text mode for compatibility; but only iff it has CRs
7686                  * XXX this is a questionable hack at best. */
7687                 if (PL_bufend-PL_bufptr > 2
7688                     && PL_bufend[-1] == '\n' && PL_bufend[-2] == '\r')
7689                 {
7690                     Off_t loc = 0;
7691                     if (IoTYPE(GvIOp(gv)) == IoTYPE_RDONLY) {
7692                         loc = PerlIO_tell(PL_rsfp);
7693                         (void)PerlIO_seek(PL_rsfp, 0L, 0);
7694                     }
7695 #ifdef NETWARE
7696                         if (PerlLIO_setmode(PL_rsfp, O_TEXT) != -1) {
7697 #else
7698                     if (PerlLIO_setmode(PerlIO_fileno(PL_rsfp), O_TEXT) != -1) {
7699 #endif  /* NETWARE */
7700                         if (loc > 0)
7701                             PerlIO_seek(PL_rsfp, loc, 0);
7702                     }
7703                 }
7704 #endif
7705 #ifdef PERLIO_LAYERS
7706                 if (!IN_BYTES) {
7707                     if (UTF)
7708                         PerlIO_apply_layers(aTHX_ PL_rsfp, NULL, ":utf8");
7709                 }
7710 #endif
7711                 PL_rsfp = NULL;
7712             }
7713             goto fake_eof;
7714         }
7715
7716         case KEY___SUB__:
7717             FUN0OP(CvCLONE(PL_compcv)
7718                         ? newOP(OP_RUNCV, 0)
7719                         : newPVOP(OP_RUNCV,0,NULL));
7720
7721         case KEY_AUTOLOAD:
7722         case KEY_DESTROY:
7723         case KEY_BEGIN:
7724         case KEY_UNITCHECK:
7725         case KEY_CHECK:
7726         case KEY_INIT:
7727         case KEY_END:
7728             if (PL_expect == XSTATE) {
7729                 s = PL_bufptr;
7730                 goto really_sub;
7731             }
7732             goto just_a_word;
7733
7734         case_KEY_CORE:
7735             {
7736                 STRLEN olen = len;
7737                 d = s;
7738                 s += 2;
7739                 s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
7740                 if ((*s == ':' && s[1] == ':')
7741                  || (!(tmp = keyword(PL_tokenbuf, len, 1)) && *s == '\''))
7742                 {
7743                     s = d;
7744                     len = olen;
7745                     Copy(PL_bufptr, PL_tokenbuf, olen, char);
7746                     goto just_a_word;
7747                 }
7748                 if (!tmp)
7749                     Perl_croak(aTHX_ "CORE::%" UTF8f " is not a keyword",
7750                                       UTF8fARG(UTF, len, PL_tokenbuf));
7751                 if (tmp < 0)
7752                     tmp = -tmp;
7753                 else if (tmp == KEY_require || tmp == KEY_do
7754                       || tmp == KEY_glob)
7755                     /* that's a way to remember we saw "CORE::" */
7756                     orig_keyword = tmp;
7757                 goto reserved_word;
7758             }
7759
7760         case KEY_abs:
7761             UNI(OP_ABS);
7762
7763         case KEY_alarm:
7764             UNI(OP_ALARM);
7765
7766         case KEY_accept:
7767             LOP(OP_ACCEPT,XTERM);
7768
7769         case KEY_and:
7770             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7771                 return REPORT(0);
7772             OPERATOR(ANDOP);
7773
7774         case KEY_atan2:
7775             LOP(OP_ATAN2,XTERM);
7776
7777         case KEY_bind:
7778             LOP(OP_BIND,XTERM);
7779
7780         case KEY_binmode:
7781             LOP(OP_BINMODE,XTERM);
7782
7783         case KEY_bless:
7784             LOP(OP_BLESS,XTERM);
7785
7786         case KEY_break:
7787             FUN0(OP_BREAK);
7788
7789         case KEY_chop:
7790             UNI(OP_CHOP);
7791
7792         case KEY_continue:
7793                     /* We have to disambiguate the two senses of
7794                       "continue". If the next token is a '{' then
7795                       treat it as the start of a continue block;
7796                       otherwise treat it as a control operator.
7797                      */
7798                     s = skipspace(s);
7799                     if (*s == '{')
7800             PREBLOCK(CONTINUE);
7801                     else
7802                         FUN0(OP_CONTINUE);
7803
7804         case KEY_chdir:
7805             /* may use HOME */
7806             (void)gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV);
7807             UNI(OP_CHDIR);
7808
7809         case KEY_close:
7810             UNI(OP_CLOSE);
7811
7812         case KEY_closedir:
7813             UNI(OP_CLOSEDIR);
7814
7815         case KEY_cmp:
7816             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7817                 return REPORT(0);
7818             Eop(OP_SCMP);
7819
7820         case KEY_caller:
7821             UNI(OP_CALLER);
7822
7823         case KEY_crypt:
7824 #ifdef FCRYPT
7825             if (!PL_cryptseen) {
7826                 PL_cryptseen = TRUE;
7827                 init_des();
7828             }
7829 #endif
7830             LOP(OP_CRYPT,XTERM);
7831
7832         case KEY_chmod:
7833             LOP(OP_CHMOD,XTERM);
7834
7835         case KEY_chown:
7836             LOP(OP_CHOWN,XTERM);
7837
7838         case KEY_connect:
7839             LOP(OP_CONNECT,XTERM);
7840
7841         case KEY_chr:
7842             UNI(OP_CHR);
7843
7844         case KEY_cos:
7845             UNI(OP_COS);
7846
7847         case KEY_chroot:
7848             UNI(OP_CHROOT);
7849
7850         case KEY_default:
7851             PREBLOCK(DEFAULT);
7852
7853         case KEY_do:
7854             s = skipspace(s);
7855             if (*s == '{')
7856                 PRETERMBLOCK(DO);
7857             if (*s != '\'') {
7858                 *PL_tokenbuf = '&';
7859                 d = scan_word(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
7860                               1, &len);
7861                 if (len && memNEs(PL_tokenbuf+1, len, "CORE")
7862                  && !keyword(PL_tokenbuf + 1, len, 0)) {
7863                     SSize_t off = s-SvPVX(PL_linestr);
7864                     d = skipspace(d);
7865                     s = SvPVX(PL_linestr)+off;
7866                     if (*d == '(') {
7867                         force_ident_maybe_lex('&');
7868                         s = d;
7869                     }
7870                 }
7871             }
7872             if (orig_keyword == KEY_do) {
7873                 orig_keyword = 0;
7874                 pl_yylval.ival = 1;
7875             }
7876             else
7877                 pl_yylval.ival = 0;
7878             OPERATOR(DO);
7879
7880         case KEY_die:
7881             PL_hints |= HINT_BLOCK_SCOPE;
7882             LOP(OP_DIE,XTERM);
7883
7884         case KEY_defined:
7885             UNI(OP_DEFINED);
7886
7887         case KEY_delete:
7888             UNI(OP_DELETE);
7889
7890         case KEY_dbmopen:
7891             Perl_populate_isa(aTHX_ STR_WITH_LEN("AnyDBM_File::ISA"),
7892                               STR_WITH_LEN("NDBM_File::"),
7893                               STR_WITH_LEN("DB_File::"),
7894                               STR_WITH_LEN("GDBM_File::"),
7895                               STR_WITH_LEN("SDBM_File::"),
7896                               STR_WITH_LEN("ODBM_File::"),
7897                               NULL);
7898             LOP(OP_DBMOPEN,XTERM);
7899
7900         case KEY_dbmclose:
7901             UNI(OP_DBMCLOSE);
7902
7903         case KEY_dump:
7904             LOOPX(OP_DUMP);
7905
7906         case KEY_else:
7907             PREBLOCK(ELSE);
7908
7909         case KEY_elsif:
7910             pl_yylval.ival = CopLINE(PL_curcop);
7911             OPERATOR(ELSIF);
7912
7913         case KEY_eq:
7914             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7915                 return REPORT(0);
7916             Eop(OP_SEQ);
7917
7918         case KEY_exists:
7919             UNI(OP_EXISTS);
7920
7921         case KEY_exit:
7922             UNI(OP_EXIT);
7923
7924         case KEY_eval:
7925             s = skipspace(s);
7926             if (*s == '{') { /* block eval */
7927                 PL_expect = XTERMBLOCK;
7928                 UNIBRACK(OP_ENTERTRY);
7929             }
7930             else { /* string eval */
7931                 PL_expect = XTERM;
7932                 UNIBRACK(OP_ENTEREVAL);
7933             }
7934
7935         case KEY_evalbytes:
7936             PL_expect = XTERM;
7937             UNIBRACK(-OP_ENTEREVAL);
7938
7939         case KEY_eof:
7940             UNI(OP_EOF);
7941
7942         case KEY_exp:
7943             UNI(OP_EXP);
7944
7945         case KEY_each:
7946             UNI(OP_EACH);
7947
7948         case KEY_exec:
7949             LOP(OP_EXEC,XREF);
7950
7951         case KEY_endhostent:
7952             FUN0(OP_EHOSTENT);
7953
7954         case KEY_endnetent:
7955             FUN0(OP_ENETENT);
7956
7957         case KEY_endservent:
7958             FUN0(OP_ESERVENT);
7959
7960         case KEY_endprotoent:
7961             FUN0(OP_EPROTOENT);
7962
7963         case KEY_endpwent:
7964             FUN0(OP_EPWENT);
7965
7966         case KEY_endgrent:
7967             FUN0(OP_EGRENT);
7968
7969         case KEY_for:
7970         case KEY_foreach:
7971             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7972                 return REPORT(0);
7973             pl_yylval.ival = CopLINE(PL_curcop);
7974             s = skipspace(s);
7975             if (   PL_expect == XSTATE
7976                 && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
7977             {
7978                 char *p = s;
7979                 SSize_t s_off = s - SvPVX(PL_linestr);
7980
7981                 if (   memBEGINPs(p, (STRLEN) (PL_bufend - p), "my")
7982                     && isSPACE(*(p + 2)))
7983                 {
7984                     p += 2;
7985                 }
7986                 else if (   memBEGINPs(p, (STRLEN) (PL_bufend - p), "our")
7987                          && isSPACE(*(p + 3)))
7988                 {
7989                     p += 3;
7990                 }
7991
7992                 p = skipspace(p);
7993                 /* skip optional package name, as in "for my abc $x (..)" */
7994                 if (isIDFIRST_lazy_if_safe(p, PL_bufend, UTF)) {
7995                     p = scan_word(p, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
7996                     p = skipspace(p);
7997                 }
7998                 if (*p != '$' && *p != '\\')
7999                     Perl_croak(aTHX_ "Missing $ on loop variable");
8000
8001                 /* The buffer may have been reallocated, update s */
8002                 s = SvPVX(PL_linestr) + s_off;
8003             }
8004             OPERATOR(FOR);
8005
8006         case KEY_formline:
8007             LOP(OP_FORMLINE,XTERM);
8008
8009         case KEY_fork:
8010             FUN0(OP_FORK);
8011
8012         case KEY_fc:
8013             UNI(OP_FC);
8014
8015         case KEY_fcntl:
8016             LOP(OP_FCNTL,XTERM);
8017
8018         case KEY_fileno:
8019             UNI(OP_FILENO);
8020
8021         case KEY_flock:
8022             LOP(OP_FLOCK,XTERM);
8023
8024         case KEY_gt:
8025             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8026                 return REPORT(0);
8027             Rop(OP_SGT);
8028
8029         case KEY_ge:
8030             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8031                 return REPORT(0);
8032             Rop(OP_SGE);
8033
8034         case KEY_grep:
8035             LOP(OP_GREPSTART, XREF);
8036
8037         case KEY_goto:
8038             LOOPX(OP_GOTO);
8039
8040         case KEY_gmtime:
8041             UNI(OP_GMTIME);
8042
8043         case KEY_getc:
8044             UNIDOR(OP_GETC);
8045
8046         case KEY_getppid:
8047             FUN0(OP_GETPPID);
8048
8049         case KEY_getpgrp:
8050             UNI(OP_GETPGRP);
8051
8052         case KEY_getpriority:
8053             LOP(OP_GETPRIORITY,XTERM);
8054
8055         case KEY_getprotobyname:
8056             UNI(OP_GPBYNAME);
8057
8058         case KEY_getprotobynumber:
8059             LOP(OP_GPBYNUMBER,XTERM);
8060
8061         case KEY_getprotoent:
8062             FUN0(OP_GPROTOENT);
8063
8064         case KEY_getpwent:
8065             FUN0(OP_GPWENT);
8066
8067         case KEY_getpwnam:
8068             UNI(OP_GPWNAM);
8069
8070         case KEY_getpwuid:
8071             UNI(OP_GPWUID);
8072
8073         case KEY_getpeername:
8074             UNI(OP_GETPEERNAME);
8075
8076         case KEY_gethostbyname:
8077             UNI(OP_GHBYNAME);
8078
8079         case KEY_gethostbyaddr:
8080             LOP(OP_GHBYADDR,XTERM);
8081
8082         case KEY_gethostent:
8083             FUN0(OP_GHOSTENT);
8084
8085         case KEY_getnetbyname:
8086             UNI(OP_GNBYNAME);
8087
8088         case KEY_getnetbyaddr:
8089             LOP(OP_GNBYADDR,XTERM);
8090
8091         case KEY_getnetent:
8092             FUN0(OP_GNETENT);
8093
8094         case KEY_getservbyname:
8095             LOP(OP_GSBYNAME,XTERM);
8096
8097         case KEY_getservbyport:
8098             LOP(OP_GSBYPORT,XTERM);
8099
8100         case KEY_getservent:
8101             FUN0(OP_GSERVENT);
8102
8103         case KEY_getsockname:
8104             UNI(OP_GETSOCKNAME);
8105
8106         case KEY_getsockopt:
8107             LOP(OP_GSOCKOPT,XTERM);
8108
8109         case KEY_getgrent:
8110             FUN0(OP_GGRENT);
8111
8112         case KEY_getgrnam:
8113             UNI(OP_GGRNAM);
8114
8115         case KEY_getgrgid:
8116             UNI(OP_GGRGID);
8117
8118         case KEY_getlogin:
8119             FUN0(OP_GETLOGIN);
8120
8121         case KEY_given:
8122             pl_yylval.ival = CopLINE(PL_curcop);
8123             Perl_ck_warner_d(aTHX_
8124                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8125                 "given is experimental");
8126             OPERATOR(GIVEN);
8127
8128         case KEY_glob:
8129             LOP(
8130              orig_keyword==KEY_glob ? -OP_GLOB : OP_GLOB,
8131              XTERM
8132             );
8133
8134         case KEY_hex:
8135             UNI(OP_HEX);
8136
8137         case KEY_if:
8138             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8139                 return REPORT(0);
8140             pl_yylval.ival = CopLINE(PL_curcop);
8141             OPERATOR(IF);
8142
8143         case KEY_index:
8144             LOP(OP_INDEX,XTERM);
8145
8146         case KEY_int:
8147             UNI(OP_INT);
8148
8149         case KEY_ioctl:
8150             LOP(OP_IOCTL,XTERM);
8151
8152         case KEY_join:
8153             LOP(OP_JOIN,XTERM);
8154
8155         case KEY_keys:
8156             UNI(OP_KEYS);
8157
8158         case KEY_kill:
8159             LOP(OP_KILL,XTERM);
8160
8161         case KEY_last:
8162             LOOPX(OP_LAST);
8163
8164         case KEY_lc:
8165             UNI(OP_LC);
8166
8167         case KEY_lcfirst:
8168             UNI(OP_LCFIRST);
8169
8170         case KEY_local:
8171             OPERATOR(LOCAL);
8172
8173         case KEY_length:
8174             UNI(OP_LENGTH);
8175
8176         case KEY_lt:
8177             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8178                 return REPORT(0);
8179             Rop(OP_SLT);
8180
8181         case KEY_le:
8182             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8183                 return REPORT(0);
8184             Rop(OP_SLE);
8185
8186         case KEY_localtime:
8187             UNI(OP_LOCALTIME);
8188
8189         case KEY_log:
8190             UNI(OP_LOG);
8191
8192         case KEY_link:
8193             LOP(OP_LINK,XTERM);
8194
8195         case KEY_listen:
8196             LOP(OP_LISTEN,XTERM);
8197
8198         case KEY_lock:
8199             UNI(OP_LOCK);
8200
8201         case KEY_lstat:
8202             UNI(OP_LSTAT);
8203
8204         case KEY_m:
8205             s = scan_pat(s,OP_MATCH);
8206             TERM(sublex_start());
8207
8208         case KEY_map:
8209             LOP(OP_MAPSTART, XREF);
8210
8211         case KEY_mkdir:
8212             LOP(OP_MKDIR,XTERM);
8213
8214         case KEY_msgctl:
8215             LOP(OP_MSGCTL,XTERM);
8216
8217         case KEY_msgget:
8218             LOP(OP_MSGGET,XTERM);
8219
8220         case KEY_msgrcv:
8221             LOP(OP_MSGRCV,XTERM);
8222
8223         case KEY_msgsnd:
8224             LOP(OP_MSGSND,XTERM);
8225
8226         case KEY_our:
8227         case KEY_my:
8228         case KEY_state:
8229             if (PL_in_my) {
8230                 PL_bufptr = s;
8231                 yyerror(Perl_form(aTHX_
8232                                   "Can't redeclare \"%s\" in \"%s\"",
8233                                    tmp      == KEY_my    ? "my" :
8234                                    tmp      == KEY_state ? "state" : "our",
8235                                    PL_in_my == KEY_my    ? "my" :
8236                                    PL_in_my == KEY_state ? "state" : "our"));
8237             }
8238             PL_in_my = (U16)tmp;
8239             s = skipspace(s);
8240             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
8241                 s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
8242                 if (memEQs(PL_tokenbuf, len, "sub"))
8243                     goto really_sub;
8244                 PL_in_my_stash = find_in_my_stash(PL_tokenbuf, len);
8245                 if (!PL_in_my_stash) {
8246                     char tmpbuf[1024];
8247                     int len;
8248                     PL_bufptr = s;
8249                     len = my_snprintf(tmpbuf, sizeof(tmpbuf), "No such class %.1000s", PL_tokenbuf);
8250                     PERL_MY_SNPRINTF_POST_GUARD(len, sizeof(tmpbuf));
8251                     yyerror_pv(tmpbuf, UTF ? SVf_UTF8 : 0);
8252                 }
8253             }
8254             else if (*s == '\\') {
8255                 if (!FEATURE_MYREF_IS_ENABLED)
8256                     Perl_croak(aTHX_ "The experimental declared_refs "
8257                                      "feature is not enabled");
8258                 Perl_ck_warner_d(aTHX_
8259                      packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
8260                     "Declaring references is experimental");
8261             }
8262             OPERATOR(MY);
8263
8264         case KEY_next:
8265             LOOPX(OP_NEXT);
8266
8267         case KEY_ne:
8268             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8269                 return REPORT(0);
8270             Eop(OP_SNE);
8271
8272         case KEY_no:
8273             s = tokenize_use(0, s);
8274             TOKEN(USE);
8275
8276         case KEY_not:
8277             if (*s == '(' || (s = skipspace(s), *s == '('))
8278                 FUN1(OP_NOT);
8279             else {
8280                 if (!PL_lex_allbrackets
8281                     && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
8282                 {
8283                     PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
8284                 }
8285                 OPERATOR(NOTOP);
8286             }
8287
8288         case KEY_open:
8289             s = skipspace(s);
8290             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
8291                 const char *t;
8292                 d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE,
8293                               &len);
8294                 for (t=d; isSPACE(*t);)
8295                     t++;
8296                 if ( *t && strchr("|&*+-=!?:.", *t) && ckWARN_d(WARN_PRECEDENCE)
8297                     /* [perl #16184] */
8298                     && !(t[0] == '=' && t[1] == '>')
8299                     && !(t[0] == ':' && t[1] == ':')
8300                     && !keyword(s, d-s, 0)
8301                 ) {
8302                     Perl_warner(aTHX_ packWARN(WARN_PRECEDENCE),
8303                        "Precedence problem: open %" UTF8f " should be open(%" UTF8f ")",
8304                         UTF8fARG(UTF, d-s, s), UTF8fARG(UTF, d-s, s));
8305                 }
8306             }
8307             LOP(OP_OPEN,XTERM);
8308
8309         case KEY_or:
8310             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8311                 return REPORT(0);
8312             pl_yylval.ival = OP_OR;
8313             OPERATOR(OROP);
8314
8315         case KEY_ord:
8316             UNI(OP_ORD);
8317
8318         case KEY_oct:
8319             UNI(OP_OCT);
8320
8321         case KEY_opendir:
8322             LOP(OP_OPEN_DIR,XTERM);
8323
8324         case KEY_print:
8325             checkcomma(s,PL_tokenbuf,"filehandle");
8326             LOP(OP_PRINT,XREF);
8327
8328         case KEY_printf:
8329             checkcomma(s,PL_tokenbuf,"filehandle");
8330             LOP(OP_PRTF,XREF);
8331
8332         case KEY_prototype:
8333             UNI(OP_PROTOTYPE);
8334
8335         case KEY_push:
8336             LOP(OP_PUSH,XTERM);
8337
8338         case KEY_pop:
8339             UNIDOR(OP_POP);
8340
8341         case KEY_pos:
8342             UNIDOR(OP_POS);
8343
8344         case KEY_pack:
8345             LOP(OP_PACK,XTERM);
8346
8347         case KEY_package:
8348             s = force_word(s,BAREWORD,FALSE,TRUE);
8349             s = skipspace(s);
8350             s = force_strict_version(s);
8351             PREBLOCK(PACKAGE);
8352
8353         case KEY_pipe:
8354             LOP(OP_PIPE_OP,XTERM);
8355
8356         case KEY_q:
8357             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8358             if (!s)
8359                 missingterm(NULL, 0);
8360             COPLINE_SET_FROM_MULTI_END;
8361             pl_yylval.ival = OP_CONST;
8362             TERM(sublex_start());
8363
8364         case KEY_quotemeta:
8365             UNI(OP_QUOTEMETA);
8366
8367         case KEY_qw: {
8368             OP *words = NULL;
8369             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8370             if (!s)
8371                 missingterm(NULL, 0);
8372             COPLINE_SET_FROM_MULTI_END;
8373             PL_expect = XOPERATOR;
8374             if (SvCUR(PL_lex_stuff)) {
8375                 int warned_comma = !ckWARN(WARN_QW);
8376                 int warned_comment = warned_comma;
8377                 d = SvPV_force(PL_lex_stuff, len);
8378                 while (len) {
8379                     for (; isSPACE(*d) && len; --len, ++d)
8380                         /**/;
8381                     if (len) {
8382                         SV *sv;
8383                         const char *b = d;
8384                         if (!warned_comma || !warned_comment) {
8385                             for (; !isSPACE(*d) && len; --len, ++d) {
8386                                 if (!warned_comma && *d == ',') {
8387                                     Perl_warner(aTHX_ packWARN(WARN_QW),
8388                                         "Possible attempt to separate words with commas");
8389                                     ++warned_comma;
8390                                 }
8391                                 else if (!warned_comment && *d == '#') {
8392                                     Perl_warner(aTHX_ packWARN(WARN_QW),
8393                                         "Possible attempt to put comments in qw() list");
8394                                     ++warned_comment;
8395                                 }
8396                             }
8397                         }
8398                         else {
8399                             for (; !isSPACE(*d) && len; --len, ++d)
8400                                 /**/;
8401                         }
8402                         sv = newSVpvn_utf8(b, d-b, DO_UTF8(PL_lex_stuff));
8403                         words = op_append_elem(OP_LIST, words,
8404                                             newSVOP(OP_CONST, 0, tokeq(sv)));
8405                     }
8406                 }
8407             }
8408             if (!words)
8409                 words = newNULLLIST();
8410             SvREFCNT_dec_NN(PL_lex_stuff);
8411             PL_lex_stuff = NULL;
8412             PL_expect = XOPERATOR;
8413             pl_yylval.opval = sawparens(words);
8414             TOKEN(QWLIST);
8415         }
8416
8417         case KEY_qq:
8418             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8419             if (!s)
8420                 missingterm(NULL, 0);
8421             pl_yylval.ival = OP_STRINGIFY;
8422             if (SvIVX(PL_lex_stuff) == '\'')
8423                 SvIV_set(PL_lex_stuff, 0);      /* qq'$foo' should interpolate */
8424             TERM(sublex_start());
8425
8426         case KEY_qr:
8427             s = scan_pat(s,OP_QR);
8428             TERM(sublex_start());
8429
8430         case KEY_qx:
8431             s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8432             if (!s)
8433                 missingterm(NULL, 0);
8434             pl_yylval.ival = OP_BACKTICK;
8435             TERM(sublex_start());
8436
8437         case KEY_return:
8438             OLDLOP(OP_RETURN);
8439
8440         case KEY_require:
8441             s = skipspace(s);
8442             if (isDIGIT(*s)) {
8443                 s = force_version(s, FALSE);
8444             }
8445             else if (*s != 'v' || !isDIGIT(s[1])
8446                     || (s = force_version(s, TRUE), *s == 'v'))
8447             {
8448                 *PL_tokenbuf = '\0';
8449                 s = force_word(s,BAREWORD,TRUE,TRUE);
8450                 if (isIDFIRST_lazy_if_safe(PL_tokenbuf,
8451                                            PL_tokenbuf + sizeof(PL_tokenbuf),
8452                                            UTF))
8453                 {
8454                     gv_stashpvn(PL_tokenbuf, strlen(PL_tokenbuf),
8455                                 GV_ADD | (UTF ? SVf_UTF8 : 0));
8456                 }
8457                 else if (*s == '<')
8458                     yyerror("<> at require-statement should be quotes");
8459             }
8460             if (orig_keyword == KEY_require) {
8461                 orig_keyword = 0;
8462                 pl_yylval.ival = 1;
8463             }
8464             else
8465                 pl_yylval.ival = 0;
8466             PL_expect = PL_nexttoke ? XOPERATOR : XTERM;
8467             PL_bufptr = s;
8468             PL_last_uni = PL_oldbufptr;
8469             PL_last_lop_op = OP_REQUIRE;
8470             s = skipspace(s);
8471             return REPORT( (int)REQUIRE );
8472
8473         case KEY_reset:
8474             UNI(OP_RESET);
8475
8476         case KEY_redo:
8477             LOOPX(OP_REDO);
8478
8479         case KEY_rename:
8480             LOP(OP_RENAME,XTERM);
8481
8482         case KEY_rand:
8483             UNI(OP_RAND);
8484
8485         case KEY_rmdir:
8486             UNI(OP_RMDIR);
8487
8488         case KEY_rindex:
8489             LOP(OP_RINDEX,XTERM);
8490
8491         case KEY_read:
8492             LOP(OP_READ,XTERM);
8493
8494         case KEY_readdir:
8495             UNI(OP_READDIR);
8496
8497         case KEY_readline:
8498             UNIDOR(OP_READLINE);
8499
8500         case KEY_readpipe:
8501             UNIDOR(OP_BACKTICK);
8502
8503         case KEY_rewinddir:
8504             UNI(OP_REWINDDIR);
8505
8506         case KEY_recv:
8507             LOP(OP_RECV,XTERM);
8508
8509         case KEY_reverse:
8510             LOP(OP_REVERSE,XTERM);
8511
8512         case KEY_readlink:
8513             UNIDOR(OP_READLINK);
8514
8515         case KEY_ref:
8516             UNI(OP_REF);
8517
8518         case KEY_s:
8519             s = scan_subst(s);
8520             if (pl_yylval.opval)
8521                 TERM(sublex_start());
8522             else
8523                 TOKEN(1);       /* force error */
8524
8525         case KEY_say:
8526             checkcomma(s,PL_tokenbuf,"filehandle");
8527             LOP(OP_SAY,XREF);
8528
8529         case KEY_chomp:
8530             UNI(OP_CHOMP);
8531
8532         case KEY_scalar:
8533             UNI(OP_SCALAR);
8534
8535         case KEY_select:
8536             LOP(OP_SELECT,XTERM);
8537
8538         case KEY_seek:
8539             LOP(OP_SEEK,XTERM);
8540
8541         case KEY_semctl:
8542             LOP(OP_SEMCTL,XTERM);
8543
8544         case KEY_semget:
8545             LOP(OP_SEMGET,XTERM);
8546
8547         case KEY_semop:
8548             LOP(OP_SEMOP,XTERM);
8549
8550         case KEY_send:
8551             LOP(OP_SEND,XTERM);
8552
8553         case KEY_setpgrp:
8554             LOP(OP_SETPGRP,XTERM);
8555
8556         case KEY_setpriority:
8557             LOP(OP_SETPRIORITY,XTERM);
8558
8559         case KEY_sethostent:
8560             UNI(OP_SHOSTENT);
8561
8562         case KEY_setnetent:
8563             UNI(OP_SNETENT);
8564
8565         case KEY_setservent:
8566             UNI(OP_SSERVENT);
8567
8568         case KEY_setprotoent:
8569             UNI(OP_SPROTOENT);
8570
8571         case KEY_setpwent:
8572             FUN0(OP_SPWENT);
8573
8574         case KEY_setgrent:
8575             FUN0(OP_SGRENT);
8576
8577         case KEY_seekdir:
8578             LOP(OP_SEEKDIR,XTERM);
8579
8580         case KEY_setsockopt:
8581             LOP(OP_SSOCKOPT,XTERM);
8582
8583         case KEY_shift:
8584             UNIDOR(OP_SHIFT);
8585
8586         case KEY_shmctl:
8587             LOP(OP_SHMCTL,XTERM);
8588
8589         case KEY_shmget:
8590             LOP(OP_SHMGET,XTERM);
8591
8592         case KEY_shmread:
8593             LOP(OP_SHMREAD,XTERM);
8594
8595         case KEY_shmwrite:
8596             LOP(OP_SHMWRITE,XTERM);
8597
8598         case KEY_shutdown:
8599             LOP(OP_SHUTDOWN,XTERM);
8600
8601         case KEY_sin:
8602             UNI(OP_SIN);
8603
8604         case KEY_sleep:
8605             UNI(OP_SLEEP);
8606
8607         case KEY_socket:
8608             LOP(OP_SOCKET,XTERM);
8609
8610         case KEY_socketpair:
8611             LOP(OP_SOCKPAIR,XTERM);
8612
8613         case KEY_sort:
8614             checkcomma(s,PL_tokenbuf,"subroutine name");
8615             s = skipspace(s);
8616             PL_expect = XTERM;
8617             s = force_word(s,BAREWORD,TRUE,TRUE);
8618             LOP(OP_SORT,XREF);
8619
8620         case KEY_split:
8621             LOP(OP_SPLIT,XTERM);
8622
8623         case KEY_sprintf:
8624             LOP(OP_SPRINTF,XTERM);
8625
8626         case KEY_splice:
8627             LOP(OP_SPLICE,XTERM);
8628
8629         case KEY_sqrt:
8630             UNI(OP_SQRT);
8631
8632         case KEY_srand:
8633             UNI(OP_SRAND);
8634
8635         case KEY_stat:
8636             UNI(OP_STAT);
8637
8638         case KEY_study:
8639             UNI(OP_STUDY);
8640
8641         case KEY_substr:
8642             LOP(OP_SUBSTR,XTERM);
8643
8644         case KEY_format:
8645         case KEY_sub:
8646           really_sub:
8647             {
8648                 char * const tmpbuf = PL_tokenbuf + 1;
8649                 expectation attrful;
8650                 bool have_name, have_proto;
8651                 const int key = tmp;
8652                 SV *format_name = NULL;
8653
8654                 SSize_t off = s-SvPVX(PL_linestr);
8655                 s = skipspace(s);
8656                 d = SvPVX(PL_linestr)+off;
8657
8658                 if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
8659                     || *s == '\''
8660                     || (*s == ':' && s[1] == ':'))
8661                 {
8662
8663                     PL_expect = XBLOCK;
8664                     attrful = XATTRBLOCK;
8665                     d = scan_word(s, tmpbuf, sizeof PL_tokenbuf - 1, TRUE,
8666                                   &len);
8667                     if (key == KEY_format)
8668                         format_name = S_newSV_maybe_utf8(aTHX_ s, d - s);
8669                     *PL_tokenbuf = '&';
8670                     if (memchr(tmpbuf, ':', len) || key != KEY_sub
8671                      || pad_findmy_pvn(
8672                             PL_tokenbuf, len + 1, 0
8673                         ) != NOT_IN_PAD)
8674                         sv_setpvn(PL_subname, tmpbuf, len);
8675                     else {
8676                         sv_setsv(PL_subname,PL_curstname);
8677                         sv_catpvs(PL_subname,"::");
8678                         sv_catpvn(PL_subname,tmpbuf,len);
8679                     }
8680                     if (SvUTF8(PL_linestr))
8681                         SvUTF8_on(PL_subname);
8682                     have_name = TRUE;
8683
8684
8685                     s = skipspace(d);
8686                 }
8687                 else {
8688                     if (key == KEY_my || key == KEY_our || key==KEY_state)
8689                     {
8690                         *d = '\0';
8691                         /* diag_listed_as: Missing name in "%s sub" */
8692                         Perl_croak(aTHX_
8693                                   "Missing name in \"%s\"", PL_bufptr);
8694                     }
8695                     PL_expect = XTERMBLOCK;
8696                     attrful = XATTRTERM;
8697                     sv_setpvs(PL_subname,"?");
8698                     have_name = FALSE;
8699                 }
8700
8701                 if (key == KEY_format) {
8702                     if (format_name) {
8703                         NEXTVAL_NEXTTOKE.opval
8704                             = newSVOP(OP_CONST,0, format_name);
8705                         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
8706                         force_next(BAREWORD);
8707                     }
8708                     PREBLOCK(FORMAT);
8709                 }
8710
8711                 /* Look for a prototype */
8712                 if (*s == '(' && !FEATURE_SIGNATURES_IS_ENABLED) {
8713                     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8714                     COPLINE_SET_FROM_MULTI_END;
8715                     if (!s)
8716                         Perl_croak(aTHX_ "Prototype not terminated");
8717                     (void)validate_proto(PL_subname, PL_lex_stuff,
8718                                          ckWARN(WARN_ILLEGALPROTO), 0);
8719                     have_proto = TRUE;
8720
8721                     s = skipspace(s);
8722                 }
8723                 else
8724                     have_proto = FALSE;
8725
8726                 if (*s == ':' && s[1] != ':')
8727                     PL_expect = attrful;
8728                 else if ((*s != '{' && *s != '(') && key != KEY_format) {
8729                     assert(key == KEY_sub || key == KEY_AUTOLOAD ||
8730                            key == KEY_DESTROY || key == KEY_BEGIN ||
8731                            key == KEY_UNITCHECK || key == KEY_CHECK ||
8732                            key == KEY_INIT || key == KEY_END ||
8733                            key == KEY_my || key == KEY_state ||
8734                            key == KEY_our);
8735                     if (!have_name)
8736                         Perl_croak(aTHX_ "Illegal declaration of anonymous subroutine");
8737                     else if (*s != ';' && *s != '}')
8738                         Perl_croak(aTHX_ "Illegal declaration of subroutine %" SVf, SVfARG(PL_subname));
8739                 }
8740
8741                 if (have_proto) {
8742                     NEXTVAL_NEXTTOKE.opval =
8743                         newSVOP(OP_CONST, 0, PL_lex_stuff);
8744                     PL_lex_stuff = NULL;
8745                     force_next(THING);
8746                 }
8747                 if (!have_name) {
8748                     if (PL_curstash)
8749                         sv_setpvs(PL_subname, "__ANON__");
8750                     else
8751                         sv_setpvs(PL_subname, "__ANON__::__ANON__");
8752                     TOKEN(ANONSUB);
8753                 }
8754                 force_ident_maybe_lex('&');
8755                 TOKEN(SUB);
8756             }
8757
8758         case KEY_system:
8759             LOP(OP_SYSTEM,XREF);
8760
8761         case KEY_symlink:
8762             LOP(OP_SYMLINK,XTERM);
8763
8764         case KEY_syscall:
8765             LOP(OP_SYSCALL,XTERM);
8766
8767         case KEY_sysopen:
8768             LOP(OP_SYSOPEN,XTERM);
8769
8770         case KEY_sysseek:
8771             LOP(OP_SYSSEEK,XTERM);
8772
8773         case KEY_sysread:
8774             LOP(OP_SYSREAD,XTERM);
8775
8776         case KEY_syswrite:
8777             LOP(OP_SYSWRITE,XTERM);
8778
8779         case KEY_tr:
8780         case KEY_y:
8781             s = scan_trans(s);
8782             TERM(sublex_start());
8783
8784         case KEY_tell:
8785             UNI(OP_TELL);
8786
8787         case KEY_telldir:
8788             UNI(OP_TELLDIR);
8789
8790         case KEY_tie:
8791             LOP(OP_TIE,XTERM);
8792
8793         case KEY_tied:
8794             UNI(OP_TIED);
8795
8796         case KEY_time:
8797             FUN0(OP_TIME);
8798
8799         case KEY_times:
8800             FUN0(OP_TMS);
8801
8802         case KEY_truncate:
8803             LOP(OP_TRUNCATE,XTERM);
8804
8805         case KEY_uc:
8806             UNI(OP_UC);
8807
8808         case KEY_ucfirst:
8809             UNI(OP_UCFIRST);
8810
8811         case KEY_untie:
8812             UNI(OP_UNTIE);
8813
8814         case KEY_until:
8815             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8816                 return REPORT(0);
8817             pl_yylval.ival = CopLINE(PL_curcop);
8818             OPERATOR(UNTIL);
8819
8820         case KEY_unless:
8821             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8822                 return REPORT(0);
8823             pl_yylval.ival = CopLINE(PL_curcop);
8824             OPERATOR(UNLESS);
8825
8826         case KEY_unlink:
8827             LOP(OP_UNLINK,XTERM);
8828
8829         case KEY_undef:
8830             UNIDOR(OP_UNDEF);
8831
8832         case KEY_unpack:
8833             LOP(OP_UNPACK,XTERM);
8834
8835         case KEY_utime:
8836             LOP(OP_UTIME,XTERM);
8837
8838         case KEY_umask:
8839             UNIDOR(OP_UMASK);
8840
8841         case KEY_unshift:
8842             LOP(OP_UNSHIFT,XTERM);
8843
8844         case KEY_use:
8845             s = tokenize_use(1, s);
8846             TOKEN(USE);
8847
8848         case KEY_values:
8849             UNI(OP_VALUES);
8850
8851         case KEY_vec:
8852             LOP(OP_VEC,XTERM);
8853
8854         case KEY_when:
8855             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8856                 return REPORT(0);
8857             pl_yylval.ival = CopLINE(PL_curcop);
8858             Perl_ck_warner_d(aTHX_
8859                 packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8860                 "when is experimental");
8861             OPERATOR(WHEN);
8862
8863         case KEY_while:
8864             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8865                 return REPORT(0);
8866             pl_yylval.ival = CopLINE(PL_curcop);
8867             OPERATOR(WHILE);
8868
8869         case KEY_warn:
8870             PL_hints |= HINT_BLOCK_SCOPE;
8871             LOP(OP_WARN,XTERM);
8872
8873         case KEY_wait:
8874             FUN0(OP_WAIT);
8875
8876         case KEY_waitpid:
8877             LOP(OP_WAITPID,XTERM);
8878
8879         case KEY_wantarray:
8880             FUN0(OP_WANTARRAY);
8881
8882         case KEY_write:
8883             /* Make sure $^L is defined. 0x0C is CTRL-L on ASCII platforms, and
8884              * we use the same number on EBCDIC */
8885             gv_fetchpvs("\x0C", GV_ADD|GV_NOTQUAL, SVt_PV);
8886             UNI(OP_ENTERWRITE);
8887
8888         case KEY_x:
8889             if (PL_expect == XOPERATOR) {
8890                 if (*s == '=' && !PL_lex_allbrackets
8891                     && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8892                 {
8893                     return REPORT(0);
8894                 }
8895                 Mop(OP_REPEAT);
8896             }
8897             check_uni();
8898             goto just_a_word;
8899
8900         case KEY_xor:
8901             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8902                 return REPORT(0);
8903             pl_yylval.ival = OP_XOR;
8904             OPERATOR(OROP);
8905         }
8906     }}
8907 }
8908
8909 /*
8910   S_pending_ident
8911
8912   Looks up an identifier in the pad or in a package
8913
8914   is_sig indicates that this is a subroutine signature variable
8915   rather than a plain pad var.
8916
8917   Returns:
8918     PRIVATEREF if this is a lexical name.
8919     BAREWORD   if this belongs to a package.
8920
8921   Structure:
8922       if we're in a my declaration
8923           croak if they tried to say my($foo::bar)
8924           build the ops for a my() declaration
8925       if it's an access to a my() variable
8926           build ops for access to a my() variable
8927       if in a dq string, and they've said @foo and we can't find @foo
8928           warn
8929       build ops for a bareword
8930 */
8931
8932 static int
8933 S_pending_ident(pTHX)
8934 {
8935     PADOFFSET tmp = 0;
8936     const char pit = (char)pl_yylval.ival;
8937     const STRLEN tokenbuf_len = strlen(PL_tokenbuf);
8938     /* All routes through this function want to know if there is a colon.  */
8939     const char *const has_colon = (const char*) memchr (PL_tokenbuf, ':', tokenbuf_len);
8940
8941     DEBUG_T({ PerlIO_printf(Perl_debug_log,
8942           "### Pending identifier '%s'\n", PL_tokenbuf); });
8943
8944     /* if we're in a my(), we can't allow dynamics here.
8945        $foo'bar has already been turned into $foo::bar, so
8946        just check for colons.
8947
8948        if it's a legal name, the OP is a PADANY.
8949     */
8950     if (PL_in_my) {
8951         if (PL_in_my == KEY_our) {      /* "our" is merely analogous to "my" */
8952             if (has_colon)
8953                 /* diag_listed_as: No package name allowed for variable %s
8954                                    in "our" */
8955                 yyerror_pv(Perl_form(aTHX_ "No package name allowed for "
8956                                   "%se %s in \"our\"",
8957                                   *PL_tokenbuf=='&' ?"subroutin":"variabl",
8958                                   PL_tokenbuf), UTF ? SVf_UTF8 : 0);
8959             tmp = allocmy(PL_tokenbuf, tokenbuf_len, UTF ? SVf_UTF8 : 0);
8960         }
8961         else {
8962             OP *o;
8963             if (has_colon) {
8964                 /* "my" variable %s can't be in a package */
8965                 /* PL_no_myglob is constant */
8966                 GCC_DIAG_IGNORE(-Wformat-nonliteral);
8967                 yyerror_pv(Perl_form(aTHX_ PL_no_myglob,
8968                             PL_in_my == KEY_my ? "my" : "state",
8969                             *PL_tokenbuf == '&' ? "subroutin" : "variabl",
8970                             PL_tokenbuf),
8971                             UTF ? SVf_UTF8 : 0);
8972                 GCC_DIAG_RESTORE;
8973             }
8974
8975             if (PL_in_my == KEY_sigvar) {
8976                 /* A signature 'padop' needs in addition, an op_first to
8977                  * point to a child sigdefelem, and an extra field to hold
8978                  * the signature index. We can achieve both by using an
8979                  * UNOP_AUX and (ab)using the op_aux field to hold the
8980                  * index. If we ever need more fields, use a real malloced
8981                  * aux strut instead.
8982                  */
8983                 o = newUNOP_AUX(OP_ARGELEM, 0, NULL,
8984                                     INT2PTR(UNOP_AUX_item *,
8985                                         (PL_parser->sig_elems)));
8986                 o->op_private |= (  PL_tokenbuf[0] == '$' ? OPpARGELEM_SV
8987                                   : PL_tokenbuf[0] == '@' ? OPpARGELEM_AV
8988                                   :                         OPpARGELEM_HV);
8989             }
8990             else
8991                 o = newOP(OP_PADANY, 0);
8992             o->op_targ = allocmy(PL_tokenbuf, tokenbuf_len,
8993                                                         UTF ? SVf_UTF8 : 0);
8994             if (PL_in_my == KEY_sigvar)
8995                 PL_in_my = 0;
8996
8997             pl_yylval.opval = o;
8998             return PRIVATEREF;
8999         }
9000     }
9001
9002     /*
9003        build the ops for accesses to a my() variable.
9004     */
9005
9006     if (!has_colon) {
9007         if (!PL_in_my)
9008             tmp = pad_findmy_pvn(PL_tokenbuf, tokenbuf_len,
9009                                  0);
9010         if (tmp != NOT_IN_PAD) {
9011             /* might be an "our" variable" */
9012             if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
9013                 /* build ops for a bareword */
9014                 HV *  const stash = PAD_COMPNAME_OURSTASH(tmp);
9015                 HEK * const stashname = HvNAME_HEK(stash);
9016                 SV *  const sym = newSVhek(stashname);
9017                 sv_catpvs(sym, "::");
9018                 sv_catpvn_flags(sym, PL_tokenbuf+1, tokenbuf_len - 1, (UTF ? SV_CATUTF8 : SV_CATBYTES ));
9019                 pl_yylval.opval = newSVOP(OP_CONST, 0, sym);
9020                 pl_yylval.opval->op_private = OPpCONST_ENTERED;
9021                 if (pit != '&')
9022                   gv_fetchsv(sym,
9023                     GV_ADDMULTI,
9024                     ((PL_tokenbuf[0] == '$') ? SVt_PV
9025                      : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9026                      : SVt_PVHV));
9027                 return BAREWORD;
9028             }
9029
9030             pl_yylval.opval = newOP(OP_PADANY, 0);
9031             pl_yylval.opval->op_targ = tmp;
9032             return PRIVATEREF;
9033         }
9034     }
9035
9036     /*
9037        Whine if they've said @foo or @foo{key} in a doublequoted string,
9038        and @foo (or %foo) isn't a variable we can find in the symbol
9039        table.
9040     */
9041     if (ckWARN(WARN_AMBIGUOUS)
9042         && pit == '@'
9043         && PL_lex_state != LEX_NORMAL
9044         && !PL_lex_brackets)
9045     {
9046         GV *const gv = gv_fetchpvn_flags(PL_tokenbuf + 1, tokenbuf_len - 1,
9047                                          ( UTF ? SVf_UTF8 : 0 ) | GV_ADDMG,
9048                                          SVt_PVAV);
9049         if ((!gv || ((PL_tokenbuf[0] == '@') ? !GvAV(gv) : !GvHV(gv)))
9050            )
9051         {
9052             /* Downgraded from fatal to warning 20000522 mjd */
9053             Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9054                         "Possible unintended interpolation of %" UTF8f
9055                         " in string",
9056                         UTF8fARG(UTF, tokenbuf_len, PL_tokenbuf));
9057         }
9058     }
9059
9060     /* build ops for a bareword */
9061     pl_yylval.opval = newSVOP(OP_CONST, 0,
9062                                    newSVpvn_flags(PL_tokenbuf + 1,
9063                                                       tokenbuf_len - 1,
9064                                                       UTF ? SVf_UTF8 : 0 ));
9065     pl_yylval.opval->op_private = OPpCONST_ENTERED;
9066     if (pit != '&')
9067         gv_fetchpvn_flags(PL_tokenbuf+1, tokenbuf_len - 1,
9068                      (PL_in_eval ? GV_ADDMULTI : GV_ADD)
9069                      | ( UTF ? SVf_UTF8 : 0 ),
9070                      ((PL_tokenbuf[0] == '$') ? SVt_PV
9071                       : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9072                       : SVt_PVHV));
9073     return BAREWORD;
9074 }
9075
9076 STATIC void
9077 S_checkcomma(pTHX_ const char *s, const char *name, const char *what)
9078 {
9079     PERL_ARGS_ASSERT_CHECKCOMMA;
9080
9081     if (*s == ' ' && s[1] == '(') {     /* XXX gotta be a better way */
9082         if (ckWARN(WARN_SYNTAX)) {
9083             int level = 1;
9084             const char *w;
9085             for (w = s+2; *w && level; w++) {
9086                 if (*w == '(')
9087                     ++level;
9088                 else if (*w == ')')
9089                     --level;
9090             }
9091             while (isSPACE(*w))
9092                 ++w;
9093             /* the list of chars below is for end of statements or
9094              * block / parens, boolean operators (&&, ||, //) and branch
9095              * constructs (or, and, if, until, unless, while, err, for).
9096              * Not a very solid hack... */
9097             if (!*w || !strchr(";&/|})]oaiuwef!=", *w))
9098                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9099                             "%s (...) interpreted as function",name);
9100         }
9101     }
9102     while (s < PL_bufend && isSPACE(*s))
9103         s++;
9104     if (*s == '(')
9105         s++;
9106     while (s < PL_bufend && isSPACE(*s))
9107         s++;
9108     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
9109         const char * const w = s;
9110         s += UTF ? UTF8SKIP(s) : 1;
9111         while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
9112             s += UTF ? UTF8SKIP(s) : 1;
9113         while (s < PL_bufend && isSPACE(*s))
9114             s++;
9115         if (*s == ',') {
9116             GV* gv;
9117             if (keyword(w, s - w, 0))
9118                 return;
9119
9120             gv = gv_fetchpvn_flags(w, s - w, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
9121             if (gv && GvCVu(gv))
9122                 return;
9123             if (s - w <= 254) {
9124                 PADOFFSET off;
9125                 char tmpbuf[256];
9126                 Copy(w, tmpbuf+1, s - w, char);
9127                 *tmpbuf = '&';
9128                 off = pad_findmy_pvn(tmpbuf, s-w+1, 0);
9129                 if (off != NOT_IN_PAD) return;
9130             }
9131             Perl_croak(aTHX_ "No comma allowed after %s", what);
9132         }
9133     }
9134 }
9135
9136 /* S_new_constant(): do any overload::constant lookup.
9137
9138    Either returns sv, or mortalizes/frees sv and returns a new SV*.
9139    Best used as sv=new_constant(..., sv, ...).
9140    If s, pv are NULL, calls subroutine with one argument,
9141    and <type> is used with error messages only.
9142    <type> is assumed to be well formed UTF-8 */
9143
9144 STATIC SV *
9145 S_new_constant(pTHX_ const char *s, STRLEN len, const char *key, STRLEN keylen,
9146                SV *sv, SV *pv, const char *type, STRLEN typelen)
9147 {
9148     dSP;
9149     HV * table = GvHV(PL_hintgv);                /* ^H */
9150     SV *res;
9151     SV *errsv = NULL;
9152     SV **cvp;
9153     SV *cv, *typesv;
9154     const char *why1 = "", *why2 = "", *why3 = "";
9155
9156     PERL_ARGS_ASSERT_NEW_CONSTANT;
9157     /* We assume that this is true: */
9158     if (*key == 'c') { assert (strEQ(key, "charnames")); }
9159     assert(type || s);
9160
9161     /* charnames doesn't work well if there have been errors found */
9162     if (PL_error_count > 0 && *key == 'c')
9163     {
9164         SvREFCNT_dec_NN(sv);
9165         return &PL_sv_undef;
9166     }
9167
9168     sv_2mortal(sv);                     /* Parent created it permanently */
9169     if (!table
9170         || ! (PL_hints & HINT_LOCALIZE_HH)
9171         || ! (cvp = hv_fetch(table, key, keylen, FALSE))
9172         || ! SvOK(*cvp))
9173     {
9174         char *msg;
9175
9176         /* Here haven't found what we're looking for.  If it is charnames,
9177          * perhaps it needs to be loaded.  Try doing that before giving up */
9178         if (*key == 'c') {
9179             Perl_load_module(aTHX_
9180                             0,
9181                             newSVpvs("_charnames"),
9182                              /* version parameter; no need to specify it, as if
9183                               * we get too early a version, will fail anyway,
9184                               * not being able to find '_charnames' */
9185                             NULL,
9186                             newSVpvs(":full"),
9187                             newSVpvs(":short"),
9188                             NULL);
9189             assert(sp == PL_stack_sp);
9190             table = GvHV(PL_hintgv);
9191             if (table
9192                 && (PL_hints & HINT_LOCALIZE_HH)
9193                 && (cvp = hv_fetch(table, key, keylen, FALSE))
9194                 && SvOK(*cvp))
9195             {
9196                 goto now_ok;
9197             }
9198         }
9199         if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
9200             msg = Perl_form(aTHX_
9201                                "Constant(%.*s) unknown",
9202                                 (int)(type ? typelen : len),
9203                                 (type ? type: s));
9204         }
9205         else {
9206             why1 = "$^H{";
9207             why2 = key;
9208             why3 = "} is not defined";
9209         report:
9210             if (*key == 'c') {
9211                 msg = Perl_form(aTHX_
9212                             /* The +3 is for '\N{'; -4 for that, plus '}' */
9213                             "Unknown charname '%.*s'", (int)typelen - 4, type + 3
9214                       );
9215             }
9216             else {
9217                 msg = Perl_form(aTHX_ "Constant(%.*s): %s%s%s",
9218                                     (int)(type ? typelen : len),
9219                                     (type ? type: s), why1, why2, why3);
9220             }
9221         }
9222         yyerror_pv(msg, UTF ? SVf_UTF8 : 0);
9223         return SvREFCNT_inc_simple_NN(sv);
9224     }
9225   now_ok:
9226     cv = *cvp;
9227     if (!pv && s)
9228         pv = newSVpvn_flags(s, len, SVs_TEMP);
9229     if (type && pv)
9230         typesv = newSVpvn_flags(type, typelen, SVs_TEMP);
9231     else
9232         typesv = &PL_sv_undef;
9233
9234     PUSHSTACKi(PERLSI_OVERLOAD);
9235     ENTER ;
9236     SAVETMPS;
9237
9238     PUSHMARK(SP) ;
9239     EXTEND(sp, 3);
9240     if (pv)
9241         PUSHs(pv);
9242     PUSHs(sv);
9243     if (pv)
9244         PUSHs(typesv);
9245     PUTBACK;
9246     call_sv(cv, G_SCALAR | ( PL_in_eval ? 0 : G_EVAL));
9247
9248     SPAGAIN ;
9249
9250     /* Check the eval first */
9251     if (!PL_in_eval && ((errsv = ERRSV), SvTRUE_NN(errsv))) {
9252         STRLEN errlen;
9253         const char * errstr;
9254         sv_catpvs(errsv, "Propagated");
9255         errstr = SvPV_const(errsv, errlen);
9256         yyerror_pvn(errstr, errlen, 0); /* Duplicates the message inside eval */
9257         (void)POPs;
9258         res = SvREFCNT_inc_simple_NN(sv);
9259     }
9260     else {
9261         res = POPs;
9262         SvREFCNT_inc_simple_void_NN(res);
9263     }
9264
9265     PUTBACK ;
9266     FREETMPS ;
9267     LEAVE ;
9268     POPSTACK;
9269
9270     if (!SvOK(res)) {
9271         why1 = "Call to &{$^H{";
9272         why2 = key;
9273         why3 = "}} did not return a defined value";
9274         sv = res;
9275         (void)sv_2mortal(sv);
9276         goto report;
9277     }
9278
9279     return res;
9280 }
9281
9282 PERL_STATIC_INLINE void
9283 S_parse_ident(pTHX_ char **s, char **d, char * const e, int allow_package,
9284                     bool is_utf8, bool check_dollar)
9285 {
9286     PERL_ARGS_ASSERT_PARSE_IDENT;
9287
9288     while (*s < PL_bufend) {
9289         if (*d >= e)
9290             Perl_croak(aTHX_ "%s", ident_too_long);
9291         if (is_utf8 && isIDFIRST_utf8_safe(*s, PL_bufend)) {
9292              /* The UTF-8 case must come first, otherwise things
9293              * like c\N{COMBINING TILDE} would start failing, as the
9294              * isWORDCHAR_A case below would gobble the 'c' up.
9295              */
9296
9297             char *t = *s + UTF8SKIP(*s);
9298             while (isIDCONT_utf8_safe((const U8*) t, (const U8*) PL_bufend)) {
9299                 t += UTF8SKIP(t);
9300             }
9301             if (*d + (t - *s) > e)
9302                 Perl_croak(aTHX_ "%s", ident_too_long);
9303             Copy(*s, *d, t - *s, char);
9304             *d += t - *s;
9305             *s = t;
9306         }
9307         else if ( isWORDCHAR_A(**s) ) {
9308             do {
9309                 *(*d)++ = *(*s)++;
9310             } while (isWORDCHAR_A(**s) && *d < e);
9311         }
9312         else if (   allow_package
9313                  && **s == '\''
9314                  && isIDFIRST_lazy_if_safe((*s)+1, PL_bufend, is_utf8))
9315         {
9316             *(*d)++ = ':';
9317             *(*d)++ = ':';
9318             (*s)++;
9319         }
9320         else if (allow_package && **s == ':' && (*s)[1] == ':'
9321            /* Disallow things like Foo::$bar. For the curious, this is
9322             * the code path that triggers the "Bad name after" warning
9323             * when looking for barewords.
9324             */
9325            && !(check_dollar && (*s)[2] == '$')) {
9326             *(*d)++ = *(*s)++;
9327             *(*d)++ = *(*s)++;
9328         }
9329         else
9330             break;
9331     }
9332     return;
9333 }
9334
9335 /* Returns a NUL terminated string, with the length of the string written to
9336    *slp
9337    */
9338 STATIC char *
9339 S_scan_word(pTHX_ char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
9340 {
9341     char *d = dest;
9342     char * const e = d + destlen - 3;  /* two-character token, ending NUL */
9343     bool is_utf8 = cBOOL(UTF);
9344
9345     PERL_ARGS_ASSERT_SCAN_WORD;
9346
9347     parse_ident(&s, &d, e, allow_package, is_utf8, TRUE);
9348     *d = '\0';
9349     *slp = d - dest;
9350     return s;
9351 }
9352
9353 /* Is the byte 'd' a legal single character identifier name?  'u' is true
9354  * iff Unicode semantics are to be used.  The legal ones are any of:
9355  *  a) all ASCII characters except:
9356  *          1) control and space-type ones, like NUL, SOH, \t, and SPACE;
9357  *          2) '{'
9358  *     The final case currently doesn't get this far in the program, so we
9359  *     don't test for it.  If that were to change, it would be ok to allow it.
9360  *  b) When not under Unicode rules, any upper Latin1 character
9361  *  c) Otherwise, when unicode rules are used, all XIDS characters.
9362  *
9363  *      Because all ASCII characters have the same representation whether
9364  *      encoded in UTF-8 or not, we can use the foo_A macros below and '\0' and
9365  *      '{' without knowing if is UTF-8 or not. */
9366 #define VALID_LEN_ONE_IDENT(s, e, is_utf8)                                  \
9367     (isGRAPH_A(*(s)) || ((is_utf8)                                          \
9368                          ? isIDFIRST_utf8_safe(s, e)                        \
9369                          : (isGRAPH_L1(*s)                                  \
9370                             && LIKELY((U8) *(s) != LATIN1_TO_NATIVE(0xAD)))))
9371
9372 STATIC char *
9373 S_scan_ident(pTHX_ char *s, char *dest, STRLEN destlen, I32 ck_uni)
9374 {
9375     I32 herelines = PL_parser->herelines;
9376     SSize_t bracket = -1;
9377     char funny = *s++;
9378     char *d = dest;
9379     char * const e = d + destlen - 3;    /* two-character token, ending NUL */
9380     bool is_utf8 = cBOOL(UTF);
9381     I32 orig_copline = 0, tmp_copline = 0;
9382
9383     PERL_ARGS_ASSERT_SCAN_IDENT;
9384
9385     if (isSPACE(*s) || !*s)
9386         s = skipspace(s);
9387     if (isDIGIT(*s)) {
9388         while (isDIGIT(*s)) {
9389             if (d >= e)
9390                 Perl_croak(aTHX_ "%s", ident_too_long);
9391             *d++ = *s++;
9392         }
9393     }
9394     else {  /* See if it is a "normal" identifier */
9395         parse_ident(&s, &d, e, 1, is_utf8, FALSE);
9396     }
9397     *d = '\0';
9398     d = dest;
9399     if (*d) {
9400         /* Either a digit variable, or parse_ident() found an identifier
9401            (anything valid as a bareword), so job done and return.  */
9402         if (PL_lex_state != LEX_NORMAL)
9403             PL_lex_state = LEX_INTERPENDMAYBE;
9404         return s;
9405     }
9406
9407     /* Here, it is not a run-of-the-mill identifier name */
9408
9409     if (*s == '$' && s[1]
9410         && (   isIDFIRST_lazy_if_safe(s+1, PL_bufend, is_utf8)
9411             || isDIGIT_A((U8)s[1])
9412             || s[1] == '$'
9413             || s[1] == '{'
9414             || memBEGINs(s+1, (STRLEN) (PL_bufend - (s+1)), "::")) )
9415     {
9416         /* Dereferencing a value in a scalar variable.
9417            The alternatives are different syntaxes for a scalar variable.
9418            Using ' as a leading package separator isn't allowed. :: is.   */
9419         return s;
9420     }
9421     /* Handle the opening { of @{...}, &{...}, *{...}, %{...}, ${...}  */
9422     if (*s == '{') {
9423         bracket = s - SvPVX(PL_linestr);
9424         s++;
9425         orig_copline = CopLINE(PL_curcop);
9426         if (s < PL_bufend && isSPACE(*s)) {
9427             s = skipspace(s);
9428         }
9429     }
9430     if ((s <= PL_bufend - (is_utf8)
9431                           ? UTF8SKIP(s)
9432                           : 1)
9433         && VALID_LEN_ONE_IDENT(s, PL_bufend, is_utf8))
9434     {
9435         if (is_utf8) {
9436             const STRLEN skip = UTF8SKIP(s);
9437             STRLEN i;
9438             d[skip] = '\0';
9439             for ( i = 0; i < skip; i++ )
9440                 d[i] = *s++;
9441         }
9442         else {
9443             *d = *s++;
9444             d[1] = '\0';
9445         }
9446     }
9447     /* Convert $^F, ${^F} and the ^F of ${^FOO} to control characters */
9448     if (*d == '^' && *s && isCONTROLVAR(*s)) {
9449         *d = toCTRL(*s);
9450         s++;
9451     }
9452     /* Warn about ambiguous code after unary operators if {...} notation isn't
9453        used.  There's no difference in ambiguity; it's merely a heuristic
9454        about when not to warn.  */
9455     else if (ck_uni && bracket == -1)
9456         check_uni();
9457     if (bracket != -1) {
9458         bool skip;
9459         char *s2;
9460         /* If we were processing {...} notation then...  */
9461         if (isIDFIRST_lazy_if_safe(d, e, is_utf8)
9462             || (!isPRINT(*d) /* isCNTRL(d), plus all non-ASCII */
9463                  && isWORDCHAR(*s))
9464         ) {
9465             /* note we have to check for a normal identifier first,
9466              * as it handles utf8 symbols, and only after that has
9467              * been ruled out can we look at the caret words */
9468             if (isIDFIRST_lazy_if_safe(d, e, is_utf8) ) {
9469                 /* if it starts as a valid identifier, assume that it is one.
9470                    (the later check for } being at the expected point will trap
9471                    cases where this doesn't pan out.)  */
9472                 d += is_utf8 ? UTF8SKIP(d) : 1;
9473                 parse_ident(&s, &d, e, 1, is_utf8, TRUE);
9474                 *d = '\0';
9475             }
9476             else { /* caret word: ${^Foo} ${^CAPTURE[0]} */
9477                 d++;
9478                 while (isWORDCHAR(*s) && d < e) {
9479                     *d++ = *s++;
9480                 }
9481                 if (d >= e)
9482                     Perl_croak(aTHX_ "%s", ident_too_long);
9483                 *d = '\0';
9484             }
9485             tmp_copline = CopLINE(PL_curcop);
9486             if (s < PL_bufend && isSPACE(*s)) {
9487                 s = skipspace(s);
9488             }
9489             if ((*s == '[' || (*s == '{' && strNE(dest, "sub")))) {
9490                 /* ${foo[0]} and ${foo{bar}} and ${^CAPTURE[0]} notation.  */
9491                 if (ckWARN(WARN_AMBIGUOUS) && keyword(dest, d - dest, 0)) {
9492                     const char * const brack =
9493                         (const char *)
9494                         ((*s == '[') ? "[...]" : "{...}");
9495                     orig_copline = CopLINE(PL_curcop);
9496                     CopLINE_set(PL_curcop, tmp_copline);
9497    /* diag_listed_as: Ambiguous use of %c{%s[...]} resolved to %c%s[...] */
9498                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9499                         "Ambiguous use of %c{%s%s} resolved to %c%s%s",
9500                         funny, dest, brack, funny, dest, brack);
9501                     CopLINE_set(PL_curcop, orig_copline);
9502                 }
9503                 bracket++;
9504                 PL_lex_brackstack[PL_lex_brackets++] = (char)(XOPERATOR | XFAKEBRACK);
9505                 PL_lex_allbrackets++;
9506                 return s;
9507             }
9508         }
9509
9510         if ( !tmp_copline )
9511             tmp_copline = CopLINE(PL_curcop);
9512         if ((skip = s < PL_bufend && isSPACE(*s))) {
9513             /* Avoid incrementing line numbers or resetting PL_linestart,
9514                in case we have to back up.  */
9515             STRLEN s_off = s - SvPVX(PL_linestr);
9516             s2 = peekspace(s);
9517             s = SvPVX(PL_linestr) + s_off;
9518         }
9519         else
9520             s2 = s;
9521
9522         /* Expect to find a closing } after consuming any trailing whitespace.
9523          */
9524         if (*s2 == '}') {
9525             /* Now increment line numbers if applicable.  */
9526             if (skip)
9527                 s = skipspace(s);
9528             s++;
9529             if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
9530                 PL_lex_state = LEX_INTERPEND;
9531                 PL_expect = XREF;
9532             }
9533             if (PL_lex_state == LEX_NORMAL) {
9534                 if (ckWARN(WARN_AMBIGUOUS)
9535                     && (keyword(dest, d - dest, 0)
9536                         || get_cvn_flags(dest, d - dest, is_utf8
9537                            ? SVf_UTF8
9538                            : 0)))
9539                 {
9540                     SV *tmp = newSVpvn_flags( dest, d - dest,
9541                                         SVs_TEMP | (is_utf8 ? SVf_UTF8 : 0) );
9542                     if (funny == '#')
9543                         funny = '@';
9544                     orig_copline = CopLINE(PL_curcop);
9545                     CopLINE_set(PL_curcop, tmp_copline);
9546                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9547                         "Ambiguous use of %c{%" SVf "} resolved to %c%" SVf,
9548                         funny, SVfARG(tmp), funny, SVfARG(tmp));
9549                     CopLINE_set(PL_curcop, orig_copline);
9550                 }
9551             }
9552         }
9553         else {
9554             /* Didn't find the closing } at the point we expected, so restore
9555                state such that the next thing to process is the opening { and */
9556             s = SvPVX(PL_linestr) + bracket; /* let the parser handle it */
9557             CopLINE_set(PL_curcop, orig_copline);
9558             PL_parser->herelines = herelines;
9559             *dest = '\0';
9560         }
9561     }
9562     else if (   PL_lex_state == LEX_INTERPNORMAL
9563              && !PL_lex_brackets
9564              && !intuit_more(s, PL_bufend))
9565         PL_lex_state = LEX_INTERPEND;
9566     return s;
9567 }
9568
9569 static bool
9570 S_pmflag(pTHX_ const char* const valid_flags, U32 * pmfl, char** s, char* charset, unsigned int * x_mod_count) {
9571
9572     /* Adds, subtracts to/from 'pmfl' based on the next regex modifier flag
9573      * found in the parse starting at 's', based on the subset that are valid
9574      * in this context input to this routine in 'valid_flags'. Advances s.
9575      * Returns TRUE if the input should be treated as a valid flag, so the next
9576      * char may be as well; otherwise FALSE. 'charset' should point to a NUL
9577      * upon first call on the current regex.  This routine will set it to any
9578      * charset modifier found.  The caller shouldn't change it.  This way,
9579      * another charset modifier encountered in the parse can be detected as an
9580      * error, as we have decided to allow only one */
9581
9582     const char c = **s;
9583     STRLEN charlen = UTF ? UTF8SKIP(*s) : 1;
9584
9585     if ( charlen != 1 || ! strchr(valid_flags, c) ) {
9586         if (isWORDCHAR_lazy_if_safe( *s, PL_bufend, UTF)) {
9587             yyerror_pv(Perl_form(aTHX_ "Unknown regexp modifier \"/%.*s\"", (int)charlen, *s),
9588                        UTF ? SVf_UTF8 : 0);
9589             (*s) += charlen;
9590             /* Pretend that it worked, so will continue processing before
9591              * dieing */
9592             return TRUE;
9593         }
9594         return FALSE;
9595     }
9596
9597     switch (c) {
9598
9599         CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, *x_mod_count);
9600         case GLOBAL_PAT_MOD:      *pmfl |= PMf_GLOBAL; break;
9601         case CONTINUE_PAT_MOD:    *pmfl |= PMf_CONTINUE; break;
9602         case ONCE_PAT_MOD:        *pmfl |= PMf_KEEP; break;
9603         case KEEPCOPY_PAT_MOD:    *pmfl |= RXf_PMf_KEEPCOPY; break;
9604         case NONDESTRUCT_PAT_MOD: *pmfl |= PMf_NONDESTRUCT; break;
9605         case LOCALE_PAT_MOD:
9606             if (*charset) {
9607                 goto multiple_charsets;
9608             }
9609             set_regex_charset(pmfl, REGEX_LOCALE_CHARSET);
9610             *charset = c;
9611             break;
9612         case UNICODE_PAT_MOD:
9613             if (*charset) {
9614                 goto multiple_charsets;
9615             }
9616             set_regex_charset(pmfl, REGEX_UNICODE_CHARSET);
9617             *charset = c;
9618             break;
9619         case ASCII_RESTRICT_PAT_MOD:
9620             if (! *charset) {
9621                 set_regex_charset(pmfl, REGEX_ASCII_RESTRICTED_CHARSET);
9622             }
9623             else {
9624
9625                 /* Error if previous modifier wasn't an 'a', but if it was, see
9626                  * if, and accept, a second occurrence (only) */
9627                 if (*charset != 'a'
9628                     || get_regex_charset(*pmfl)
9629                         != REGEX_ASCII_RESTRICTED_CHARSET)
9630                 {
9631                         goto multiple_charsets;
9632                 }
9633                 set_regex_charset(pmfl, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
9634             }
9635             *charset = c;
9636             break;
9637         case DEPENDS_PAT_MOD:
9638             if (*charset) {
9639                 goto multiple_charsets;
9640             }
9641             set_regex_charset(pmfl, REGEX_DEPENDS_CHARSET);
9642             *charset = c;
9643             break;
9644     }
9645
9646     (*s)++;
9647     return TRUE;
9648
9649     multiple_charsets:
9650         if (*charset != c) {
9651             yyerror(Perl_form(aTHX_ "Regexp modifiers \"/%c\" and \"/%c\" are mutually exclusive", *charset, c));
9652         }
9653         else if (c == 'a') {
9654   /* diag_listed_as: Regexp modifier "/%c" may appear a maximum of twice */
9655             yyerror("Regexp modifier \"/a\" may appear a maximum of twice");
9656         }
9657         else {
9658             yyerror(Perl_form(aTHX_ "Regexp modifier \"/%c\" may not appear twice", c));
9659         }
9660
9661         /* Pretend that it worked, so will continue processing before dieing */
9662         (*s)++;
9663         return TRUE;
9664 }
9665
9666 STATIC char *
9667 S_scan_pat(pTHX_ char *start, I32 type)
9668 {
9669     PMOP *pm;
9670     char *s;
9671     const char * const valid_flags =
9672         (const char *)((type == OP_QR) ? QR_PAT_MODS : M_PAT_MODS);
9673     char charset = '\0';    /* character set modifier */
9674     unsigned int x_mod_count = 0;
9675
9676     PERL_ARGS_ASSERT_SCAN_PAT;
9677
9678     s = scan_str(start,TRUE,FALSE, (PL_in_eval & EVAL_RE_REPARSING), NULL);
9679     if (!s)
9680         Perl_croak(aTHX_ "Search pattern not terminated");
9681
9682     pm = (PMOP*)newPMOP(type, 0);
9683     if (PL_multi_open == '?') {
9684         /* This is the only point in the code that sets PMf_ONCE:  */
9685         pm->op_pmflags |= PMf_ONCE;
9686
9687         /* Hence it's safe to do this bit of PMOP book-keeping here, which
9688            allows us to restrict the list needed by reset to just the ??
9689            matches.  */
9690         assert(type != OP_TRANS);
9691         if (PL_curstash) {
9692             MAGIC *mg = mg_find((const SV *)PL_curstash, PERL_MAGIC_symtab);
9693             U32 elements;
9694             if (!mg) {
9695                 mg = sv_magicext(MUTABLE_SV(PL_curstash), 0, PERL_MAGIC_symtab, 0, 0,
9696                                  0);
9697             }
9698             elements = mg->mg_len / sizeof(PMOP**);
9699             Renewc(mg->mg_ptr, elements + 1, PMOP*, char);
9700             ((PMOP**)mg->mg_ptr) [elements++] = pm;
9701             mg->mg_len = elements * sizeof(PMOP**);
9702             PmopSTASH_set(pm,PL_curstash);
9703         }
9704     }
9705
9706     /* if qr/...(?{..}).../, then need to parse the pattern within a new
9707      * anon CV. False positives like qr/[(?{]/ are harmless */
9708
9709     if (type == OP_QR) {
9710         STRLEN len;
9711         char *e, *p = SvPV(PL_lex_stuff, len);
9712         e = p + len;
9713         for (; p < e; p++) {
9714             if (p[0] == '(' && p[1] == '?'
9715                 && (p[2] == '{' || (p[2] == '?' && p[3] == '{')))
9716             {
9717                 pm->op_pmflags |= PMf_HAS_CV;
9718                 break;
9719             }
9720         }
9721         pm->op_pmflags |= PMf_IS_QR;
9722     }
9723
9724     while (*s && S_pmflag(aTHX_ valid_flags, &(pm->op_pmflags),
9725                                 &s, &charset, &x_mod_count))
9726     {};
9727     /* issue a warning if /c is specified,but /g is not */
9728     if ((pm->op_pmflags & PMf_CONTINUE) && !(pm->op_pmflags & PMf_GLOBAL))
9729     {
9730         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
9731                        "Use of /c modifier is meaningless without /g" );
9732     }
9733
9734     PL_lex_op = (OP*)pm;
9735     pl_yylval.ival = OP_MATCH;
9736     return s;
9737 }
9738
9739 STATIC char *
9740 S_scan_subst(pTHX_ char *start)
9741 {
9742     char *s;
9743     PMOP *pm;
9744     I32 first_start;
9745     line_t first_line;
9746     line_t linediff = 0;
9747     I32 es = 0;
9748     char charset = '\0';    /* character set modifier */
9749     unsigned int x_mod_count = 0;
9750     char *t;
9751
9752     PERL_ARGS_ASSERT_SCAN_SUBST;
9753
9754     pl_yylval.ival = OP_NULL;
9755
9756     s = scan_str(start, TRUE, FALSE, FALSE, &t);
9757
9758     if (!s)
9759         Perl_croak(aTHX_ "Substitution pattern not terminated");
9760
9761     s = t;
9762
9763     first_start = PL_multi_start;
9764     first_line = CopLINE(PL_curcop);
9765     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
9766     if (!s) {
9767         SvREFCNT_dec_NN(PL_lex_stuff);
9768         PL_lex_stuff = NULL;
9769         Perl_croak(aTHX_ "Substitution replacement not terminated");
9770     }
9771     PL_multi_start = first_start;       /* so whole substitution is taken together */
9772
9773     pm = (PMOP*)newPMOP(OP_SUBST, 0);
9774
9775
9776     while (*s) {
9777         if (*s == EXEC_PAT_MOD) {
9778             s++;
9779             es++;
9780         }
9781         else if (! S_pmflag(aTHX_ S_PAT_MODS, &(pm->op_pmflags),
9782                                   &s, &charset, &x_mod_count))
9783         {
9784             break;
9785         }
9786     }
9787
9788     if ((pm->op_pmflags & PMf_CONTINUE)) {
9789         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Use of /c modifier is meaningless in s///" );
9790     }
9791
9792     if (es) {
9793         SV * const repl = newSVpvs("");
9794
9795         PL_multi_end = 0;
9796         pm->op_pmflags |= PMf_EVAL;
9797         for (; es > 1; es--) {
9798             sv_catpvs(repl, "eval ");
9799         }
9800         sv_catpvs(repl, "do {");
9801         sv_catsv(repl, PL_parser->lex_sub_repl);
9802         sv_catpvs(repl, "}");
9803         SvREFCNT_dec(PL_parser->lex_sub_repl);
9804         PL_parser->lex_sub_repl = repl;
9805     }
9806
9807
9808     linediff = CopLINE(PL_curcop) - first_line;
9809     if (linediff)
9810         CopLINE_set(PL_curcop, first_line);
9811
9812     if (linediff || es) {
9813         /* the IVX field indicates that the replacement string is a s///e;
9814          * the NVX field indicates how many src code lines the replacement
9815          * spreads over */
9816         sv_upgrade(PL_parser->lex_sub_repl, SVt_PVNV);
9817         ((XPVNV*)SvANY(PL_parser->lex_sub_repl))->xnv_u.xnv_lines = 0;
9818         ((XPVIV*)SvANY(PL_parser->lex_sub_repl))->xiv_u.xivu_eval_seen =
9819                                                                     cBOOL(es);
9820     }
9821
9822     PL_lex_op = (OP*)pm;
9823     pl_yylval.ival = OP_SUBST;
9824     return s;
9825 }
9826
9827 STATIC char *
9828 S_scan_trans(pTHX_ char *start)
9829 {
9830     char* s;
9831     OP *o;
9832     U8 squash;
9833     U8 del;
9834     U8 complement;
9835     bool nondestruct = 0;
9836     char *t;
9837
9838     PERL_ARGS_ASSERT_SCAN_TRANS;
9839
9840     pl_yylval.ival = OP_NULL;
9841
9842     s = scan_str(start,FALSE,FALSE,FALSE,&t);
9843     if (!s)
9844         Perl_croak(aTHX_ "Transliteration pattern not terminated");
9845
9846     s = t;
9847
9848     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
9849     if (!s) {
9850         SvREFCNT_dec_NN(PL_lex_stuff);
9851         PL_lex_stuff = NULL;
9852         Perl_croak(aTHX_ "Transliteration replacement not terminated");
9853     }
9854
9855     complement = del = squash = 0;
9856     while (1) {
9857         switch (*s) {
9858         case 'c':
9859             complement = OPpTRANS_COMPLEMENT;
9860             break;
9861         case 'd':
9862             del = OPpTRANS_DELETE;
9863             break;
9864         case 's':
9865             squash = OPpTRANS_SQUASH;
9866             break;
9867         case 'r':
9868             nondestruct = 1;
9869             break;
9870         default:
9871             goto no_more;
9872         }
9873         s++;
9874     }
9875   no_more:
9876
9877     o = newPVOP(nondestruct ? OP_TRANSR : OP_TRANS, 0, (char*)NULL);
9878     o->op_private &= ~OPpTRANS_ALL;
9879     o->op_private |= del|squash|complement|
9880       (DO_UTF8(PL_lex_stuff)? OPpTRANS_FROM_UTF : 0)|
9881       (DO_UTF8(PL_parser->lex_sub_repl) ? OPpTRANS_TO_UTF   : 0);
9882
9883     PL_lex_op = o;
9884     pl_yylval.ival = nondestruct ? OP_TRANSR : OP_TRANS;
9885
9886
9887     return s;
9888 }
9889
9890 /* scan_heredoc
9891    Takes a pointer to the first < in <<FOO.
9892    Returns a pointer to the byte following <<FOO.
9893
9894    This function scans a heredoc, which involves different methods
9895    depending on whether we are in a string eval, quoted construct, etc.
9896    This is because PL_linestr could containing a single line of input, or
9897    a whole string being evalled, or the contents of the current quote-
9898    like operator.
9899
9900    The two basic methods are:
9901     - Steal lines from the input stream
9902     - Scan the heredoc in PL_linestr and remove it therefrom
9903
9904    In a file scope or filtered eval, the first method is used; in a
9905    string eval, the second.
9906
9907    In a quote-like operator, we have to choose between the two,
9908    depending on where we can find a newline.  We peek into outer lex-
9909    ing scopes until we find one with a newline in it.  If we reach the
9910    outermost lexing scope and it is a file, we use the stream method.
9911    Otherwise it is treated as an eval.
9912 */
9913
9914 STATIC char *
9915 S_scan_heredoc(pTHX_ char *s)
9916 {
9917     I32 op_type = OP_SCALAR;
9918     I32 len;
9919     SV *tmpstr;
9920     char term;
9921     char *d;
9922     char *e;
9923     char *peek;
9924     char *indent = 0;
9925     I32 indent_len = 0;
9926     bool indented = FALSE;
9927     const bool infile = PL_rsfp || PL_parser->filtered;
9928     const line_t origline = CopLINE(PL_curcop);
9929     LEXSHARED *shared = PL_parser->lex_shared;
9930
9931     PERL_ARGS_ASSERT_SCAN_HEREDOC;
9932
9933     s += 2;
9934     d = PL_tokenbuf + 1;
9935     e = PL_tokenbuf + sizeof PL_tokenbuf - 1;
9936     *PL_tokenbuf = '\n';
9937     peek = s;
9938     if (*peek == '~') {
9939         indented = TRUE;
9940         peek++; s++;
9941     }
9942     while (SPACE_OR_TAB(*peek))
9943         peek++;
9944     if (*peek == '`' || *peek == '\'' || *peek =='"') {
9945         s = peek;
9946         term = *s++;
9947         s = delimcpy(d, e, s, PL_bufend, term, &len);
9948         if (s == PL_bufend)
9949             Perl_croak(aTHX_ "Unterminated delimiter for here document");
9950         d += len;
9951         s++;
9952     }
9953     else {
9954         if (*s == '\\')
9955             /* <<\FOO is equivalent to <<'FOO' */
9956             s++, term = '\'';
9957         else
9958             term = '"';
9959         if (! isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
9960             Perl_croak(aTHX_ "Use of bare << to mean <<\"\" is forbidden");
9961         peek = s;
9962         while (isWORDCHAR_lazy_if_safe(peek, PL_bufend, UTF)) {
9963             peek += UTF ? UTF8SKIP(peek) : 1;
9964         }
9965         len = (peek - s >= e - d) ? (e - d) : (peek - s);
9966         Copy(s, d, len, char);
9967         s += len;
9968         d += len;
9969     }
9970     if (d >= PL_tokenbuf + sizeof PL_tokenbuf - 1)
9971         Perl_croak(aTHX_ "Delimiter for here document is too long");
9972     *d++ = '\n';
9973     *d = '\0';
9974     len = d - PL_tokenbuf;
9975
9976 #ifndef PERL_STRICT_CR
9977     d = (char *) memchr(s, '\r', PL_bufend - s);
9978     if (d) {
9979         char * const olds = s;
9980         s = d;
9981         while (s < PL_bufend) {
9982             if (*s == '\r') {
9983                 *d++ = '\n';
9984                 if (*++s == '\n')
9985                     s++;
9986             }
9987             else if (*s == '\n' && s[1] == '\r') {      /* \015\013 on a mac? */
9988                 *d++ = *s++;
9989                 s++;
9990             }
9991             else
9992                 *d++ = *s++;
9993         }
9994         *d = '\0';
9995         PL_bufend = d;
9996         SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
9997         s = olds;
9998     }
9999 #endif
10000
10001     tmpstr = newSV_type(SVt_PVIV);
10002     SvGROW(tmpstr, 80);
10003     if (term == '\'') {
10004         op_type = OP_CONST;
10005         SvIV_set(tmpstr, -1);
10006     }
10007     else if (term == '`') {
10008         op_type = OP_BACKTICK;
10009         SvIV_set(tmpstr, '\\');
10010     }
10011
10012     PL_multi_start = origline + 1 + PL_parser->herelines;
10013     PL_multi_open = PL_multi_close = '<';
10014     /* inside a string eval or quote-like operator */
10015     if (!infile || PL_lex_inwhat) {
10016         SV *linestr;
10017         char *bufend;
10018         char * const olds = s;
10019         PERL_CONTEXT * const cx = CX_CUR();
10020         /* These two fields are not set until an inner lexing scope is
10021            entered.  But we need them set here. */
10022         shared->ls_bufptr  = s;
10023         shared->ls_linestr = PL_linestr;
10024         if (PL_lex_inwhat)
10025           /* Look for a newline.  If the current buffer does not have one,
10026              peek into the line buffer of the parent lexing scope, going
10027              up as many levels as necessary to find one with a newline
10028              after bufptr.
10029            */
10030           while (!(s = (char *)memchr(
10031                     (void *)shared->ls_bufptr, '\n',
10032                     SvEND(shared->ls_linestr)-shared->ls_bufptr
10033                 ))) {
10034             shared = shared->ls_prev;
10035             /* shared is only null if we have gone beyond the outermost
10036                lexing scope.  In a file, we will have broken out of the
10037                loop in the previous iteration.  In an eval, the string buf-
10038                fer ends with "\n;", so the while condition above will have
10039                evaluated to false.  So shared can never be null.  Or so you
10040                might think.  Odd syntax errors like s;@{<<; can gobble up
10041                the implicit semicolon at the end of a flie, causing the
10042                file handle to be closed even when we are not in a string
10043                eval.  So shared may be null in that case.
10044                (Closing '}' here to balance the earlier open brace for
10045                editors that look for matched pairs.) */
10046             if (UNLIKELY(!shared))
10047                 goto interminable;
10048             /* A LEXSHARED struct with a null ls_prev pointer is the outer-
10049                most lexing scope.  In a file, shared->ls_linestr at that
10050                level is just one line, so there is no body to steal. */
10051             if (infile && !shared->ls_prev) {
10052                 s = olds;
10053                 goto streaming;
10054             }
10055           }
10056         else {  /* eval or we've already hit EOF */
10057             s = (char*)memchr((void*)s, '\n', PL_bufend - s);
10058             if (!s)
10059                 goto interminable;
10060         }
10061         linestr = shared->ls_linestr;
10062         bufend = SvEND(linestr);
10063         d = s;
10064         if (indented) {
10065             char *myolds = s;
10066
10067             while (s < bufend - len + 1) {
10068                 if (*s++ == '\n')
10069                     ++PL_parser->herelines;
10070
10071                 if (memEQ(s, PL_tokenbuf + 1, len - 1)) {
10072                     char *backup = s;
10073                     indent_len = 0;
10074
10075                     /* Only valid if it's preceded by whitespace only */
10076                     while (backup != myolds && --backup >= myolds) {
10077                         if (! SPACE_OR_TAB(*backup)) {
10078                             break;
10079                         }
10080
10081                         indent_len++;
10082                     }
10083
10084                     /* No whitespace or all! */
10085                     if (backup == s || *backup == '\n') {
10086                         Newx(indent, indent_len + 1, char);
10087                         memcpy(indent, backup + 1, indent_len);
10088                         indent[indent_len] = 0;
10089                         s--; /* before our delimiter */
10090                         PL_parser->herelines--; /* this line doesn't count */
10091                         break;
10092                     }
10093                 }
10094             }
10095         } else {
10096             while (s < bufend - len + 1
10097                    && memNE(s,PL_tokenbuf,len) )
10098             {
10099                 if (*s++ == '\n')
10100                     ++PL_parser->herelines;
10101             }
10102         }
10103
10104         if (s >= bufend - len + 1) {
10105             goto interminable;
10106         }
10107         sv_setpvn(tmpstr,d+1,s-d);
10108         s += len - 1;
10109         /* the preceding stmt passes a newline */
10110         PL_parser->herelines++;
10111
10112         /* s now points to the newline after the heredoc terminator.
10113            d points to the newline before the body of the heredoc.
10114          */
10115
10116         /* We are going to modify linestr in place here, so set
10117            aside copies of the string if necessary for re-evals or
10118            (caller $n)[6]. */
10119         /* See the Paranoia note in case LEX_INTERPEND in yylex, for why we
10120            check shared->re_eval_str. */
10121         if (shared->re_eval_start || shared->re_eval_str) {
10122             /* Set aside the rest of the regexp */
10123             if (!shared->re_eval_str)
10124                 shared->re_eval_str =
10125                        newSVpvn(shared->re_eval_start,
10126                                 bufend - shared->re_eval_start);
10127             shared->re_eval_start -= s-d;
10128         }
10129         if (cxstack_ix >= 0
10130             && CxTYPE(cx) == CXt_EVAL
10131             && CxOLD_OP_TYPE(cx) == OP_ENTEREVAL
10132             && cx->blk_eval.cur_text == linestr)
10133         {
10134             cx->blk_eval.cur_text = newSVsv(linestr);
10135             cx->blk_u16 |= 0x40; /* indicate cur_text is ref counted */
10136         }
10137         /* Copy everything from s onwards back to d. */
10138         Move(s,d,bufend-s + 1,char);
10139         SvCUR_set(linestr, SvCUR(linestr) - (s-d));
10140         /* Setting PL_bufend only applies when we have not dug deeper
10141            into other scopes, because sublex_done sets PL_bufend to
10142            SvEND(PL_linestr). */
10143         if (shared == PL_parser->lex_shared) PL_bufend = SvEND(linestr);
10144         s = olds;
10145     }
10146     else
10147     {
10148       SV *linestr_save;
10149       char *oldbufptr_save;
10150       char *oldoldbufptr_save;
10151      streaming:
10152       SvPVCLEAR(tmpstr);   /* avoid "uninitialized" warning */
10153       term = PL_tokenbuf[1];
10154       len--;
10155       linestr_save = PL_linestr; /* must restore this afterwards */
10156       d = s;                     /* and this */
10157       oldbufptr_save = PL_oldbufptr;
10158       oldoldbufptr_save = PL_oldoldbufptr;
10159       PL_linestr = newSVpvs("");
10160       PL_bufend = SvPVX(PL_linestr);
10161       while (1) {
10162         PL_bufptr = PL_bufend;
10163         CopLINE_set(PL_curcop,
10164                     origline + 1 + PL_parser->herelines);
10165         if (!lex_next_chunk(LEX_NO_TERM)
10166          && (!SvCUR(tmpstr) || SvEND(tmpstr)[-1] != '\n')) {
10167             /* Simply freeing linestr_save might seem simpler here, as it
10168                does not matter what PL_linestr points to, since we are
10169                about to croak; but in a quote-like op, linestr_save
10170                will have been prospectively freed already, via
10171                SAVEFREESV(PL_linestr) in sublex_push, so it’s easier to
10172                restore PL_linestr. */
10173             SvREFCNT_dec_NN(PL_linestr);
10174             PL_linestr = linestr_save;
10175             PL_oldbufptr = oldbufptr_save;
10176             PL_oldoldbufptr = oldoldbufptr_save;
10177             goto interminable;
10178         }
10179         CopLINE_set(PL_curcop, origline);
10180         if (!SvCUR(PL_linestr) || PL_bufend[-1] != '\n') {
10181             s = lex_grow_linestr(SvLEN(PL_linestr) + 3);
10182             /* ^That should be enough to avoid this needing to grow:  */
10183             sv_catpvs(PL_linestr, "\n\0");
10184             assert(s == SvPVX(PL_linestr));
10185             PL_bufend = SvEND(PL_linestr);
10186         }
10187         s = PL_bufptr;
10188         PL_parser->herelines++;
10189         PL_last_lop = PL_last_uni = NULL;
10190 #ifndef PERL_STRICT_CR
10191         if (PL_bufend - PL_linestart >= 2) {
10192             if (   (PL_bufend[-2] == '\r' && PL_bufend[-1] == '\n')
10193                 || (PL_bufend[-2] == '\n' && PL_bufend[-1] == '\r'))
10194             {
10195                 PL_bufend[-2] = '\n';
10196                 PL_bufend--;
10197                 SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10198             }
10199             else if (PL_bufend[-1] == '\r')
10200                 PL_bufend[-1] = '\n';
10201         }
10202         else if (PL_bufend - PL_linestart == 1 && PL_bufend[-1] == '\r')
10203             PL_bufend[-1] = '\n';
10204 #endif
10205         if (indented && (PL_bufend-s) >= len) {
10206             char * found = ninstr(s, PL_bufend, (PL_tokenbuf + 1), (PL_tokenbuf +1 + len));
10207
10208             if (found) {
10209                 char *backup = found;
10210                 indent_len = 0;
10211
10212                 /* Only valid if it's preceded by whitespace only */
10213                 while (backup != s && --backup >= s) {
10214                     if (! SPACE_OR_TAB(*backup)) {
10215                         break;
10216                     }
10217                     indent_len++;
10218                 }
10219
10220                 /* All whitespace or none! */
10221                 if (backup == found || SPACE_OR_TAB(*backup)) {
10222                     Newx(indent, indent_len + 1, char);
10223                     memcpy(indent, backup, indent_len);
10224                     indent[indent_len] = 0;
10225                     SvREFCNT_dec(PL_linestr);
10226                     PL_linestr = linestr_save;
10227                     PL_linestart = SvPVX(linestr_save);
10228                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10229                     PL_oldbufptr = oldbufptr_save;
10230                     PL_oldoldbufptr = oldoldbufptr_save;
10231                     s = d;
10232                     break;
10233                 }
10234             }
10235
10236             /* Didn't find it */
10237             sv_catsv(tmpstr,PL_linestr);
10238         } else {
10239             if (*s == term && PL_bufend-s >= len
10240                 && memEQ(s,PL_tokenbuf + 1,len))
10241             {
10242                 SvREFCNT_dec(PL_linestr);
10243                 PL_linestr = linestr_save;
10244                 PL_linestart = SvPVX(linestr_save);
10245                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10246                 PL_oldbufptr = oldbufptr_save;
10247                 PL_oldoldbufptr = oldoldbufptr_save;
10248                 s = d;
10249                 break;
10250             } else {
10251                 sv_catsv(tmpstr,PL_linestr);
10252             }
10253         }
10254       }
10255     }
10256     PL_multi_end = origline + PL_parser->herelines;
10257     if (indented && indent) {
10258         STRLEN linecount = 1;
10259         STRLEN herelen = SvCUR(tmpstr);
10260         char *ss = SvPVX(tmpstr);
10261         char *se = ss + herelen;
10262         SV *newstr = newSV(herelen+1);
10263         SvPOK_on(newstr);
10264
10265         /* Trim leading whitespace */
10266         while (ss < se) {
10267             /* newline only? Copy and move on */
10268             if (*ss == '\n') {
10269                 sv_catpv(newstr,"\n");
10270                 ss++;
10271                 linecount++;
10272
10273             /* Found our indentation? Strip it */
10274             } else if (se - ss >= indent_len
10275                        && memEQ(ss, indent, indent_len))
10276             {
10277                 STRLEN le = 0;
10278
10279                 ss += indent_len;
10280
10281                 while ((ss + le) < se && *(ss + le) != '\n')
10282                     le++;
10283
10284                 sv_catpvn(newstr, ss, le);
10285
10286                 ss += le;
10287
10288             /* Line doesn't begin with our indentation? Croak */
10289             } else {
10290                 Perl_croak(aTHX_
10291                     "Indentation on line %d of here-doc doesn't match delimiter",
10292                     (int)linecount
10293                 );
10294             }
10295         }
10296         /* avoid sv_setsv() as we dont wan't to COW here */
10297         sv_setpvn(tmpstr,SvPVX(newstr),SvCUR(newstr));
10298         Safefree(indent);
10299         SvREFCNT_dec_NN(newstr);
10300     }
10301     if (SvCUR(tmpstr) + 5 < SvLEN(tmpstr)) {
10302         SvPV_shrink_to_cur(tmpstr);
10303     }
10304     if (!IN_BYTES) {
10305         if (UTF && is_utf8_string((U8*)SvPVX_const(tmpstr), SvCUR(tmpstr)))
10306             SvUTF8_on(tmpstr);
10307     }
10308     PL_lex_stuff = tmpstr;
10309     pl_yylval.ival = op_type;
10310     return s;
10311
10312   interminable:
10313     SvREFCNT_dec(tmpstr);
10314     CopLINE_set(PL_curcop, origline);
10315     missingterm(PL_tokenbuf + 1, sizeof(PL_tokenbuf) - 1);
10316 }
10317
10318 /* scan_inputsymbol
10319    takes: position of first '<' in input buffer
10320    returns: position of first char following the matching '>' in
10321             input buffer
10322    side-effects: pl_yylval and lex_op are set.
10323
10324    This code handles:
10325
10326    <>           read from ARGV
10327    <<>>         read from ARGV without magic open
10328    <FH>         read from filehandle
10329    <pkg::FH>    read from package qualified filehandle
10330    <pkg'FH>     read from package qualified filehandle
10331    <$fh>        read from filehandle in $fh
10332    <*.h>        filename glob
10333
10334 */
10335
10336 STATIC char *
10337 S_scan_inputsymbol(pTHX_ char *start)
10338 {
10339     char *s = start;            /* current position in buffer */
10340     char *end;
10341     I32 len;
10342     bool nomagicopen = FALSE;
10343     char *d = PL_tokenbuf;                                      /* start of temp holding space */
10344     const char * const e = PL_tokenbuf + sizeof PL_tokenbuf;    /* end of temp holding space */
10345
10346     PERL_ARGS_ASSERT_SCAN_INPUTSYMBOL;
10347
10348     end = (char *) memchr(s, '\n', PL_bufend - s);
10349     if (!end)
10350         end = PL_bufend;
10351     if (s[1] == '<' && s[2] == '>' && s[3] == '>') {
10352         nomagicopen = TRUE;
10353         *d = '\0';
10354         len = 0;
10355         s += 3;
10356     }
10357     else
10358         s = delimcpy(d, e, s + 1, end, '>', &len);      /* extract until > */
10359
10360     /* die if we didn't have space for the contents of the <>,
10361        or if it didn't end, or if we see a newline
10362     */
10363
10364     if (len >= (I32)sizeof PL_tokenbuf)
10365         Perl_croak(aTHX_ "Excessively long <> operator");
10366     if (s >= end)
10367         Perl_croak(aTHX_ "Unterminated <> operator");
10368
10369     s++;
10370
10371     /* check for <$fh>
10372        Remember, only scalar variables are interpreted as filehandles by
10373        this code.  Anything more complex (e.g., <$fh{$num}>) will be
10374        treated as a glob() call.
10375        This code makes use of the fact that except for the $ at the front,
10376        a scalar variable and a filehandle look the same.
10377     */
10378     if (*d == '$' && d[1]) d++;
10379
10380     /* allow <Pkg'VALUE> or <Pkg::VALUE> */
10381     while (isWORDCHAR_lazy_if_safe(d, e, UTF) || *d == '\'' || *d == ':') {
10382         d += UTF ? UTF8SKIP(d) : 1;
10383     }
10384
10385     /* If we've tried to read what we allow filehandles to look like, and
10386        there's still text left, then it must be a glob() and not a getline.
10387        Use scan_str to pull out the stuff between the <> and treat it
10388        as nothing more than a string.
10389     */
10390
10391     if (d - PL_tokenbuf != len) {
10392         pl_yylval.ival = OP_GLOB;
10393         s = scan_str(start,FALSE,FALSE,FALSE,NULL);
10394         if (!s)
10395            Perl_croak(aTHX_ "Glob not terminated");
10396         return s;
10397     }
10398     else {
10399         bool readline_overriden = FALSE;
10400         GV *gv_readline;
10401         /* we're in a filehandle read situation */
10402         d = PL_tokenbuf;
10403
10404         /* turn <> into <ARGV> */
10405         if (!len)
10406             Copy("ARGV",d,5,char);
10407
10408         /* Check whether readline() is overriden */
10409         if ((gv_readline = gv_override("readline",8)))
10410             readline_overriden = TRUE;
10411
10412         /* if <$fh>, create the ops to turn the variable into a
10413            filehandle
10414         */
10415         if (*d == '$') {
10416             /* try to find it in the pad for this block, otherwise find
10417                add symbol table ops
10418             */
10419             const PADOFFSET tmp = pad_findmy_pvn(d, len, 0);
10420             if (tmp != NOT_IN_PAD) {
10421                 if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
10422                     HV * const stash = PAD_COMPNAME_OURSTASH(tmp);
10423                     HEK * const stashname = HvNAME_HEK(stash);
10424                     SV * const sym = sv_2mortal(newSVhek(stashname));
10425                     sv_catpvs(sym, "::");
10426                     sv_catpv(sym, d+1);
10427                     d = SvPVX(sym);
10428                     goto intro_sym;
10429                 }
10430                 else {
10431                     OP * const o = newOP(OP_PADSV, 0);
10432                     o->op_targ = tmp;
10433                     PL_lex_op = readline_overriden
10434                         ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10435                                 op_append_elem(OP_LIST, o,
10436                                     newCVREF(0, newGVOP(OP_GV,0,gv_readline))))
10437                         : newUNOP(OP_READLINE, 0, o);
10438                 }
10439             }
10440             else {
10441                 GV *gv;
10442                 ++d;
10443               intro_sym:
10444                 gv = gv_fetchpv(d,
10445                                 GV_ADDMULTI | ( UTF ? SVf_UTF8 : 0 ),
10446                                 SVt_PV);
10447                 PL_lex_op = readline_overriden
10448                     ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10449                             op_append_elem(OP_LIST,
10450                                 newUNOP(OP_RV2SV, 0, newGVOP(OP_GV, 0, gv)),
10451                                 newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10452                     : newUNOP(OP_READLINE, 0,
10453                             newUNOP(OP_RV2SV, 0,
10454                                 newGVOP(OP_GV, 0, gv)));
10455             }
10456             /* we created the ops in PL_lex_op, so make pl_yylval.ival a null op */
10457             pl_yylval.ival = OP_NULL;
10458         }
10459
10460         /* If it's none of the above, it must be a literal filehandle
10461            (<Foo::BAR> or <FOO>) so build a simple readline OP */
10462         else {
10463             GV * const gv = gv_fetchpv(d, GV_ADD | ( UTF ? SVf_UTF8 : 0 ), SVt_PVIO);
10464             PL_lex_op = readline_overriden
10465                 ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10466                         op_append_elem(OP_LIST,
10467                             newGVOP(OP_GV, 0, gv),
10468                             newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10469                 : newUNOP(OP_READLINE, nomagicopen ? OPf_SPECIAL : 0, newGVOP(OP_GV, 0, gv));
10470             pl_yylval.ival = OP_NULL;
10471         }
10472     }
10473
10474     return s;
10475 }
10476
10477
10478 /* scan_str
10479    takes:
10480         start                   position in buffer
10481         keep_bracketed_quoted   preserve \ quoting of embedded delimiters, but
10482                                 only if they are of the open/close form
10483         keep_delims             preserve the delimiters around the string
10484         re_reparse              compiling a run-time /(?{})/:
10485                                    collapse // to /,  and skip encoding src
10486         delimp                  if non-null, this is set to the position of
10487                                 the closing delimiter, or just after it if
10488                                 the closing and opening delimiters differ
10489                                 (i.e., the opening delimiter of a substitu-
10490                                 tion replacement)
10491    returns: position to continue reading from buffer
10492    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
10493         updates the read buffer.
10494
10495    This subroutine pulls a string out of the input.  It is called for:
10496         q               single quotes           q(literal text)
10497         '               single quotes           'literal text'
10498         qq              double quotes           qq(interpolate $here please)
10499         "               double quotes           "interpolate $here please"
10500         qx              backticks               qx(/bin/ls -l)
10501         `               backticks               `/bin/ls -l`
10502         qw              quote words             @EXPORT_OK = qw( func() $spam )
10503         m//             regexp match            m/this/
10504         s///            regexp substitute       s/this/that/
10505         tr///           string transliterate    tr/this/that/
10506         y///            string transliterate    y/this/that/
10507         ($*@)           sub prototypes          sub foo ($)
10508         (stuff)         sub attr parameters     sub foo : attr(stuff)
10509         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
10510
10511    In most of these cases (all but <>, patterns and transliterate)
10512    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
10513    calls scan_str().  s/// makes yylex() call scan_subst() which calls
10514    scan_str().  tr/// and y/// make yylex() call scan_trans() which
10515    calls scan_str().
10516
10517    It skips whitespace before the string starts, and treats the first
10518    character as the delimiter.  If the delimiter is one of ([{< then
10519    the corresponding "close" character )]}> is used as the closing
10520    delimiter.  It allows quoting of delimiters, and if the string has
10521    balanced delimiters ([{<>}]) it allows nesting.
10522
10523    On success, the SV with the resulting string is put into lex_stuff or,
10524    if that is already non-NULL, into lex_repl. The second case occurs only
10525    when parsing the RHS of the special constructs s/// and tr/// (y///).
10526    For convenience, the terminating delimiter character is stuffed into
10527    SvIVX of the SV.
10528 */
10529
10530 STATIC char *
10531 S_scan_str(pTHX_ char *start, int keep_bracketed_quoted, int keep_delims, int re_reparse,
10532                  char **delimp
10533     )
10534 {
10535     SV *sv;                     /* scalar value: string */
10536     const char *tmps;           /* temp string, used for delimiter matching */
10537     char *s = start;            /* current position in the buffer */
10538     char term;                  /* terminating character */
10539     char *to;                   /* current position in the sv's data */
10540     I32 brackets = 1;           /* bracket nesting level */
10541     bool has_utf8 = FALSE;      /* is there any utf8 content? */
10542     IV termcode;                /* terminating char. code */
10543     U8 termstr[UTF8_MAXBYTES];  /* terminating string */
10544     STRLEN termlen;             /* length of terminating string */
10545     line_t herelines;
10546
10547     /* The delimiters that have a mirror-image closing one */
10548     const char * opening_delims = "([{<";
10549     const char * closing_delims = ")]}>";
10550
10551     const char * non_grapheme_msg = "Use of unassigned code point or"
10552                                     " non-standalone grapheme for a delimiter"
10553                                     " will be a fatal error starting in Perl"
10554                                     " 5.30";
10555     /* The only non-UTF character that isn't a stand alone grapheme is
10556      * white-space, hence can't be a delimiter.  So can skip for non-UTF-8 */
10557     bool check_grapheme = UTF && ckWARN_d(WARN_DEPRECATED);
10558
10559     PERL_ARGS_ASSERT_SCAN_STR;
10560
10561     /* skip space before the delimiter */
10562     if (isSPACE(*s)) {
10563         s = skipspace(s);
10564     }
10565
10566     /* mark where we are, in case we need to report errors */
10567     CLINE;
10568
10569     /* after skipping whitespace, the next character is the terminator */
10570     term = *s;
10571     if (!UTF || UTF8_IS_INVARIANT(term)) {
10572         termcode = termstr[0] = term;
10573         termlen = 1;
10574     }
10575     else {
10576         termcode = utf8_to_uvchr_buf((U8*)s, (U8*)PL_bufend, &termlen);
10577         if (check_grapheme) {
10578             if (   UNLIKELY(UNICODE_IS_SUPER(termcode))
10579                 || UNLIKELY(UNICODE_IS_NONCHAR(termcode)))
10580             {
10581                 /* These are considered graphemes, and since the ending
10582                  * delimiter will be the same, we don't have to check the other
10583                  * end */
10584                 check_grapheme = FALSE;
10585             }
10586             else if (UNLIKELY(! _is_grapheme((U8 *) start,
10587                                              (U8 *) s,
10588                                              (U8 *) PL_bufend,
10589                                              termcode)))
10590             {
10591                 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED), "%s", non_grapheme_msg);
10592
10593                 /* Don't have to check the other end, as have already warned at
10594                  * this one */
10595                 check_grapheme = FALSE;
10596             }
10597         }
10598
10599         Copy(s, termstr, termlen, U8);
10600     }
10601
10602     /* mark where we are */
10603     PL_multi_start = CopLINE(PL_curcop);
10604     PL_multi_open = termcode;
10605     herelines = PL_parser->herelines;
10606
10607     /* If the delimiter has a mirror-image closing one, get it */
10608     if (term && (tmps = strchr(opening_delims, term))) {
10609         termcode = termstr[0] = term = closing_delims[tmps - opening_delims];
10610     }
10611
10612     PL_multi_close = termcode;
10613
10614     if (PL_multi_open == PL_multi_close) {
10615         keep_bracketed_quoted = FALSE;
10616     }
10617
10618     /* create a new SV to hold the contents.  79 is the SV's initial length.
10619        What a random number. */
10620     sv = newSV_type(SVt_PVIV);
10621     SvGROW(sv, 80);
10622     SvIV_set(sv, termcode);
10623     (void)SvPOK_only(sv);               /* validate pointer */
10624
10625     /* move past delimiter and try to read a complete string */
10626     if (keep_delims)
10627         sv_catpvn(sv, s, termlen);
10628     s += termlen;
10629     for (;;) {
10630         /* extend sv if need be */
10631         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
10632         /* set 'to' to the next character in the sv's string */
10633         to = SvPVX(sv)+SvCUR(sv);
10634
10635         /* if open delimiter is the close delimiter read unbridle */
10636         if (PL_multi_open == PL_multi_close) {
10637             for (; s < PL_bufend; s++,to++) {
10638                 /* embedded newlines increment the current line number */
10639                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
10640                     COPLINE_INC_WITH_HERELINES;
10641                 /* handle quoted delimiters */
10642                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
10643                     if (!keep_bracketed_quoted
10644                         && (s[1] == term
10645                             || (re_reparse && s[1] == '\\'))
10646                     )
10647                         s++;
10648                     else /* any other quotes are simply copied straight through */
10649                         *to++ = *s++;
10650                 }
10651                 /* terminate when run out of buffer (the for() condition), or
10652                    have found the terminator */
10653                 else if (*s == term) {  /* First byte of terminator matches */
10654                     if (termlen == 1)   /* If is the only byte, are done */
10655                         break;
10656
10657                     /* If the remainder of the terminator matches, also are
10658                      * done, after checking that is a separate grapheme */
10659                     if (   s + termlen <= PL_bufend
10660                         && memEQ(s + 1, (char*)termstr + 1, termlen - 1))
10661                     {
10662                         if (   check_grapheme
10663                             && UNLIKELY(! _is_grapheme((U8 *) start,
10664                                                               (U8 *) s,
10665                                                               (U8 *) PL_bufend,
10666                                                               termcode)))
10667                         {
10668                             Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
10669                                         "%s", non_grapheme_msg);
10670                         }
10671                         break;
10672                     }
10673                 }
10674                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF) {
10675                     has_utf8 = TRUE;
10676                 }
10677
10678                 *to = *s;
10679             }
10680         }
10681
10682         /* if the terminator isn't the same as the start character (e.g.,
10683            matched brackets), we have to allow more in the quoting, and
10684            be prepared for nested brackets.
10685         */
10686         else {
10687             /* read until we run out of string, or we find the terminator */
10688             for (; s < PL_bufend; s++,to++) {
10689                 /* embedded newlines increment the line count */
10690                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
10691                     COPLINE_INC_WITH_HERELINES;
10692                 /* backslashes can escape the open or closing characters */
10693                 if (*s == '\\' && s+1 < PL_bufend) {
10694                     if (!keep_bracketed_quoted
10695                        && ( ((UV)s[1] == PL_multi_open)
10696                          || ((UV)s[1] == PL_multi_close) ))
10697                     {
10698                         s++;
10699                     }
10700                     else
10701                         *to++ = *s++;
10702                 }
10703                 /* allow nested opens and closes */
10704                 else if ((UV)*s == PL_multi_close && --brackets <= 0)
10705                     break;
10706                 else if ((UV)*s == PL_multi_open)
10707                     brackets++;
10708                 else if (!has_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
10709                     has_utf8 = TRUE;
10710                 *to = *s;
10711             }
10712         }
10713         /* terminate the copied string and update the sv's end-of-string */
10714         *to = '\0';
10715         SvCUR_set(sv, to - SvPVX_const(sv));
10716
10717         /*
10718          * this next chunk reads more into the buffer if we're not done yet
10719          */
10720
10721         if (s < PL_bufend)
10722             break;              /* handle case where we are done yet :-) */
10723
10724 #ifndef PERL_STRICT_CR
10725         if (to - SvPVX_const(sv) >= 2) {
10726             if (   (to[-2] == '\r' && to[-1] == '\n')
10727                 || (to[-2] == '\n' && to[-1] == '\r'))
10728             {
10729                 to[-2] = '\n';
10730                 to--;
10731                 SvCUR_set(sv, to - SvPVX_const(sv));
10732             }
10733             else if (to[-1] == '\r')
10734                 to[-1] = '\n';
10735         }
10736         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
10737             to[-1] = '\n';
10738 #endif
10739
10740         /* if we're out of file, or a read fails, bail and reset the current
10741            line marker so we can report where the unterminated string began
10742         */
10743         COPLINE_INC_WITH_HERELINES;
10744         PL_bufptr = PL_bufend;
10745         if (!lex_next_chunk(0)) {
10746             sv_free(sv);
10747             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
10748             return NULL;
10749         }
10750         s = start = PL_bufptr;
10751     }
10752
10753     /* at this point, we have successfully read the delimited string */
10754
10755     if (keep_delims)
10756             sv_catpvn(sv, s, termlen);
10757     s += termlen;
10758
10759     if (has_utf8)
10760         SvUTF8_on(sv);
10761
10762     PL_multi_end = CopLINE(PL_curcop);
10763     CopLINE_set(PL_curcop, PL_multi_start);
10764     PL_parser->herelines = herelines;
10765
10766     /* if we allocated too much space, give some back */
10767     if (SvCUR(sv) + 5 < SvLEN(sv)) {
10768         SvLEN_set(sv, SvCUR(sv) + 1);
10769         SvPV_renew(sv, SvLEN(sv));
10770     }
10771
10772     /* decide whether this is the first or second quoted string we've read
10773        for this op
10774     */
10775
10776     if (PL_lex_stuff)
10777         PL_parser->lex_sub_repl = sv;
10778     else
10779         PL_lex_stuff = sv;
10780     if (delimp) *delimp = PL_multi_open == PL_multi_close ? s-termlen : s;
10781     return s;
10782 }
10783
10784 /*
10785   scan_num
10786   takes: pointer to position in buffer
10787   returns: pointer to new position in buffer
10788   side-effects: builds ops for the constant in pl_yylval.op
10789
10790   Read a number in any of the formats that Perl accepts:
10791
10792   \d(_?\d)*(\.(\d(_?\d)*)?)?[Ee][\+\-]?(\d(_?\d)*)      12 12.34 12.
10793   \.\d(_?\d)*[Ee][\+\-]?(\d(_?\d)*)                     .34
10794   0b[01](_?[01])*                                       binary integers
10795   0[0-7](_?[0-7])*                                      octal integers
10796   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*                         hexadecimal integers
10797   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*(?:\.\d*)?p[+-]?[0-9]+   hexadecimal floats
10798
10799   Like most scan_ routines, it uses the PL_tokenbuf buffer to hold the
10800   thing it reads.
10801
10802   If it reads a number without a decimal point or an exponent, it will
10803   try converting the number to an integer and see if it can do so
10804   without loss of precision.
10805 */
10806
10807 char *
10808 Perl_scan_num(pTHX_ const char *start, YYSTYPE* lvalp)
10809 {
10810     const char *s = start;      /* current position in buffer */
10811     char *d;                    /* destination in temp buffer */
10812     char *e;                    /* end of temp buffer */
10813     NV nv;                              /* number read, as a double */
10814     SV *sv = NULL;                      /* place to put the converted number */
10815     bool floatit;                       /* boolean: int or float? */
10816     const char *lastub = NULL;          /* position of last underbar */
10817     static const char* const number_too_long = "Number too long";
10818     bool warned_about_underscore = 0;
10819 #define WARN_ABOUT_UNDERSCORE() \
10820         do { \
10821             if (!warned_about_underscore) { \
10822                 warned_about_underscore = 1; \
10823                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), \
10824                                "Misplaced _ in number"); \
10825             } \
10826         } while(0)
10827     /* Hexadecimal floating point.
10828      *
10829      * In many places (where we have quads and NV is IEEE 754 double)
10830      * we can fit the mantissa bits of a NV into an unsigned quad.
10831      * (Note that UVs might not be quads even when we have quads.)
10832      * This will not work everywhere, though (either no quads, or
10833      * using long doubles), in which case we have to resort to NV,
10834      * which will probably mean horrible loss of precision due to
10835      * multiple fp operations. */
10836     bool hexfp = FALSE;
10837     int total_bits = 0;
10838     int significant_bits = 0;
10839 #if NVSIZE == 8 && defined(HAS_QUAD) && defined(Uquad_t)
10840 #  define HEXFP_UQUAD
10841     Uquad_t hexfp_uquad = 0;
10842     int hexfp_frac_bits = 0;
10843 #else
10844 #  define HEXFP_NV
10845     NV hexfp_nv = 0.0;
10846 #endif
10847     NV hexfp_mult = 1.0;
10848     UV high_non_zero = 0; /* highest digit */
10849     int non_zero_integer_digits = 0;
10850
10851     PERL_ARGS_ASSERT_SCAN_NUM;
10852
10853     /* We use the first character to decide what type of number this is */
10854
10855     switch (*s) {
10856     default:
10857         Perl_croak(aTHX_ "panic: scan_num, *s=%d", *s);
10858
10859     /* if it starts with a 0, it could be an octal number, a decimal in
10860        0.13 disguise, or a hexadecimal number, or a binary number. */
10861     case '0':
10862         {
10863           /* variables:
10864              u          holds the "number so far"
10865              shift      the power of 2 of the base
10866                         (hex == 4, octal == 3, binary == 1)
10867              overflowed was the number more than we can hold?
10868
10869              Shift is used when we add a digit.  It also serves as an "are
10870              we in octal/hex/binary?" indicator to disallow hex characters
10871              when in octal mode.
10872            */
10873             NV n = 0.0;
10874             UV u = 0;
10875             I32 shift;
10876             bool overflowed = FALSE;
10877             bool just_zero  = TRUE;     /* just plain 0 or binary number? */
10878             static const NV nvshift[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
10879             static const char* const bases[5] =
10880               { "", "binary", "", "octal", "hexadecimal" };
10881             static const char* const Bases[5] =
10882               { "", "Binary", "", "Octal", "Hexadecimal" };
10883             static const char* const maxima[5] =
10884               { "",
10885                 "0b11111111111111111111111111111111",
10886                 "",
10887                 "037777777777",
10888                 "0xffffffff" };
10889             const char *base, *Base, *max;
10890
10891             /* check for hex */
10892             if (isALPHA_FOLD_EQ(s[1], 'x')) {
10893                 shift = 4;
10894                 s += 2;
10895                 just_zero = FALSE;
10896             } else if (isALPHA_FOLD_EQ(s[1], 'b')) {
10897                 shift = 1;
10898                 s += 2;
10899                 just_zero = FALSE;
10900             }
10901             /* check for a decimal in disguise */
10902             else if (s[1] == '.' || isALPHA_FOLD_EQ(s[1], 'e'))
10903                 goto decimal;
10904             /* so it must be octal */
10905             else {
10906                 shift = 3;
10907                 s++;
10908             }
10909
10910             if (*s == '_') {
10911                 WARN_ABOUT_UNDERSCORE();
10912                lastub = s++;
10913             }
10914
10915             base = bases[shift];
10916             Base = Bases[shift];
10917             max  = maxima[shift];
10918
10919             /* read the rest of the number */
10920             for (;;) {
10921                 /* x is used in the overflow test,
10922                    b is the digit we're adding on. */
10923                 UV x, b;
10924
10925                 switch (*s) {
10926
10927                 /* if we don't mention it, we're done */
10928                 default:
10929                     goto out;
10930
10931                 /* _ are ignored -- but warned about if consecutive */
10932                 case '_':
10933                     if (lastub && s == lastub + 1)
10934                         WARN_ABOUT_UNDERSCORE();
10935                     lastub = s++;
10936                     break;
10937
10938                 /* 8 and 9 are not octal */
10939                 case '8': case '9':
10940                     if (shift == 3)
10941                         yyerror(Perl_form(aTHX_ "Illegal octal digit '%c'", *s));
10942                     /* FALLTHROUGH */
10943
10944                 /* octal digits */
10945                 case '2': case '3': case '4':
10946                 case '5': case '6': case '7':
10947                     if (shift == 1)
10948                         yyerror(Perl_form(aTHX_ "Illegal binary digit '%c'", *s));
10949                     /* FALLTHROUGH */
10950
10951                 case '0': case '1':
10952                     b = *s++ & 15;              /* ASCII digit -> value of digit */
10953                     goto digit;
10954
10955                 /* hex digits */
10956                 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
10957                 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
10958                     /* make sure they said 0x */
10959                     if (shift != 4)
10960                         goto out;
10961                     b = (*s++ & 7) + 9;
10962
10963                     /* Prepare to put the digit we have onto the end
10964                        of the number so far.  We check for overflows.
10965                     */
10966
10967                   digit:
10968                     just_zero = FALSE;
10969                     if (!overflowed) {
10970                         x = u << shift; /* make room for the digit */
10971
10972                         total_bits += shift;
10973
10974                         if ((x >> shift) != u
10975                             && !(PL_hints & HINT_NEW_BINARY)) {
10976                             overflowed = TRUE;
10977                             n = (NV) u;
10978                             Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
10979                                              "Integer overflow in %s number",
10980                                              base);
10981                         } else
10982                             u = x | b;          /* add the digit to the end */
10983                     }
10984                     if (overflowed) {
10985                         n *= nvshift[shift];
10986                         /* If an NV has not enough bits in its
10987                          * mantissa to represent an UV this summing of
10988                          * small low-order numbers is a waste of time
10989                          * (because the NV cannot preserve the
10990                          * low-order bits anyway): we could just
10991                          * remember when did we overflow and in the
10992                          * end just multiply n by the right
10993                          * amount. */
10994                         n += (NV) b;
10995                     }
10996
10997                     if (high_non_zero == 0 && b > 0)
10998                         high_non_zero = b;
10999
11000                     if (high_non_zero)
11001                         non_zero_integer_digits++;
11002
11003                     /* this could be hexfp, but peek ahead
11004                      * to avoid matching ".." */
11005                     if (UNLIKELY(HEXFP_PEEK(s))) {
11006                         goto out;
11007                     }
11008
11009                     break;
11010                 }
11011             }
11012
11013           /* if we get here, we had success: make a scalar value from
11014              the number.
11015           */
11016           out:
11017
11018             /* final misplaced underbar check */
11019             if (s[-1] == '_')
11020                 WARN_ABOUT_UNDERSCORE();
11021
11022             if (UNLIKELY(HEXFP_PEEK(s))) {
11023                 /* Do sloppy (on the underbars) but quick detection
11024                  * (and value construction) for hexfp, the decimal
11025                  * detection will shortly be more thorough with the
11026                  * underbar checks. */
11027                 const char* h = s;
11028                 significant_bits = non_zero_integer_digits * shift;
11029 #ifdef HEXFP_UQUAD
11030                 hexfp_uquad = u;
11031 #else /* HEXFP_NV */
11032                 hexfp_nv = u;
11033 #endif
11034                 /* Ignore the leading zero bits of
11035                  * the high (first) non-zero digit. */
11036                 if (high_non_zero) {
11037                     if (high_non_zero < 0x8)
11038                         significant_bits--;
11039                     if (high_non_zero < 0x4)
11040                         significant_bits--;
11041                     if (high_non_zero < 0x2)
11042                         significant_bits--;
11043                 }
11044
11045                 if (*h == '.') {
11046 #ifdef HEXFP_NV
11047                     NV nv_mult = 1.0;
11048 #endif
11049                     bool accumulate = TRUE;
11050                     for (h++; (isXDIGIT(*h) || *h == '_'); h++) {
11051                         if (isXDIGIT(*h)) {
11052                             U8 b = XDIGIT_VALUE(*h);
11053                             significant_bits += shift;
11054 #ifdef HEXFP_UQUAD
11055                             if (accumulate) {
11056                                 if (significant_bits < NV_MANT_DIG) {
11057                                     /* We are in the long "run" of xdigits,
11058                                      * accumulate the full four bits. */
11059                                     hexfp_uquad <<= shift;
11060                                     hexfp_uquad |= b;
11061                                     hexfp_frac_bits += shift;
11062                                 } else {
11063                                     /* We are at a hexdigit either at,
11064                                      * or straddling, the edge of mantissa.
11065                                      * We will try grabbing as many as
11066                                      * possible bits. */
11067                                     int tail =
11068                                       significant_bits - NV_MANT_DIG;
11069                                     if (tail <= 0)
11070                                        tail += shift;
11071                                     hexfp_uquad <<= tail;
11072                                     hexfp_uquad |= b >> (shift - tail);
11073                                     hexfp_frac_bits += tail;
11074
11075                                     /* Ignore the trailing zero bits
11076                                      * of the last non-zero xdigit.
11077                                      *
11078                                      * The assumption here is that if
11079                                      * one has input of e.g. the xdigit
11080                                      * eight (0x8), there is only one
11081                                      * bit being input, not the full
11082                                      * four bits.  Conversely, if one
11083                                      * specifies a zero xdigit, the
11084                                      * assumption is that one really
11085                                      * wants all those bits to be zero. */
11086                                     if (b) {
11087                                         if ((b & 0x1) == 0x0) {
11088                                             significant_bits--;
11089                                             if ((b & 0x2) == 0x0) {
11090                                                 significant_bits--;
11091                                                 if ((b & 0x4) == 0x0) {
11092                                                     significant_bits--;
11093                                                 }
11094                                             }
11095                                         }
11096                                     }
11097
11098                                     accumulate = FALSE;
11099                                 }
11100                             } else {
11101                                 /* Keep skipping the xdigits, and
11102                                  * accumulating the significant bits,
11103                                  * but do not shift the uquad
11104                                  * (which would catastrophically drop
11105                                  * high-order bits) or accumulate the
11106                                  * xdigits anymore. */
11107                             }
11108 #else /* HEXFP_NV */
11109                             if (accumulate) {
11110                                 nv_mult /= 16.0;
11111                                 if (nv_mult > 0.0)
11112                                     hexfp_nv += b * nv_mult;
11113                                 else
11114                                     accumulate = FALSE;
11115                             }
11116 #endif
11117                         }
11118                         if (significant_bits >= NV_MANT_DIG)
11119                             accumulate = FALSE;
11120                     }
11121                 }
11122
11123                 if ((total_bits > 0 || significant_bits > 0) &&
11124                     isALPHA_FOLD_EQ(*h, 'p')) {
11125                     bool negexp = FALSE;
11126                     h++;
11127                     if (*h == '+')
11128                         h++;
11129                     else if (*h == '-') {
11130                         negexp = TRUE;
11131                         h++;
11132                     }
11133                     if (isDIGIT(*h)) {
11134                         I32 hexfp_exp = 0;
11135                         while (isDIGIT(*h) || *h == '_') {
11136                             if (isDIGIT(*h)) {
11137                                 hexfp_exp *= 10;
11138                                 hexfp_exp += *h - '0';
11139 #ifdef NV_MIN_EXP
11140                                 if (negexp
11141                                     && -hexfp_exp < NV_MIN_EXP - 1) {
11142                                     /* NOTE: this means that the exponent
11143                                      * underflow warning happens for
11144                                      * the IEEE 754 subnormals (denormals),
11145                                      * because DBL_MIN_EXP etc are the lowest
11146                                      * possible binary (or, rather, DBL_RADIX-base)
11147                                      * exponent for normals, not subnormals.
11148                                      *
11149                                      * This may or may not be a good thing. */
11150                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11151                                                    "Hexadecimal float: exponent underflow");
11152                                     break;
11153                                 }
11154 #endif
11155 #ifdef NV_MAX_EXP
11156                                 if (!negexp
11157                                     && hexfp_exp > NV_MAX_EXP - 1) {
11158                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11159                                                    "Hexadecimal float: exponent overflow");
11160                                     break;
11161                                 }
11162 #endif
11163                             }
11164                             h++;
11165                         }
11166                         if (negexp)
11167                             hexfp_exp = -hexfp_exp;
11168 #ifdef HEXFP_UQUAD
11169                         hexfp_exp -= hexfp_frac_bits;
11170 #endif
11171                         hexfp_mult = Perl_pow(2.0, hexfp_exp);
11172                         hexfp = TRUE;
11173                         goto decimal;
11174                     }
11175                 }
11176             }
11177
11178             if (overflowed) {
11179                 if (n > 4294967295.0)
11180                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11181                                    "%s number > %s non-portable",
11182                                    Base, max);
11183                 sv = newSVnv(n);
11184             }
11185             else {
11186 #if UVSIZE > 4
11187                 if (u > 0xffffffff)
11188                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11189                                    "%s number > %s non-portable",
11190                                    Base, max);
11191 #endif
11192                 sv = newSVuv(u);
11193             }
11194             if (just_zero && (PL_hints & HINT_NEW_INTEGER))
11195                 sv = new_constant(start, s - start, "integer",
11196                                   sv, NULL, NULL, 0);
11197             else if (PL_hints & HINT_NEW_BINARY)
11198                 sv = new_constant(start, s - start, "binary", sv, NULL, NULL, 0);
11199         }
11200         break;
11201
11202     /*
11203       handle decimal numbers.
11204       we're also sent here when we read a 0 as the first digit
11205     */
11206     case '1': case '2': case '3': case '4': case '5':
11207     case '6': case '7': case '8': case '9': case '.':
11208       decimal:
11209         d = PL_tokenbuf;
11210         e = PL_tokenbuf + sizeof PL_tokenbuf - 6; /* room for various punctuation */
11211         floatit = FALSE;
11212         if (hexfp) {
11213             floatit = TRUE;
11214             *d++ = '0';
11215             *d++ = 'x';
11216             s = start + 2;
11217         }
11218
11219         /* read next group of digits and _ and copy into d */
11220         while (isDIGIT(*s)
11221                || *s == '_'
11222                || UNLIKELY(hexfp && isXDIGIT(*s)))
11223         {
11224             /* skip underscores, checking for misplaced ones
11225                if -w is on
11226             */
11227             if (*s == '_') {
11228                 if (lastub && s == lastub + 1)
11229                     WARN_ABOUT_UNDERSCORE();
11230                 lastub = s++;
11231             }
11232             else {
11233                 /* check for end of fixed-length buffer */
11234                 if (d >= e)
11235                     Perl_croak(aTHX_ "%s", number_too_long);
11236                 /* if we're ok, copy the character */
11237                 *d++ = *s++;
11238             }
11239         }
11240
11241         /* final misplaced underbar check */
11242         if (lastub && s == lastub + 1)
11243             WARN_ABOUT_UNDERSCORE();
11244
11245         /* read a decimal portion if there is one.  avoid
11246            3..5 being interpreted as the number 3. followed
11247            by .5
11248         */
11249         if (*s == '.' && s[1] != '.') {
11250             floatit = TRUE;
11251             *d++ = *s++;
11252
11253             if (*s == '_') {
11254                 WARN_ABOUT_UNDERSCORE();
11255                 lastub = s;
11256             }
11257
11258             /* copy, ignoring underbars, until we run out of digits.
11259             */
11260             for (; isDIGIT(*s)
11261                    || *s == '_'
11262                    || UNLIKELY(hexfp && isXDIGIT(*s));
11263                  s++)
11264             {
11265                 /* fixed length buffer check */
11266                 if (d >= e)
11267                     Perl_croak(aTHX_ "%s", number_too_long);
11268                 if (*s == '_') {
11269                    if (lastub && s == lastub + 1)
11270                         WARN_ABOUT_UNDERSCORE();
11271                    lastub = s;
11272                 }
11273                 else
11274                     *d++ = *s;
11275             }
11276             /* fractional part ending in underbar? */
11277             if (s[-1] == '_')
11278                 WARN_ABOUT_UNDERSCORE();
11279             if (*s == '.' && isDIGIT(s[1])) {
11280                 /* oops, it's really a v-string, but without the "v" */
11281                 s = start;
11282                 goto vstring;
11283             }
11284         }
11285
11286         /* read exponent part, if present */
11287         if ((isALPHA_FOLD_EQ(*s, 'e')
11288               || UNLIKELY(hexfp && isALPHA_FOLD_EQ(*s, 'p')))
11289             && strchr("+-0123456789_", s[1]))
11290         {
11291             int exp_digits = 0;
11292             const char *save_s = s;
11293             char * save_d = d;
11294
11295             /* regardless of whether user said 3E5 or 3e5, use lower 'e',
11296                ditto for p (hexfloats) */
11297             if ((isALPHA_FOLD_EQ(*s, 'e'))) {
11298                 /* At least some Mach atof()s don't grok 'E' */
11299                 *d++ = 'e';
11300             }
11301             else if (UNLIKELY(hexfp && (isALPHA_FOLD_EQ(*s, 'p')))) {
11302                 *d++ = 'p';
11303             }
11304
11305             s++;
11306
11307
11308             /* stray preinitial _ */
11309             if (*s == '_') {
11310                 WARN_ABOUT_UNDERSCORE();
11311                 lastub = s++;
11312             }
11313
11314             /* allow positive or negative exponent */
11315             if (*s == '+' || *s == '-')
11316                 *d++ = *s++;
11317
11318             /* stray initial _ */
11319             if (*s == '_') {
11320                 WARN_ABOUT_UNDERSCORE();
11321                 lastub = s++;
11322             }
11323
11324             /* read digits of exponent */
11325             while (isDIGIT(*s) || *s == '_') {
11326                 if (isDIGIT(*s)) {
11327                     ++exp_digits;
11328                     if (d >= e)
11329                         Perl_croak(aTHX_ "%s", number_too_long);
11330                     *d++ = *s++;
11331                 }
11332                 else {
11333                    if (((lastub && s == lastub + 1)
11334                         || (!isDIGIT(s[1]) && s[1] != '_')))
11335                         WARN_ABOUT_UNDERSCORE();
11336                    lastub = s++;
11337                 }
11338             }
11339
11340             if (!exp_digits) {
11341                 /* no exponent digits, the [eEpP] could be for something else,
11342                  * though in practice we don't get here for p since that's preparsed
11343                  * earlier, and results in only the 0xX being consumed, so behave similarly
11344                  * for decimal floats and consume only the D.DD, leaving the [eE] to the
11345                  * next token.
11346                  */
11347                 s = save_s;
11348                 d = save_d;
11349             }
11350             else {
11351                 floatit = TRUE;
11352             }
11353         }
11354
11355
11356         /*
11357            We try to do an integer conversion first if no characters
11358            indicating "float" have been found.
11359          */
11360
11361         if (!floatit) {
11362             UV uv;
11363             const int flags = grok_number (PL_tokenbuf, d - PL_tokenbuf, &uv);
11364
11365             if (flags == IS_NUMBER_IN_UV) {
11366               if (uv <= IV_MAX)
11367                 sv = newSViv(uv); /* Prefer IVs over UVs. */
11368               else
11369                 sv = newSVuv(uv);
11370             } else if (flags == (IS_NUMBER_IN_UV | IS_NUMBER_NEG)) {
11371               if (uv <= (UV) IV_MIN)
11372                 sv = newSViv(-(IV)uv);
11373               else
11374                 floatit = TRUE;
11375             } else
11376               floatit = TRUE;
11377         }
11378         if (floatit) {
11379             STORE_LC_NUMERIC_UNDERLYING_SET_STANDARD();
11380             /* terminate the string */
11381             *d = '\0';
11382             if (UNLIKELY(hexfp)) {
11383 #  ifdef NV_MANT_DIG
11384                 if (significant_bits > NV_MANT_DIG)
11385                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11386                                    "Hexadecimal float: mantissa overflow");
11387 #  endif
11388 #ifdef HEXFP_UQUAD
11389                 nv = hexfp_uquad * hexfp_mult;
11390 #else /* HEXFP_NV */
11391                 nv = hexfp_nv * hexfp_mult;
11392 #endif
11393             } else {
11394                 nv = Atof(PL_tokenbuf);
11395             }
11396             RESTORE_LC_NUMERIC_UNDERLYING();
11397             sv = newSVnv(nv);
11398         }
11399
11400         if ( floatit
11401              ? (PL_hints & HINT_NEW_FLOAT) : (PL_hints & HINT_NEW_INTEGER) ) {
11402             const char *const key = floatit ? "float" : "integer";
11403             const STRLEN keylen = floatit ? 5 : 7;
11404             sv = S_new_constant(aTHX_ PL_tokenbuf, d - PL_tokenbuf,
11405                                 key, keylen, sv, NULL, NULL, 0);
11406         }
11407         break;
11408
11409     /* if it starts with a v, it could be a v-string */
11410     case 'v':
11411     vstring:
11412                 sv = newSV(5); /* preallocate storage space */
11413                 ENTER_with_name("scan_vstring");
11414                 SAVEFREESV(sv);
11415                 s = scan_vstring(s, PL_bufend, sv);
11416                 SvREFCNT_inc_simple_void_NN(sv);
11417                 LEAVE_with_name("scan_vstring");
11418         break;
11419     }
11420
11421     /* make the op for the constant and return */
11422
11423     if (sv)
11424         lvalp->opval = newSVOP(OP_CONST, 0, sv);
11425     else
11426         lvalp->opval = NULL;
11427
11428     return (char *)s;
11429 }
11430
11431 STATIC char *
11432 S_scan_formline(pTHX_ char *s)
11433 {
11434     SV * const stuff = newSVpvs("");
11435     bool needargs = FALSE;
11436     bool eofmt = FALSE;
11437
11438     PERL_ARGS_ASSERT_SCAN_FORMLINE;
11439
11440     while (!needargs) {
11441         char *eol;
11442         if (*s == '.') {
11443             char *t = s+1;
11444 #ifdef PERL_STRICT_CR
11445             while (SPACE_OR_TAB(*t))
11446                 t++;
11447 #else
11448             while (SPACE_OR_TAB(*t) || *t == '\r')
11449                 t++;
11450 #endif
11451             if (*t == '\n' || t == PL_bufend) {
11452                 eofmt = TRUE;
11453                 break;
11454             }
11455         }
11456         eol = (char *) memchr(s,'\n',PL_bufend-s);
11457         if (!eol++)
11458                 eol = PL_bufend;
11459         if (*s != '#') {
11460             char *t;
11461             for (t = s; t < eol; t++) {
11462                 if (*t == '~' && t[1] == '~' && SvCUR(stuff)) {
11463                     needargs = FALSE;
11464                     goto enough;        /* ~~ must be first line in formline */
11465                 }
11466                 if (*t == '@' || *t == '^')
11467                     needargs = TRUE;
11468             }
11469             if (eol > s) {
11470                 sv_catpvn(stuff, s, eol-s);
11471 #ifndef PERL_STRICT_CR
11472                 if (eol-s > 1 && eol[-2] == '\r' && eol[-1] == '\n') {
11473                     char *end = SvPVX(stuff) + SvCUR(stuff);
11474                     end[-2] = '\n';
11475                     end[-1] = '\0';
11476                     SvCUR_set(stuff, SvCUR(stuff) - 1);
11477                 }
11478 #endif
11479             }
11480             else
11481               break;
11482         }
11483         s = (char*)eol;
11484         if ((PL_rsfp || PL_parser->filtered)
11485          && PL_parser->form_lex_state == LEX_NORMAL) {
11486             bool got_some;
11487             PL_bufptr = PL_bufend;
11488             COPLINE_INC_WITH_HERELINES;
11489             got_some = lex_next_chunk(0);
11490             CopLINE_dec(PL_curcop);
11491             s = PL_bufptr;
11492             if (!got_some)
11493                 break;
11494         }
11495         incline(s, PL_bufend);
11496     }
11497   enough:
11498     if (!SvCUR(stuff) || needargs)
11499         PL_lex_state = PL_parser->form_lex_state;
11500     if (SvCUR(stuff)) {
11501         PL_expect = XSTATE;
11502         if (needargs) {
11503             const char *s2 = s;
11504             while (isSPACE(*s2) && *s2 != '\n')
11505                 s2++;
11506             if (*s2 == '{') {
11507                 PL_expect = XTERMBLOCK;
11508                 NEXTVAL_NEXTTOKE.ival = 0;
11509                 force_next(DO);
11510             }
11511             NEXTVAL_NEXTTOKE.ival = 0;
11512             force_next(FORMLBRACK);
11513         }
11514         if (!IN_BYTES) {
11515             if (UTF && is_utf8_string((U8*)SvPVX_const(stuff), SvCUR(stuff)))
11516                 SvUTF8_on(stuff);
11517         }
11518         NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0, stuff);
11519         force_next(THING);
11520     }
11521     else {
11522         SvREFCNT_dec(stuff);
11523         if (eofmt)
11524             PL_lex_formbrack = 0;
11525     }
11526     return s;
11527 }
11528
11529 I32
11530 Perl_start_subparse(pTHX_ I32 is_format, U32 flags)
11531 {
11532     const I32 oldsavestack_ix = PL_savestack_ix;
11533     CV* const outsidecv = PL_compcv;
11534
11535     SAVEI32(PL_subline);
11536     save_item(PL_subname);
11537     SAVESPTR(PL_compcv);
11538
11539     PL_compcv = MUTABLE_CV(newSV_type(is_format ? SVt_PVFM : SVt_PVCV));
11540     CvFLAGS(PL_compcv) |= flags;
11541
11542     PL_subline = CopLINE(PL_curcop);
11543     CvPADLIST(PL_compcv) = pad_new(padnew_SAVE|padnew_SAVESUB);
11544     CvOUTSIDE(PL_compcv) = MUTABLE_CV(SvREFCNT_inc_simple(outsidecv));
11545     CvOUTSIDE_SEQ(PL_compcv) = PL_cop_seqmax;
11546     if (outsidecv && CvPADLIST(outsidecv))
11547         CvPADLIST(PL_compcv)->xpadl_outid = CvPADLIST(outsidecv)->xpadl_id;
11548
11549     return oldsavestack_ix;
11550 }
11551
11552 static int
11553 S_yywarn(pTHX_ const char *const s, U32 flags)
11554 {
11555     PERL_ARGS_ASSERT_YYWARN;
11556
11557     PL_in_eval |= EVAL_WARNONLY;
11558     yyerror_pv(s, flags);
11559     return 0;
11560 }
11561
11562 void
11563 Perl_abort_execution(pTHX_ const char * const msg, const char * const name)
11564 {
11565     PERL_ARGS_ASSERT_ABORT_EXECUTION;
11566
11567     if (PL_minus_c)
11568         Perl_croak(aTHX_ "%s%s had compilation errors.\n", msg, name);
11569     else {
11570         Perl_croak(aTHX_
11571                 "%sExecution of %s aborted due to compilation errors.\n", msg, name);
11572     }
11573     NOT_REACHED; /* NOTREACHED */
11574 }
11575
11576 void
11577 Perl_yyquit(pTHX)
11578 {
11579     /* Called, after at least one error has been found, to abort the parse now,
11580      * instead of trying to forge ahead */
11581
11582     yyerror_pvn(NULL, 0, 0);
11583 }
11584
11585 int
11586 Perl_yyerror(pTHX_ const char *const s)
11587 {
11588     PERL_ARGS_ASSERT_YYERROR;
11589     return yyerror_pvn(s, strlen(s), 0);
11590 }
11591
11592 int
11593 Perl_yyerror_pv(pTHX_ const char *const s, U32 flags)
11594 {
11595     PERL_ARGS_ASSERT_YYERROR_PV;
11596     return yyerror_pvn(s, strlen(s), flags);
11597 }
11598
11599 int
11600 Perl_yyerror_pvn(pTHX_ const char *const s, STRLEN len, U32 flags)
11601 {
11602     const char *context = NULL;
11603     int contlen = -1;
11604     SV *msg;
11605     SV * const where_sv = newSVpvs_flags("", SVs_TEMP);
11606     int yychar  = PL_parser->yychar;
11607
11608     /* Output error message 's' with length 'len'.  'flags' are SV flags that
11609      * apply.  If the number of errors found is large enough, it abandons
11610      * parsing.  If 's' is NULL, there is no message, and it abandons
11611      * processing unconditionally */
11612
11613     if (s != NULL) {
11614         if (!yychar || (yychar == ';' && !PL_rsfp))
11615             sv_catpvs(where_sv, "at EOF");
11616         else if (   PL_oldoldbufptr
11617                  && PL_bufptr > PL_oldoldbufptr
11618                  && PL_bufptr - PL_oldoldbufptr < 200
11619                  && PL_oldoldbufptr != PL_oldbufptr
11620                  && PL_oldbufptr != PL_bufptr)
11621         {
11622             /*
11623                     Only for NetWare:
11624                     The code below is removed for NetWare because it
11625                     abends/crashes on NetWare when the script has error such as
11626                     not having the closing quotes like:
11627                         if ($var eq "value)
11628                     Checking of white spaces is anyway done in NetWare code.
11629             */
11630 #ifndef NETWARE
11631             while (isSPACE(*PL_oldoldbufptr))
11632                 PL_oldoldbufptr++;
11633 #endif
11634             context = PL_oldoldbufptr;
11635             contlen = PL_bufptr - PL_oldoldbufptr;
11636         }
11637         else if (  PL_oldbufptr
11638                 && PL_bufptr > PL_oldbufptr
11639                 && PL_bufptr - PL_oldbufptr < 200
11640                 && PL_oldbufptr != PL_bufptr) {
11641             /*
11642                     Only for NetWare:
11643                     The code below is removed for NetWare because it
11644                     abends/crashes on NetWare when the script has error such as
11645                     not having the closing quotes like:
11646                         if ($var eq "value)
11647                     Checking of white spaces is anyway done in NetWare code.
11648             */
11649 #ifndef NETWARE
11650             while (isSPACE(*PL_oldbufptr))
11651                 PL_oldbufptr++;
11652 #endif
11653             context = PL_oldbufptr;
11654             contlen = PL_bufptr - PL_oldbufptr;
11655         }
11656         else if (yychar > 255)
11657             sv_catpvs(where_sv, "next token ???");
11658         else if (yychar == YYEMPTY) {
11659             if (PL_lex_state == LEX_NORMAL)
11660                 sv_catpvs(where_sv, "at end of line");
11661             else if (PL_lex_inpat)
11662                 sv_catpvs(where_sv, "within pattern");
11663             else
11664                 sv_catpvs(where_sv, "within string");
11665         }
11666         else {
11667             sv_catpvs(where_sv, "next char ");
11668             if (yychar < 32)
11669                 Perl_sv_catpvf(aTHX_ where_sv, "^%c", toCTRL(yychar));
11670             else if (isPRINT_LC(yychar)) {
11671                 const char string = yychar;
11672                 sv_catpvn(where_sv, &string, 1);
11673             }
11674             else
11675                 Perl_sv_catpvf(aTHX_ where_sv, "\\%03o", yychar & 255);
11676         }
11677         msg = newSVpvn_flags(s, len, (flags & SVf_UTF8) | SVs_TEMP);
11678         Perl_sv_catpvf(aTHX_ msg, " at %s line %" IVdf ", ",
11679             OutCopFILE(PL_curcop),
11680             (IV)(PL_parser->preambling == NOLINE
11681                    ? CopLINE(PL_curcop)
11682                    : PL_parser->preambling));
11683         if (context)
11684             Perl_sv_catpvf(aTHX_ msg, "near \"%" UTF8f "\"\n",
11685                                  UTF8fARG(UTF, contlen, context));
11686         else
11687             Perl_sv_catpvf(aTHX_ msg, "%" SVf "\n", SVfARG(where_sv));
11688         if (   PL_multi_start < PL_multi_end
11689             && (U32)(CopLINE(PL_curcop) - PL_multi_end) <= 1)
11690         {
11691             Perl_sv_catpvf(aTHX_ msg,
11692             "  (Might be a runaway multi-line %c%c string starting on"
11693             " line %" IVdf ")\n",
11694                     (int)PL_multi_open,(int)PL_multi_close,(IV)PL_multi_start);
11695             PL_multi_end = 0;
11696         }
11697         if (PL_in_eval & EVAL_WARNONLY) {
11698             PL_in_eval &= ~EVAL_WARNONLY;
11699             Perl_ck_warner_d(aTHX_ packWARN(WARN_SYNTAX), "%" SVf, SVfARG(msg));
11700         }
11701         else {
11702             qerror(msg);
11703         }
11704     }
11705     if (s == NULL || PL_error_count >= 10) {
11706         const char * msg = "";
11707         const char * const name = OutCopFILE(PL_curcop);
11708
11709         if (PL_in_eval) {
11710             SV * errsv = ERRSV;
11711             if (SvCUR(errsv)) {
11712                 msg = Perl_form(aTHX_ "%" SVf, SVfARG(errsv));
11713             }
11714         }
11715
11716         if (s == NULL) {
11717             abort_execution(msg, name);
11718         }
11719         else {
11720             Perl_croak(aTHX_ "%s%s has too many errors.\n", msg, name);
11721         }
11722     }
11723     PL_in_my = 0;
11724     PL_in_my_stash = NULL;
11725     return 0;
11726 }
11727
11728 STATIC char*
11729 S_swallow_bom(pTHX_ U8 *s)
11730 {
11731     const STRLEN slen = SvCUR(PL_linestr);
11732
11733     PERL_ARGS_ASSERT_SWALLOW_BOM;
11734
11735     switch (s[0]) {
11736     case 0xFF:
11737         if (s[1] == 0xFE) {
11738             /* UTF-16 little-endian? (or UTF-32LE?) */
11739             if (s[2] == 0 && s[3] == 0)  /* UTF-32 little-endian */
11740                 /* diag_listed_as: Unsupported script encoding %s */
11741                 Perl_croak(aTHX_ "Unsupported script encoding UTF-32LE");
11742 #ifndef PERL_NO_UTF16_FILTER
11743 #ifdef DEBUGGING
11744             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (BOM)\n");
11745 #endif
11746             s += 2;
11747             if (PL_bufend > (char*)s) {
11748                 s = add_utf16_textfilter(s, TRUE);
11749             }
11750 #else
11751             /* diag_listed_as: Unsupported script encoding %s */
11752             Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
11753 #endif
11754         }
11755         break;
11756     case 0xFE:
11757         if (s[1] == 0xFF) {   /* UTF-16 big-endian? */
11758 #ifndef PERL_NO_UTF16_FILTER
11759 #ifdef DEBUGGING
11760             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (BOM)\n");
11761 #endif
11762             s += 2;
11763             if (PL_bufend > (char *)s) {
11764                 s = add_utf16_textfilter(s, FALSE);
11765             }
11766 #else
11767             /* diag_listed_as: Unsupported script encoding %s */
11768             Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
11769 #endif
11770         }
11771         break;
11772     case BOM_UTF8_FIRST_BYTE: {
11773         if (memBEGINs(s+1, slen - 1, BOM_UTF8_TAIL)) {
11774 #ifdef DEBUGGING
11775             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-8 script encoding (BOM)\n");
11776 #endif
11777             s += sizeof(BOM_UTF8) - 1;                     /* UTF-8 */
11778         }
11779         break;
11780     }
11781     case 0:
11782         if (slen > 3) {
11783              if (s[1] == 0) {
11784                   if (s[2] == 0xFE && s[3] == 0xFF) {
11785                        /* UTF-32 big-endian */
11786                        /* diag_listed_as: Unsupported script encoding %s */
11787                        Perl_croak(aTHX_ "Unsupported script encoding UTF-32BE");
11788                   }
11789              }
11790              else if (s[2] == 0 && s[3] != 0) {
11791                   /* Leading bytes
11792                    * 00 xx 00 xx
11793                    * are a good indicator of UTF-16BE. */
11794 #ifndef PERL_NO_UTF16_FILTER
11795 #ifdef DEBUGGING
11796                   if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (no BOM)\n");
11797 #endif
11798                   s = add_utf16_textfilter(s, FALSE);
11799 #else
11800                   /* diag_listed_as: Unsupported script encoding %s */
11801                   Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
11802 #endif
11803              }
11804         }
11805         break;
11806
11807     default:
11808          if (slen > 3 && s[1] == 0 && s[2] != 0 && s[3] == 0) {
11809                   /* Leading bytes
11810                    * xx 00 xx 00
11811                    * are a good indicator of UTF-16LE. */
11812 #ifndef PERL_NO_UTF16_FILTER
11813 #ifdef DEBUGGING
11814               if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (no BOM)\n");
11815 #endif
11816               s = add_utf16_textfilter(s, TRUE);
11817 #else
11818               /* diag_listed_as: Unsupported script encoding %s */
11819               Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
11820 #endif
11821          }
11822     }
11823     return (char*)s;
11824 }
11825
11826
11827 #ifndef PERL_NO_UTF16_FILTER
11828 static I32
11829 S_utf16_textfilter(pTHX_ int idx, SV *sv, int maxlen)
11830 {
11831     SV *const filter = FILTER_DATA(idx);
11832     /* We re-use this each time round, throwing the contents away before we
11833        return.  */
11834     SV *const utf16_buffer = MUTABLE_SV(IoTOP_GV(filter));
11835     SV *const utf8_buffer = filter;
11836     IV status = IoPAGE(filter);
11837     const bool reverse = cBOOL(IoLINES(filter));
11838     I32 retval;
11839
11840     PERL_ARGS_ASSERT_UTF16_TEXTFILTER;
11841
11842     /* As we're automatically added, at the lowest level, and hence only called
11843        from this file, we can be sure that we're not called in block mode. Hence
11844        don't bother writing code to deal with block mode.  */
11845     if (maxlen) {
11846         Perl_croak(aTHX_ "panic: utf16_textfilter called in block mode (for %d characters)", maxlen);
11847     }
11848     if (status < 0) {
11849         Perl_croak(aTHX_ "panic: utf16_textfilter called after error (status=%" IVdf ")", status);
11850     }
11851     DEBUG_P(PerlIO_printf(Perl_debug_log,
11852                           "utf16_textfilter(%p,%ce): idx=%d maxlen=%d status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
11853                           FPTR2DPTR(void *, S_utf16_textfilter),
11854                           reverse ? 'l' : 'b', idx, maxlen, status,
11855                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
11856
11857     while (1) {
11858         STRLEN chars;
11859         STRLEN have;
11860         I32 newlen;
11861         U8 *end;
11862         /* First, look in our buffer of existing UTF-8 data:  */
11863         char *nl = (char *)memchr(SvPVX(utf8_buffer), '\n', SvCUR(utf8_buffer));
11864
11865         if (nl) {
11866             ++nl;
11867         } else if (status == 0) {
11868             /* EOF */
11869             IoPAGE(filter) = 0;
11870             nl = SvEND(utf8_buffer);
11871         }
11872         if (nl) {
11873             STRLEN got = nl - SvPVX(utf8_buffer);
11874             /* Did we have anything to append?  */
11875             retval = got != 0;
11876             sv_catpvn(sv, SvPVX(utf8_buffer), got);
11877             /* Everything else in this code works just fine if SVp_POK isn't
11878                set.  This, however, needs it, and we need it to work, else
11879                we loop infinitely because the buffer is never consumed.  */
11880             sv_chop(utf8_buffer, nl);
11881             break;
11882         }
11883
11884         /* OK, not a complete line there, so need to read some more UTF-16.
11885            Read an extra octect if the buffer currently has an odd number. */
11886         while (1) {
11887             if (status <= 0)
11888                 break;
11889             if (SvCUR(utf16_buffer) >= 2) {
11890                 /* Location of the high octet of the last complete code point.
11891                    Gosh, UTF-16 is a pain. All the benefits of variable length,
11892                    *coupled* with all the benefits of partial reads and
11893                    endianness.  */
11894                 const U8 *const last_hi = (U8*)SvPVX(utf16_buffer)
11895                     + ((SvCUR(utf16_buffer) & ~1) - (reverse ? 1 : 2));
11896
11897                 if (*last_hi < 0xd8 || *last_hi > 0xdb) {
11898                     break;
11899                 }
11900
11901                 /* We have the first half of a surrogate. Read more.  */
11902                 DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter partial surrogate detected at %p\n", last_hi));
11903             }
11904
11905             status = FILTER_READ(idx + 1, utf16_buffer,
11906                                  160 + (SvCUR(utf16_buffer) & 1));
11907             DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter status=%" IVdf " SvCUR(sv)=%" UVuf "\n", status, (UV)SvCUR(utf16_buffer)));
11908             DEBUG_P({ sv_dump(utf16_buffer); sv_dump(utf8_buffer);});
11909             if (status < 0) {
11910                 /* Error */
11911                 IoPAGE(filter) = status;
11912                 return status;
11913             }
11914         }
11915
11916         /* 'chars' isn't quite the right name, as code points above 0xFFFF
11917          * require 4 bytes per char */
11918         chars = SvCUR(utf16_buffer) >> 1;
11919         have = SvCUR(utf8_buffer);
11920
11921         /* Assume the worst case size as noted by the functions: twice the
11922          * number of input bytes */
11923         SvGROW(utf8_buffer, have + chars * 4 + 1);
11924
11925         if (reverse) {
11926             end = utf16_to_utf8_reversed((U8*)SvPVX(utf16_buffer),
11927                                          (U8*)SvPVX_const(utf8_buffer) + have,
11928                                          chars * 2, &newlen);
11929         } else {
11930             end = utf16_to_utf8((U8*)SvPVX(utf16_buffer),
11931                                 (U8*)SvPVX_const(utf8_buffer) + have,
11932                                 chars * 2, &newlen);
11933         }
11934         SvCUR_set(utf8_buffer, have + newlen);
11935         *end = '\0';
11936
11937         /* No need to keep this SV "well-formed" with a '\0' after the end, as
11938            it's private to us, and utf16_to_utf8{,reversed} take a
11939            (pointer,length) pair, rather than a NUL-terminated string.  */
11940         if(SvCUR(utf16_buffer) & 1) {
11941             *SvPVX(utf16_buffer) = SvEND(utf16_buffer)[-1];
11942             SvCUR_set(utf16_buffer, 1);
11943         } else {
11944             SvCUR_set(utf16_buffer, 0);
11945         }
11946     }
11947     DEBUG_P(PerlIO_printf(Perl_debug_log,
11948                           "utf16_textfilter: returns, status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
11949                           status,
11950                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
11951     DEBUG_P({ sv_dump(utf8_buffer); sv_dump(sv);});
11952     return retval;
11953 }
11954
11955 static U8 *
11956 S_add_utf16_textfilter(pTHX_ U8 *const s, bool reversed)
11957 {
11958     SV *filter = filter_add(S_utf16_textfilter, NULL);
11959
11960     PERL_ARGS_ASSERT_ADD_UTF16_TEXTFILTER;
11961
11962     IoTOP_GV(filter) = MUTABLE_GV(newSVpvn((char *)s, PL_bufend - (char*)s));
11963     SvPVCLEAR(filter);
11964     IoLINES(filter) = reversed;
11965     IoPAGE(filter) = 1; /* Not EOF */
11966
11967     /* Sadly, we have to return a valid pointer, come what may, so we have to
11968        ignore any error return from this.  */
11969     SvCUR_set(PL_linestr, 0);
11970     if (FILTER_READ(0, PL_linestr, 0)) {
11971         SvUTF8_on(PL_linestr);
11972     } else {
11973         SvUTF8_on(PL_linestr);
11974     }
11975     PL_bufend = SvEND(PL_linestr);
11976     return (U8*)SvPVX(PL_linestr);
11977 }
11978 #endif
11979
11980 /*
11981 Returns a pointer to the next character after the parsed
11982 vstring, as well as updating the passed in sv.
11983
11984 Function must be called like
11985
11986         sv = sv_2mortal(newSV(5));
11987         s = scan_vstring(s,e,sv);
11988
11989 where s and e are the start and end of the string.
11990 The sv should already be large enough to store the vstring
11991 passed in, for performance reasons.
11992
11993 This function may croak if fatal warnings are enabled in the
11994 calling scope, hence the sv_2mortal in the example (to prevent
11995 a leak).  Make sure to do SvREFCNT_inc afterwards if you use
11996 sv_2mortal.
11997
11998 */
11999
12000 char *
12001 Perl_scan_vstring(pTHX_ const char *s, const char *const e, SV *sv)
12002 {
12003     const char *pos = s;
12004     const char *start = s;
12005
12006     PERL_ARGS_ASSERT_SCAN_VSTRING;
12007
12008     if (*pos == 'v') pos++;  /* get past 'v' */
12009     while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12010         pos++;
12011     if ( *pos != '.') {
12012         /* this may not be a v-string if followed by => */
12013         const char *next = pos;
12014         while (next < e && isSPACE(*next))
12015             ++next;
12016         if ((e - next) >= 2 && *next == '=' && next[1] == '>' ) {
12017             /* return string not v-string */
12018             sv_setpvn(sv,(char *)s,pos-s);
12019             return (char *)pos;
12020         }
12021     }
12022
12023     if (!isALPHA(*pos)) {
12024         U8 tmpbuf[UTF8_MAXBYTES+1];
12025
12026         if (*s == 'v')
12027             s++;  /* get past 'v' */
12028
12029         SvPVCLEAR(sv);
12030
12031         for (;;) {
12032             /* this is atoi() that tolerates underscores */
12033             U8 *tmpend;
12034             UV rev = 0;
12035             const char *end = pos;
12036             UV mult = 1;
12037             while (--end >= s) {
12038                 if (*end != '_') {
12039                     const UV orev = rev;
12040                     rev += (*end - '0') * mult;
12041                     mult *= 10;
12042                     if (orev > rev)
12043                         /* diag_listed_as: Integer overflow in %s number */
12044                         Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
12045                                          "Integer overflow in decimal number");
12046                 }
12047             }
12048
12049             /* Append native character for the rev point */
12050             tmpend = uvchr_to_utf8(tmpbuf, rev);
12051             sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
12052             if (!UVCHR_IS_INVARIANT(rev))
12053                  SvUTF8_on(sv);
12054             if (pos + 1 < e && *pos == '.' && isDIGIT(pos[1]))
12055                  s = ++pos;
12056             else {
12057                  s = pos;
12058                  break;
12059             }
12060             while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12061                  pos++;
12062         }
12063         SvPOK_on(sv);
12064         sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
12065         SvRMAGICAL_on(sv);
12066     }
12067     return (char *)s;
12068 }
12069
12070 int
12071 Perl_keyword_plugin_standard(pTHX_
12072         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
12073 {
12074     PERL_ARGS_ASSERT_KEYWORD_PLUGIN_STANDARD;
12075     PERL_UNUSED_CONTEXT;
12076     PERL_UNUSED_ARG(keyword_ptr);
12077     PERL_UNUSED_ARG(keyword_len);
12078     PERL_UNUSED_ARG(op_ptr);
12079     return KEYWORD_PLUGIN_DECLINE;
12080 }
12081
12082 /*
12083 =for apidoc Amx|void|wrap_keyword_plugin|Perl_keyword_plugin_t new_plugin|Perl_keyword_plugin_t *old_plugin_p
12084
12085 Puts a C function into the chain of keyword plugins.  This is the
12086 preferred way to manipulate the L</PL_keyword_plugin> variable.
12087 C<new_plugin> is a pointer to the C function that is to be added to the
12088 keyword plugin chain, and C<old_plugin_p> points to the storage location
12089 where a pointer to the next function in the chain will be stored.  The
12090 value of C<new_plugin> is written into the L</PL_keyword_plugin> variable,
12091 while the value previously stored there is written to C<*old_plugin_p>.
12092
12093 L</PL_keyword_plugin> is global to an entire process, and a module wishing
12094 to hook keyword parsing may find itself invoked more than once per
12095 process, typically in different threads.  To handle that situation, this
12096 function is idempotent.  The location C<*old_plugin_p> must initially
12097 (once per process) contain a null pointer.  A C variable of static
12098 duration (declared at file scope, typically also marked C<static> to give
12099 it internal linkage) will be implicitly initialised appropriately, if it
12100 does not have an explicit initialiser.  This function will only actually
12101 modify the plugin chain if it finds C<*old_plugin_p> to be null.  This
12102 function is also thread safe on the small scale.  It uses appropriate
12103 locking to avoid race conditions in accessing L</PL_keyword_plugin>.
12104
12105 When this function is called, the function referenced by C<new_plugin>
12106 must be ready to be called, except for C<*old_plugin_p> being unfilled.
12107 In a threading situation, C<new_plugin> may be called immediately, even
12108 before this function has returned.  C<*old_plugin_p> will always be
12109 appropriately set before C<new_plugin> is called.  If C<new_plugin>
12110 decides not to do anything special with the identifier that it is given
12111 (which is the usual case for most calls to a keyword plugin), it must
12112 chain the plugin function referenced by C<*old_plugin_p>.
12113
12114 Taken all together, XS code to install a keyword plugin should typically
12115 look something like this:
12116
12117     static Perl_keyword_plugin_t next_keyword_plugin;
12118     static OP *my_keyword_plugin(pTHX_
12119         char *keyword_plugin, STRLEN keyword_len, OP **op_ptr)
12120     {
12121         if (memEQs(keyword_ptr, keyword_len,
12122                    "my_new_keyword")) {
12123             ...
12124         } else {
12125             return next_keyword_plugin(aTHX_
12126                 keyword_ptr, keyword_len, op_ptr);
12127         }
12128     }
12129     BOOT:
12130         wrap_keyword_plugin(my_keyword_plugin,
12131                             &next_keyword_plugin);
12132
12133 Direct access to L</PL_keyword_plugin> should be avoided.
12134
12135 =cut
12136 */
12137
12138 void
12139 Perl_wrap_keyword_plugin(pTHX_
12140     Perl_keyword_plugin_t new_plugin, Perl_keyword_plugin_t *old_plugin_p)
12141 {
12142     dVAR;
12143
12144     PERL_UNUSED_CONTEXT;
12145     PERL_ARGS_ASSERT_WRAP_KEYWORD_PLUGIN;
12146     if (*old_plugin_p) return;
12147     KEYWORD_PLUGIN_MUTEX_LOCK;
12148     if (!*old_plugin_p) {
12149         *old_plugin_p = PL_keyword_plugin;
12150         PL_keyword_plugin = new_plugin;
12151     }
12152     KEYWORD_PLUGIN_MUTEX_UNLOCK;
12153 }
12154
12155 #define parse_recdescent(g,p) S_parse_recdescent(aTHX_ g,p)
12156 static void
12157 S_parse_recdescent(pTHX_ int gramtype, I32 fakeeof)
12158 {
12159     SAVEI32(PL_lex_brackets);
12160     if (PL_lex_brackets > 100)
12161         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
12162     PL_lex_brackstack[PL_lex_brackets++] = XFAKEEOF;
12163     SAVEI32(PL_lex_allbrackets);
12164     PL_lex_allbrackets = 0;
12165     SAVEI8(PL_lex_fakeeof);
12166     PL_lex_fakeeof = (U8)fakeeof;
12167     if(yyparse(gramtype) && !PL_parser->error_count)
12168         qerror(Perl_mess(aTHX_ "Parse error"));
12169 }
12170
12171 #define parse_recdescent_for_op(g,p) S_parse_recdescent_for_op(aTHX_ g,p)
12172 static OP *
12173 S_parse_recdescent_for_op(pTHX_ int gramtype, I32 fakeeof)
12174 {
12175     OP *o;
12176     ENTER;
12177     SAVEVPTR(PL_eval_root);
12178     PL_eval_root = NULL;
12179     parse_recdescent(gramtype, fakeeof);
12180     o = PL_eval_root;
12181     LEAVE;
12182     return o;
12183 }
12184
12185 #define parse_expr(p,f) S_parse_expr(aTHX_ p,f)
12186 static OP *
12187 S_parse_expr(pTHX_ I32 fakeeof, U32 flags)
12188 {
12189     OP *exprop;
12190     if (flags & ~PARSE_OPTIONAL)
12191         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_expr");
12192     exprop = parse_recdescent_for_op(GRAMEXPR, fakeeof);
12193     if (!exprop && !(flags & PARSE_OPTIONAL)) {
12194         if (!PL_parser->error_count)
12195             qerror(Perl_mess(aTHX_ "Parse error"));
12196         exprop = newOP(OP_NULL, 0);
12197     }
12198     return exprop;
12199 }
12200
12201 /*
12202 =for apidoc Amx|OP *|parse_arithexpr|U32 flags
12203
12204 Parse a Perl arithmetic expression.  This may contain operators of precedence
12205 down to the bit shift operators.  The expression must be followed (and thus
12206 terminated) either by a comparison or lower-precedence operator or by
12207 something that would normally terminate an expression such as semicolon.
12208 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12209 otherwise it is mandatory.  It is up to the caller to ensure that the
12210 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12211 the source of the code to be parsed and the lexical context for the
12212 expression.
12213
12214 The op tree representing the expression is returned.  If an optional
12215 expression is absent, a null pointer is returned, otherwise the pointer
12216 will be non-null.
12217
12218 If an error occurs in parsing or compilation, in most cases a valid op
12219 tree is returned anyway.  The error is reflected in the parser state,
12220 normally resulting in a single exception at the top level of parsing
12221 which covers all the compilation errors that occurred.  Some compilation
12222 errors, however, will throw an exception immediately.
12223
12224 =cut
12225 */
12226
12227 OP *
12228 Perl_parse_arithexpr(pTHX_ U32 flags)
12229 {
12230     return parse_expr(LEX_FAKEEOF_COMPARE, flags);
12231 }
12232
12233 /*
12234 =for apidoc Amx|OP *|parse_termexpr|U32 flags
12235
12236 Parse a Perl term expression.  This may contain operators of precedence
12237 down to the assignment operators.  The expression must be followed (and thus
12238 terminated) either by a comma or lower-precedence operator or by
12239 something that would normally terminate an expression such as semicolon.
12240 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12241 otherwise it is mandatory.  It is up to the caller to ensure that the
12242 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12243 the source of the code to be parsed and the lexical context for the
12244 expression.
12245
12246 The op tree representing the expression is returned.  If an optional
12247 expression is absent, a null pointer is returned, otherwise the pointer
12248 will be non-null.
12249
12250 If an error occurs in parsing or compilation, in most cases a valid op
12251 tree is returned anyway.  The error is reflected in the parser state,
12252 normally resulting in a single exception at the top level of parsing
12253 which covers all the compilation errors that occurred.  Some compilation
12254 errors, however, will throw an exception immediately.
12255
12256 =cut
12257 */
12258
12259 OP *
12260 Perl_parse_termexpr(pTHX_ U32 flags)
12261 {
12262     return parse_expr(LEX_FAKEEOF_COMMA, flags);
12263 }
12264
12265 /*
12266 =for apidoc Amx|OP *|parse_listexpr|U32 flags
12267
12268 Parse a Perl list expression.  This may contain operators of precedence
12269 down to the comma operator.  The expression must be followed (and thus
12270 terminated) either by a low-precedence logic operator such as C<or> or by
12271 something that would normally terminate an expression such as semicolon.
12272 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12273 otherwise it is mandatory.  It is up to the caller to ensure that the
12274 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12275 the source of the code to be parsed and the lexical context for the
12276 expression.
12277
12278 The op tree representing the expression is returned.  If an optional
12279 expression is absent, a null pointer is returned, otherwise the pointer
12280 will be non-null.
12281
12282 If an error occurs in parsing or compilation, in most cases a valid op
12283 tree is returned anyway.  The error is reflected in the parser state,
12284 normally resulting in a single exception at the top level of parsing
12285 which covers all the compilation errors that occurred.  Some compilation
12286 errors, however, will throw an exception immediately.
12287
12288 =cut
12289 */
12290
12291 OP *
12292 Perl_parse_listexpr(pTHX_ U32 flags)
12293 {
12294     return parse_expr(LEX_FAKEEOF_LOWLOGIC, flags);
12295 }
12296
12297 /*
12298 =for apidoc Amx|OP *|parse_fullexpr|U32 flags
12299
12300 Parse a single complete Perl expression.  This allows the full
12301 expression grammar, including the lowest-precedence operators such
12302 as C<or>.  The expression must be followed (and thus terminated) by a
12303 token that an expression would normally be terminated by: end-of-file,
12304 closing bracketing punctuation, semicolon, or one of the keywords that
12305 signals a postfix expression-statement modifier.  If C<flags> has the
12306 C<PARSE_OPTIONAL> bit set, then the expression is optional, otherwise it is
12307 mandatory.  It is up to the caller to ensure that the dynamic parser
12308 state (L</PL_parser> et al) is correctly set to reflect the source of
12309 the code to be parsed and the lexical context for the expression.
12310
12311 The op tree representing the expression is returned.  If an optional
12312 expression is absent, a null pointer is returned, otherwise the pointer
12313 will be non-null.
12314
12315 If an error occurs in parsing or compilation, in most cases a valid op
12316 tree is returned anyway.  The error is reflected in the parser state,
12317 normally resulting in a single exception at the top level of parsing
12318 which covers all the compilation errors that occurred.  Some compilation
12319 errors, however, will throw an exception immediately.
12320
12321 =cut
12322 */
12323
12324 OP *
12325 Perl_parse_fullexpr(pTHX_ U32 flags)
12326 {
12327     return parse_expr(LEX_FAKEEOF_NONEXPR, flags);
12328 }
12329
12330 /*
12331 =for apidoc Amx|OP *|parse_block|U32 flags
12332
12333 Parse a single complete Perl code block.  This consists of an opening
12334 brace, a sequence of statements, and a closing brace.  The block
12335 constitutes a lexical scope, so C<my> variables and various compile-time
12336 effects can be contained within it.  It is up to the caller to ensure
12337 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12338 reflect the source of the code to be parsed and the lexical context for
12339 the statement.
12340
12341 The op tree representing the code block is returned.  This is always a
12342 real op, never a null pointer.  It will normally be a C<lineseq> list,
12343 including C<nextstate> or equivalent ops.  No ops to construct any kind
12344 of runtime scope are included by virtue of it being a block.
12345
12346 If an error occurs in parsing or compilation, in most cases a valid op
12347 tree (most likely null) is returned anyway.  The error is reflected in
12348 the parser state, normally resulting in a single exception at the top
12349 level of parsing which covers all the compilation errors that occurred.
12350 Some compilation errors, however, will throw an exception immediately.
12351
12352 The C<flags> parameter is reserved for future use, and must always
12353 be zero.
12354
12355 =cut
12356 */
12357
12358 OP *
12359 Perl_parse_block(pTHX_ U32 flags)
12360 {
12361     if (flags)
12362         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_block");
12363     return parse_recdescent_for_op(GRAMBLOCK, LEX_FAKEEOF_NEVER);
12364 }
12365
12366 /*
12367 =for apidoc Amx|OP *|parse_barestmt|U32 flags
12368
12369 Parse a single unadorned Perl statement.  This may be a normal imperative
12370 statement or a declaration that has compile-time effect.  It does not
12371 include any label or other affixture.  It is up to the caller to ensure
12372 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12373 reflect the source of the code to be parsed and the lexical context for
12374 the statement.
12375
12376 The op tree representing the statement is returned.  This may be a
12377 null pointer if the statement is null, for example if it was actually
12378 a subroutine definition (which has compile-time side effects).  If not
12379 null, it will be ops directly implementing the statement, suitable to
12380 pass to L</newSTATEOP>.  It will not normally include a C<nextstate> or
12381 equivalent op (except for those embedded in a scope contained entirely
12382 within the statement).
12383
12384 If an error occurs in parsing or compilation, in most cases a valid op
12385 tree (most likely null) is returned anyway.  The error is reflected in
12386 the parser state, normally resulting in a single exception at the top
12387 level of parsing which covers all the compilation errors that occurred.
12388 Some compilation errors, however, will throw an exception immediately.
12389
12390 The C<flags> parameter is reserved for future use, and must always
12391 be zero.
12392
12393 =cut
12394 */
12395
12396 OP *
12397 Perl_parse_barestmt(pTHX_ U32 flags)
12398 {
12399     if (flags)
12400         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_barestmt");
12401     return parse_recdescent_for_op(GRAMBARESTMT, LEX_FAKEEOF_NEVER);
12402 }
12403
12404 /*
12405 =for apidoc Amx|SV *|parse_label|U32 flags
12406
12407 Parse a single label, possibly optional, of the type that may prefix a
12408 Perl statement.  It is up to the caller to ensure that the dynamic parser
12409 state (L</PL_parser> et al) is correctly set to reflect the source of
12410 the code to be parsed.  If C<flags> has the C<PARSE_OPTIONAL> bit set, then the
12411 label is optional, otherwise it is mandatory.
12412
12413 The name of the label is returned in the form of a fresh scalar.  If an
12414 optional label is absent, a null pointer is returned.
12415
12416 If an error occurs in parsing, which can only occur if the label is
12417 mandatory, a valid label is returned anyway.  The error is reflected in
12418 the parser state, normally resulting in a single exception at the top
12419 level of parsing which covers all the compilation errors that occurred.
12420
12421 =cut
12422 */
12423
12424 SV *
12425 Perl_parse_label(pTHX_ U32 flags)
12426 {
12427     if (flags & ~PARSE_OPTIONAL)
12428         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_label");
12429     if (PL_nexttoke) {
12430         PL_parser->yychar = yylex();
12431         if (PL_parser->yychar == LABEL) {
12432             char * const lpv = pl_yylval.pval;
12433             STRLEN llen = strlen(lpv);
12434             PL_parser->yychar = YYEMPTY;
12435             return newSVpvn_flags(lpv, llen, lpv[llen+1] ? SVf_UTF8 : 0);
12436         } else {
12437             yyunlex();
12438             goto no_label;
12439         }
12440     } else {
12441         char *s, *t;
12442         STRLEN wlen, bufptr_pos;
12443         lex_read_space(0);
12444         t = s = PL_bufptr;
12445         if (!isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
12446             goto no_label;
12447         t = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &wlen);
12448         if (word_takes_any_delimiter(s, wlen))
12449             goto no_label;
12450         bufptr_pos = s - SvPVX(PL_linestr);
12451         PL_bufptr = t;
12452         lex_read_space(LEX_KEEP_PREVIOUS);
12453         t = PL_bufptr;
12454         s = SvPVX(PL_linestr) + bufptr_pos;
12455         if (t[0] == ':' && t[1] != ':') {
12456             PL_oldoldbufptr = PL_oldbufptr;
12457             PL_oldbufptr = s;
12458             PL_bufptr = t+1;
12459             return newSVpvn_flags(s, wlen, UTF ? SVf_UTF8 : 0);
12460         } else {
12461             PL_bufptr = s;
12462             no_label:
12463             if (flags & PARSE_OPTIONAL) {
12464                 return NULL;
12465             } else {
12466                 qerror(Perl_mess(aTHX_ "Parse error"));
12467                 return newSVpvs("x");
12468             }
12469         }
12470     }
12471 }
12472
12473 /*
12474 =for apidoc Amx|OP *|parse_fullstmt|U32 flags
12475
12476 Parse a single complete Perl statement.  This may be a normal imperative
12477 statement or a declaration that has compile-time effect, and may include
12478 optional labels.  It is up to the caller to ensure that the dynamic
12479 parser state (L</PL_parser> et al) is correctly set to reflect the source
12480 of the code to be parsed and the lexical context for the statement.
12481
12482 The op tree representing the statement is returned.  This may be a
12483 null pointer if the statement is null, for example if it was actually
12484 a subroutine definition (which has compile-time side effects).  If not
12485 null, it will be the result of a L</newSTATEOP> call, normally including
12486 a C<nextstate> or equivalent op.
12487
12488 If an error occurs in parsing or compilation, in most cases a valid op
12489 tree (most likely null) is returned anyway.  The error is reflected in
12490 the parser state, normally resulting in a single exception at the top
12491 level of parsing which covers all the compilation errors that occurred.
12492 Some compilation errors, however, will throw an exception immediately.
12493
12494 The C<flags> parameter is reserved for future use, and must always
12495 be zero.
12496
12497 =cut
12498 */
12499
12500 OP *
12501 Perl_parse_fullstmt(pTHX_ U32 flags)
12502 {
12503     if (flags)
12504         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_fullstmt");
12505     return parse_recdescent_for_op(GRAMFULLSTMT, LEX_FAKEEOF_NEVER);
12506 }
12507
12508 /*
12509 =for apidoc Amx|OP *|parse_stmtseq|U32 flags
12510
12511 Parse a sequence of zero or more Perl statements.  These may be normal
12512 imperative statements, including optional labels, or declarations
12513 that have compile-time effect, or any mixture thereof.  The statement
12514 sequence ends when a closing brace or end-of-file is encountered in a
12515 place where a new statement could have validly started.  It is up to
12516 the caller to ensure that the dynamic parser state (L</PL_parser> et al)
12517 is correctly set to reflect the source of the code to be parsed and the
12518 lexical context for the statements.
12519
12520 The op tree representing the statement sequence is returned.  This may
12521 be a null pointer if the statements were all null, for example if there
12522 were no statements or if there were only subroutine definitions (which
12523 have compile-time side effects).  If not null, it will be a C<lineseq>
12524 list, normally including C<nextstate> or equivalent ops.
12525
12526 If an error occurs in parsing or compilation, in most cases a valid op
12527 tree is returned anyway.  The error is reflected in the parser state,
12528 normally resulting in a single exception at the top level of parsing
12529 which covers all the compilation errors that occurred.  Some compilation
12530 errors, however, will throw an exception immediately.
12531
12532 The C<flags> parameter is reserved for future use, and must always
12533 be zero.
12534
12535 =cut
12536 */
12537
12538 OP *
12539 Perl_parse_stmtseq(pTHX_ U32 flags)
12540 {
12541     OP *stmtseqop;
12542     I32 c;
12543     if (flags)
12544         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_stmtseq");
12545     stmtseqop = parse_recdescent_for_op(GRAMSTMTSEQ, LEX_FAKEEOF_CLOSING);
12546     c = lex_peek_unichar(0);
12547     if (c != -1 && c != /*{*/'}')
12548         qerror(Perl_mess(aTHX_ "Parse error"));
12549     return stmtseqop;
12550 }
12551
12552 /*
12553  * ex: set ts=8 sts=4 sw=4 et:
12554  */