This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
PATCH: gh #17319 Segfault
[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 AmnU|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 #include "invlist_inline.h"
43
44 #define new_constant(a,b,c,d,e,f,g, h)  \
45         S_new_constant(aTHX_ a,b,STR_WITH_LEN(c),d,e,f, g, h)
46
47 #define pl_yylval       (PL_parser->yylval)
48
49 /* XXX temporary backwards compatibility */
50 #define PL_lex_brackets         (PL_parser->lex_brackets)
51 #define PL_lex_allbrackets      (PL_parser->lex_allbrackets)
52 #define PL_lex_fakeeof          (PL_parser->lex_fakeeof)
53 #define PL_lex_brackstack       (PL_parser->lex_brackstack)
54 #define PL_lex_casemods         (PL_parser->lex_casemods)
55 #define PL_lex_casestack        (PL_parser->lex_casestack)
56 #define PL_lex_dojoin           (PL_parser->lex_dojoin)
57 #define PL_lex_formbrack        (PL_parser->lex_formbrack)
58 #define PL_lex_inpat            (PL_parser->lex_inpat)
59 #define PL_lex_inwhat           (PL_parser->lex_inwhat)
60 #define PL_lex_op               (PL_parser->lex_op)
61 #define PL_lex_repl             (PL_parser->lex_repl)
62 #define PL_lex_starts           (PL_parser->lex_starts)
63 #define PL_lex_stuff            (PL_parser->lex_stuff)
64 #define PL_multi_start          (PL_parser->multi_start)
65 #define PL_multi_open           (PL_parser->multi_open)
66 #define PL_multi_close          (PL_parser->multi_close)
67 #define PL_preambled            (PL_parser->preambled)
68 #define PL_linestr              (PL_parser->linestr)
69 #define PL_expect               (PL_parser->expect)
70 #define PL_copline              (PL_parser->copline)
71 #define PL_bufptr               (PL_parser->bufptr)
72 #define PL_oldbufptr            (PL_parser->oldbufptr)
73 #define PL_oldoldbufptr         (PL_parser->oldoldbufptr)
74 #define PL_linestart            (PL_parser->linestart)
75 #define PL_bufend               (PL_parser->bufend)
76 #define PL_last_uni             (PL_parser->last_uni)
77 #define PL_last_lop             (PL_parser->last_lop)
78 #define PL_last_lop_op          (PL_parser->last_lop_op)
79 #define PL_lex_state            (PL_parser->lex_state)
80 #define PL_rsfp                 (PL_parser->rsfp)
81 #define PL_rsfp_filters         (PL_parser->rsfp_filters)
82 #define PL_in_my                (PL_parser->in_my)
83 #define PL_in_my_stash          (PL_parser->in_my_stash)
84 #define PL_tokenbuf             (PL_parser->tokenbuf)
85 #define PL_multi_end            (PL_parser->multi_end)
86 #define PL_error_count          (PL_parser->error_count)
87
88 #  define PL_nexttoke           (PL_parser->nexttoke)
89 #  define PL_nexttype           (PL_parser->nexttype)
90 #  define PL_nextval            (PL_parser->nextval)
91
92
93 #define SvEVALED(sv) \
94     (SvTYPE(sv) >= SVt_PVNV \
95     && ((XPVIV*)SvANY(sv))->xiv_u.xivu_eval_seen)
96
97 static const char* const ident_too_long = "Identifier too long";
98
99 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
100
101 #define XENUMMASK  0x3f
102 #define XFAKEEOF   0x40
103 #define XFAKEBRACK 0x80
104
105 #ifdef USE_UTF8_SCRIPTS
106 #   define UTF cBOOL(!IN_BYTES)
107 #else
108 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
109 #endif
110
111 /* The maximum number of characters preceding the unrecognized one to display */
112 #define UNRECOGNIZED_PRECEDE_COUNT 10
113
114 /* In variables named $^X, these are the legal values for X.
115  * 1999-02-27 mjd-perl-patch@plover.com */
116 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
117
118 #define SPACE_OR_TAB(c) isBLANK_A(c)
119
120 #define HEXFP_PEEK(s)     \
121     (((s[0] == '.') && \
122       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
123      isALPHA_FOLD_EQ(s[0], 'p'))
124
125 /* LEX_* are values for PL_lex_state, the state of the lexer.
126  * They are arranged oddly so that the guard on the switch statement
127  * can get by with a single comparison (if the compiler is smart enough).
128  *
129  * These values refer to the various states within a sublex parse,
130  * i.e. within a double quotish string
131  */
132
133 /* #define LEX_NOTPARSING               11 is done in perl.h. */
134
135 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
136 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
137 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
138 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
139 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
140
141                                    /* at end of code, eg "$x" followed by:  */
142 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
143 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
144
145 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
146                                         string or after \E, $foo, etc       */
147 #define LEX_INTERPCONST          2 /* NOT USED */
148 #define LEX_FORMLINE             1 /* expecting a format line               */
149
150
151 #ifdef DEBUGGING
152 static const char* const lex_state_names[] = {
153     "KNOWNEXT",
154     "FORMLINE",
155     "INTERPCONST",
156     "INTERPCONCAT",
157     "INTERPENDMAYBE",
158     "INTERPEND",
159     "INTERPSTART",
160     "INTERPPUSH",
161     "INTERPCASEMOD",
162     "INTERPNORMAL",
163     "NORMAL"
164 };
165 #endif
166
167 #include "keywords.h"
168
169 /* CLINE is a macro that ensures PL_copline has a sane value */
170
171 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
172
173 /*
174  * Convenience functions to return different tokens and prime the
175  * lexer for the next token.  They all take an argument.
176  *
177  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
178  * OPERATOR     : generic operator
179  * AOPERATOR    : assignment operator
180  * PREBLOCK     : beginning the block after an if, while, foreach, ...
181  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
182  * PREREF       : *EXPR where EXPR is not a simple identifier
183  * TERM         : expression term
184  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
185  * LOOPX        : loop exiting command (goto, last, dump, etc)
186  * FTST         : file test operator
187  * FUN0         : zero-argument function
188  * FUN0OP       : zero-argument function, with its op created in this file
189  * FUN1         : not used, except for not, which isn't a UNIOP
190  * BOop         : bitwise or or xor
191  * BAop         : bitwise and
192  * BCop         : bitwise complement
193  * SHop         : shift operator
194  * PWop         : power operator
195  * PMop         : pattern-matching operator
196  * Aop          : addition-level operator
197  * AopNOASSIGN  : addition-level operator that is never part of .=
198  * Mop          : multiplication-level operator
199  * Eop          : equality-testing operator
200  * Rop          : relational operator <= != gt
201  *
202  * Also see LOP and lop() below.
203  */
204
205 #ifdef DEBUGGING /* Serve -DT. */
206 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
207 #else
208 #   define REPORT(retval) (retval)
209 #endif
210
211 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
212 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
213 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
214 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
215 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
216 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
217 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
218 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
219 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
220                          pl_yylval.ival=f, \
221                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
222                          REPORT((int)LOOPEX))
223 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
224 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
225 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
226 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
227 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
228 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
229 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
230                        REPORT('~')
231 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
232 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
233 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
234 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
235 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
236 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
237 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
238 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
239
240 /* This bit of chicanery makes a unary function followed by
241  * a parenthesis into a function with one argument, highest precedence.
242  * The UNIDOR macro is for unary functions that can be followed by the //
243  * operator (such as C<shift // 0>).
244  */
245 #define UNI3(f,x,have_x) { \
246         pl_yylval.ival = f; \
247         if (have_x) PL_expect = x; \
248         PL_bufptr = s; \
249         PL_last_uni = PL_oldbufptr; \
250         PL_last_lop_op = (f) < 0 ? -(f) : (f); \
251         if (*s == '(') \
252             return REPORT( (int)FUNC1 ); \
253         s = skipspace(s); \
254         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
255         }
256 #define UNI(f)    UNI3(f,XTERM,1)
257 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
258 #define UNIPROTO(f,optional) { \
259         if (optional) PL_last_uni = PL_oldbufptr; \
260         OPERATOR(f); \
261         }
262
263 #define UNIBRACK(f) UNI3(f,0,0)
264
265 /* grandfather return to old style */
266 #define OLDLOP(f) \
267         do { \
268             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
269                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
270             pl_yylval.ival = (f); \
271             PL_expect = XTERM; \
272             PL_bufptr = s; \
273             return (int)LSTOP; \
274         } while(0)
275
276 #define COPLINE_INC_WITH_HERELINES                  \
277     STMT_START {                                     \
278         CopLINE_inc(PL_curcop);                       \
279         if (PL_parser->herelines)                      \
280             CopLINE(PL_curcop) += PL_parser->herelines, \
281             PL_parser->herelines = 0;                    \
282     } STMT_END
283 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
284  * is no sublex_push to follow. */
285 #define COPLINE_SET_FROM_MULTI_END            \
286     STMT_START {                               \
287         CopLINE_set(PL_curcop, PL_multi_end);   \
288         if (PL_multi_end != PL_multi_start)      \
289             PL_parser->herelines = 0;             \
290     } STMT_END
291
292
293 /* A file-local structure for passing around information about subroutines and
294  * related definable words */
295 struct code {
296     SV *sv;
297     CV *cv;
298     GV *gv, **gvp;
299     OP *rv2cv_op;
300     PADOFFSET off;
301     bool lex;
302 };
303
304 static const struct code no_code = { NULL, NULL, NULL, NULL, NULL, 0, FALSE };
305
306
307 #ifdef DEBUGGING
308
309 /* how to interpret the pl_yylval associated with the token */
310 enum token_type {
311     TOKENTYPE_NONE,
312     TOKENTYPE_IVAL,
313     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
314     TOKENTYPE_PVAL,
315     TOKENTYPE_OPVAL
316 };
317
318 static struct debug_tokens {
319     const int token;
320     enum token_type type;
321     const char *name;
322 } const debug_tokens[] =
323 {
324     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
325     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
326     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
327     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
328     { ANON_SIGSUB,      TOKENTYPE_IVAL,         "ANON_SIGSUB" },
329     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
330     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
331     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
332     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
333     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
334     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
335     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
336     { DO,               TOKENTYPE_NONE,         "DO" },
337     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
338     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
339     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
340     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
341     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
342     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
343     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
344     { FOR,              TOKENTYPE_IVAL,         "FOR" },
345     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
346     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
347     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
348     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
349     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
350     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
351     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
352     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
353     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
354     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
355     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
356     { IF,               TOKENTYPE_IVAL,         "IF" },
357     { LABEL,            TOKENTYPE_OPVAL,        "LABEL" },
358     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
359     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
360     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
361     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
362     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
363     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
364     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
365     { MY,               TOKENTYPE_IVAL,         "MY" },
366     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
367     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
368     { OROP,             TOKENTYPE_IVAL,         "OROP" },
369     { OROR,             TOKENTYPE_NONE,         "OROR" },
370     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
371     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
372     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
373     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
374     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
375     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
376     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
377     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
378     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
379     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
380     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
381     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
382     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
383     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
384     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
385     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
386     { SIGSUB,           TOKENTYPE_NONE,         "SIGSUB" },
387     { SUB,              TOKENTYPE_NONE,         "SUB" },
388     { SUBLEXEND,        TOKENTYPE_NONE,         "SUBLEXEND" },
389     { SUBLEXSTART,      TOKENTYPE_NONE,         "SUBLEXSTART" },
390     { THING,            TOKENTYPE_OPVAL,        "THING" },
391     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
392     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
393     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
394     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
395     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
396     { USE,              TOKENTYPE_IVAL,         "USE" },
397     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
398     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
399     { BAREWORD,         TOKENTYPE_OPVAL,        "BAREWORD" },
400     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
401     { 0,                TOKENTYPE_NONE,         NULL }
402 };
403
404 /* dump the returned token in rv, plus any optional arg in pl_yylval */
405
406 STATIC int
407 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
408 {
409     PERL_ARGS_ASSERT_TOKEREPORT;
410
411     if (DEBUG_T_TEST) {
412         const char *name = NULL;
413         enum token_type type = TOKENTYPE_NONE;
414         const struct debug_tokens *p;
415         SV* const report = newSVpvs("<== ");
416
417         for (p = debug_tokens; p->token; p++) {
418             if (p->token == (int)rv) {
419                 name = p->name;
420                 type = p->type;
421                 break;
422             }
423         }
424         if (name)
425             Perl_sv_catpv(aTHX_ report, name);
426         else if (isGRAPH(rv))
427         {
428             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
429             if ((char)rv == 'p')
430                 sv_catpvs(report, " (pending identifier)");
431         }
432         else if (!rv)
433             sv_catpvs(report, "EOF");
434         else
435             Perl_sv_catpvf(aTHX_ report, "?? %" IVdf, (IV)rv);
436         switch (type) {
437         case TOKENTYPE_NONE:
438             break;
439         case TOKENTYPE_IVAL:
440             Perl_sv_catpvf(aTHX_ report, "(ival=%" IVdf ")", (IV)lvalp->ival);
441             break;
442         case TOKENTYPE_OPNUM:
443             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
444                                     PL_op_name[lvalp->ival]);
445             break;
446         case TOKENTYPE_PVAL:
447             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
448             break;
449         case TOKENTYPE_OPVAL:
450             if (lvalp->opval) {
451                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
452                                     PL_op_name[lvalp->opval->op_type]);
453                 if (lvalp->opval->op_type == OP_CONST) {
454                     Perl_sv_catpvf(aTHX_ report, " %s",
455                         SvPEEK(cSVOPx_sv(lvalp->opval)));
456                 }
457
458             }
459             else
460                 sv_catpvs(report, "(opval=null)");
461             break;
462         }
463         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
464     };
465     return (int)rv;
466 }
467
468
469 /* print the buffer with suitable escapes */
470
471 STATIC void
472 S_printbuf(pTHX_ const char *const fmt, const char *const s)
473 {
474     SV* const tmp = newSVpvs("");
475
476     PERL_ARGS_ASSERT_PRINTBUF;
477
478     GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
479     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
480     GCC_DIAG_RESTORE_STMT;
481     SvREFCNT_dec(tmp);
482 }
483
484 #endif
485
486 /*
487  * S_ao
488  *
489  * This subroutine looks for an '=' next to the operator that has just been
490  * parsed and turns it into an ASSIGNOP if it finds one.
491  */
492
493 STATIC int
494 S_ao(pTHX_ int toketype)
495 {
496     if (*PL_bufptr == '=') {
497         PL_bufptr++;
498         if (toketype == ANDAND)
499             pl_yylval.ival = OP_ANDASSIGN;
500         else if (toketype == OROR)
501             pl_yylval.ival = OP_ORASSIGN;
502         else if (toketype == DORDOR)
503             pl_yylval.ival = OP_DORASSIGN;
504         toketype = ASSIGNOP;
505     }
506     return REPORT(toketype);
507 }
508
509 /*
510  * S_no_op
511  * When Perl expects an operator and finds something else, no_op
512  * prints the warning.  It always prints "<something> found where
513  * operator expected.  It prints "Missing semicolon on previous line?"
514  * if the surprise occurs at the start of the line.  "do you need to
515  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
516  * where the compiler doesn't know if foo is a method call or a function.
517  * It prints "Missing operator before end of line" if there's nothing
518  * after the missing operator, or "... before <...>" if there is something
519  * after the missing operator.
520  *
521  * PL_bufptr is expected to point to the start of the thing that was found,
522  * and s after the next token or partial token.
523  */
524
525 STATIC void
526 S_no_op(pTHX_ const char *const what, char *s)
527 {
528     char * const oldbp = PL_bufptr;
529     const bool is_first = (PL_oldbufptr == PL_linestart);
530
531     PERL_ARGS_ASSERT_NO_OP;
532
533     if (!s)
534         s = oldbp;
535     else
536         PL_bufptr = s;
537     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
538     if (ckWARN_d(WARN_SYNTAX)) {
539         if (is_first)
540             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
541                     "\t(Missing semicolon on previous line?)\n");
542         else if (PL_oldoldbufptr && isIDFIRST_lazy_if_safe(PL_oldoldbufptr,
543                                                            PL_bufend,
544                                                            UTF))
545         {
546             const char *t;
547             for (t = PL_oldoldbufptr;
548                  (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF) || *t == ':');
549                  t += UTF ? UTF8SKIP(t) : 1)
550             {
551                 NOOP;
552             }
553             if (t < PL_bufptr && isSPACE(*t))
554                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
555                         "\t(Do you need to predeclare %" UTF8f "?)\n",
556                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
557         }
558         else {
559             assert(s >= oldbp);
560             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
561                     "\t(Missing operator before %" UTF8f "?)\n",
562                      UTF8fARG(UTF, s - oldbp, oldbp));
563         }
564     }
565     PL_bufptr = oldbp;
566 }
567
568 /*
569  * S_missingterm
570  * Complain about missing quote/regexp/heredoc terminator.
571  * If it's called with NULL then it cauterizes the line buffer.
572  * If we're in a delimited string and the delimiter is a control
573  * character, it's reformatted into a two-char sequence like ^C.
574  * This is fatal.
575  */
576
577 STATIC void
578 S_missingterm(pTHX_ char *s, STRLEN len)
579 {
580     char tmpbuf[UTF8_MAXBYTES + 1];
581     char q;
582     bool uni = FALSE;
583     SV *sv;
584     if (s) {
585         char * const nl = (char *) my_memrchr(s, '\n', len);
586         if (nl) {
587             *nl = '\0';
588             len = nl - s;
589         }
590         uni = UTF;
591     }
592     else if (PL_multi_close < 32) {
593         *tmpbuf = '^';
594         tmpbuf[1] = (char)toCTRL(PL_multi_close);
595         tmpbuf[2] = '\0';
596         s = tmpbuf;
597         len = 2;
598     }
599     else {
600         if (LIKELY(PL_multi_close < 256)) {
601             *tmpbuf = (char)PL_multi_close;
602             tmpbuf[1] = '\0';
603             len = 1;
604         }
605         else {
606             char *end = (char *)uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close);
607             *end = '\0';
608             len = end - tmpbuf;
609             uni = TRUE;
610         }
611         s = tmpbuf;
612     }
613     q = memchr(s, '"', len) ? '\'' : '"';
614     sv = sv_2mortal(newSVpvn(s, len));
615     if (uni)
616         SvUTF8_on(sv);
617     Perl_croak(aTHX_ "Can't find string terminator %c%" SVf "%c"
618                      " anywhere before EOF", q, SVfARG(sv), q);
619 }
620
621 #include "feature.h"
622
623 /*
624  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
625  * utf16-to-utf8-reversed.
626  */
627
628 #ifdef PERL_CR_FILTER
629 static void
630 strip_return(SV *sv)
631 {
632     const char *s = SvPVX_const(sv);
633     const char * const e = s + SvCUR(sv);
634
635     PERL_ARGS_ASSERT_STRIP_RETURN;
636
637     /* outer loop optimized to do nothing if there are no CR-LFs */
638     while (s < e) {
639         if (*s++ == '\r' && *s == '\n') {
640             /* hit a CR-LF, need to copy the rest */
641             char *d = s - 1;
642             *d++ = *s++;
643             while (s < e) {
644                 if (*s == '\r' && s[1] == '\n')
645                     s++;
646                 *d++ = *s++;
647             }
648             SvCUR(sv) -= s - d;
649             return;
650         }
651     }
652 }
653
654 STATIC I32
655 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
656 {
657     const I32 count = FILTER_READ(idx+1, sv, maxlen);
658     if (count > 0 && !maxlen)
659         strip_return(sv);
660     return count;
661 }
662 #endif
663
664 /*
665 =for apidoc lex_start
666
667 Creates and initialises a new lexer/parser state object, supplying
668 a context in which to lex and parse from a new source of Perl code.
669 A pointer to the new state object is placed in L</PL_parser>.  An entry
670 is made on the save stack so that upon unwinding, the new state object
671 will be destroyed and the former value of L</PL_parser> will be restored.
672 Nothing else need be done to clean up the parsing context.
673
674 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
675 non-null, provides a string (in SV form) containing code to be parsed.
676 A copy of the string is made, so subsequent modification of C<line>
677 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
678 from which code will be read to be parsed.  If both are non-null, the
679 code in C<line> comes first and must consist of complete lines of input,
680 and C<rsfp> supplies the remainder of the source.
681
682 The C<flags> parameter is reserved for future use.  Currently it is only
683 used by perl internally, so extensions should always pass zero.
684
685 =cut
686 */
687
688 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
689    can share filters with the current parser.
690    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
691    caller, hence isn't owned by the parser, so shouldn't be closed on parser
692    destruction. This is used to handle the case of defaulting to reading the
693    script from the standard input because no filename was given on the command
694    line (without getting confused by situation where STDIN has been closed, so
695    the script handle is opened on fd 0)  */
696
697 void
698 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
699 {
700     const char *s = NULL;
701     yy_parser *parser, *oparser;
702
703     if (flags && flags & ~LEX_START_FLAGS)
704         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
705
706     /* create and initialise a parser */
707
708     Newxz(parser, 1, yy_parser);
709     parser->old_parser = oparser = PL_parser;
710     PL_parser = parser;
711
712     parser->stack = NULL;
713     parser->stack_max1 = NULL;
714     parser->ps = NULL;
715
716     /* on scope exit, free this parser and restore any outer one */
717     SAVEPARSER(parser);
718     parser->saved_curcop = PL_curcop;
719
720     /* initialise lexer state */
721
722     parser->nexttoke = 0;
723     parser->error_count = oparser ? oparser->error_count : 0;
724     parser->copline = parser->preambling = NOLINE;
725     parser->lex_state = LEX_NORMAL;
726     parser->expect = XSTATE;
727     parser->rsfp = rsfp;
728     parser->recheck_utf8_validity = TRUE;
729     parser->rsfp_filters =
730       !(flags & LEX_START_SAME_FILTER) || !oparser
731         ? NULL
732         : MUTABLE_AV(SvREFCNT_inc(
733             oparser->rsfp_filters
734              ? oparser->rsfp_filters
735              : (oparser->rsfp_filters = newAV())
736           ));
737
738     Newx(parser->lex_brackstack, 120, char);
739     Newx(parser->lex_casestack, 12, char);
740     *parser->lex_casestack = '\0';
741     Newxz(parser->lex_shared, 1, LEXSHARED);
742
743     if (line) {
744         STRLEN len;
745         const U8* first_bad_char_loc;
746
747         s = SvPV_const(line, len);
748
749         if (   SvUTF8(line)
750             && UNLIKELY(! is_utf8_string_loc((U8 *) s,
751                                              SvCUR(line),
752                                              &first_bad_char_loc)))
753         {
754             _force_out_malformed_utf8_message(first_bad_char_loc,
755                                               (U8 *) s + SvCUR(line),
756                                               0,
757                                               1 /* 1 means die */ );
758             NOT_REACHED; /* NOTREACHED */
759         }
760
761         parser->linestr = flags & LEX_START_COPIED
762                             ? SvREFCNT_inc_simple_NN(line)
763                             : newSVpvn_flags(s, len, SvUTF8(line));
764         if (!rsfp)
765             sv_catpvs(parser->linestr, "\n;");
766     } else {
767         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
768     }
769
770     parser->oldoldbufptr =
771         parser->oldbufptr =
772         parser->bufptr =
773         parser->linestart = SvPVX(parser->linestr);
774     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
775     parser->last_lop = parser->last_uni = NULL;
776
777     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
778                                                         |LEX_DONT_CLOSE_RSFP));
779     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
780                                                         |LEX_DONT_CLOSE_RSFP));
781
782     parser->in_pod = parser->filtered = 0;
783 }
784
785
786 /* delete a parser object */
787
788 void
789 Perl_parser_free(pTHX_  const yy_parser *parser)
790 {
791     PERL_ARGS_ASSERT_PARSER_FREE;
792
793     PL_curcop = parser->saved_curcop;
794     SvREFCNT_dec(parser->linestr);
795
796     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
797         PerlIO_clearerr(parser->rsfp);
798     else if (parser->rsfp && (!parser->old_parser
799           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
800         PerlIO_close(parser->rsfp);
801     SvREFCNT_dec(parser->rsfp_filters);
802     SvREFCNT_dec(parser->lex_stuff);
803     SvREFCNT_dec(parser->lex_sub_repl);
804
805     Safefree(parser->lex_brackstack);
806     Safefree(parser->lex_casestack);
807     Safefree(parser->lex_shared);
808     PL_parser = parser->old_parser;
809     Safefree(parser);
810 }
811
812 void
813 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
814 {
815     I32 nexttoke = parser->nexttoke;
816     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
817     while (nexttoke--) {
818         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
819          && parser->nextval[nexttoke].opval
820          && parser->nextval[nexttoke].opval->op_slabbed
821          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
822             op_free(parser->nextval[nexttoke].opval);
823             parser->nextval[nexttoke].opval = NULL;
824         }
825     }
826 }
827
828
829 /*
830 =for apidoc AmnxUN|SV *|PL_parser-E<gt>linestr
831
832 Buffer scalar containing the chunk currently under consideration of the
833 text currently being lexed.  This is always a plain string scalar (for
834 which C<SvPOK> is true).  It is not intended to be used as a scalar by
835 normal scalar means; instead refer to the buffer directly by the pointer
836 variables described below.
837
838 The lexer maintains various C<char*> pointers to things in the
839 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
840 reallocated, all of these pointers must be updated.  Don't attempt to
841 do this manually, but rather use L</lex_grow_linestr> if you need to
842 reallocate the buffer.
843
844 The content of the text chunk in the buffer is commonly exactly one
845 complete line of input, up to and including a newline terminator,
846 but there are situations where it is otherwise.  The octets of the
847 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
848 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
849 flag on this scalar, which may disagree with it.
850
851 For direct examination of the buffer, the variable
852 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
853 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
854 of these pointers is usually preferable to examination of the scalar
855 through normal scalar means.
856
857 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufend
858
859 Direct pointer to the end of the chunk of text currently being lexed, the
860 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
861 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
862 always located at the end of the buffer, and does not count as part of
863 the buffer's contents.
864
865 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufptr
866
867 Points to the current position of lexing inside the lexer buffer.
868 Characters around this point may be freely examined, within
869 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
870 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
871 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
872
873 Lexing code (whether in the Perl core or not) moves this pointer past
874 the characters that it consumes.  It is also expected to perform some
875 bookkeeping whenever a newline character is consumed.  This movement
876 can be more conveniently performed by the function L</lex_read_to>,
877 which handles newlines appropriately.
878
879 Interpretation of the buffer's octets can be abstracted out by
880 using the slightly higher-level functions L</lex_peek_unichar> and
881 L</lex_read_unichar>.
882
883 =for apidoc AmnxUN|char *|PL_parser-E<gt>linestart
884
885 Points to the start of the current line inside the lexer buffer.
886 This is useful for indicating at which column an error occurred, and
887 not much else.  This must be updated by any lexing code that consumes
888 a newline; the function L</lex_read_to> handles this detail.
889
890 =cut
891 */
892
893 /*
894 =for apidoc lex_bufutf8
895
896 Indicates whether the octets in the lexer buffer
897 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
898 of Unicode characters.  If not, they should be interpreted as Latin-1
899 characters.  This is analogous to the C<SvUTF8> flag for scalars.
900
901 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
902 contains valid UTF-8.  Lexing code must be robust in the face of invalid
903 encoding.
904
905 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
906 is significant, but not the whole story regarding the input character
907 encoding.  Normally, when a file is being read, the scalar contains octets
908 and its C<SvUTF8> flag is off, but the octets should be interpreted as
909 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
910 however, the scalar may have the C<SvUTF8> flag on, and in this case its
911 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
912 is in effect.  This logic may change in the future; use this function
913 instead of implementing the logic yourself.
914
915 =cut
916 */
917
918 bool
919 Perl_lex_bufutf8(pTHX)
920 {
921     return UTF;
922 }
923
924 /*
925 =for apidoc lex_grow_linestr
926
927 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
928 at least C<len> octets (including terminating C<NUL>).  Returns a
929 pointer to the reallocated buffer.  This is necessary before making
930 any direct modification of the buffer that would increase its length.
931 L</lex_stuff_pvn> provides a more convenient way to insert text into
932 the buffer.
933
934 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
935 this function updates all of the lexer's variables that point directly
936 into the buffer.
937
938 =cut
939 */
940
941 char *
942 Perl_lex_grow_linestr(pTHX_ STRLEN len)
943 {
944     SV *linestr;
945     char *buf;
946     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
947     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
948     bool current;
949
950     linestr = PL_parser->linestr;
951     buf = SvPVX(linestr);
952     if (len <= SvLEN(linestr))
953         return buf;
954
955     /* Is the lex_shared linestr SV the same as the current linestr SV?
956      * Only in this case does re_eval_start need adjusting, since it
957      * points within lex_shared->ls_linestr's buffer */
958     current = (   !PL_parser->lex_shared->ls_linestr
959                || linestr == PL_parser->lex_shared->ls_linestr);
960
961     bufend_pos = PL_parser->bufend - buf;
962     bufptr_pos = PL_parser->bufptr - buf;
963     oldbufptr_pos = PL_parser->oldbufptr - buf;
964     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
965     linestart_pos = PL_parser->linestart - buf;
966     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
967     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
968     re_eval_start_pos = (current && PL_parser->lex_shared->re_eval_start) ?
969                             PL_parser->lex_shared->re_eval_start - buf : 0;
970
971     buf = sv_grow(linestr, len);
972
973     PL_parser->bufend = buf + bufend_pos;
974     PL_parser->bufptr = buf + bufptr_pos;
975     PL_parser->oldbufptr = buf + oldbufptr_pos;
976     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
977     PL_parser->linestart = buf + linestart_pos;
978     if (PL_parser->last_uni)
979         PL_parser->last_uni = buf + last_uni_pos;
980     if (PL_parser->last_lop)
981         PL_parser->last_lop = buf + last_lop_pos;
982     if (current && PL_parser->lex_shared->re_eval_start)
983         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
984     return buf;
985 }
986
987 /*
988 =for apidoc lex_stuff_pvn
989
990 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
991 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
992 reallocating the buffer if necessary.  This means that lexing code that
993 runs later will see the characters as if they had appeared in the input.
994 It is not recommended to do this as part of normal parsing, and most
995 uses of this facility run the risk of the inserted characters being
996 interpreted in an unintended manner.
997
998 The string to be inserted is represented by C<len> octets starting
999 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
1000 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
1001 The characters are recoded for the lexer buffer, according to how the
1002 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
1003 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
1004 function is more convenient.
1005
1006 =cut
1007 */
1008
1009 void
1010 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
1011 {
1012     dVAR;
1013     char *bufptr;
1014     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
1015     if (flags & ~(LEX_STUFF_UTF8))
1016         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
1017     if (UTF) {
1018         if (flags & LEX_STUFF_UTF8) {
1019             goto plain_copy;
1020         } else {
1021             STRLEN highhalf = variant_under_utf8_count((U8 *) pv,
1022                                                        (U8 *) pv + len);
1023             const char *p, *e = pv+len;;
1024             if (!highhalf)
1025                 goto plain_copy;
1026             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
1027             bufptr = PL_parser->bufptr;
1028             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
1029             SvCUR_set(PL_parser->linestr,
1030                 SvCUR(PL_parser->linestr) + len+highhalf);
1031             PL_parser->bufend += len+highhalf;
1032             for (p = pv; p != e; p++) {
1033                 append_utf8_from_native_byte(*p, (U8 **) &bufptr);
1034             }
1035         }
1036     } else {
1037         if (flags & LEX_STUFF_UTF8) {
1038             STRLEN highhalf = 0;
1039             const char *p, *e = pv+len;
1040             for (p = pv; p != e; p++) {
1041                 U8 c = (U8)*p;
1042                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1043                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1044                                 "non-Latin-1 character into Latin-1 input");
1045                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1046                     p++;
1047                     highhalf++;
1048                 } else assert(UTF8_IS_INVARIANT(c));
1049             }
1050             if (!highhalf)
1051                 goto plain_copy;
1052             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1053             bufptr = PL_parser->bufptr;
1054             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1055             SvCUR_set(PL_parser->linestr,
1056                 SvCUR(PL_parser->linestr) + len-highhalf);
1057             PL_parser->bufend += len-highhalf;
1058             p = pv;
1059             while (p < e) {
1060                 if (UTF8_IS_INVARIANT(*p)) {
1061                     *bufptr++ = *p;
1062                     p++;
1063                 }
1064                 else {
1065                     assert(p < e -1 );
1066                     *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1067                     p += 2;
1068                 }
1069             }
1070         } else {
1071           plain_copy:
1072             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1073             bufptr = PL_parser->bufptr;
1074             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1075             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1076             PL_parser->bufend += len;
1077             Copy(pv, bufptr, len, char);
1078         }
1079     }
1080 }
1081
1082 /*
1083 =for apidoc lex_stuff_pv
1084
1085 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1086 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1087 reallocating the buffer if necessary.  This means that lexing code that
1088 runs later will see the characters as if they had appeared in the input.
1089 It is not recommended to do this as part of normal parsing, and most
1090 uses of this facility run the risk of the inserted characters being
1091 interpreted in an unintended manner.
1092
1093 The string to be inserted is represented by octets starting at C<pv>
1094 and continuing to the first nul.  These octets are interpreted as either
1095 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1096 in C<flags>.  The characters are recoded for the lexer buffer, according
1097 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1098 If it is not convenient to nul-terminate a string to be inserted, the
1099 L</lex_stuff_pvn> function is more appropriate.
1100
1101 =cut
1102 */
1103
1104 void
1105 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1106 {
1107     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1108     lex_stuff_pvn(pv, strlen(pv), flags);
1109 }
1110
1111 /*
1112 =for apidoc lex_stuff_sv
1113
1114 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1115 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1116 reallocating the buffer if necessary.  This means that lexing code that
1117 runs later will see the characters as if they had appeared in the input.
1118 It is not recommended to do this as part of normal parsing, and most
1119 uses of this facility run the risk of the inserted characters being
1120 interpreted in an unintended manner.
1121
1122 The string to be inserted is the string value of C<sv>.  The characters
1123 are recoded for the lexer buffer, according to how the buffer is currently
1124 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1125 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1126 need to construct a scalar.
1127
1128 =cut
1129 */
1130
1131 void
1132 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1133 {
1134     char *pv;
1135     STRLEN len;
1136     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1137     if (flags)
1138         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1139     pv = SvPV(sv, len);
1140     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1141 }
1142
1143 /*
1144 =for apidoc lex_unstuff
1145
1146 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1147 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1148 This hides the discarded text from any lexing code that runs later,
1149 as if the text had never appeared.
1150
1151 This is not the normal way to consume lexed text.  For that, use
1152 L</lex_read_to>.
1153
1154 =cut
1155 */
1156
1157 void
1158 Perl_lex_unstuff(pTHX_ char *ptr)
1159 {
1160     char *buf, *bufend;
1161     STRLEN unstuff_len;
1162     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1163     buf = PL_parser->bufptr;
1164     if (ptr < buf)
1165         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1166     if (ptr == buf)
1167         return;
1168     bufend = PL_parser->bufend;
1169     if (ptr > bufend)
1170         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1171     unstuff_len = ptr - buf;
1172     Move(ptr, buf, bufend+1-ptr, char);
1173     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1174     PL_parser->bufend = bufend - unstuff_len;
1175 }
1176
1177 /*
1178 =for apidoc lex_read_to
1179
1180 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1181 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1182 performing the correct bookkeeping whenever a newline character is passed.
1183 This is the normal way to consume lexed text.
1184
1185 Interpretation of the buffer's octets can be abstracted out by
1186 using the slightly higher-level functions L</lex_peek_unichar> and
1187 L</lex_read_unichar>.
1188
1189 =cut
1190 */
1191
1192 void
1193 Perl_lex_read_to(pTHX_ char *ptr)
1194 {
1195     char *s;
1196     PERL_ARGS_ASSERT_LEX_READ_TO;
1197     s = PL_parser->bufptr;
1198     if (ptr < s || ptr > PL_parser->bufend)
1199         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1200     for (; s != ptr; s++)
1201         if (*s == '\n') {
1202             COPLINE_INC_WITH_HERELINES;
1203             PL_parser->linestart = s+1;
1204         }
1205     PL_parser->bufptr = ptr;
1206 }
1207
1208 /*
1209 =for apidoc lex_discard_to
1210
1211 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1212 up to C<ptr>.  The remaining content of the buffer will be moved, and
1213 all pointers into the buffer updated appropriately.  C<ptr> must not
1214 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1215 it is not permitted to discard text that has yet to be lexed.
1216
1217 Normally it is not necessarily to do this directly, because it suffices to
1218 use the implicit discarding behaviour of L</lex_next_chunk> and things
1219 based on it.  However, if a token stretches across multiple lines,
1220 and the lexing code has kept multiple lines of text in the buffer for
1221 that purpose, then after completion of the token it would be wise to
1222 explicitly discard the now-unneeded earlier lines, to avoid future
1223 multi-line tokens growing the buffer without bound.
1224
1225 =cut
1226 */
1227
1228 void
1229 Perl_lex_discard_to(pTHX_ char *ptr)
1230 {
1231     char *buf;
1232     STRLEN discard_len;
1233     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1234     buf = SvPVX(PL_parser->linestr);
1235     if (ptr < buf)
1236         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1237     if (ptr == buf)
1238         return;
1239     if (ptr > PL_parser->bufptr)
1240         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1241     discard_len = ptr - buf;
1242     if (PL_parser->oldbufptr < ptr)
1243         PL_parser->oldbufptr = ptr;
1244     if (PL_parser->oldoldbufptr < ptr)
1245         PL_parser->oldoldbufptr = ptr;
1246     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1247         PL_parser->last_uni = NULL;
1248     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1249         PL_parser->last_lop = NULL;
1250     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1251     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1252     PL_parser->bufend -= discard_len;
1253     PL_parser->bufptr -= discard_len;
1254     PL_parser->oldbufptr -= discard_len;
1255     PL_parser->oldoldbufptr -= discard_len;
1256     if (PL_parser->last_uni)
1257         PL_parser->last_uni -= discard_len;
1258     if (PL_parser->last_lop)
1259         PL_parser->last_lop -= discard_len;
1260 }
1261
1262 void
1263 Perl_notify_parser_that_changed_to_utf8(pTHX)
1264 {
1265     /* Called when $^H is changed to indicate that HINT_UTF8 has changed from
1266      * off to on.  At compile time, this has the effect of entering a 'use
1267      * utf8' section.  This means that any input was not previously checked for
1268      * UTF-8 (because it was off), but now we do need to check it, or our
1269      * assumptions about the input being sane could be wrong, and we could
1270      * segfault.  This routine just sets a flag so that the next time we look
1271      * at the input we do the well-formed UTF-8 check.  If we aren't in the
1272      * proper phase, there may not be a parser object, but if there is, setting
1273      * the flag is harmless */
1274
1275     if (PL_parser) {
1276         PL_parser->recheck_utf8_validity = TRUE;
1277     }
1278 }
1279
1280 /*
1281 =for apidoc lex_next_chunk
1282
1283 Reads in the next chunk of text to be lexed, appending it to
1284 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1285 looked to the end of the current chunk and wants to know more.  It is
1286 usual, but not necessary, for lexing to have consumed the entirety of
1287 the current chunk at this time.
1288
1289 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1290 chunk (i.e., the current chunk has been entirely consumed), normally the
1291 current chunk will be discarded at the same time that the new chunk is
1292 read in.  If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1293 will not be discarded.  If the current chunk has not been entirely
1294 consumed, then it will not be discarded regardless of the flag.
1295
1296 Returns true if some new text was added to the buffer, or false if the
1297 buffer has reached the end of the input text.
1298
1299 =cut
1300 */
1301
1302 #define LEX_FAKE_EOF 0x80000000
1303 #define LEX_NO_TERM  0x40000000 /* here-doc */
1304
1305 bool
1306 Perl_lex_next_chunk(pTHX_ U32 flags)
1307 {
1308     SV *linestr;
1309     char *buf;
1310     STRLEN old_bufend_pos, new_bufend_pos;
1311     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1312     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1313     bool got_some_for_debugger = 0;
1314     bool got_some;
1315
1316     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1317         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1318     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1319         return FALSE;
1320     linestr = PL_parser->linestr;
1321     buf = SvPVX(linestr);
1322     if (!(flags & LEX_KEEP_PREVIOUS)
1323           && PL_parser->bufptr == PL_parser->bufend)
1324     {
1325         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1326         linestart_pos = 0;
1327         if (PL_parser->last_uni != PL_parser->bufend)
1328             PL_parser->last_uni = NULL;
1329         if (PL_parser->last_lop != PL_parser->bufend)
1330             PL_parser->last_lop = NULL;
1331         last_uni_pos = last_lop_pos = 0;
1332         *buf = 0;
1333         SvCUR_set(linestr, 0);
1334     } else {
1335         old_bufend_pos = PL_parser->bufend - buf;
1336         bufptr_pos = PL_parser->bufptr - buf;
1337         oldbufptr_pos = PL_parser->oldbufptr - buf;
1338         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1339         linestart_pos = PL_parser->linestart - buf;
1340         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1341         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1342     }
1343     if (flags & LEX_FAKE_EOF) {
1344         goto eof;
1345     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1346         got_some = 0;
1347     } else if (filter_gets(linestr, old_bufend_pos)) {
1348         got_some = 1;
1349         got_some_for_debugger = 1;
1350     } else if (flags & LEX_NO_TERM) {
1351         got_some = 0;
1352     } else {
1353         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1354             SvPVCLEAR(linestr);
1355         eof:
1356         /* End of real input.  Close filehandle (unless it was STDIN),
1357          * then add implicit termination.
1358          */
1359         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1360             PerlIO_clearerr(PL_parser->rsfp);
1361         else if (PL_parser->rsfp)
1362             (void)PerlIO_close(PL_parser->rsfp);
1363         PL_parser->rsfp = NULL;
1364         PL_parser->in_pod = PL_parser->filtered = 0;
1365         if (!PL_in_eval && PL_minus_p) {
1366             sv_catpvs(linestr,
1367                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1368             PL_minus_n = PL_minus_p = 0;
1369         } else if (!PL_in_eval && PL_minus_n) {
1370             sv_catpvs(linestr, /*{*/";}");
1371             PL_minus_n = 0;
1372         } else
1373             sv_catpvs(linestr, ";");
1374         got_some = 1;
1375     }
1376     buf = SvPVX(linestr);
1377     new_bufend_pos = SvCUR(linestr);
1378     PL_parser->bufend = buf + new_bufend_pos;
1379     PL_parser->bufptr = buf + bufptr_pos;
1380
1381     if (UTF) {
1382         const U8* first_bad_char_loc;
1383         if (UNLIKELY(! is_utf8_string_loc(
1384                             (U8 *) PL_parser->bufptr,
1385                                    PL_parser->bufend - PL_parser->bufptr,
1386                                    &first_bad_char_loc)))
1387         {
1388             _force_out_malformed_utf8_message(first_bad_char_loc,
1389                                               (U8 *) PL_parser->bufend,
1390                                               0,
1391                                               1 /* 1 means die */ );
1392             NOT_REACHED; /* NOTREACHED */
1393         }
1394     }
1395
1396     PL_parser->oldbufptr = buf + oldbufptr_pos;
1397     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1398     PL_parser->linestart = buf + linestart_pos;
1399     if (PL_parser->last_uni)
1400         PL_parser->last_uni = buf + last_uni_pos;
1401     if (PL_parser->last_lop)
1402         PL_parser->last_lop = buf + last_lop_pos;
1403     if (PL_parser->preambling != NOLINE) {
1404         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1405         PL_parser->preambling = NOLINE;
1406     }
1407     if (   got_some_for_debugger
1408         && PERLDB_LINE_OR_SAVESRC
1409         && PL_curstash != PL_debstash)
1410     {
1411         /* debugger active and we're not compiling the debugger code,
1412          * so store the line into the debugger's array of lines
1413          */
1414         update_debugger_info(NULL, buf+old_bufend_pos,
1415             new_bufend_pos-old_bufend_pos);
1416     }
1417     return got_some;
1418 }
1419
1420 /*
1421 =for apidoc lex_peek_unichar
1422
1423 Looks ahead one (Unicode) character in the text currently being lexed.
1424 Returns the codepoint (unsigned integer value) of the next character,
1425 or -1 if lexing has reached the end of the input text.  To consume the
1426 peeked character, use L</lex_read_unichar>.
1427
1428 If the next character is in (or extends into) the next chunk of input
1429 text, the next chunk will be read in.  Normally the current chunk will be
1430 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1431 bit set, then the current chunk will not be discarded.
1432
1433 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1434 is encountered, an exception is generated.
1435
1436 =cut
1437 */
1438
1439 I32
1440 Perl_lex_peek_unichar(pTHX_ U32 flags)
1441 {
1442     dVAR;
1443     char *s, *bufend;
1444     if (flags & ~(LEX_KEEP_PREVIOUS))
1445         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1446     s = PL_parser->bufptr;
1447     bufend = PL_parser->bufend;
1448     if (UTF) {
1449         U8 head;
1450         I32 unichar;
1451         STRLEN len, retlen;
1452         if (s == bufend) {
1453             if (!lex_next_chunk(flags))
1454                 return -1;
1455             s = PL_parser->bufptr;
1456             bufend = PL_parser->bufend;
1457         }
1458         head = (U8)*s;
1459         if (UTF8_IS_INVARIANT(head))
1460             return head;
1461         if (UTF8_IS_START(head)) {
1462             len = UTF8SKIP(&head);
1463             while ((STRLEN)(bufend-s) < len) {
1464                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1465                     break;
1466                 s = PL_parser->bufptr;
1467                 bufend = PL_parser->bufend;
1468             }
1469         }
1470         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1471         if (retlen == (STRLEN)-1) {
1472             _force_out_malformed_utf8_message((U8 *) s,
1473                                               (U8 *) bufend,
1474                                               0,
1475                                               1 /* 1 means die */ );
1476             NOT_REACHED; /* NOTREACHED */
1477         }
1478         return unichar;
1479     } else {
1480         if (s == bufend) {
1481             if (!lex_next_chunk(flags))
1482                 return -1;
1483             s = PL_parser->bufptr;
1484         }
1485         return (U8)*s;
1486     }
1487 }
1488
1489 /*
1490 =for apidoc lex_read_unichar
1491
1492 Reads the next (Unicode) character in the text currently being lexed.
1493 Returns the codepoint (unsigned integer value) of the character read,
1494 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1495 if lexing has reached the end of the input text.  To non-destructively
1496 examine the next character, use L</lex_peek_unichar> instead.
1497
1498 If the next character is in (or extends into) the next chunk of input
1499 text, the next chunk will be read in.  Normally the current chunk will be
1500 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1501 bit set, then the current chunk will not be discarded.
1502
1503 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1504 is encountered, an exception is generated.
1505
1506 =cut
1507 */
1508
1509 I32
1510 Perl_lex_read_unichar(pTHX_ U32 flags)
1511 {
1512     I32 c;
1513     if (flags & ~(LEX_KEEP_PREVIOUS))
1514         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1515     c = lex_peek_unichar(flags);
1516     if (c != -1) {
1517         if (c == '\n')
1518             COPLINE_INC_WITH_HERELINES;
1519         if (UTF)
1520             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1521         else
1522             ++(PL_parser->bufptr);
1523     }
1524     return c;
1525 }
1526
1527 /*
1528 =for apidoc lex_read_space
1529
1530 Reads optional spaces, in Perl style, in the text currently being
1531 lexed.  The spaces may include ordinary whitespace characters and
1532 Perl-style comments.  C<#line> directives are processed if encountered.
1533 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1534 at a non-space character (or the end of the input text).
1535
1536 If spaces extend into the next chunk of input text, the next chunk will
1537 be read in.  Normally the current chunk will be discarded at the same
1538 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1539 chunk will not be discarded.
1540
1541 =cut
1542 */
1543
1544 #define LEX_NO_INCLINE    0x40000000
1545 #define LEX_NO_NEXT_CHUNK 0x80000000
1546
1547 void
1548 Perl_lex_read_space(pTHX_ U32 flags)
1549 {
1550     char *s, *bufend;
1551     const bool can_incline = !(flags & LEX_NO_INCLINE);
1552     bool need_incline = 0;
1553     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1554         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1555     s = PL_parser->bufptr;
1556     bufend = PL_parser->bufend;
1557     while (1) {
1558         char c = *s;
1559         if (c == '#') {
1560             do {
1561                 c = *++s;
1562             } while (!(c == '\n' || (c == 0 && s == bufend)));
1563         } else if (c == '\n') {
1564             s++;
1565             if (can_incline) {
1566                 PL_parser->linestart = s;
1567                 if (s == bufend)
1568                     need_incline = 1;
1569                 else
1570                     incline(s, bufend);
1571             }
1572         } else if (isSPACE(c)) {
1573             s++;
1574         } else if (c == 0 && s == bufend) {
1575             bool got_more;
1576             line_t l;
1577             if (flags & LEX_NO_NEXT_CHUNK)
1578                 break;
1579             PL_parser->bufptr = s;
1580             l = CopLINE(PL_curcop);
1581             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1582             got_more = lex_next_chunk(flags);
1583             CopLINE_set(PL_curcop, l);
1584             s = PL_parser->bufptr;
1585             bufend = PL_parser->bufend;
1586             if (!got_more)
1587                 break;
1588             if (can_incline && need_incline && PL_parser->rsfp) {
1589                 incline(s, bufend);
1590                 need_incline = 0;
1591             }
1592         } else if (!c) {
1593             s++;
1594         } else {
1595             break;
1596         }
1597     }
1598     PL_parser->bufptr = s;
1599 }
1600
1601 /*
1602
1603 =for apidoc validate_proto
1604
1605 This function performs syntax checking on a prototype, C<proto>.
1606 If C<warn> is true, any illegal characters or mismatched brackets
1607 will trigger illegalproto warnings, declaring that they were
1608 detected in the prototype for C<name>.
1609
1610 The return value is C<true> if this is a valid prototype, and
1611 C<false> if it is not, regardless of whether C<warn> was C<true> or
1612 C<false>.
1613
1614 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1615
1616 =cut
1617
1618  */
1619
1620 bool
1621 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn, bool curstash)
1622 {
1623     STRLEN len, origlen;
1624     char *p;
1625     bool bad_proto = FALSE;
1626     bool in_brackets = FALSE;
1627     bool after_slash = FALSE;
1628     char greedy_proto = ' ';
1629     bool proto_after_greedy_proto = FALSE;
1630     bool must_be_last = FALSE;
1631     bool underscore = FALSE;
1632     bool bad_proto_after_underscore = FALSE;
1633
1634     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1635
1636     if (!proto)
1637         return TRUE;
1638
1639     p = SvPV(proto, len);
1640     origlen = len;
1641     for (; len--; p++) {
1642         if (!isSPACE(*p)) {
1643             if (must_be_last)
1644                 proto_after_greedy_proto = TRUE;
1645             if (underscore) {
1646                 if (!strchr(";@%", *p))
1647                     bad_proto_after_underscore = TRUE;
1648                 underscore = FALSE;
1649             }
1650             if (!strchr("$@%*;[]&\\_+", *p) || *p == '\0') {
1651                 bad_proto = TRUE;
1652             }
1653             else {
1654                 if (*p == '[')
1655                     in_brackets = TRUE;
1656                 else if (*p == ']')
1657                     in_brackets = FALSE;
1658                 else if ((*p == '@' || *p == '%')
1659                          && !after_slash
1660                          && !in_brackets )
1661                 {
1662                     must_be_last = TRUE;
1663                     greedy_proto = *p;
1664                 }
1665                 else if (*p == '_')
1666                     underscore = TRUE;
1667             }
1668             if (*p == '\\')
1669                 after_slash = TRUE;
1670             else
1671                 after_slash = FALSE;
1672         }
1673     }
1674
1675     if (warn) {
1676         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1677         p -= origlen;
1678         p = SvUTF8(proto)
1679             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1680                              origlen, UNI_DISPLAY_ISPRINT)
1681             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1682
1683         if (curstash && !memchr(SvPVX(name), ':', SvCUR(name))) {
1684             SV *name2 = sv_2mortal(newSVsv(PL_curstname));
1685             sv_catpvs(name2, "::");
1686             sv_catsv(name2, (SV *)name);
1687             name = name2;
1688         }
1689
1690         if (proto_after_greedy_proto)
1691             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1692                         "Prototype after '%c' for %" SVf " : %s",
1693                         greedy_proto, SVfARG(name), p);
1694         if (in_brackets)
1695             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1696                         "Missing ']' in prototype for %" SVf " : %s",
1697                         SVfARG(name), p);
1698         if (bad_proto)
1699             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1700                         "Illegal character in prototype for %" SVf " : %s",
1701                         SVfARG(name), p);
1702         if (bad_proto_after_underscore)
1703             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1704                         "Illegal character after '_' in prototype for %" SVf " : %s",
1705                         SVfARG(name), p);
1706     }
1707
1708     return (! (proto_after_greedy_proto || bad_proto) );
1709 }
1710
1711 /*
1712  * S_incline
1713  * This subroutine has nothing to do with tilting, whether at windmills
1714  * or pinball tables.  Its name is short for "increment line".  It
1715  * increments the current line number in CopLINE(PL_curcop) and checks
1716  * to see whether the line starts with a comment of the form
1717  *    # line 500 "foo.pm"
1718  * If so, it sets the current line number and file to the values in the comment.
1719  */
1720
1721 STATIC void
1722 S_incline(pTHX_ const char *s, const char *end)
1723 {
1724     const char *t;
1725     const char *n;
1726     const char *e;
1727     line_t line_num;
1728     UV uv;
1729
1730     PERL_ARGS_ASSERT_INCLINE;
1731
1732     assert(end >= s);
1733
1734     COPLINE_INC_WITH_HERELINES;
1735     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1736      && s+1 == PL_bufend && *s == ';') {
1737         /* fake newline in string eval */
1738         CopLINE_dec(PL_curcop);
1739         return;
1740     }
1741     if (*s++ != '#')
1742         return;
1743     while (SPACE_OR_TAB(*s))
1744         s++;
1745     if (memBEGINs(s, (STRLEN) (end - s), "line"))
1746         s += sizeof("line") - 1;
1747     else
1748         return;
1749     if (SPACE_OR_TAB(*s))
1750         s++;
1751     else
1752         return;
1753     while (SPACE_OR_TAB(*s))
1754         s++;
1755     if (!isDIGIT(*s))
1756         return;
1757
1758     n = s;
1759     while (isDIGIT(*s))
1760         s++;
1761     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1762         return;
1763     while (SPACE_OR_TAB(*s))
1764         s++;
1765     if (*s == '"' && (t = (char *) memchr(s+1, '"', end - s))) {
1766         s++;
1767         e = t + 1;
1768     }
1769     else {
1770         t = s;
1771         while (*t && !isSPACE(*t))
1772             t++;
1773         e = t;
1774     }
1775     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1776         e++;
1777     if (*e != '\n' && *e != '\0')
1778         return;         /* false alarm */
1779
1780     if (!grok_atoUV(n, &uv, &e))
1781         return;
1782     line_num = ((line_t)uv) - 1;
1783
1784     if (t - s > 0) {
1785         const STRLEN len = t - s;
1786
1787         if (!PL_rsfp && !PL_parser->filtered) {
1788             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1789              * to *{"::_<newfilename"} */
1790             /* However, the long form of evals is only turned on by the
1791                debugger - usually they're "(eval %lu)" */
1792             GV * const cfgv = CopFILEGV(PL_curcop);
1793             if (cfgv) {
1794                 char smallbuf[128];
1795                 STRLEN tmplen2 = len;
1796                 char *tmpbuf2;
1797                 GV *gv2;
1798
1799                 if (tmplen2 + 2 <= sizeof smallbuf)
1800                     tmpbuf2 = smallbuf;
1801                 else
1802                     Newx(tmpbuf2, tmplen2 + 2, char);
1803
1804                 tmpbuf2[0] = '_';
1805                 tmpbuf2[1] = '<';
1806
1807                 memcpy(tmpbuf2 + 2, s, tmplen2);
1808                 tmplen2 += 2;
1809
1810                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1811                 if (!isGV(gv2)) {
1812                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1813                     /* adjust ${"::_<newfilename"} to store the new file name */
1814                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1815                     /* The line number may differ. If that is the case,
1816                        alias the saved lines that are in the array.
1817                        Otherwise alias the whole array. */
1818                     if (CopLINE(PL_curcop) == line_num) {
1819                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1820                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1821                     }
1822                     else if (GvAV(cfgv)) {
1823                         AV * const av = GvAV(cfgv);
1824                         const line_t start = CopLINE(PL_curcop)+1;
1825                         SSize_t items = AvFILLp(av) - start;
1826                         if (items > 0) {
1827                             AV * const av2 = GvAVn(gv2);
1828                             SV **svp = AvARRAY(av) + start;
1829                             Size_t l = line_num+1;
1830                             while (items-- && l < SSize_t_MAX && l == (line_t)l)
1831                                 av_store(av2, (SSize_t)l++, SvREFCNT_inc(*svp++));
1832                         }
1833                     }
1834                 }
1835
1836                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1837             }
1838         }
1839         CopFILE_free(PL_curcop);
1840         CopFILE_setn(PL_curcop, s, len);
1841     }
1842     CopLINE_set(PL_curcop, line_num);
1843 }
1844
1845 STATIC void
1846 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1847 {
1848     AV *av = CopFILEAVx(PL_curcop);
1849     if (av) {
1850         SV * sv;
1851         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1852         else {
1853             sv = *av_fetch(av, 0, 1);
1854             SvUPGRADE(sv, SVt_PVMG);
1855         }
1856         if (!SvPOK(sv)) SvPVCLEAR(sv);
1857         if (orig_sv)
1858             sv_catsv(sv, orig_sv);
1859         else
1860             sv_catpvn(sv, buf, len);
1861         if (!SvIOK(sv)) {
1862             (void)SvIOK_on(sv);
1863             SvIV_set(sv, 0);
1864         }
1865         if (PL_parser->preambling == NOLINE)
1866             av_store(av, CopLINE(PL_curcop), sv);
1867     }
1868 }
1869
1870 /*
1871  * skipspace
1872  * Called to gobble the appropriate amount and type of whitespace.
1873  * Skips comments as well.
1874  * Returns the next character after the whitespace that is skipped.
1875  *
1876  * peekspace
1877  * Same thing, but look ahead without incrementing line numbers or
1878  * adjusting PL_linestart.
1879  */
1880
1881 #define skipspace(s) skipspace_flags(s, 0)
1882 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1883
1884 char *
1885 Perl_skipspace_flags(pTHX_ char *s, U32 flags)
1886 {
1887     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1888     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1889         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1890             s++;
1891     } else {
1892         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1893         PL_bufptr = s;
1894         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1895                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1896                     LEX_NO_NEXT_CHUNK : 0));
1897         s = PL_bufptr;
1898         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1899         if (PL_linestart > PL_bufptr)
1900             PL_bufptr = PL_linestart;
1901         return s;
1902     }
1903     return s;
1904 }
1905
1906 /*
1907  * S_check_uni
1908  * Check the unary operators to ensure there's no ambiguity in how they're
1909  * used.  An ambiguous piece of code would be:
1910  *     rand + 5
1911  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1912  * the +5 is its argument.
1913  */
1914
1915 STATIC void
1916 S_check_uni(pTHX)
1917 {
1918     const char *s;
1919
1920     if (PL_oldoldbufptr != PL_last_uni)
1921         return;
1922     while (isSPACE(*PL_last_uni))
1923         PL_last_uni++;
1924     s = PL_last_uni;
1925     while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF) || *s == '-')
1926         s += UTF ? UTF8SKIP(s) : 1;
1927     if (s < PL_bufptr && memchr(s, '(', PL_bufptr - s))
1928         return;
1929
1930     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1931                      "Warning: Use of \"%" UTF8f "\" without parentheses is ambiguous",
1932                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1933 }
1934
1935 /*
1936  * LOP : macro to build a list operator.  Its behaviour has been replaced
1937  * with a subroutine, S_lop() for which LOP is just another name.
1938  */
1939
1940 #define LOP(f,x) return lop(f,x,s)
1941
1942 /*
1943  * S_lop
1944  * Build a list operator (or something that might be one).  The rules:
1945  *  - if we have a next token, then it's a list operator (no parens) for
1946  *    which the next token has already been parsed; e.g.,
1947  *       sort foo @args
1948  *       sort foo (@args)
1949  *  - if the next thing is an opening paren, then it's a function
1950  *  - else it's a list operator
1951  */
1952
1953 STATIC I32
1954 S_lop(pTHX_ I32 f, U8 x, char *s)
1955 {
1956     PERL_ARGS_ASSERT_LOP;
1957
1958     pl_yylval.ival = f;
1959     CLINE;
1960     PL_bufptr = s;
1961     PL_last_lop = PL_oldbufptr;
1962     PL_last_lop_op = (OPCODE)f;
1963     if (PL_nexttoke)
1964         goto lstop;
1965     PL_expect = x;
1966     if (*s == '(')
1967         return REPORT(FUNC);
1968     s = skipspace(s);
1969     if (*s == '(')
1970         return REPORT(FUNC);
1971     else {
1972         lstop:
1973         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1974             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1975         return REPORT(LSTOP);
1976     }
1977 }
1978
1979 /*
1980  * S_force_next
1981  * When the lexer realizes it knows the next token (for instance,
1982  * it is reordering tokens for the parser) then it can call S_force_next
1983  * to know what token to return the next time the lexer is called.  Caller
1984  * will need to set PL_nextval[] and possibly PL_expect to ensure
1985  * the lexer handles the token correctly.
1986  */
1987
1988 STATIC void
1989 S_force_next(pTHX_ I32 type)
1990 {
1991 #ifdef DEBUGGING
1992     if (DEBUG_T_TEST) {
1993         PerlIO_printf(Perl_debug_log, "### forced token:\n");
1994         tokereport(type, &NEXTVAL_NEXTTOKE);
1995     }
1996 #endif
1997     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
1998     PL_nexttype[PL_nexttoke] = type;
1999     PL_nexttoke++;
2000 }
2001
2002 /*
2003  * S_postderef
2004  *
2005  * This subroutine handles postfix deref syntax after the arrow has already
2006  * been emitted.  @* $* etc. are emitted as two separate tokens right here.
2007  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
2008  * only the first, leaving yylex to find the next.
2009  */
2010
2011 static int
2012 S_postderef(pTHX_ int const funny, char const next)
2013 {
2014     assert(funny == DOLSHARP || strchr("$@%&*", funny));
2015     if (next == '*') {
2016         PL_expect = XOPERATOR;
2017         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
2018             assert('@' == funny || '$' == funny || DOLSHARP == funny);
2019             PL_lex_state = LEX_INTERPEND;
2020             if ('@' == funny)
2021                 force_next(POSTJOIN);
2022         }
2023         force_next(next);
2024         PL_bufptr+=2;
2025     }
2026     else {
2027         if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
2028          && !PL_lex_brackets)
2029             PL_lex_dojoin = 2;
2030         PL_expect = XOPERATOR;
2031         PL_bufptr++;
2032     }
2033     return funny;
2034 }
2035
2036 void
2037 Perl_yyunlex(pTHX)
2038 {
2039     int yyc = PL_parser->yychar;
2040     if (yyc != YYEMPTY) {
2041         if (yyc) {
2042             NEXTVAL_NEXTTOKE = PL_parser->yylval;
2043             if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
2044                 PL_lex_allbrackets--;
2045                 PL_lex_brackets--;
2046                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
2047             } else if (yyc == '('/*)*/) {
2048                 PL_lex_allbrackets--;
2049                 yyc |= (2<<24);
2050             }
2051             force_next(yyc);
2052         }
2053         PL_parser->yychar = YYEMPTY;
2054     }
2055 }
2056
2057 STATIC SV *
2058 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
2059 {
2060     SV * const sv = newSVpvn_utf8(start, len,
2061                     ! IN_BYTES
2062                   &&  UTF
2063                   &&  len != 0
2064                   &&  is_utf8_non_invariant_string((const U8*)start, len));
2065     return sv;
2066 }
2067
2068 /*
2069  * S_force_word
2070  * When the lexer knows the next thing is a word (for instance, it has
2071  * just seen -> and it knows that the next char is a word char, then
2072  * it calls S_force_word to stick the next word into the PL_nexttoke/val
2073  * lookahead.
2074  *
2075  * Arguments:
2076  *   char *start : buffer position (must be within PL_linestr)
2077  *   int token   : PL_next* will be this type of bare word
2078  *                 (e.g., METHOD,BAREWORD)
2079  *   int check_keyword : if true, Perl checks to make sure the word isn't
2080  *       a keyword (do this if the word is a label, e.g. goto FOO)
2081  *   int allow_pack : if true, : characters will also be allowed (require,
2082  *       use, etc. do this)
2083  */
2084
2085 STATIC char *
2086 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2087 {
2088     char *s;
2089     STRLEN len;
2090
2091     PERL_ARGS_ASSERT_FORCE_WORD;
2092
2093     start = skipspace(start);
2094     s = start;
2095     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
2096         || (allow_pack && *s == ':' && s[1] == ':') )
2097     {
2098         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2099         if (check_keyword) {
2100           char *s2 = PL_tokenbuf;
2101           STRLEN len2 = len;
2102           if (allow_pack && memBEGINPs(s2, len, "CORE::")) {
2103             s2 += sizeof("CORE::") - 1;
2104             len2 -= sizeof("CORE::") - 1;
2105           }
2106           if (keyword(s2, len2, 0))
2107             return start;
2108         }
2109         if (token == METHOD) {
2110             s = skipspace(s);
2111             if (*s == '(')
2112                 PL_expect = XTERM;
2113             else {
2114                 PL_expect = XOPERATOR;
2115             }
2116         }
2117         NEXTVAL_NEXTTOKE.opval
2118             = newSVOP(OP_CONST,0,
2119                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2120         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2121         force_next(token);
2122     }
2123     return s;
2124 }
2125
2126 /*
2127  * S_force_ident
2128  * Called when the lexer wants $foo *foo &foo etc, but the program
2129  * text only contains the "foo" portion.  The first argument is a pointer
2130  * to the "foo", and the second argument is the type symbol to prefix.
2131  * Forces the next token to be a "BAREWORD".
2132  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2133  */
2134
2135 STATIC void
2136 S_force_ident(pTHX_ const char *s, int kind)
2137 {
2138     PERL_ARGS_ASSERT_FORCE_IDENT;
2139
2140     if (s[0]) {
2141         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2142         OP* const o = newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2143                                                                 UTF ? SVf_UTF8 : 0));
2144         NEXTVAL_NEXTTOKE.opval = o;
2145         force_next(BAREWORD);
2146         if (kind) {
2147             o->op_private = OPpCONST_ENTERED;
2148             /* XXX see note in pp_entereval() for why we forgo typo
2149                warnings if the symbol must be introduced in an eval.
2150                GSAR 96-10-12 */
2151             gv_fetchpvn_flags(s, len,
2152                               (PL_in_eval ? GV_ADDMULTI
2153                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2154                               kind == '$' ? SVt_PV :
2155                               kind == '@' ? SVt_PVAV :
2156                               kind == '%' ? SVt_PVHV :
2157                               SVt_PVGV
2158                               );
2159         }
2160     }
2161 }
2162
2163 static void
2164 S_force_ident_maybe_lex(pTHX_ char pit)
2165 {
2166     NEXTVAL_NEXTTOKE.ival = pit;
2167     force_next('p');
2168 }
2169
2170 NV
2171 Perl_str_to_version(pTHX_ SV *sv)
2172 {
2173     NV retval = 0.0;
2174     NV nshift = 1.0;
2175     STRLEN len;
2176     const char *start = SvPV_const(sv,len);
2177     const char * const end = start + len;
2178     const bool utf = cBOOL(SvUTF8(sv));
2179
2180     PERL_ARGS_ASSERT_STR_TO_VERSION;
2181
2182     while (start < end) {
2183         STRLEN skip;
2184         UV n;
2185         if (utf)
2186             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2187         else {
2188             n = *(U8*)start;
2189             skip = 1;
2190         }
2191         retval += ((NV)n)/nshift;
2192         start += skip;
2193         nshift *= 1000;
2194     }
2195     return retval;
2196 }
2197
2198 /*
2199  * S_force_version
2200  * Forces the next token to be a version number.
2201  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2202  * and if "guessing" is TRUE, then no new token is created (and the caller
2203  * must use an alternative parsing method).
2204  */
2205
2206 STATIC char *
2207 S_force_version(pTHX_ char *s, int guessing)
2208 {
2209     OP *version = NULL;
2210     char *d;
2211
2212     PERL_ARGS_ASSERT_FORCE_VERSION;
2213
2214     s = skipspace(s);
2215
2216     d = s;
2217     if (*d == 'v')
2218         d++;
2219     if (isDIGIT(*d)) {
2220         while (isDIGIT(*d) || *d == '_' || *d == '.')
2221             d++;
2222         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2223             SV *ver;
2224             s = scan_num(s, &pl_yylval);
2225             version = pl_yylval.opval;
2226             ver = cSVOPx(version)->op_sv;
2227             if (SvPOK(ver) && !SvNIOK(ver)) {
2228                 SvUPGRADE(ver, SVt_PVNV);
2229                 SvNV_set(ver, str_to_version(ver));
2230                 SvNOK_on(ver);          /* hint that it is a version */
2231             }
2232         }
2233         else if (guessing) {
2234             return s;
2235         }
2236     }
2237
2238     /* NOTE: The parser sees the package name and the VERSION swapped */
2239     NEXTVAL_NEXTTOKE.opval = version;
2240     force_next(BAREWORD);
2241
2242     return s;
2243 }
2244
2245 /*
2246  * S_force_strict_version
2247  * Forces the next token to be a version number using strict syntax rules.
2248  */
2249
2250 STATIC char *
2251 S_force_strict_version(pTHX_ char *s)
2252 {
2253     OP *version = NULL;
2254     const char *errstr = NULL;
2255
2256     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2257
2258     while (isSPACE(*s)) /* leading whitespace */
2259         s++;
2260
2261     if (is_STRICT_VERSION(s,&errstr)) {
2262         SV *ver = newSV(0);
2263         s = (char *)scan_version(s, ver, 0);
2264         version = newSVOP(OP_CONST, 0, ver);
2265     }
2266     else if ((*s != ';' && *s != '{' && *s != '}' )
2267              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2268     {
2269         PL_bufptr = s;
2270         if (errstr)
2271             yyerror(errstr); /* version required */
2272         return s;
2273     }
2274
2275     /* NOTE: The parser sees the package name and the VERSION swapped */
2276     NEXTVAL_NEXTTOKE.opval = version;
2277     force_next(BAREWORD);
2278
2279     return s;
2280 }
2281
2282 /*
2283  * S_tokeq
2284  * Turns any \\ into \ in a quoted string passed in in 'sv', returning 'sv',
2285  * modified as necessary.  However, if HINT_NEW_STRING is on, 'sv' is
2286  * unchanged, and a new SV containing the modified input is returned.
2287  */
2288
2289 STATIC SV *
2290 S_tokeq(pTHX_ SV *sv)
2291 {
2292     char *s;
2293     char *send;
2294     char *d;
2295     SV *pv = sv;
2296
2297     PERL_ARGS_ASSERT_TOKEQ;
2298
2299     assert (SvPOK(sv));
2300     assert (SvLEN(sv));
2301     assert (!SvIsCOW(sv));
2302     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2303         goto finish;
2304     s = SvPVX(sv);
2305     send = SvEND(sv);
2306     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2307     while (s < send && !(*s == '\\' && s[1] == '\\'))
2308         s++;
2309     if (s == send)
2310         goto finish;
2311     d = s;
2312     if ( PL_hints & HINT_NEW_STRING ) {
2313         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2314                             SVs_TEMP | SvUTF8(sv));
2315     }
2316     while (s < send) {
2317         if (*s == '\\') {
2318             if (s + 1 < send && (s[1] == '\\'))
2319                 s++;            /* all that, just for this */
2320         }
2321         *d++ = *s++;
2322     }
2323     *d = '\0';
2324     SvCUR_set(sv, d - SvPVX_const(sv));
2325   finish:
2326     if ( PL_hints & HINT_NEW_STRING )
2327        return new_constant(NULL, 0, "q", sv, pv, "q", 1, NULL);
2328     return sv;
2329 }
2330
2331 /*
2332  * Now come three functions related to double-quote context,
2333  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2334  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2335  * interact with PL_lex_state, and create fake ( ... ) argument lists
2336  * to handle functions and concatenation.
2337  * For example,
2338  *   "foo\lbar"
2339  * is tokenised as
2340  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2341  */
2342
2343 /*
2344  * S_sublex_start
2345  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2346  *
2347  * Pattern matching will set PL_lex_op to the pattern-matching op to
2348  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2349  *
2350  * OP_CONST is easy--just make the new op and return.
2351  *
2352  * Everything else becomes a FUNC.
2353  *
2354  * Sets PL_lex_state to LEX_INTERPPUSH unless ival was OP_NULL or we
2355  * had an OP_CONST.  This just sets us up for a
2356  * call to S_sublex_push().
2357  */
2358
2359 STATIC I32
2360 S_sublex_start(pTHX)
2361 {
2362     const I32 op_type = pl_yylval.ival;
2363
2364     if (op_type == OP_NULL) {
2365         pl_yylval.opval = PL_lex_op;
2366         PL_lex_op = NULL;
2367         return THING;
2368     }
2369     if (op_type == OP_CONST) {
2370         SV *sv = PL_lex_stuff;
2371         PL_lex_stuff = NULL;
2372         sv = tokeq(sv);
2373
2374         if (SvTYPE(sv) == SVt_PVIV) {
2375             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2376             STRLEN len;
2377             const char * const p = SvPV_const(sv, len);
2378             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2379             SvREFCNT_dec(sv);
2380             sv = nsv;
2381         }
2382         pl_yylval.opval = newSVOP(op_type, 0, sv);
2383         return THING;
2384     }
2385
2386     PL_parser->lex_super_state = PL_lex_state;
2387     PL_parser->lex_sub_inwhat = (U16)op_type;
2388     PL_parser->lex_sub_op = PL_lex_op;
2389     PL_parser->sub_no_recover = FALSE;
2390     PL_parser->sub_error_count = PL_error_count;
2391     PL_lex_state = LEX_INTERPPUSH;
2392
2393     PL_expect = XTERM;
2394     if (PL_lex_op) {
2395         pl_yylval.opval = PL_lex_op;
2396         PL_lex_op = NULL;
2397         return PMFUNC;
2398     }
2399     else
2400         return FUNC;
2401 }
2402
2403 /*
2404  * S_sublex_push
2405  * Create a new scope to save the lexing state.  The scope will be
2406  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2407  * to the uc, lc, etc. found before.
2408  * Sets PL_lex_state to LEX_INTERPCONCAT.
2409  */
2410
2411 STATIC I32
2412 S_sublex_push(pTHX)
2413 {
2414     LEXSHARED *shared;
2415     const bool is_heredoc = PL_multi_close == '<';
2416     ENTER;
2417
2418     PL_lex_state = PL_parser->lex_super_state;
2419     SAVEI8(PL_lex_dojoin);
2420     SAVEI32(PL_lex_brackets);
2421     SAVEI32(PL_lex_allbrackets);
2422     SAVEI32(PL_lex_formbrack);
2423     SAVEI8(PL_lex_fakeeof);
2424     SAVEI32(PL_lex_casemods);
2425     SAVEI32(PL_lex_starts);
2426     SAVEI8(PL_lex_state);
2427     SAVESPTR(PL_lex_repl);
2428     SAVEVPTR(PL_lex_inpat);
2429     SAVEI16(PL_lex_inwhat);
2430     if (is_heredoc)
2431     {
2432         SAVECOPLINE(PL_curcop);
2433         SAVEI32(PL_multi_end);
2434         SAVEI32(PL_parser->herelines);
2435         PL_parser->herelines = 0;
2436     }
2437     SAVEIV(PL_multi_close);
2438     SAVEPPTR(PL_bufptr);
2439     SAVEPPTR(PL_bufend);
2440     SAVEPPTR(PL_oldbufptr);
2441     SAVEPPTR(PL_oldoldbufptr);
2442     SAVEPPTR(PL_last_lop);
2443     SAVEPPTR(PL_last_uni);
2444     SAVEPPTR(PL_linestart);
2445     SAVESPTR(PL_linestr);
2446     SAVEGENERICPV(PL_lex_brackstack);
2447     SAVEGENERICPV(PL_lex_casestack);
2448     SAVEGENERICPV(PL_parser->lex_shared);
2449     SAVEBOOL(PL_parser->lex_re_reparsing);
2450     SAVEI32(PL_copline);
2451
2452     /* The here-doc parser needs to be able to peek into outer lexing
2453        scopes to find the body of the here-doc.  So we put PL_linestr and
2454        PL_bufptr into lex_shared, to â€˜share’ those values.
2455      */
2456     PL_parser->lex_shared->ls_linestr = PL_linestr;
2457     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2458
2459     PL_linestr = PL_lex_stuff;
2460     PL_lex_repl = PL_parser->lex_sub_repl;
2461     PL_lex_stuff = NULL;
2462     PL_parser->lex_sub_repl = NULL;
2463
2464     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2465        set for an inner quote-like operator and then an error causes scope-
2466        popping.  We must not have a PL_lex_stuff value left dangling, as
2467        that breaks assumptions elsewhere.  See bug #123617.  */
2468     SAVEGENERICSV(PL_lex_stuff);
2469     SAVEGENERICSV(PL_parser->lex_sub_repl);
2470
2471     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2472         = SvPVX(PL_linestr);
2473     PL_bufend += SvCUR(PL_linestr);
2474     PL_last_lop = PL_last_uni = NULL;
2475     SAVEFREESV(PL_linestr);
2476     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2477
2478     PL_lex_dojoin = FALSE;
2479     PL_lex_brackets = PL_lex_formbrack = 0;
2480     PL_lex_allbrackets = 0;
2481     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2482     Newx(PL_lex_brackstack, 120, char);
2483     Newx(PL_lex_casestack, 12, char);
2484     PL_lex_casemods = 0;
2485     *PL_lex_casestack = '\0';
2486     PL_lex_starts = 0;
2487     PL_lex_state = LEX_INTERPCONCAT;
2488     if (is_heredoc)
2489         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2490     PL_copline = NOLINE;
2491
2492     Newxz(shared, 1, LEXSHARED);
2493     shared->ls_prev = PL_parser->lex_shared;
2494     PL_parser->lex_shared = shared;
2495
2496     PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2497     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2498     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2499         PL_lex_inpat = PL_parser->lex_sub_op;
2500     else
2501         PL_lex_inpat = NULL;
2502
2503     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2504     PL_in_eval &= ~EVAL_RE_REPARSING;
2505
2506     return SUBLEXSTART;
2507 }
2508
2509 /*
2510  * S_sublex_done
2511  * Restores lexer state after a S_sublex_push.
2512  */
2513
2514 STATIC I32
2515 S_sublex_done(pTHX)
2516 {
2517     if (!PL_lex_starts++) {
2518         SV * const sv = newSVpvs("");
2519         if (SvUTF8(PL_linestr))
2520             SvUTF8_on(sv);
2521         PL_expect = XOPERATOR;
2522         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
2523         return THING;
2524     }
2525
2526     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2527         PL_lex_state = LEX_INTERPCASEMOD;
2528         return yylex();
2529     }
2530
2531     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2532     assert(PL_lex_inwhat != OP_TRANSR);
2533     if (PL_lex_repl) {
2534         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2535         PL_linestr = PL_lex_repl;
2536         PL_lex_inpat = 0;
2537         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2538         PL_bufend += SvCUR(PL_linestr);
2539         PL_last_lop = PL_last_uni = NULL;
2540         PL_lex_dojoin = FALSE;
2541         PL_lex_brackets = 0;
2542         PL_lex_allbrackets = 0;
2543         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2544         PL_lex_casemods = 0;
2545         *PL_lex_casestack = '\0';
2546         PL_lex_starts = 0;
2547         if (SvEVALED(PL_lex_repl)) {
2548             PL_lex_state = LEX_INTERPNORMAL;
2549             PL_lex_starts++;
2550             /*  we don't clear PL_lex_repl here, so that we can check later
2551                 whether this is an evalled subst; that means we rely on the
2552                 logic to ensure sublex_done() is called again only via the
2553                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2554         }
2555         else {
2556             PL_lex_state = LEX_INTERPCONCAT;
2557             PL_lex_repl = NULL;
2558         }
2559         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2560             CopLINE(PL_curcop) +=
2561                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2562                  + PL_parser->herelines;
2563             PL_parser->herelines = 0;
2564         }
2565         return '/';
2566     }
2567     else {
2568         const line_t l = CopLINE(PL_curcop);
2569         LEAVE;
2570         if (PL_parser->sub_error_count != PL_error_count) {
2571             if (PL_parser->sub_no_recover) {
2572                 yyquit();
2573                 NOT_REACHED;
2574             }
2575         }
2576         if (PL_multi_close == '<')
2577             PL_parser->herelines += l - PL_multi_end;
2578         PL_bufend = SvPVX(PL_linestr);
2579         PL_bufend += SvCUR(PL_linestr);
2580         PL_expect = XOPERATOR;
2581         return SUBLEXEND;
2582     }
2583 }
2584
2585 STATIC SV*
2586 S_get_and_check_backslash_N_name_wrapper(pTHX_ const char* s, const char* const e)
2587 {
2588     /* This justs wraps get_and_check_backslash_N_name() to output any error
2589      * message it returns. */
2590
2591     const char * error_msg = NULL;
2592     SV * result;
2593
2594     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME_WRAPPER;
2595
2596     /* charnames doesn't work well if there have been errors found */
2597     if (PL_error_count > 0) {
2598         return NULL;
2599     }
2600
2601     result = get_and_check_backslash_N_name(s, e, cBOOL(UTF), &error_msg);
2602
2603     if (error_msg) {
2604         yyerror_pv(error_msg, UTF ? SVf_UTF8 : 0);
2605     }
2606
2607     return result;
2608 }
2609
2610 SV*
2611 Perl_get_and_check_backslash_N_name(pTHX_ const char* s,
2612                                           const char* const e,
2613                                           const bool is_utf8,
2614                                           const char ** error_msg)
2615 {
2616     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2617      * interior, hence to the "}".  Finds what the name resolves to, returning
2618      * an SV* containing it; NULL if no valid one found.
2619      *
2620      * 'is_utf8' is TRUE if we know we want the result to be UTF-8 even if it
2621      * doesn't have to be. */
2622
2623     SV* res;
2624     HV * table;
2625     SV **cvp;
2626     SV *cv;
2627     SV *rv;
2628     HV *stash;
2629     const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2630     dVAR;
2631
2632     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2633
2634     assert(e >= s);
2635     assert(s > (char *) 3);
2636
2637     res = newSVpvn_flags(s, e - s, (is_utf8) ? SVf_UTF8 : 0);
2638
2639     if (!SvCUR(res)) {
2640         SvREFCNT_dec_NN(res);
2641         /* diag_listed_as: Unknown charname '%s' */
2642         *error_msg = Perl_form(aTHX_ "Unknown charname ''");
2643         return NULL;
2644     }
2645
2646     res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2647                         /* include the <}> */
2648                         e - backslash_ptr + 1, error_msg);
2649     if (! SvPOK(res)) {
2650         SvREFCNT_dec_NN(res);
2651         return NULL;
2652     }
2653
2654     /* See if the charnames handler is the Perl core's, and if so, we can skip
2655      * the validation needed for a user-supplied one, as Perl's does its own
2656      * validation. */
2657     table = GvHV(PL_hintgv);             /* ^H */
2658     cvp = hv_fetchs(table, "charnames", FALSE);
2659     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2660         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2661     {
2662         const char * const name = HvNAME(stash);
2663          if (memEQs(name, HvNAMELEN(stash), "_charnames")) {
2664            return res;
2665        }
2666     }
2667
2668     /* Here, it isn't Perl's charname handler.  We can't rely on a
2669      * user-supplied handler to validate the input name.  For non-ut8 input,
2670      * look to see that the first character is legal.  Then loop through the
2671      * rest checking that each is a continuation */
2672
2673     /* This code makes the reasonable assumption that the only Latin1-range
2674      * characters that begin a character name alias are alphabetic, otherwise
2675      * would have to create a isCHARNAME_BEGIN macro */
2676
2677     if (! is_utf8) {
2678         if (! isALPHAU(*s)) {
2679             goto bad_charname;
2680         }
2681         s++;
2682         while (s < e) {
2683             if (! isCHARNAME_CONT(*s)) {
2684                 goto bad_charname;
2685             }
2686             if (*s == ' ' && *(s-1) == ' ') {
2687                 goto multi_spaces;
2688             }
2689             s++;
2690         }
2691     }
2692     else {
2693         /* Similarly for utf8.  For invariants can check directly; for other
2694          * Latin1, can calculate their code point and check; otherwise  use an
2695          * inversion list */
2696         if (UTF8_IS_INVARIANT(*s)) {
2697             if (! isALPHAU(*s)) {
2698                 goto bad_charname;
2699             }
2700             s++;
2701         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2702             if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2703                 goto bad_charname;
2704             }
2705             s += 2;
2706         }
2707         else {
2708             if (! _invlist_contains_cp(PL_utf8_charname_begin,
2709                                        utf8_to_uvchr_buf((U8 *) s,
2710                                                          (U8 *) e,
2711                                                          NULL)))
2712             {
2713                 goto bad_charname;
2714             }
2715             s += UTF8SKIP(s);
2716         }
2717
2718         while (s < e) {
2719             if (UTF8_IS_INVARIANT(*s)) {
2720                 if (! isCHARNAME_CONT(*s)) {
2721                     goto bad_charname;
2722                 }
2723                 if (*s == ' ' && *(s-1) == ' ') {
2724                     goto multi_spaces;
2725                 }
2726                 s++;
2727             }
2728             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2729                 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2730                 {
2731                     goto bad_charname;
2732                 }
2733                 s += 2;
2734             }
2735             else {
2736                 if (! _invlist_contains_cp(PL_utf8_charname_continue,
2737                                            utf8_to_uvchr_buf((U8 *) s,
2738                                                              (U8 *) e,
2739                                                              NULL)))
2740                 {
2741                     goto bad_charname;
2742                 }
2743                 s += UTF8SKIP(s);
2744             }
2745         }
2746     }
2747     if (*(s-1) == ' ') {
2748         /* diag_listed_as: charnames alias definitions may not contain
2749                            trailing white-space; marked by <-- HERE in %s
2750          */
2751         *error_msg = Perl_form(aTHX_
2752             "charnames alias definitions may not contain trailing "
2753             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2754             (int)(s - backslash_ptr + 1), backslash_ptr,
2755             (int)(e - s + 1), s + 1);
2756         return NULL;
2757     }
2758
2759     if (SvUTF8(res)) { /* Don't accept malformed charname value */
2760         const U8* first_bad_char_loc;
2761         STRLEN len;
2762         const char* const str = SvPV_const(res, len);
2763         if (UNLIKELY(! is_utf8_string_loc((U8 *) str, len,
2764                                           &first_bad_char_loc)))
2765         {
2766             _force_out_malformed_utf8_message(first_bad_char_loc,
2767                                               (U8 *) PL_parser->bufend,
2768                                               0,
2769                                               0 /* 0 means don't die */ );
2770             /* diag_listed_as: Malformed UTF-8 returned by \N{%s}
2771                                immediately after '%s' */
2772             *error_msg = Perl_form(aTHX_
2773                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2774                  (int) (e - backslash_ptr + 1), backslash_ptr,
2775                  (int) ((char *) first_bad_char_loc - str), str);
2776             return NULL;
2777         }
2778     }
2779
2780     return res;
2781
2782   bad_charname: {
2783
2784         /* The final %.*s makes sure that should the trailing NUL be missing
2785          * that this print won't run off the end of the string */
2786         /* diag_listed_as: Invalid character in \N{...}; marked by <-- HERE
2787                            in \N{%s} */
2788         *error_msg = Perl_form(aTHX_
2789             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2790             (int)(s - backslash_ptr + 1), backslash_ptr,
2791             (int)(e - s + 1), s + 1);
2792         return NULL;
2793     }
2794
2795   multi_spaces:
2796         /* diag_listed_as: charnames alias definitions may not contain a
2797                            sequence of multiple spaces; marked by <-- HERE
2798                            in %s */
2799         *error_msg = Perl_form(aTHX_
2800             "charnames alias definitions may not contain a sequence of "
2801             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2802             (int)(s - backslash_ptr + 1), backslash_ptr,
2803             (int)(e - s + 1), s + 1);
2804         return NULL;
2805 }
2806
2807 /*
2808   scan_const
2809
2810   Extracts the next constant part of a pattern, double-quoted string,
2811   or transliteration.  This is terrifying code.
2812
2813   For example, in parsing the double-quoted string "ab\x63$d", it would
2814   stop at the '$' and return an OP_CONST containing 'abc'.
2815
2816   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2817   processing a pattern (PL_lex_inpat is true), a transliteration
2818   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2819
2820   Returns a pointer to the character scanned up to. If this is
2821   advanced from the start pointer supplied (i.e. if anything was
2822   successfully parsed), will leave an OP_CONST for the substring scanned
2823   in pl_yylval. Caller must intuit reason for not parsing further
2824   by looking at the next characters herself.
2825
2826   In patterns:
2827     expand:
2828       \N{FOO}  => \N{U+hex_for_character_FOO}
2829       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2830
2831     pass through:
2832         all other \-char, including \N and \N{ apart from \N{ABC}
2833
2834     stops on:
2835         @ and $ where it appears to be a var, but not for $ as tail anchor
2836         \l \L \u \U \Q \E
2837         (?{  or  (??{
2838
2839   In transliterations:
2840     characters are VERY literal, except for - not at the start or end
2841     of the string, which indicates a range.  However some backslash sequences
2842     are recognized: \r, \n, and the like
2843                     \007 \o{}, \x{}, \N{}
2844     If all elements in the transliteration are below 256,
2845     scan_const expands the range to the full set of intermediate
2846     characters. If the range is in utf8, the hyphen is replaced with
2847     a certain range mark which will be handled by pmtrans() in op.c.
2848
2849   In double-quoted strings:
2850     backslashes:
2851       all those recognized in transliterations
2852       deprecated backrefs: \1 (in substitution replacements)
2853       case and quoting: \U \Q \E
2854     stops on @ and $
2855
2856   scan_const does *not* construct ops to handle interpolated strings.
2857   It stops processing as soon as it finds an embedded $ or @ variable
2858   and leaves it to the caller to work out what's going on.
2859
2860   embedded arrays (whether in pattern or not) could be:
2861       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2862
2863   $ in double-quoted strings must be the symbol of an embedded scalar.
2864
2865   $ in pattern could be $foo or could be tail anchor.  Assumption:
2866   it's a tail anchor if $ is the last thing in the string, or if it's
2867   followed by one of "()| \r\n\t"
2868
2869   \1 (backreferences) are turned into $1 in substitutions
2870
2871   The structure of the code is
2872       while (there's a character to process) {
2873           handle transliteration ranges
2874           skip regexp comments /(?#comment)/ and codes /(?{code})/
2875           skip #-initiated comments in //x patterns
2876           check for embedded arrays
2877           check for embedded scalars
2878           if (backslash) {
2879               deprecate \1 in substitution replacements
2880               handle string-changing backslashes \l \U \Q \E, etc.
2881               switch (what was escaped) {
2882                   handle \- in a transliteration (becomes a literal -)
2883                   if a pattern and not \N{, go treat as regular character
2884                   handle \132 (octal characters)
2885                   handle \x15 and \x{1234} (hex characters)
2886                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2887                   handle \cV (control characters)
2888                   handle printf-style backslashes (\f, \r, \n, etc)
2889               } (end switch)
2890               continue
2891           } (end if backslash)
2892           handle regular character
2893     } (end while character to read)
2894
2895 */
2896
2897 STATIC char *
2898 S_scan_const(pTHX_ char *start)
2899 {
2900     char *send = PL_bufend;             /* end of the constant */
2901     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
2902                                            on sizing. */
2903     char *s = start;                    /* start of the constant */
2904     char *d = SvPVX(sv);                /* destination for copies */
2905     bool dorange = FALSE;               /* are we in a translit range? */
2906     bool didrange = FALSE;              /* did we just finish a range? */
2907     bool in_charclass = FALSE;          /* within /[...]/ */
2908     bool s_is_utf8 = cBOOL(UTF);        /* Is the source string assumed to be
2909                                            UTF8?  But, this can show as true
2910                                            when the source isn't utf8, as for
2911                                            example when it is entirely composed
2912                                            of hex constants */
2913     bool d_is_utf8 = FALSE;             /* Output constant is UTF8 */
2914     STRLEN utf8_variant_count = 0;      /* When not in UTF-8, this counts the
2915                                            number of characters found so far
2916                                            that will expand (into 2 bytes)
2917                                            should we have to convert to
2918                                            UTF-8) */
2919     SV *res;                            /* result from charnames */
2920     STRLEN offset_to_max = 0;   /* The offset in the output to where the range
2921                                    high-end character is temporarily placed */
2922
2923     /* Does something require special handling in tr/// ?  This avoids extra
2924      * work in a less likely case.  As such, khw didn't feel it was worth
2925      * adding any branches to the more mainline code to handle this, which
2926      * means that this doesn't get set in some circumstances when things like
2927      * \x{100} get expanded out.  As a result there needs to be extra testing
2928      * done in the tr code */
2929     bool has_above_latin1 = FALSE;
2930
2931     /* Note on sizing:  The scanned constant is placed into sv, which is
2932      * initialized by newSV() assuming one byte of output for every byte of
2933      * input.  This routine expects newSV() to allocate an extra byte for a
2934      * trailing NUL, which this routine will append if it gets to the end of
2935      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2936      * CAPITAL LETTER A}), or more output than input if the constant ends up
2937      * recoded to utf8, but each time a construct is found that might increase
2938      * the needed size, SvGROW() is called.  Its size parameter each time is
2939      * based on the best guess estimate at the time, namely the length used so
2940      * far, plus the length the current construct will occupy, plus room for
2941      * the trailing NUL, plus one byte for every input byte still unscanned */
2942
2943     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2944                        before set */
2945 #ifdef EBCDIC
2946     int backslash_N = 0;            /* ? was the character from \N{} */
2947     int non_portable_endpoint = 0;  /* ? In a range is an endpoint
2948                                        platform-specific like \x65 */
2949 #endif
2950
2951     PERL_ARGS_ASSERT_SCAN_CONST;
2952
2953     assert(PL_lex_inwhat != OP_TRANSR);
2954
2955     /* Protect sv from errors and fatal warnings. */
2956     ENTER_with_name("scan_const");
2957     SAVEFREESV(sv);
2958
2959     /* A bunch of code in the loop below assumes that if s[n] exists and is not
2960      * NUL, then s[n+1] exists.  This assertion makes sure that assumption is
2961      * valid */
2962     assert(*send == '\0');
2963
2964     while (s < send
2965            || dorange   /* Handle tr/// range at right edge of input */
2966     ) {
2967
2968         /* get transliterations out of the way (they're most literal) */
2969         if (PL_lex_inwhat == OP_TRANS) {
2970
2971             /* But there isn't any special handling necessary unless there is a
2972              * range, so for most cases we just drop down and handle the value
2973              * as any other.  There are two exceptions.
2974              *
2975              * 1.  A hyphen indicates that we are actually going to have a
2976              *     range.  In this case, skip the '-', set a flag, then drop
2977              *     down to handle what should be the end range value.
2978              * 2.  After we've handled that value, the next time through, that
2979              *     flag is set and we fix up the range.
2980              *
2981              * Ranges entirely within Latin1 are expanded out entirely, in
2982              * order to make the transliteration a simple table look-up.
2983              * Ranges that extend above Latin1 have to be done differently, so
2984              * there is no advantage to expanding them here, so they are
2985              * stored here as Min, RANGE_INDICATOR, Max.  'RANGE_INDICATOR' is
2986              * a byte that can't occur in legal UTF-8, and hence can signify a
2987              * hyphen without any possible ambiguity.  On EBCDIC machines, if
2988              * the range is expressed as Unicode, the Latin1 portion is
2989              * expanded out even if the range extends above Latin1.  This is
2990              * because each code point in it has to be processed here
2991              * individually to get its native translation */
2992
2993             if (! dorange) {
2994
2995                 /* Here, we don't think we're in a range.  If the new character
2996                  * is not a hyphen; or if it is a hyphen, but it's too close to
2997                  * either edge to indicate a range, or if we haven't output any
2998                  * characters yet then it's a regular character. */
2999                 if (*s != '-' || s >= send - 1 || s == start || d == SvPVX(sv))
3000                 {
3001
3002                     /* A regular character.  Process like any other, but first
3003                      * clear any flags */
3004                     didrange = FALSE;
3005                     dorange = FALSE;
3006 #ifdef EBCDIC
3007                     non_portable_endpoint = 0;
3008                     backslash_N = 0;
3009 #endif
3010                     /* The tests here for being above Latin1 and similar ones
3011                      * in the following 'else' suffice to find all such
3012                      * occurences in the constant, except those added by a
3013                      * backslash escape sequence, like \x{100}.  Mostly, those
3014                      * set 'has_above_latin1' as appropriate */
3015                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3016                         has_above_latin1 = TRUE;
3017                     }
3018
3019                     /* Drops down to generic code to process current byte */
3020                 }
3021                 else {  /* Is a '-' in the context where it means a range */
3022                     if (didrange) { /* Something like y/A-C-Z// */
3023                         Perl_croak(aTHX_ "Ambiguous range in transliteration"
3024                                          " operator");
3025                     }
3026
3027                     dorange = TRUE;
3028
3029                     s++;    /* Skip past the hyphen */
3030
3031                     /* d now points to where the end-range character will be
3032                      * placed.  Drop down to get that character.  We'll finish
3033                      * processing the range the next time through the loop */
3034
3035                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3036                         has_above_latin1 = TRUE;
3037                     }
3038
3039                     /* Drops down to generic code to process current byte */
3040                 }
3041             }  /* End of not a range */
3042             else {
3043                 /* Here we have parsed a range.  Now must handle it.  At this
3044                  * point:
3045                  * 'sv' is a SV* that contains the output string we are
3046                  *      constructing.  The final two characters in that string
3047                  *      are the range start and range end, in order.
3048                  * 'd'  points to just beyond the range end in the 'sv' string,
3049                  *      where we would next place something
3050                  */
3051                 char * max_ptr;
3052                 char * min_ptr;
3053                 IV range_min;
3054                 IV range_max;   /* last character in range */
3055                 STRLEN grow;
3056                 Size_t offset_to_min = 0;
3057                 Size_t extras = 0;
3058 #ifdef EBCDIC
3059                 bool convert_unicode;
3060                 IV real_range_max = 0;
3061 #endif
3062                 /* Get the code point values of the range ends. */
3063                 max_ptr = (d_is_utf8) ? (char *) utf8_hop( (U8*) d, -1) : d - 1;
3064                 offset_to_max = max_ptr - SvPVX_const(sv);
3065                 if (d_is_utf8) {
3066                     /* We know the utf8 is valid, because we just constructed
3067                      * it ourselves in previous loop iterations */
3068                     min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
3069                     range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
3070                     range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
3071
3072                     /* This compensates for not all code setting
3073                      * 'has_above_latin1', so that we don't skip stuff that
3074                      * should be executed */
3075                     if (range_max > 255) {
3076                         has_above_latin1 = TRUE;
3077                     }
3078                 }
3079                 else {
3080                     min_ptr = max_ptr - 1;
3081                     range_min = * (U8*) min_ptr;
3082                     range_max = * (U8*) max_ptr;
3083                 }
3084
3085                 /* If the range is just a single code point, like tr/a-a/.../,
3086                  * that code point is already in the output, twice.  We can
3087                  * just back up over the second instance and avoid all the rest
3088                  * of the work.  But if it is a variant character, it's been
3089                  * counted twice, so decrement.  (This unlikely scenario is
3090                  * special cased, like the one for a range of 2 code points
3091                  * below, only because the main-line code below needs a range
3092                  * of 3 or more to work without special casing.  Might as well
3093                  * get it out of the way now.) */
3094                 if (UNLIKELY(range_max == range_min)) {
3095                     d = max_ptr;
3096                     if (! d_is_utf8 && ! UVCHR_IS_INVARIANT(range_max)) {
3097                         utf8_variant_count--;
3098                     }
3099                     goto range_done;
3100                 }
3101
3102 #ifdef EBCDIC
3103                 /* On EBCDIC platforms, we may have to deal with portable
3104                  * ranges.  These happen if at least one range endpoint is a
3105                  * Unicode value (\N{...}), or if the range is a subset of
3106                  * [A-Z] or [a-z], and both ends are literal characters,
3107                  * like 'A', and not like \x{C1} */
3108                 convert_unicode =
3109                                cBOOL(backslash_N)   /* \N{} forces Unicode,
3110                                                        hence portable range */
3111                     || (     ! non_portable_endpoint
3112                         && ((  isLOWER_A(range_min) && isLOWER_A(range_max))
3113                            || (isUPPER_A(range_min) && isUPPER_A(range_max))));
3114                 if (convert_unicode) {
3115
3116                     /* Special handling is needed for these portable ranges.
3117                      * They are defined to be in Unicode terms, which includes
3118                      * all the Unicode code points between the end points.
3119                      * Convert to Unicode to get the Unicode range.  Later we
3120                      * will convert each code point in the range back to
3121                      * native.  */
3122                     range_min = NATIVE_TO_UNI(range_min);
3123                     range_max = NATIVE_TO_UNI(range_max);
3124                 }
3125 #endif
3126
3127                 if (range_min > range_max) {
3128 #ifdef EBCDIC
3129                     if (convert_unicode) {
3130                         /* Need to convert back to native for meaningful
3131                          * messages for this platform */
3132                         range_min = UNI_TO_NATIVE(range_min);
3133                         range_max = UNI_TO_NATIVE(range_max);
3134                     }
3135 #endif
3136                     /* Use the characters themselves for the error message if
3137                      * ASCII printables; otherwise some visible representation
3138                      * of them */
3139                     if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3140                         Perl_croak(aTHX_
3141                          "Invalid range \"%c-%c\" in transliteration operator",
3142                          (char)range_min, (char)range_max);
3143                     }
3144 #ifdef EBCDIC
3145                     else if (convert_unicode) {
3146         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3147                         Perl_croak(aTHX_
3148                            "Invalid range \"\\N{U+%04" UVXf "}-\\N{U+%04"
3149                            UVXf "}\" in transliteration operator",
3150                            range_min, range_max);
3151                     }
3152 #endif
3153                     else {
3154         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3155                         Perl_croak(aTHX_
3156                            "Invalid range \"\\x{%04" UVXf "}-\\x{%04" UVXf "}\""
3157                            " in transliteration operator",
3158                            range_min, range_max);
3159                     }
3160                 }
3161
3162                 /* If the range is exactly two code points long, they are
3163                  * already both in the output */
3164                 if (UNLIKELY(range_min + 1 == range_max)) {
3165                     goto range_done;
3166                 }
3167
3168                 /* Here the range contains at least 3 code points */
3169
3170                 if (d_is_utf8) {
3171
3172                     /* If everything in the transliteration is below 256, we
3173                      * can avoid special handling later.  A translation table
3174                      * for each of those bytes is created by op.c.  So we
3175                      * expand out all ranges to their constituent code points.
3176                      * But if we've encountered something above 255, the
3177                      * expanding won't help, so skip doing that.  But if it's
3178                      * EBCDIC, we may have to look at each character below 256
3179                      * if we have to convert to/from Unicode values */
3180                     if (   has_above_latin1
3181 #ifdef EBCDIC
3182                         && (range_min > 255 || ! convert_unicode)
3183 #endif
3184                     ) {
3185                         const STRLEN off = d - SvPVX(sv);
3186                         const STRLEN extra = 1 + (send - s) + 1;
3187                         char *e;
3188
3189                         /* Move the high character one byte to the right; then
3190                          * insert between it and the range begin, an illegal
3191                          * byte which serves to indicate this is a range (using
3192                          * a '-' would be ambiguous). */
3193
3194                         if (off + extra > SvLEN(sv)) {
3195                             d = off + SvGROW(sv, off + extra);
3196                             max_ptr = d - off + offset_to_max;
3197                         }
3198
3199                         e = d++;
3200                         while (e-- > max_ptr) {
3201                             *(e + 1) = *e;
3202                         }
3203                         *(e + 1) = (char) RANGE_INDICATOR;
3204                         goto range_done;
3205                     }
3206
3207                     /* Here, we're going to expand out the range.  For EBCDIC
3208                      * the range can extend above 255 (not so in ASCII), so
3209                      * for EBCDIC, split it into the parts above and below
3210                      * 255/256 */
3211 #ifdef EBCDIC
3212                     if (range_max > 255) {
3213                         real_range_max = range_max;
3214                         range_max = 255;
3215                     }
3216 #endif
3217                 }
3218
3219                 /* Here we need to expand out the string to contain each
3220                  * character in the range.  Grow the output to handle this.
3221                  * For non-UTF8, we need a byte for each code point in the
3222                  * range, minus the three that we've already allocated for: the
3223                  * hyphen, the min, and the max.  For UTF-8, we need this
3224                  * plus an extra byte for each code point that occupies two
3225                  * bytes (is variant) when in UTF-8 (except we've already
3226                  * allocated for the end points, including if they are
3227                  * variants).  For ASCII platforms and Unicode ranges on EBCDIC
3228                  * platforms, it's easy to calculate a precise number.  To
3229                  * start, we count the variants in the range, which we need
3230                  * elsewhere in this function anyway.  (For the case where it
3231                  * isn't easy to calculate, 'extras' has been initialized to 0,
3232                  * and the calculation is done in a loop further down.) */
3233 #ifdef EBCDIC
3234                 if (convert_unicode)
3235 #endif
3236                 {
3237                     /* This is executed unconditionally on ASCII, and for
3238                      * Unicode ranges on EBCDIC.  Under these conditions, all
3239                      * code points above a certain value are variant; and none
3240                      * under that value are.  We just need to find out how much
3241                      * of the range is above that value.  We don't count the
3242                      * end points here, as they will already have been counted
3243                      * as they were parsed. */
3244                     if (range_min >= UTF_CONTINUATION_MARK) {
3245
3246                         /* The whole range is made up of variants */
3247                         extras = (range_max - 1) - (range_min + 1) + 1;
3248                     }
3249                     else if (range_max >= UTF_CONTINUATION_MARK) {
3250
3251                         /* Only the higher portion of the range is variants */
3252                         extras = (range_max - 1) - UTF_CONTINUATION_MARK + 1;
3253                     }
3254
3255                     utf8_variant_count += extras;
3256                 }
3257
3258                 /* The base growth is the number of code points in the range,
3259                  * not including the endpoints, which have already been sized
3260                  * for (and output).  We don't subtract for the hyphen, as it
3261                  * has been parsed but not output, and the SvGROW below is
3262                  * based only on what's been output plus what's left to parse.
3263                  * */
3264                 grow = (range_max - 1) - (range_min + 1) + 1;
3265
3266                 if (d_is_utf8) {
3267 #ifdef EBCDIC
3268                     /* In some cases in EBCDIC, we haven't yet calculated a
3269                      * precise amount needed for the UTF-8 variants.  Just
3270                      * assume the worst case, that everything will expand by a
3271                      * byte */
3272                     if (! convert_unicode) {
3273                         grow *= 2;
3274                     }
3275                     else
3276 #endif
3277                     {
3278                         /* Otherwise we know exactly how many variants there
3279                          * are in the range. */
3280                         grow += extras;
3281                     }
3282                 }
3283
3284                 /* Grow, but position the output to overwrite the range min end
3285                  * point, because in some cases we overwrite that */
3286                 SvCUR_set(sv, d - SvPVX_const(sv));
3287                 offset_to_min = min_ptr - SvPVX_const(sv);
3288
3289                 /* See Note on sizing above. */
3290                 d = offset_to_min + SvGROW(sv, SvCUR(sv)
3291                                              + (send - s)
3292                                              + grow
3293                                              + 1 /* Trailing NUL */ );
3294
3295                 /* Now, we can expand out the range. */
3296 #ifdef EBCDIC
3297                 if (convert_unicode) {
3298                     SSize_t i;
3299
3300                     /* Recall that the min and max are now in Unicode terms, so
3301                      * we have to convert each character to its native
3302                      * equivalent */
3303                     if (d_is_utf8) {
3304                         for (i = range_min; i <= range_max; i++) {
3305                             append_utf8_from_native_byte(
3306                                                     LATIN1_TO_NATIVE((U8) i),
3307                                                     (U8 **) &d);
3308                         }
3309                     }
3310                     else {
3311                         for (i = range_min; i <= range_max; i++) {
3312                             *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3313                         }
3314                     }
3315                 }
3316                 else
3317 #endif
3318                 /* Always gets run for ASCII, and sometimes for EBCDIC. */
3319                 {
3320                     /* Here, no conversions are necessary, which means that the
3321                      * first character in the range is already in 'd' and
3322                      * valid, so we can skip overwriting it */
3323                     if (d_is_utf8) {
3324                         SSize_t i;
3325                         d += UTF8SKIP(d);
3326                         for (i = range_min + 1; i <= range_max; i++) {
3327                             append_utf8_from_native_byte((U8) i, (U8 **) &d);
3328                         }
3329                     }
3330                     else {
3331                         SSize_t i;
3332                         d++;
3333                         assert(range_min + 1 <= range_max);
3334                         for (i = range_min + 1; i < range_max; i++) {
3335 #ifdef EBCDIC
3336                             /* In this case on EBCDIC, we haven't calculated
3337                              * the variants.  Do it here, as we go along */
3338                             if (! UVCHR_IS_INVARIANT(i)) {
3339                                 utf8_variant_count++;
3340                             }
3341 #endif
3342                             *d++ = (char)i;
3343                         }
3344
3345                         /* The range_max is done outside the loop so as to
3346                          * avoid having to special case not incrementing
3347                          * 'utf8_variant_count' on EBCDIC (it's already been
3348                          * counted when originally parsed) */
3349                         *d++ = (char) range_max;
3350                     }
3351                 }
3352
3353 #ifdef EBCDIC
3354                 /* If the original range extended above 255, add in that
3355                  * portion. */
3356                 if (real_range_max) {
3357                     *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3358                     *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3359                     if (real_range_max > 0x100) {
3360                         if (real_range_max > 0x101) {
3361                             *d++ = (char) RANGE_INDICATOR;
3362                         }
3363                         d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3364                     }
3365                 }
3366 #endif
3367
3368               range_done:
3369                 /* mark the range as done, and continue */
3370                 didrange = TRUE;
3371                 dorange = FALSE;
3372 #ifdef EBCDIC
3373                 non_portable_endpoint = 0;
3374                 backslash_N = 0;
3375 #endif
3376                 continue;
3377             } /* End of is a range */
3378         } /* End of transliteration.  Joins main code after these else's */
3379         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3380             char *s1 = s-1;
3381             int esc = 0;
3382             while (s1 >= start && *s1-- == '\\')
3383                 esc = !esc;
3384             if (!esc)
3385                 in_charclass = TRUE;
3386         }
3387         else if (*s == ']' && PL_lex_inpat && in_charclass) {
3388             char *s1 = s-1;
3389             int esc = 0;
3390             while (s1 >= start && *s1-- == '\\')
3391                 esc = !esc;
3392             if (!esc)
3393                 in_charclass = FALSE;
3394         }
3395             /* skip for regexp comments /(?#comment)/, except for the last
3396              * char, which will be done separately.  Stop on (?{..}) and
3397              * friends */
3398         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3399             if (s[2] == '#') {
3400                 if (s_is_utf8) {
3401                     PERL_UINT_FAST8_T  len = UTF8SKIP(s);
3402
3403                     while (s + len < send && *s != ')') {
3404                         Copy(s, d, len, U8);
3405                         d += len;
3406                         s += len;
3407                         len = UTF8_SAFE_SKIP(s, send);
3408                     }
3409                 }
3410                 else while (s+1 < send && *s != ')') {
3411                     *d++ = *s++;
3412                 }
3413             }
3414             else if (!PL_lex_casemods
3415                      && (    s[2] == '{' /* This should match regcomp.c */
3416                          || (s[2] == '?' && s[3] == '{')))
3417             {
3418                 break;
3419             }
3420         }
3421             /* likewise skip #-initiated comments in //x patterns */
3422         else if (*s == '#'
3423                  && PL_lex_inpat
3424                  && !in_charclass
3425                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3426         {
3427             while (s < send && *s != '\n')
3428                 *d++ = *s++;
3429         }
3430             /* no further processing of single-quoted regex */
3431         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3432             goto default_action;
3433
3434             /* check for embedded arrays
3435              * (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3436              */
3437         else if (*s == '@' && s[1]) {
3438             if (UTF
3439                ? isIDFIRST_utf8_safe(s+1, send)
3440                : isWORDCHAR_A(s[1]))
3441             {
3442                 break;
3443             }
3444             if (strchr(":'{$", s[1]))
3445                 break;
3446             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3447                 break; /* in regexp, neither @+ nor @- are interpolated */
3448         }
3449             /* check for embedded scalars.  only stop if we're sure it's a
3450              * variable.  */
3451         else if (*s == '$') {
3452             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3453                 break;
3454             if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
3455                 if (s[1] == '\\') {
3456                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3457                                    "Possible unintended interpolation of $\\ in regex");
3458                 }
3459                 break;          /* in regexp, $ might be tail anchor */
3460             }
3461         }
3462
3463         /* End of else if chain - OP_TRANS rejoin rest */
3464
3465         if (UNLIKELY(s >= send)) {
3466             assert(s == send);
3467             break;
3468         }
3469
3470         /* backslashes */
3471         if (*s == '\\' && s+1 < send) {
3472             char* e;    /* Can be used for ending '}', etc. */
3473
3474             s++;
3475
3476             /* warn on \1 - \9 in substitution replacements, but note that \11
3477              * is an octal; and \19 is \1 followed by '9' */
3478             if (PL_lex_inwhat == OP_SUBST
3479                 && !PL_lex_inpat
3480                 && isDIGIT(*s)
3481                 && *s != '0'
3482                 && !isDIGIT(s[1]))
3483             {
3484                 /* diag_listed_as: \%d better written as $%d */
3485                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3486                 *--s = '$';
3487                 break;
3488             }
3489
3490             /* string-change backslash escapes */
3491             if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQF", *s)) {
3492                 --s;
3493                 break;
3494             }
3495             /* In a pattern, process \N, but skip any other backslash escapes.
3496              * This is because we don't want to translate an escape sequence
3497              * into a meta symbol and have the regex compiler use the meta
3498              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3499              * in spite of this, we do have to process \N here while the proper
3500              * charnames handler is in scope.  See bugs #56444 and #62056.
3501              *
3502              * There is a complication because \N in a pattern may also stand
3503              * for 'match a non-nl', and not mean a charname, in which case its
3504              * processing should be deferred to the regex compiler.  To be a
3505              * charname it must be followed immediately by a '{', and not look
3506              * like \N followed by a curly quantifier, i.e., not something like
3507              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3508              * quantifier */
3509             else if (PL_lex_inpat
3510                     && (*s != 'N'
3511                         || s[1] != '{'
3512                         || regcurly(s + 1)))
3513             {
3514                 *d++ = '\\';
3515                 goto default_action;
3516             }
3517
3518             switch (*s) {
3519             default:
3520                 {
3521                     if ((isALPHANUMERIC(*s)))
3522                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3523                                        "Unrecognized escape \\%c passed through",
3524                                        *s);
3525                     /* default action is to copy the quoted character */
3526                     goto default_action;
3527                 }
3528
3529             /* eg. \132 indicates the octal constant 0132 */
3530             case '0': case '1': case '2': case '3':
3531             case '4': case '5': case '6': case '7':
3532                 {
3533                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
3534                     STRLEN len = 3;
3535                     uv = grok_oct(s, &len, &flags, NULL);
3536                     s += len;
3537                     if (len < 3 && s < send && isDIGIT(*s)
3538                         && ckWARN(WARN_MISC))
3539                     {
3540                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3541                                     "%s", form_short_octal_warning(s, len));
3542                     }
3543                 }
3544                 goto NUM_ESCAPE_INSERT;
3545
3546             /* eg. \o{24} indicates the octal constant \024 */
3547             case 'o':
3548                 {
3549                     const char* error;
3550
3551                     bool valid = grok_bslash_o(&s, send,
3552                                                &uv, &error,
3553                                                TRUE, /* Output warning */
3554                                                FALSE, /* Not strict */
3555                                                TRUE, /* Output warnings for
3556                                                          non-portables */
3557                                                UTF);
3558                     if (! valid) {
3559                         yyerror(error);
3560                         uv = 0; /* drop through to ensure range ends are set */
3561                     }
3562                     goto NUM_ESCAPE_INSERT;
3563                 }
3564
3565             /* eg. \x24 indicates the hex constant 0x24 */
3566             case 'x':
3567                 {
3568                     const char* error;
3569
3570                     bool valid = grok_bslash_x(&s, send,
3571                                                &uv, &error,
3572                                                TRUE, /* Output warning */
3573                                                FALSE, /* Not strict */
3574                                                TRUE,  /* Output warnings for
3575                                                          non-portables */
3576                                                UTF);
3577                     if (! valid) {
3578                         yyerror(error);
3579                         uv = 0; /* drop through to ensure range ends are set */
3580                     }
3581                 }
3582
3583               NUM_ESCAPE_INSERT:
3584                 /* Insert oct or hex escaped character. */
3585
3586                 /* Here uv is the ordinal of the next character being added */
3587                 if (UVCHR_IS_INVARIANT(uv)) {
3588                     *d++ = (char) uv;
3589                 }
3590                 else {
3591                     if (!d_is_utf8 && uv > 255) {
3592
3593                         /* Here, 'uv' won't fit unless we convert to UTF-8.
3594                          * If we've only seen invariants so far, all we have to
3595                          * do is turn on the flag */
3596                         if (utf8_variant_count == 0) {
3597                             SvUTF8_on(sv);
3598                         }
3599                         else {
3600                             SvCUR_set(sv, d - SvPVX_const(sv));
3601                             SvPOK_on(sv);
3602                             *d = '\0';
3603
3604                             sv_utf8_upgrade_flags_grow(
3605                                            sv,
3606                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3607
3608                                            /* Since we're having to grow here,
3609                                             * make sure we have enough room for
3610                                             * this escape and a NUL, so the
3611                                             * code immediately below won't have
3612                                             * to actually grow again */
3613                                           UVCHR_SKIP(uv)
3614                                         + (STRLEN)(send - s) + 1);
3615                             d = SvPVX(sv) + SvCUR(sv);
3616                         }
3617
3618                         has_above_latin1 = TRUE;
3619                         d_is_utf8 = TRUE;
3620                     }
3621
3622                     if (! d_is_utf8) {
3623                         *d++ = (char)uv;
3624                         utf8_variant_count++;
3625                     }
3626                     else {
3627                        /* Usually, there will already be enough room in 'sv'
3628                         * since such escapes are likely longer than any UTF-8
3629                         * sequence they can end up as.  This isn't the case on
3630                         * EBCDIC where \x{40000000} contains 12 bytes, and the
3631                         * UTF-8 for it contains 14.  And, we have to allow for
3632                         * a trailing NUL.  It probably can't happen on ASCII
3633                         * platforms, but be safe.  See Note on sizing above. */
3634                         const STRLEN needed = d - SvPVX(sv)
3635                                             + UVCHR_SKIP(uv)
3636                                             + (send - s)
3637                                             + 1;
3638                         if (UNLIKELY(needed > SvLEN(sv))) {
3639                             SvCUR_set(sv, d - SvPVX_const(sv));
3640                             d = SvCUR(sv) + SvGROW(sv, needed);
3641                         }
3642
3643                         d = (char*)uvchr_to_utf8((U8*)d, uv);
3644                     }
3645                 }
3646 #ifdef EBCDIC
3647                 non_portable_endpoint++;
3648 #endif
3649                 continue;
3650
3651             case 'N':
3652                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3653                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3654                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3655                  * GRAVE} (except y/// can't handle the latter, croaking).  For
3656                  * convenience all three forms are referred to as "named
3657                  * characters" below.
3658                  *
3659                  * For patterns, \N also can mean to match a non-newline.  Code
3660                  * before this 'switch' statement should already have handled
3661                  * this situation, and hence this code only has to deal with
3662                  * the named character cases.
3663                  *
3664                  * For non-patterns, the named characters are converted to
3665                  * their string equivalents.  In patterns, named characters are
3666                  * not converted to their ultimate forms for the same reasons
3667                  * that other escapes aren't (mainly that the ultimate
3668                  * character could be considered a meta-symbol by the regex
3669                  * compiler).  Instead, they are converted to the \N{U+...}
3670                  * form to get the value from the charnames that is in effect
3671                  * right now, while preserving the fact that it was a named
3672                  * character, so that the regex compiler knows this.
3673                  *
3674                  * The structure of this section of code (besides checking for
3675                  * errors and upgrading to utf8) is:
3676                  *    If the named character is of the form \N{U+...}, pass it
3677                  *      through if a pattern; otherwise convert the code point
3678                  *      to utf8
3679                  *    Otherwise must be some \N{NAME}: convert to
3680                  *      \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3681                  *
3682                  * Transliteration is an exception.  The conversion to utf8 is
3683                  * only done if the code point requires it to be representable.
3684                  *
3685                  * Here, 's' points to the 'N'; the test below is guaranteed to
3686                  * succeed if we are being called on a pattern, as we already
3687                  * know from a test above that the next character is a '{'.  A
3688                  * non-pattern \N must mean 'named character', which requires
3689                  * braces */
3690                 s++;
3691                 if (*s != '{') {
3692                     yyerror("Missing braces on \\N{}");
3693                     *d++ = '\0';
3694                     continue;
3695                 }
3696                 s++;
3697
3698                 /* If there is no matching '}', it is an error. */
3699                 if (! (e = (char *) memchr(s, '}', send - s))) {
3700                     if (! PL_lex_inpat) {
3701                         yyerror("Missing right brace on \\N{}");
3702                     } else {
3703                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3704                     }
3705                     yyquit(); /* Have exhausted the input. */
3706                 }
3707
3708                 /* Here it looks like a named character */
3709
3710                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3711                     s += 2;         /* Skip to next char after the 'U+' */
3712                     if (PL_lex_inpat) {
3713
3714                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3715                         /* Check the syntax.  */
3716                         const char *orig_s;
3717                         orig_s = s - 5;
3718                         if (!isXDIGIT(*s)) {
3719                           bad_NU:
3720                             yyerror(
3721                                 "Invalid hexadecimal number in \\N{U+...}"
3722                             );
3723                             s = e + 1;
3724                             *d++ = '\0';
3725                             continue;
3726                         }
3727                         while (++s < e) {
3728                             if (isXDIGIT(*s))
3729                                 continue;
3730                             else if ((*s == '.' || *s == '_')
3731                                   && isXDIGIT(s[1]))
3732                                 continue;
3733                             goto bad_NU;
3734                         }
3735
3736                         /* Pass everything through unchanged.
3737                          * +1 is for the '}' */
3738                         Copy(orig_s, d, e - orig_s + 1, char);
3739                         d += e - orig_s + 1;
3740                     }
3741                     else {  /* Not a pattern: convert the hex to string */
3742                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3743                                 | PERL_SCAN_SILENT_ILLDIGIT
3744                                 | PERL_SCAN_DISALLOW_PREFIX;
3745                         STRLEN len = e - s;
3746                         uv = grok_hex(s, &len, &flags, NULL);
3747                         if (len == 0 || (len != (STRLEN)(e - s)))
3748                             goto bad_NU;
3749
3750                          /* For non-tr///, if the destination is not in utf8,
3751                           * unconditionally recode it to be so.  This is
3752                           * because \N{} implies Unicode semantics, and scalars
3753                           * have to be in utf8 to guarantee those semantics.
3754                           * tr/// doesn't care about Unicode rules, so no need
3755                           * there to upgrade to UTF-8 for small enough code
3756                           * points */
3757                         if (! d_is_utf8 && (   uv > 0xFF
3758                                            || PL_lex_inwhat != OP_TRANS))
3759                         {
3760                             /* See Note on sizing above.  */
3761                             const STRLEN extra = OFFUNISKIP(uv) + (send - e) + 1;
3762
3763                             SvCUR_set(sv, d - SvPVX_const(sv));
3764                             SvPOK_on(sv);
3765                             *d = '\0';
3766
3767                             if (utf8_variant_count == 0) {
3768                                 SvUTF8_on(sv);
3769                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3770                             }
3771                             else {
3772                                 sv_utf8_upgrade_flags_grow(
3773                                                sv,
3774                                                SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3775                                                extra);
3776                                 d = SvPVX(sv) + SvCUR(sv);
3777                             }
3778
3779                             d_is_utf8 = TRUE;
3780                             has_above_latin1 = TRUE;
3781                         }
3782
3783                         /* Add the (Unicode) code point to the output. */
3784                         if (! d_is_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3785                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3786                         }
3787                         else {
3788                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv, 0);
3789                         }
3790                     }
3791                 }
3792                 else /* Here is \N{NAME} but not \N{U+...}. */
3793                      if (! (res = get_and_check_backslash_N_name_wrapper(s, e)))
3794                 {   /* Failed.  We should die eventually, but for now use a NUL
3795                        to keep parsing */
3796                     *d++ = '\0';
3797                 }
3798                 else {  /* Successfully evaluated the name */
3799                     STRLEN len;
3800                     const char *str = SvPV_const(res, len);
3801                     if (PL_lex_inpat) {
3802
3803                         if (! len) { /* The name resolved to an empty string */
3804                             const char empty_N[] = "\\N{_}";
3805                             Copy(empty_N, d, sizeof(empty_N) - 1, char);
3806                             d += sizeof(empty_N) - 1;
3807                         }
3808                         else {
3809                             /* In order to not lose information for the regex
3810                             * compiler, pass the result in the specially made
3811                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3812                             * the code points in hex of each character
3813                             * returned by charnames */
3814
3815                             const char *str_end = str + len;
3816                             const STRLEN off = d - SvPVX_const(sv);
3817
3818                             if (! SvUTF8(res)) {
3819                                 /* For the non-UTF-8 case, we can determine the
3820                                  * exact length needed without having to parse
3821                                  * through the string.  Each character takes up
3822                                  * 2 hex digits plus either a trailing dot or
3823                                  * the "}" */
3824                                 const char initial_text[] = "\\N{U+";
3825                                 const STRLEN initial_len = sizeof(initial_text)
3826                                                            - 1;
3827                                 d = off + SvGROW(sv, off
3828                                                     + 3 * len
3829
3830                                                     /* +1 for trailing NUL */
3831                                                     + initial_len + 1
3832
3833                                                     + (STRLEN)(send - e));
3834                                 Copy(initial_text, d, initial_len, char);
3835                                 d += initial_len;
3836                                 while (str < str_end) {
3837                                     char hex_string[4];
3838                                     int len =
3839                                         my_snprintf(hex_string,
3840                                                   sizeof(hex_string),
3841                                                   "%02X.",
3842
3843                                                   /* The regex compiler is
3844                                                    * expecting Unicode, not
3845                                                    * native */
3846                                                   NATIVE_TO_LATIN1(*str));
3847                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3848                                                            sizeof(hex_string));
3849                                     Copy(hex_string, d, 3, char);
3850                                     d += 3;
3851                                     str++;
3852                                 }
3853                                 d--;    /* Below, we will overwrite the final
3854                                            dot with a right brace */
3855                             }
3856                             else {
3857                                 STRLEN char_length; /* cur char's byte length */
3858
3859                                 /* and the number of bytes after this is
3860                                  * translated into hex digits */
3861                                 STRLEN output_length;
3862
3863                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3864                                  * for max('U+', '.'); and 1 for NUL */
3865                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3866
3867                                 /* Get the first character of the result. */
3868                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3869                                                         len,
3870                                                         &char_length,
3871                                                         UTF8_ALLOW_ANYUV);
3872                                 /* Convert first code point to Unicode hex,
3873                                  * including the boiler plate before it. */
3874                                 output_length =
3875                                     my_snprintf(hex_string, sizeof(hex_string),
3876                                              "\\N{U+%X",
3877                                              (unsigned int) NATIVE_TO_UNI(uv));
3878
3879                                 /* Make sure there is enough space to hold it */
3880                                 d = off + SvGROW(sv, off
3881                                                     + output_length
3882                                                     + (STRLEN)(send - e)
3883                                                     + 2);       /* '}' + NUL */
3884                                 /* And output it */
3885                                 Copy(hex_string, d, output_length, char);
3886                                 d += output_length;
3887
3888                                 /* For each subsequent character, append dot and
3889                                 * its Unicode code point in hex */
3890                                 while ((str += char_length) < str_end) {
3891                                     const STRLEN off = d - SvPVX_const(sv);
3892                                     U32 uv = utf8n_to_uvchr((U8 *) str,
3893                                                             str_end - str,
3894                                                             &char_length,
3895                                                             UTF8_ALLOW_ANYUV);
3896                                     output_length =
3897                                         my_snprintf(hex_string,
3898                                              sizeof(hex_string),
3899                                              ".%X",
3900                                              (unsigned int) NATIVE_TO_UNI(uv));
3901
3902                                     d = off + SvGROW(sv, off
3903                                                         + output_length
3904                                                         + (STRLEN)(send - e)
3905                                                         + 2);   /* '}' +  NUL */
3906                                     Copy(hex_string, d, output_length, char);
3907                                     d += output_length;
3908                                 }
3909                             }
3910
3911                             *d++ = '}'; /* Done.  Add the trailing brace */
3912                         }
3913                     }
3914                     else { /* Here, not in a pattern.  Convert the name to a
3915                             * string. */
3916
3917                         if (PL_lex_inwhat == OP_TRANS) {
3918                             str = SvPV_const(res, len);
3919                             if (len > ((SvUTF8(res))
3920                                        ? UTF8SKIP(str)
3921                                        : 1U))
3922                             {
3923                                 yyerror(Perl_form(aTHX_
3924                                     "%.*s must not be a named sequence"
3925                                     " in transliteration operator",
3926                                         /*  +1 to include the "}" */
3927                                     (int) (e + 1 - start), start));
3928                                 *d++ = '\0';
3929                                 goto end_backslash_N;
3930                             }
3931
3932                             if (SvUTF8(res) && UTF8_IS_ABOVE_LATIN1(*str)) {
3933                                 has_above_latin1 = TRUE;
3934                             }
3935
3936                         }
3937                         else if (! SvUTF8(res)) {
3938                             /* Make sure \N{} return is UTF-8.  This is because
3939                              * \N{} implies Unicode semantics, and scalars have
3940                              * to be in utf8 to guarantee those semantics; but
3941                              * not needed in tr/// */
3942                             sv_utf8_upgrade_flags(res, 0);
3943                             str = SvPV_const(res, len);
3944                         }
3945
3946                          /* Upgrade destination to be utf8 if this new
3947                           * component is */
3948                         if (! d_is_utf8 && SvUTF8(res)) {
3949                             /* See Note on sizing above.  */
3950                             const STRLEN extra = len + (send - s) + 1;
3951
3952                             SvCUR_set(sv, d - SvPVX_const(sv));
3953                             SvPOK_on(sv);
3954                             *d = '\0';
3955
3956                             if (utf8_variant_count == 0) {
3957                                 SvUTF8_on(sv);
3958                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3959                             }
3960                             else {
3961                                 sv_utf8_upgrade_flags_grow(sv,
3962                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3963                                                 extra);
3964                                 d = SvPVX(sv) + SvCUR(sv);
3965                             }
3966                             d_is_utf8 = TRUE;
3967                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3968
3969                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3970                              * set correctly here). */
3971                             const STRLEN extra = len + (send - e) + 1;
3972                             const STRLEN off = d - SvPVX_const(sv);
3973                             d = off + SvGROW(sv, off + extra);
3974                         }
3975                         Copy(str, d, len, char);
3976                         d += len;
3977                     }
3978
3979                     SvREFCNT_dec(res);
3980
3981                 } /* End \N{NAME} */
3982
3983               end_backslash_N:
3984 #ifdef EBCDIC
3985                 backslash_N++; /* \N{} is defined to be Unicode */
3986 #endif
3987                 s = e + 1;  /* Point to just after the '}' */
3988                 continue;
3989
3990             /* \c is a control character */
3991             case 'c':
3992                 s++;
3993                 if (s < send) {
3994                     *d++ = grok_bslash_c(*s, 1);
3995                 }
3996                 else {
3997                     yyerror("Missing control char name in \\c");
3998                     yyquit();   /* Are at end of input, no sense continuing */
3999                 }
4000 #ifdef EBCDIC
4001                 non_portable_endpoint++;
4002 #endif
4003                 break;
4004
4005             /* printf-style backslashes, formfeeds, newlines, etc */
4006             case 'b':
4007                 *d++ = '\b';
4008                 break;
4009             case 'n':
4010                 *d++ = '\n';
4011                 break;
4012             case 'r':
4013                 *d++ = '\r';
4014                 break;
4015             case 'f':
4016                 *d++ = '\f';
4017                 break;
4018             case 't':
4019                 *d++ = '\t';
4020                 break;
4021             case 'e':
4022                 *d++ = ESC_NATIVE;
4023                 break;
4024             case 'a':
4025                 *d++ = '\a';
4026                 break;
4027             } /* end switch */
4028
4029             s++;
4030             continue;
4031         } /* end if (backslash) */
4032
4033     default_action:
4034         /* Just copy the input to the output, though we may have to convert
4035          * to/from UTF-8.
4036          *
4037          * If the input has the same representation in UTF-8 as not, it will be
4038          * a single byte, and we don't care about UTF8ness; just copy the byte */
4039         if (NATIVE_BYTE_IS_INVARIANT((U8)(*s))) {
4040             *d++ = *s++;
4041         }
4042         else if (! s_is_utf8 && ! d_is_utf8) {
4043             /* If neither source nor output is UTF-8, is also a single byte,
4044              * just copy it; but this byte counts should we later have to
4045              * convert to UTF-8 */
4046             *d++ = *s++;
4047             utf8_variant_count++;
4048         }
4049         else if (s_is_utf8 && d_is_utf8) {   /* Both UTF-8, can just copy */
4050             const STRLEN len = UTF8SKIP(s);
4051
4052             /* We expect the source to have already been checked for
4053              * malformedness */
4054             assert(isUTF8_CHAR((U8 *) s, (U8 *) send));
4055
4056             Copy(s, d, len, U8);
4057             d += len;
4058             s += len;
4059         }
4060         else if (s_is_utf8) { /* UTF8ness matters: convert output to utf8 */
4061             STRLEN need = send - s + 1; /* See Note on sizing above. */
4062
4063             SvCUR_set(sv, d - SvPVX_const(sv));
4064             SvPOK_on(sv);
4065             *d = '\0';
4066
4067             if (utf8_variant_count == 0) {
4068                 SvUTF8_on(sv);
4069                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + need);
4070             }
4071             else {
4072                 sv_utf8_upgrade_flags_grow(sv,
4073                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4074                                            need);
4075                 d = SvPVX(sv) + SvCUR(sv);
4076             }
4077             d_is_utf8 = TRUE;
4078             goto default_action; /* Redo, having upgraded so both are UTF-8 */
4079         }
4080         else {  /* UTF8ness matters: convert this non-UTF8 source char to
4081                    UTF-8 for output.  It will occupy 2 bytes, but don't include
4082                    the input byte since we haven't incremented 's' yet. See
4083                    Note on sizing above. */
4084             const STRLEN off = d - SvPVX(sv);
4085             const STRLEN extra = 2 + (send - s - 1) + 1;
4086             if (off + extra > SvLEN(sv)) {
4087                 d = off + SvGROW(sv, off + extra);
4088             }
4089             *d++ = UTF8_EIGHT_BIT_HI(*s);
4090             *d++ = UTF8_EIGHT_BIT_LO(*s);
4091             s++;
4092         }
4093     } /* while loop to process each character */
4094
4095     {
4096         const STRLEN off = d - SvPVX(sv);
4097
4098         /* See if room for the terminating NUL */
4099         if (UNLIKELY(off >= SvLEN(sv))) {
4100
4101 #ifndef DEBUGGING
4102
4103             if (off > SvLEN(sv))
4104 #endif
4105                 Perl_croak(aTHX_ "panic: constant overflowed allocated space,"
4106                         " %" UVuf " >= %" UVuf, (UV)off, (UV)SvLEN(sv));
4107
4108             /* Whew!  Here we don't have room for the terminating NUL, but
4109              * everything else so far has fit.  It's not too late to grow
4110              * to fit the NUL and continue on.  But it is a bug, as the code
4111              * above was supposed to have made room for this, so under
4112              * DEBUGGING builds, we panic anyway.  */
4113             d = off + SvGROW(sv, off + 1);
4114         }
4115     }
4116
4117     /* terminate the string and set up the sv */
4118     *d = '\0';
4119     SvCUR_set(sv, d - SvPVX_const(sv));
4120
4121     SvPOK_on(sv);
4122     if (d_is_utf8) {
4123         SvUTF8_on(sv);
4124     }
4125
4126     /* shrink the sv if we allocated more than we used */
4127     if (SvCUR(sv) + 5 < SvLEN(sv)) {
4128         SvPV_shrink_to_cur(sv);
4129     }
4130
4131     /* return the substring (via pl_yylval) only if we parsed anything */
4132     if (s > start) {
4133         char *s2 = start;
4134         for (; s2 < s; s2++) {
4135             if (*s2 == '\n')
4136                 COPLINE_INC_WITH_HERELINES;
4137         }
4138         SvREFCNT_inc_simple_void_NN(sv);
4139         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
4140             && ! PL_parser->lex_re_reparsing)
4141         {
4142             const char *const key = PL_lex_inpat ? "qr" : "q";
4143             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
4144             const char *type;
4145             STRLEN typelen;
4146
4147             if (PL_lex_inwhat == OP_TRANS) {
4148                 type = "tr";
4149                 typelen = 2;
4150             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
4151                 type = "s";
4152                 typelen = 1;
4153             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
4154                 type = "q";
4155                 typelen = 1;
4156             } else  {
4157                 type = "qq";
4158                 typelen = 2;
4159             }
4160
4161             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
4162                                 type, typelen, NULL);
4163         }
4164         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
4165     }
4166     LEAVE_with_name("scan_const");
4167     return s;
4168 }
4169
4170 /* S_intuit_more
4171  * Returns TRUE if there's more to the expression (e.g., a subscript),
4172  * FALSE otherwise.
4173  *
4174  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
4175  *
4176  * ->[ and ->{ return TRUE
4177  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
4178  * { and [ outside a pattern are always subscripts, so return TRUE
4179  * if we're outside a pattern and it's not { or [, then return FALSE
4180  * if we're in a pattern and the first char is a {
4181  *   {4,5} (any digits around the comma) returns FALSE
4182  * if we're in a pattern and the first char is a [
4183  *   [] returns FALSE
4184  *   [SOMETHING] has a funky algorithm to decide whether it's a
4185  *      character class or not.  It has to deal with things like
4186  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
4187  * anything else returns TRUE
4188  */
4189
4190 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
4191
4192 STATIC int
4193 S_intuit_more(pTHX_ char *s, char *e)
4194 {
4195     PERL_ARGS_ASSERT_INTUIT_MORE;
4196
4197     if (PL_lex_brackets)
4198         return TRUE;
4199     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
4200         return TRUE;
4201     if (*s == '-' && s[1] == '>'
4202      && FEATURE_POSTDEREF_QQ_IS_ENABLED
4203      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
4204         ||(s[2] == '@' && strchr("*[{",s[3])) ))
4205         return TRUE;
4206     if (*s != '{' && *s != '[')
4207         return FALSE;
4208     PL_parser->sub_no_recover = TRUE;
4209     if (!PL_lex_inpat)
4210         return TRUE;
4211
4212     /* In a pattern, so maybe we have {n,m}. */
4213     if (*s == '{') {
4214         if (regcurly(s)) {
4215             return FALSE;
4216         }
4217         return TRUE;
4218     }
4219
4220     /* On the other hand, maybe we have a character class */
4221
4222     s++;
4223     if (*s == ']' || *s == '^')
4224         return FALSE;
4225     else {
4226         /* this is terrifying, and it works */
4227         int weight;
4228         char seen[256];
4229         const char * const send = (char *) memchr(s, ']', e - s);
4230         unsigned char un_char, last_un_char;
4231         char tmpbuf[sizeof PL_tokenbuf * 4];
4232
4233         if (!send)              /* has to be an expression */
4234             return TRUE;
4235         weight = 2;             /* let's weigh the evidence */
4236
4237         if (*s == '$')
4238             weight -= 3;
4239         else if (isDIGIT(*s)) {
4240             if (s[1] != ']') {
4241                 if (isDIGIT(s[1]) && s[2] == ']')
4242                     weight -= 10;
4243             }
4244             else
4245                 weight -= 100;
4246         }
4247         Zero(seen,256,char);
4248         un_char = 255;
4249         for (; s < send; s++) {
4250             last_un_char = un_char;
4251             un_char = (unsigned char)*s;
4252             switch (*s) {
4253             case '@':
4254             case '&':
4255             case '$':
4256                 weight -= seen[un_char] * 10;
4257                 if (isWORDCHAR_lazy_if_safe(s+1, PL_bufend, UTF)) {
4258                     int len;
4259                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
4260                     len = (int)strlen(tmpbuf);
4261                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
4262                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
4263                         weight -= 100;
4264                     else
4265                         weight -= 10;
4266                 }
4267                 else if (*s == '$'
4268                          && s[1]
4269                          && strchr("[#!%*<>()-=",s[1]))
4270                 {
4271                     if (/*{*/ strchr("])} =",s[2]))
4272                         weight -= 10;
4273                     else
4274                         weight -= 1;
4275                 }
4276                 break;
4277             case '\\':
4278                 un_char = 254;
4279                 if (s[1]) {
4280                     if (strchr("wds]",s[1]))
4281                         weight += 100;
4282                     else if (seen[(U8)'\''] || seen[(U8)'"'])
4283                         weight += 1;
4284                     else if (strchr("rnftbxcav",s[1]))
4285                         weight += 40;
4286                     else if (isDIGIT(s[1])) {
4287                         weight += 40;
4288                         while (s[1] && isDIGIT(s[1]))
4289                             s++;
4290                     }
4291                 }
4292                 else
4293                     weight += 100;
4294                 break;
4295             case '-':
4296                 if (s[1] == '\\')
4297                     weight += 50;
4298                 if (strchr("aA01! ",last_un_char))
4299                     weight += 30;
4300                 if (strchr("zZ79~",s[1]))
4301                     weight += 30;
4302                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4303                     weight -= 5;        /* cope with negative subscript */
4304                 break;
4305             default:
4306                 if (!isWORDCHAR(last_un_char)
4307                     && !(last_un_char == '$' || last_un_char == '@'
4308                          || last_un_char == '&')
4309                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4310                     char *d = s;
4311                     while (isALPHA(*s))
4312                         s++;
4313                     if (keyword(d, s - d, 0))
4314                         weight -= 150;
4315                 }
4316                 if (un_char == last_un_char + 1)
4317                     weight += 5;
4318                 weight -= seen[un_char];
4319                 break;
4320             }
4321             seen[un_char]++;
4322         }
4323         if (weight >= 0)        /* probably a character class */
4324             return FALSE;
4325     }
4326
4327     return TRUE;
4328 }
4329
4330 /*
4331  * S_intuit_method
4332  *
4333  * Does all the checking to disambiguate
4334  *   foo bar
4335  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
4336  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4337  *
4338  * First argument is the stuff after the first token, e.g. "bar".
4339  *
4340  * Not a method if foo is a filehandle.
4341  * Not a method if foo is a subroutine prototyped to take a filehandle.
4342  * Not a method if it's really "Foo $bar"
4343  * Method if it's "foo $bar"
4344  * Not a method if it's really "print foo $bar"
4345  * Method if it's really "foo package::" (interpreted as package->foo)
4346  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4347  * Not a method if bar is a filehandle or package, but is quoted with
4348  *   =>
4349  */
4350
4351 STATIC int
4352 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4353 {
4354     char *s = start + (*start == '$');
4355     char tmpbuf[sizeof PL_tokenbuf];
4356     STRLEN len;
4357     GV* indirgv;
4358         /* Mustn't actually add anything to a symbol table.
4359            But also don't want to "initialise" any placeholder
4360            constants that might already be there into full
4361            blown PVGVs with attached PVCV.  */
4362     GV * const gv =
4363         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4364
4365     PERL_ARGS_ASSERT_INTUIT_METHOD;
4366
4367     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4368             return 0;
4369     if (cv && SvPOK(cv)) {
4370         const char *proto = CvPROTO(cv);
4371         if (proto) {
4372             while (*proto && (isSPACE(*proto) || *proto == ';'))
4373                 proto++;
4374             if (*proto == '*')
4375                 return 0;
4376         }
4377     }
4378
4379     if (*start == '$') {
4380         SSize_t start_off = start - SvPVX(PL_linestr);
4381         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4382             || isUPPER(*PL_tokenbuf))
4383             return 0;
4384         /* this could be $# */
4385         if (isSPACE(*s))
4386             s = skipspace(s);
4387         PL_bufptr = SvPVX(PL_linestr) + start_off;
4388         PL_expect = XREF;
4389         return *s == '(' ? FUNCMETH : METHOD;
4390     }
4391
4392     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4393     /* start is the beginning of the possible filehandle/object,
4394      * and s is the end of it
4395      * tmpbuf is a copy of it (but with single quotes as double colons)
4396      */
4397
4398     if (!keyword(tmpbuf, len, 0)) {
4399         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4400             len -= 2;
4401             tmpbuf[len] = '\0';
4402             goto bare_package;
4403         }
4404         indirgv = gv_fetchpvn_flags(tmpbuf, len,
4405                                     GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4406                                     SVt_PVCV);
4407         if (indirgv && SvTYPE(indirgv) != SVt_NULL
4408          && (!isGV(indirgv) || GvCVu(indirgv)))
4409             return 0;
4410         /* filehandle or package name makes it a method */
4411         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4412             s = skipspace(s);
4413             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4414                 return 0;       /* no assumptions -- "=>" quotes bareword */
4415       bare_package:
4416             NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0,
4417                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4418             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4419             PL_expect = XTERM;
4420             force_next(BAREWORD);
4421             PL_bufptr = s;
4422             return *s == '(' ? FUNCMETH : METHOD;
4423         }
4424     }
4425     return 0;
4426 }
4427
4428 /* Encoded script support. filter_add() effectively inserts a
4429  * 'pre-processing' function into the current source input stream.
4430  * Note that the filter function only applies to the current source file
4431  * (e.g., it will not affect files 'require'd or 'use'd by this one).
4432  *
4433  * The datasv parameter (which may be NULL) can be used to pass
4434  * private data to this instance of the filter. The filter function
4435  * can recover the SV using the FILTER_DATA macro and use it to
4436  * store private buffers and state information.
4437  *
4438  * The supplied datasv parameter is upgraded to a PVIO type
4439  * and the IoDIRP/IoANY field is used to store the function pointer,
4440  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4441  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4442  * private use must be set using malloc'd pointers.
4443  */
4444
4445 SV *
4446 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4447 {
4448     if (!funcp)
4449         return NULL;
4450
4451     if (!PL_parser)
4452         return NULL;
4453
4454     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4455         Perl_croak(aTHX_ "Source filters apply only to byte streams");
4456
4457     if (!PL_rsfp_filters)
4458         PL_rsfp_filters = newAV();
4459     if (!datasv)
4460         datasv = newSV(0);
4461     SvUPGRADE(datasv, SVt_PVIO);
4462     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4463     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4464     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4465                           FPTR2DPTR(void *, IoANY(datasv)),
4466                           SvPV_nolen(datasv)));
4467     av_unshift(PL_rsfp_filters, 1);
4468     av_store(PL_rsfp_filters, 0, datasv) ;
4469     if (
4470         !PL_parser->filtered
4471      && PL_parser->lex_flags & LEX_EVALBYTES
4472      && PL_bufptr < PL_bufend
4473     ) {
4474         const char *s = PL_bufptr;
4475         while (s < PL_bufend) {
4476             if (*s == '\n') {
4477                 SV *linestr = PL_parser->linestr;
4478                 char *buf = SvPVX(linestr);
4479                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4480                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4481                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4482                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4483                 STRLEN const last_uni_pos =
4484                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4485                 STRLEN const last_lop_pos =
4486                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4487                 av_push(PL_rsfp_filters, linestr);
4488                 PL_parser->linestr =
4489                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4490                 buf = SvPVX(PL_parser->linestr);
4491                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4492                 PL_parser->bufptr = buf + bufptr_pos;
4493                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4494                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4495                 PL_parser->linestart = buf + linestart_pos;
4496                 if (PL_parser->last_uni)
4497                     PL_parser->last_uni = buf + last_uni_pos;
4498                 if (PL_parser->last_lop)
4499                     PL_parser->last_lop = buf + last_lop_pos;
4500                 SvLEN_set(linestr, SvCUR(linestr));
4501                 SvCUR_set(linestr, s - SvPVX(linestr));
4502                 PL_parser->filtered = 1;
4503                 break;
4504             }
4505             s++;
4506         }
4507     }
4508     return(datasv);
4509 }
4510
4511
4512 /* Delete most recently added instance of this filter function. */
4513 void
4514 Perl_filter_del(pTHX_ filter_t funcp)
4515 {
4516     SV *datasv;
4517
4518     PERL_ARGS_ASSERT_FILTER_DEL;
4519
4520 #ifdef DEBUGGING
4521     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4522                           FPTR2DPTR(void*, funcp)));
4523 #endif
4524     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4525         return;
4526     /* if filter is on top of stack (usual case) just pop it off */
4527     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4528     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4529         sv_free(av_pop(PL_rsfp_filters));
4530
4531         return;
4532     }
4533     /* we need to search for the correct entry and clear it     */
4534     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4535 }
4536
4537
4538 /* Invoke the idxth filter function for the current rsfp.        */
4539 /* maxlen 0 = read one text line */
4540 I32
4541 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4542 {
4543     filter_t funcp;
4544     I32 ret;
4545     SV *datasv = NULL;
4546     /* This API is bad. It should have been using unsigned int for maxlen.
4547        Not sure if we want to change the API, but if not we should sanity
4548        check the value here.  */
4549     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4550
4551     PERL_ARGS_ASSERT_FILTER_READ;
4552
4553     if (!PL_parser || !PL_rsfp_filters)
4554         return -1;
4555     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4556         /* Provide a default input filter to make life easy.    */
4557         /* Note that we append to the line. This is handy.      */
4558         DEBUG_P(PerlIO_printf(Perl_debug_log,
4559                               "filter_read %d: from rsfp\n", idx));
4560         if (correct_length) {
4561             /* Want a block */
4562             int len ;
4563             const int old_len = SvCUR(buf_sv);
4564
4565             /* ensure buf_sv is large enough */
4566             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4567             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4568                                    correct_length)) <= 0) {
4569                 if (PerlIO_error(PL_rsfp))
4570                     return -1;          /* error */
4571                 else
4572                     return 0 ;          /* end of file */
4573             }
4574             SvCUR_set(buf_sv, old_len + len) ;
4575             SvPVX(buf_sv)[old_len + len] = '\0';
4576         } else {
4577             /* Want a line */
4578             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4579                 if (PerlIO_error(PL_rsfp))
4580                     return -1;          /* error */
4581                 else
4582                     return 0 ;          /* end of file */
4583             }
4584         }
4585         return SvCUR(buf_sv);
4586     }
4587     /* Skip this filter slot if filter has been deleted */
4588     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4589         DEBUG_P(PerlIO_printf(Perl_debug_log,
4590                               "filter_read %d: skipped (filter deleted)\n",
4591                               idx));
4592         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4593     }
4594     if (SvTYPE(datasv) != SVt_PVIO) {
4595         if (correct_length) {
4596             /* Want a block */
4597             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4598             if (!remainder) return 0; /* eof */
4599             if (correct_length > remainder) correct_length = remainder;
4600             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4601             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4602         } else {
4603             /* Want a line */
4604             const char *s = SvEND(datasv);
4605             const char *send = SvPVX(datasv) + SvLEN(datasv);
4606             while (s < send) {
4607                 if (*s == '\n') {
4608                     s++;
4609                     break;
4610                 }
4611                 s++;
4612             }
4613             if (s == send) return 0; /* eof */
4614             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4615             SvCUR_set(datasv, s-SvPVX(datasv));
4616         }
4617         return SvCUR(buf_sv);
4618     }
4619     /* Get function pointer hidden within datasv        */
4620     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4621     DEBUG_P(PerlIO_printf(Perl_debug_log,
4622                           "filter_read %d: via function %p (%s)\n",
4623                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4624     /* Call function. The function is expected to       */
4625     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4626     /* Return: <0:error, =0:eof, >0:not eof             */
4627     ENTER;
4628     save_scalar(PL_errgv);
4629     ret = (*funcp)(aTHX_ idx, buf_sv, correct_length);
4630     LEAVE;
4631     return ret;
4632 }
4633
4634 STATIC char *
4635 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4636 {
4637     PERL_ARGS_ASSERT_FILTER_GETS;
4638
4639 #ifdef PERL_CR_FILTER
4640     if (!PL_rsfp_filters) {
4641         filter_add(S_cr_textfilter,NULL);
4642     }
4643 #endif
4644     if (PL_rsfp_filters) {
4645         if (!append)
4646             SvCUR_set(sv, 0);   /* start with empty line        */
4647         if (FILTER_READ(0, sv, 0) > 0)
4648             return ( SvPVX(sv) ) ;
4649         else
4650             return NULL ;
4651     }
4652     else
4653         return (sv_gets(sv, PL_rsfp, append));
4654 }
4655
4656 STATIC HV *
4657 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4658 {
4659     GV *gv;
4660
4661     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4662
4663     if (memEQs(pkgname, len, "__PACKAGE__"))
4664         return PL_curstash;
4665
4666     if (len > 2
4667         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4668         && (gv = gv_fetchpvn_flags(pkgname,
4669                                    len,
4670                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4671     {
4672         return GvHV(gv);                        /* Foo:: */
4673     }
4674
4675     /* use constant CLASS => 'MyClass' */
4676     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4677     if (gv && GvCV(gv)) {
4678         SV * const sv = cv_const_sv(GvCV(gv));
4679         if (sv)
4680             return gv_stashsv(sv, 0);
4681     }
4682
4683     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4684 }
4685
4686
4687 STATIC char *
4688 S_tokenize_use(pTHX_ int is_use, char *s) {
4689     PERL_ARGS_ASSERT_TOKENIZE_USE;
4690
4691     if (PL_expect != XSTATE)
4692         /* diag_listed_as: "use" not allowed in expression */
4693         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4694                     is_use ? "use" : "no"));
4695     PL_expect = XTERM;
4696     s = skipspace(s);
4697     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4698         s = force_version(s, TRUE);
4699         if (*s == ';' || *s == '}'
4700                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4701             NEXTVAL_NEXTTOKE.opval = NULL;
4702             force_next(BAREWORD);
4703         }
4704         else if (*s == 'v') {
4705             s = force_word(s,BAREWORD,FALSE,TRUE);
4706             s = force_version(s, FALSE);
4707         }
4708     }
4709     else {
4710         s = force_word(s,BAREWORD,FALSE,TRUE);
4711         s = force_version(s, FALSE);
4712     }
4713     pl_yylval.ival = is_use;
4714     return s;
4715 }
4716 #ifdef DEBUGGING
4717     static const char* const exp_name[] =
4718         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4719           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4720           "SIGVAR", "TERMORDORDOR"
4721         };
4722 #endif
4723
4724 #define word_takes_any_delimiter(p,l) S_word_takes_any_delimiter(p,l)
4725 STATIC bool
4726 S_word_takes_any_delimiter(char *p, STRLEN len)
4727 {
4728     return (len == 1 && strchr("msyq", p[0]))
4729             || (len == 2
4730                 && ((p[0] == 't' && p[1] == 'r')
4731                     || (p[0] == 'q' && strchr("qwxr", p[1]))));
4732 }
4733
4734 static void
4735 S_check_scalar_slice(pTHX_ char *s)
4736 {
4737     s++;
4738     while (SPACE_OR_TAB(*s)) s++;
4739     if (*s == 'q' && s[1] == 'w' && !isWORDCHAR_lazy_if_safe(s+2,
4740                                                              PL_bufend,
4741                                                              UTF))
4742     {
4743         return;
4744     }
4745     while (    isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF)
4746            || (*s && strchr(" \t$#+-'\"", *s)))
4747     {
4748         s += UTF ? UTF8SKIP(s) : 1;
4749     }
4750     if (*s == '}' || *s == ']')
4751         pl_yylval.ival = OPpSLICEWARNING;
4752 }
4753
4754 #define lex_token_boundary() S_lex_token_boundary(aTHX)
4755 static void
4756 S_lex_token_boundary(pTHX)
4757 {
4758     PL_oldoldbufptr = PL_oldbufptr;
4759     PL_oldbufptr = PL_bufptr;
4760 }
4761
4762 #define vcs_conflict_marker(s) S_vcs_conflict_marker(aTHX_ s)
4763 static char *
4764 S_vcs_conflict_marker(pTHX_ char *s)
4765 {
4766     lex_token_boundary();
4767     PL_bufptr = s;
4768     yyerror("Version control conflict marker");
4769     while (s < PL_bufend && *s != '\n')
4770         s++;
4771     return s;
4772 }
4773
4774 static int
4775 yyl_sigvar(pTHX_ char *s)
4776 {
4777     /* we expect the sigil and optional var name part of a
4778      * signature element here. Since a '$' is not necessarily
4779      * followed by a var name, handle it specially here; the general
4780      * yylex code would otherwise try to interpret whatever follows
4781      * as a var; e.g. ($, ...) would be seen as the var '$,'
4782      */
4783
4784     U8 sigil;
4785
4786     s = skipspace(s);
4787     sigil = *s++;
4788     PL_bufptr = s; /* for error reporting */
4789     switch (sigil) {
4790     case '$':
4791     case '@':
4792     case '%':
4793         /* spot stuff that looks like an prototype */
4794         if (strchr("$:@%&*;\\[]", *s)) {
4795             yyerror("Illegal character following sigil in a subroutine signature");
4796             break;
4797         }
4798         /* '$#' is banned, while '$ # comment' isn't */
4799         if (*s == '#') {
4800             yyerror("'#' not allowed immediately following a sigil in a subroutine signature");
4801             break;
4802         }
4803         s = skipspace(s);
4804         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
4805             char *dest = PL_tokenbuf + 1;
4806             /* read var name, including sigil, into PL_tokenbuf */
4807             PL_tokenbuf[0] = sigil;
4808             parse_ident(&s, &dest, dest + sizeof(PL_tokenbuf) - 1,
4809                 0, cBOOL(UTF), FALSE, FALSE);
4810             *dest = '\0';
4811             assert(PL_tokenbuf[1]); /* we have a variable name */
4812         }
4813         else {
4814             *PL_tokenbuf = 0;
4815             PL_in_my = 0;
4816         }
4817
4818         s = skipspace(s);
4819         /* parse the = for the default ourselves to avoid '+=' etc being accepted here
4820          * as the ASSIGNOP, and exclude other tokens that start with =
4821          */
4822         if (*s == '=' && (!s[1] || strchr("=~>", s[1]) == 0)) {
4823             /* save now to report with the same context as we did when
4824              * all ASSIGNOPS were accepted */
4825             PL_oldbufptr = s;
4826
4827             ++s;
4828             NEXTVAL_NEXTTOKE.ival = 0;
4829             force_next(ASSIGNOP);
4830             PL_expect = XTERM;
4831         }
4832         else if (*s == ',' || *s == ')') {
4833             PL_expect = XOPERATOR;
4834         }
4835         else {
4836             /* make sure the context shows the unexpected character and
4837              * hopefully a bit more */
4838             if (*s) ++s;
4839             while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4840                 s++;
4841             PL_bufptr = s; /* for error reporting */
4842             yyerror("Illegal operator following parameter in a subroutine signature");
4843             PL_in_my = 0;
4844         }
4845         if (*PL_tokenbuf) {
4846             NEXTVAL_NEXTTOKE.ival = sigil;
4847             force_next('p'); /* force a signature pending identifier */
4848         }
4849         break;
4850
4851     case ')':
4852         PL_expect = XBLOCK;
4853         break;
4854     case ',': /* handle ($a,,$b) */
4855         break;
4856
4857     default:
4858         PL_in_my = 0;
4859         yyerror("A signature parameter must start with '$', '@' or '%'");
4860         /* very crude error recovery: skip to likely next signature
4861          * element */
4862         while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4863             s++;
4864         break;
4865     }
4866
4867     TOKEN(sigil);
4868 }
4869
4870 static int
4871 yyl_dollar(pTHX_ char *s)
4872 {
4873     CLINE;
4874
4875     if (PL_expect == XPOSTDEREF) {
4876         if (s[1] == '#') {
4877             s++;
4878             POSTDEREF(DOLSHARP);
4879         }
4880         POSTDEREF('$');
4881     }
4882
4883     if (   s[1] == '#'
4884         && (   isIDFIRST_lazy_if_safe(s+2, PL_bufend, UTF)
4885             || strchr("{$:+-@", s[2])))
4886     {
4887         PL_tokenbuf[0] = '@';
4888         s = scan_ident(s + 1, PL_tokenbuf + 1,
4889                        sizeof PL_tokenbuf - 1, FALSE);
4890         if (PL_expect == XOPERATOR) {
4891             char *d = s;
4892             if (PL_bufptr > s) {
4893                 d = PL_bufptr-1;
4894                 PL_bufptr = PL_oldbufptr;
4895             }
4896             no_op("Array length", d);
4897         }
4898         if (!PL_tokenbuf[1])
4899             PREREF(DOLSHARP);
4900         PL_expect = XOPERATOR;
4901         force_ident_maybe_lex('#');
4902         TOKEN(DOLSHARP);
4903     }
4904
4905     PL_tokenbuf[0] = '$';
4906     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
4907     if (PL_expect == XOPERATOR) {
4908         char *d = s;
4909         if (PL_bufptr > s) {
4910             d = PL_bufptr-1;
4911             PL_bufptr = PL_oldbufptr;
4912         }
4913         no_op("Scalar", d);
4914     }
4915     if (!PL_tokenbuf[1]) {
4916         if (s == PL_bufend)
4917             yyerror("Final $ should be \\$ or $name");
4918         PREREF('$');
4919     }
4920
4921     {
4922         const char tmp = *s;
4923         if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
4924             s = skipspace(s);
4925
4926         if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
4927             && intuit_more(s, PL_bufend)) {
4928             if (*s == '[') {
4929                 PL_tokenbuf[0] = '@';
4930                 if (ckWARN(WARN_SYNTAX)) {
4931                     char *t = s+1;
4932
4933                     while (   isSPACE(*t)
4934                            || isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)
4935                            || *t == '$')
4936                     {
4937                         t += UTF ? UTF8SKIP(t) : 1;
4938                     }
4939                     if (*t++ == ',') {
4940                         PL_bufptr = skipspace(PL_bufptr); /* XXX can realloc */
4941                         while (t < PL_bufend && *t != ']')
4942                             t++;
4943                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
4944                                     "Multidimensional syntax %" UTF8f " not supported",
4945                                     UTF8fARG(UTF,(int)((t - PL_bufptr) + 1), PL_bufptr));
4946                     }
4947                 }
4948             }
4949             else if (*s == '{') {
4950                 char *t;
4951                 PL_tokenbuf[0] = '%';
4952                 if (    strEQ(PL_tokenbuf+1, "SIG")
4953                     && ckWARN(WARN_SYNTAX)
4954                     && (t = (char *) memchr(s, '}', PL_bufend - s))
4955                     && (t = (char *) memchr(t, '=', PL_bufend - t)))
4956                 {
4957                     char tmpbuf[sizeof PL_tokenbuf];
4958                     do {
4959                         t++;
4960                     } while (isSPACE(*t));
4961                     if (isIDFIRST_lazy_if_safe(t, PL_bufend, UTF)) {
4962                         STRLEN len;
4963                         t = scan_word(t, tmpbuf, sizeof tmpbuf, TRUE,
4964                                         &len);
4965                         while (isSPACE(*t))
4966                             t++;
4967                         if (  *t == ';'
4968                             && get_cvn_flags(tmpbuf, len, UTF
4969                                                             ? SVf_UTF8
4970                                                             : 0))
4971                         {
4972                             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
4973                                 "You need to quote \"%" UTF8f "\"",
4974                                     UTF8fARG(UTF, len, tmpbuf));
4975                         }
4976                     }
4977                 }
4978             }
4979         }
4980
4981         PL_expect = XOPERATOR;
4982         if ((PL_lex_state == LEX_NORMAL || PL_lex_brackets) && isSPACE((char)tmp)) {
4983             const bool islop = (PL_last_lop == PL_oldoldbufptr);
4984             if (!islop || PL_last_lop_op == OP_GREPSTART)
4985                 PL_expect = XOPERATOR;
4986             else if (strchr("$@\"'`q", *s))
4987                 PL_expect = XTERM;              /* e.g. print $fh "foo" */
4988             else if (   strchr("&*<%", *s)
4989                      && isIDFIRST_lazy_if_safe(s+1, PL_bufend, UTF))
4990             {
4991                 PL_expect = XTERM;              /* e.g. print $fh &sub */
4992             }
4993             else if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
4994                 char tmpbuf[sizeof PL_tokenbuf];
4995                 int t2;
4996                 STRLEN len;
4997                 scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4998                 if ((t2 = keyword(tmpbuf, len, 0))) {
4999                     /* binary operators exclude handle interpretations */
5000                     switch (t2) {
5001                     case -KEY_x:
5002                     case -KEY_eq:
5003                     case -KEY_ne:
5004                     case -KEY_gt:
5005                     case -KEY_lt:
5006                     case -KEY_ge:
5007                     case -KEY_le:
5008                     case -KEY_cmp:
5009                         break;
5010                     default:
5011                         PL_expect = XTERM;      /* e.g. print $fh length() */
5012                         break;
5013                     }
5014                 }
5015                 else {
5016                     PL_expect = XTERM;  /* e.g. print $fh subr() */
5017                 }
5018             }
5019             else if (isDIGIT(*s))
5020                 PL_expect = XTERM;              /* e.g. print $fh 3 */
5021             else if (*s == '.' && isDIGIT(s[1]))
5022                 PL_expect = XTERM;              /* e.g. print $fh .3 */
5023             else if ((*s == '?' || *s == '-' || *s == '+')
5024                      && !isSPACE(s[1]) && s[1] != '=')
5025                 PL_expect = XTERM;              /* e.g. print $fh -1 */
5026             else if (*s == '/' && !isSPACE(s[1]) && s[1] != '='
5027                      && s[1] != '/')
5028                 PL_expect = XTERM;              /* e.g. print $fh /.../
5029                                                XXX except DORDOR operator
5030                                             */
5031             else if (*s == '<' && s[1] == '<' && !isSPACE(s[2])
5032                      && s[2] != '=')
5033                 PL_expect = XTERM;              /* print $fh <<"EOF" */
5034         }
5035     }
5036     force_ident_maybe_lex('$');
5037     TOKEN('$');
5038 }
5039
5040 static int
5041 yyl_sub(pTHX_ char *s, const int key)
5042 {
5043     char * const tmpbuf = PL_tokenbuf + 1;
5044     bool have_name, have_proto;
5045     STRLEN len;
5046     SV *format_name = NULL;
5047     bool is_sigsub = FEATURE_SIGNATURES_IS_ENABLED;
5048
5049     SSize_t off = s-SvPVX(PL_linestr);
5050     char *d;
5051
5052     s = skipspace(s); /* can move PL_linestr */
5053
5054     d = SvPVX(PL_linestr)+off;
5055
5056     SAVEBOOL(PL_parser->sig_seen);
5057     PL_parser->sig_seen = FALSE;
5058
5059     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
5060         || *s == '\''
5061         || (*s == ':' && s[1] == ':'))
5062     {
5063
5064         PL_expect = XATTRBLOCK;
5065         d = scan_word(s, tmpbuf, sizeof PL_tokenbuf - 1, TRUE,
5066                       &len);
5067         if (key == KEY_format)
5068             format_name = S_newSV_maybe_utf8(aTHX_ s, d - s);
5069         *PL_tokenbuf = '&';
5070         if (memchr(tmpbuf, ':', len) || key != KEY_sub
5071          || pad_findmy_pvn(
5072                 PL_tokenbuf, len + 1, 0
5073             ) != NOT_IN_PAD)
5074             sv_setpvn(PL_subname, tmpbuf, len);
5075         else {
5076             sv_setsv(PL_subname,PL_curstname);
5077             sv_catpvs(PL_subname,"::");
5078             sv_catpvn(PL_subname,tmpbuf,len);
5079         }
5080         if (SvUTF8(PL_linestr))
5081             SvUTF8_on(PL_subname);
5082         have_name = TRUE;
5083
5084         s = skipspace(d);
5085     }
5086     else {
5087         if (key == KEY_my || key == KEY_our || key==KEY_state) {
5088             *d = '\0';
5089             /* diag_listed_as: Missing name in "%s sub" */
5090             Perl_croak(aTHX_
5091                       "Missing name in \"%s\"", PL_bufptr);
5092         }
5093         PL_expect = XATTRTERM;
5094         sv_setpvs(PL_subname,"?");
5095         have_name = FALSE;
5096     }
5097
5098     if (key == KEY_format) {
5099         if (format_name) {
5100             NEXTVAL_NEXTTOKE.opval
5101                 = newSVOP(OP_CONST,0, format_name);
5102             NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
5103             force_next(BAREWORD);
5104         }
5105         PREBLOCK(FORMAT);
5106     }
5107
5108     /* Look for a prototype */
5109     if (*s == '(' && !is_sigsub) {
5110         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5111         if (!s)
5112             Perl_croak(aTHX_ "Prototype not terminated");
5113         COPLINE_SET_FROM_MULTI_END;
5114         (void)validate_proto(PL_subname, PL_lex_stuff,
5115                              ckWARN(WARN_ILLEGALPROTO), 0);
5116         have_proto = TRUE;
5117
5118         s = skipspace(s);
5119     }
5120     else
5121         have_proto = FALSE;
5122
5123     if (  !(*s == ':' && s[1] != ':')
5124         && (*s != '{' && *s != '(') && key != KEY_format)
5125     {
5126         assert(key == KEY_sub || key == KEY_AUTOLOAD ||
5127                key == KEY_DESTROY || key == KEY_BEGIN ||
5128                key == KEY_UNITCHECK || key == KEY_CHECK ||
5129                key == KEY_INIT || key == KEY_END ||
5130                key == KEY_my || key == KEY_state ||
5131                key == KEY_our);
5132         if (!have_name)
5133             Perl_croak(aTHX_ "Illegal declaration of anonymous subroutine");
5134         else if (*s != ';' && *s != '}')
5135             Perl_croak(aTHX_ "Illegal declaration of subroutine %" SVf, SVfARG(PL_subname));
5136     }
5137
5138     if (have_proto) {
5139         NEXTVAL_NEXTTOKE.opval =
5140             newSVOP(OP_CONST, 0, PL_lex_stuff);
5141         PL_lex_stuff = NULL;
5142         force_next(THING);
5143     }
5144     if (!have_name) {
5145         if (PL_curstash)
5146             sv_setpvs(PL_subname, "__ANON__");
5147         else
5148             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5149         if (is_sigsub)
5150             TOKEN(ANON_SIGSUB);
5151         else
5152             TOKEN(ANONSUB);
5153     }
5154     force_ident_maybe_lex('&');
5155     if (is_sigsub)
5156         TOKEN(SIGSUB);
5157     else
5158         TOKEN(SUB);
5159 }
5160
5161 static int
5162 yyl_interpcasemod(pTHX_ char *s)
5163 {
5164 #ifdef DEBUGGING
5165     if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
5166         Perl_croak(aTHX_
5167                    "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
5168                    PL_bufptr, PL_bufend, *PL_bufptr);
5169 #endif
5170
5171     if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
5172         /* if at a \E */
5173         if (PL_lex_casemods) {
5174             const char oldmod = PL_lex_casestack[--PL_lex_casemods];
5175             PL_lex_casestack[PL_lex_casemods] = '\0';
5176
5177             if (PL_bufptr != PL_bufend
5178                 && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
5179                     || oldmod == 'F')) {
5180                 PL_bufptr += 2;
5181                 PL_lex_state = LEX_INTERPCONCAT;
5182             }
5183             PL_lex_allbrackets--;
5184             return REPORT(')');
5185         }
5186         else if ( PL_bufptr != PL_bufend && PL_bufptr[1] == 'E' ) {
5187            /* Got an unpaired \E */
5188            Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5189                     "Useless use of \\E");
5190         }
5191         if (PL_bufptr != PL_bufend)
5192             PL_bufptr += 2;
5193         PL_lex_state = LEX_INTERPCONCAT;
5194         return yylex();
5195     }
5196     else {
5197         DEBUG_T({
5198             PerlIO_printf(Perl_debug_log, "### Saw case modifier\n");
5199         });
5200         s = PL_bufptr + 1;
5201         if (s[1] == '\\' && s[2] == 'E') {
5202             PL_bufptr = s + 3;
5203             PL_lex_state = LEX_INTERPCONCAT;
5204             return yylex();
5205         }
5206         else {
5207             I32 tmp;
5208             if (   memBEGINs(s, (STRLEN) (PL_bufend - s), "L\\u")
5209                 || memBEGINs(s, (STRLEN) (PL_bufend - s), "U\\l"))
5210             {
5211                 tmp = *s, *s = s[2], s[2] = (char)tmp;  /* misordered... */
5212             }
5213             if ((*s == 'L' || *s == 'U' || *s == 'F')
5214                 && (strpbrk(PL_lex_casestack, "LUF")))
5215             {
5216                 PL_lex_casestack[--PL_lex_casemods] = '\0';
5217                 PL_lex_allbrackets--;
5218                 return REPORT(')');
5219             }
5220             if (PL_lex_casemods > 10)
5221                 Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
5222             PL_lex_casestack[PL_lex_casemods++] = *s;
5223             PL_lex_casestack[PL_lex_casemods] = '\0';
5224             PL_lex_state = LEX_INTERPCONCAT;
5225             NEXTVAL_NEXTTOKE.ival = 0;
5226             force_next((2<<24)|'(');
5227             if (*s == 'l')
5228                 NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
5229             else if (*s == 'u')
5230                 NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
5231             else if (*s == 'L')
5232                 NEXTVAL_NEXTTOKE.ival = OP_LC;
5233             else if (*s == 'U')
5234                 NEXTVAL_NEXTTOKE.ival = OP_UC;
5235             else if (*s == 'Q')
5236                 NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
5237             else if (*s == 'F')
5238                 NEXTVAL_NEXTTOKE.ival = OP_FC;
5239             else
5240                 Perl_croak(aTHX_ "panic: yylex, *s=%u", *s);
5241             PL_bufptr = s + 1;
5242         }
5243         force_next(FUNC);
5244         if (PL_lex_starts) {
5245             s = PL_bufptr;
5246             PL_lex_starts = 0;
5247             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
5248             if (PL_lex_casemods == 1 && PL_lex_inpat)
5249                 TOKEN(',');
5250             else
5251                 AopNOASSIGN(OP_CONCAT);
5252         }
5253         else
5254             return yylex();
5255     }
5256 }
5257
5258 static int
5259 yyl_secondclass_keyword(pTHX_ char *s, STRLEN len, int key, I32 *orig_keyword,
5260                         GV **pgv, GV ***pgvp)
5261 {
5262     GV *ogv = NULL;     /* override (winner) */
5263     GV *hgv = NULL;     /* hidden (loser) */
5264     GV *gv = *pgv;
5265
5266     if (PL_expect != XOPERATOR && (*s != ':' || s[1] != ':')) {
5267         CV *cv;
5268         if ((gv = gv_fetchpvn_flags(PL_tokenbuf, len,
5269                                     (UTF ? SVf_UTF8 : 0)|GV_NOTQUAL,
5270                                     SVt_PVCV))
5271             && (cv = GvCVu(gv)))
5272         {
5273             if (GvIMPORTED_CV(gv))
5274                 ogv = gv;
5275             else if (! CvMETHOD(cv))
5276                 hgv = gv;
5277         }
5278         if (!ogv
5279             && (*pgvp = (GV**)hv_fetch(PL_globalstash, PL_tokenbuf, len, FALSE))
5280             && (gv = **pgvp)
5281             && (isGV_with_GP(gv)
5282                 ? GvCVu(gv) && GvIMPORTED_CV(gv)
5283                 :   SvPCS_IMPORTED(gv)
5284                 && (gv_init(gv, PL_globalstash, PL_tokenbuf,
5285                                                          len, 0), 1)))
5286         {
5287             ogv = gv;
5288         }
5289     }
5290
5291     *pgv = gv;
5292
5293     if (ogv) {
5294         *orig_keyword = key;
5295         return 0;               /* overridden by import or by GLOBAL */
5296     }
5297     else if (gv && !*pgvp
5298              && -key==KEY_lock  /* XXX generalizable kludge */
5299              && GvCVu(gv))
5300     {
5301         return 0;               /* any sub overrides "weak" keyword */
5302     }
5303     else {                      /* no override */
5304         key = -key;
5305         if (key == KEY_dump) {
5306             Perl_croak(aTHX_ "dump() must be written as CORE::dump() as of Perl 5.30");
5307         }
5308         *pgv = NULL;
5309         *pgvp = 0;
5310         if (hgv && key != KEY_x)        /* never ambiguous */
5311             Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
5312                            "Ambiguous call resolved as CORE::%s(), "
5313                            "qualify as such or use &",
5314                            GvENAME(hgv));
5315         return key;
5316     }
5317 }
5318
5319 static int
5320 yyl_qw(pTHX_ char *s, STRLEN len)
5321 {
5322     OP *words = NULL;
5323
5324     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5325     if (!s)
5326         missingterm(NULL, 0);
5327
5328     COPLINE_SET_FROM_MULTI_END;
5329     PL_expect = XOPERATOR;
5330     if (SvCUR(PL_lex_stuff)) {
5331         int warned_comma = !ckWARN(WARN_QW);
5332         int warned_comment = warned_comma;
5333         char *d = SvPV_force(PL_lex_stuff, len);
5334         while (len) {
5335             for (; isSPACE(*d) && len; --len, ++d)
5336                 /**/;
5337             if (len) {
5338                 SV *sv;
5339                 const char *b = d;
5340                 if (!warned_comma || !warned_comment) {
5341                     for (; !isSPACE(*d) && len; --len, ++d) {
5342                         if (!warned_comma && *d == ',') {
5343                             Perl_warner(aTHX_ packWARN(WARN_QW),
5344                                 "Possible attempt to separate words with commas");
5345                             ++warned_comma;
5346                         }
5347                         else if (!warned_comment && *d == '#') {
5348                             Perl_warner(aTHX_ packWARN(WARN_QW),
5349                                 "Possible attempt to put comments in qw() list");
5350                             ++warned_comment;
5351                         }
5352                     }
5353                 }
5354                 else {
5355                     for (; !isSPACE(*d) && len; --len, ++d)
5356                         /**/;
5357                 }
5358                 sv = newSVpvn_utf8(b, d-b, DO_UTF8(PL_lex_stuff));
5359                 words = op_append_elem(OP_LIST, words,
5360                                        newSVOP(OP_CONST, 0, tokeq(sv)));
5361             }
5362         }
5363     }
5364     if (!words)
5365         words = newNULLLIST();
5366     SvREFCNT_dec_NN(PL_lex_stuff);
5367     PL_lex_stuff = NULL;
5368     PL_expect = XOPERATOR;
5369     pl_yylval.opval = sawparens(words);
5370     TOKEN(QWLIST);
5371 }
5372
5373 static int
5374 yyl_hyphen(pTHX_ char *s)
5375 {
5376     if (s[1] && isALPHA(s[1]) && !isWORDCHAR(s[2])) {
5377         I32 ftst = 0;
5378         char tmp;
5379
5380         s++;
5381         PL_bufptr = s;
5382         tmp = *s++;
5383
5384         while (s < PL_bufend && SPACE_OR_TAB(*s))
5385             s++;
5386
5387         if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=>")) {
5388             s = force_word(PL_bufptr,BAREWORD,FALSE,FALSE);
5389             DEBUG_T( { printbuf("### Saw unary minus before =>, forcing word %s\n", s); } );
5390             OPERATOR('-');              /* unary minus */
5391         }
5392         switch (tmp) {
5393         case 'r': ftst = OP_FTEREAD;    break;
5394         case 'w': ftst = OP_FTEWRITE;   break;
5395         case 'x': ftst = OP_FTEEXEC;    break;
5396         case 'o': ftst = OP_FTEOWNED;   break;
5397         case 'R': ftst = OP_FTRREAD;    break;
5398         case 'W': ftst = OP_FTRWRITE;   break;
5399         case 'X': ftst = OP_FTREXEC;    break;
5400         case 'O': ftst = OP_FTROWNED;   break;
5401         case 'e': ftst = OP_FTIS;       break;
5402         case 'z': ftst = OP_FTZERO;     break;
5403         case 's': ftst = OP_FTSIZE;     break;
5404         case 'f': ftst = OP_FTFILE;     break;
5405         case 'd': ftst = OP_FTDIR;      break;
5406         case 'l': ftst = OP_FTLINK;     break;
5407         case 'p': ftst = OP_FTPIPE;     break;
5408         case 'S': ftst = OP_FTSOCK;     break;
5409         case 'u': ftst = OP_FTSUID;     break;
5410         case 'g': ftst = OP_FTSGID;     break;
5411         case 'k': ftst = OP_FTSVTX;     break;
5412         case 'b': ftst = OP_FTBLK;      break;
5413         case 'c': ftst = OP_FTCHR;      break;
5414         case 't': ftst = OP_FTTTY;      break;
5415         case 'T': ftst = OP_FTTEXT;     break;
5416         case 'B': ftst = OP_FTBINARY;   break;
5417         case 'M': case 'A': case 'C':
5418             gv_fetchpvs("\024", GV_ADD|GV_NOTQUAL, SVt_PV);
5419             switch (tmp) {
5420             case 'M': ftst = OP_FTMTIME; break;
5421             case 'A': ftst = OP_FTATIME; break;
5422             case 'C': ftst = OP_FTCTIME; break;
5423             default:                     break;
5424             }
5425             break;
5426         default:
5427             break;
5428         }
5429         if (ftst) {
5430             PL_last_uni = PL_oldbufptr;
5431             PL_last_lop_op = (OPCODE)ftst;
5432             DEBUG_T( {
5433                 PerlIO_printf(Perl_debug_log, "### Saw file test %c\n", (int)tmp);
5434             } );
5435             FTST(ftst);
5436         }
5437         else {
5438             /* Assume it was a minus followed by a one-letter named
5439              * subroutine call (or a -bareword), then. */
5440             DEBUG_T( {
5441                 PerlIO_printf(Perl_debug_log,
5442                     "### '-%c' looked like a file test but was not\n",
5443                     (int) tmp);
5444             } );
5445             s = --PL_bufptr;
5446         }
5447     }
5448     {
5449         const char tmp = *s++;
5450         if (*s == tmp) {
5451             s++;
5452             if (PL_expect == XOPERATOR)
5453                 TERM(POSTDEC);
5454             else
5455                 OPERATOR(PREDEC);
5456         }
5457         else if (*s == '>') {
5458             s++;
5459             s = skipspace(s);
5460             if (((*s == '$' || *s == '&') && s[1] == '*')
5461               ||(*s == '$' && s[1] == '#' && s[2] == '*')
5462               ||((*s == '@' || *s == '%') && strchr("*[{", s[1]))
5463               ||(*s == '*' && (s[1] == '*' || s[1] == '{'))
5464              )
5465             {
5466                 PL_expect = XPOSTDEREF;
5467                 TOKEN(ARROW);
5468             }
5469             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5470                 s = force_word(s,METHOD,FALSE,TRUE);
5471                 TOKEN(ARROW);
5472             }
5473             else if (*s == '$')
5474                 OPERATOR(ARROW);
5475             else
5476                 TERM(ARROW);
5477         }
5478         if (PL_expect == XOPERATOR) {
5479             if (*s == '='
5480                 && !PL_lex_allbrackets
5481                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5482             {
5483                 s--;
5484                 TOKEN(0);
5485             }
5486             Aop(OP_SUBTRACT);
5487         }
5488         else {
5489             if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5490                 check_uni();
5491             OPERATOR('-');              /* unary minus */
5492         }
5493     }
5494 }
5495
5496 static int
5497 yyl_plus(pTHX_ char *s)
5498 {
5499     const char tmp = *s++;
5500     if (*s == tmp) {
5501         s++;
5502         if (PL_expect == XOPERATOR)
5503             TERM(POSTINC);
5504         else
5505             OPERATOR(PREINC);
5506     }
5507     if (PL_expect == XOPERATOR) {
5508         if (*s == '='
5509             && !PL_lex_allbrackets
5510             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5511         {
5512             s--;
5513             TOKEN(0);
5514         }
5515         Aop(OP_ADD);
5516     }
5517     else {
5518         if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5519             check_uni();
5520         OPERATOR('+');
5521     }
5522 }
5523
5524 static int
5525 yyl_star(pTHX_ char *s)
5526 {
5527     if (PL_expect == XPOSTDEREF)
5528         POSTDEREF('*');
5529
5530     if (PL_expect != XOPERATOR) {
5531         s = scan_ident(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE);
5532         PL_expect = XOPERATOR;
5533         force_ident(PL_tokenbuf, '*');
5534         if (!*PL_tokenbuf)
5535             PREREF('*');
5536         TERM('*');
5537     }
5538
5539     s++;
5540     if (*s == '*') {
5541         s++;
5542         if (*s == '=' && !PL_lex_allbrackets
5543             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5544         {
5545             s -= 2;
5546             TOKEN(0);
5547         }
5548         PWop(OP_POW);
5549     }
5550
5551     if (*s == '='
5552         && !PL_lex_allbrackets
5553         && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5554     {
5555         s--;
5556         TOKEN(0);
5557     }
5558
5559     Mop(OP_MULTIPLY);
5560 }
5561
5562 static int
5563 yyl_percent(pTHX_ char *s)
5564 {
5565     if (PL_expect == XOPERATOR) {
5566         if (s[1] == '='
5567             && !PL_lex_allbrackets
5568             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5569         {
5570             TOKEN(0);
5571         }
5572         ++s;
5573         Mop(OP_MODULO);
5574     }
5575     else if (PL_expect == XPOSTDEREF)
5576         POSTDEREF('%');
5577
5578     PL_tokenbuf[0] = '%';
5579     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
5580     pl_yylval.ival = 0;
5581     if (!PL_tokenbuf[1]) {
5582         PREREF('%');
5583     }
5584     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
5585         && intuit_more(s, PL_bufend)) {
5586         if (*s == '[')
5587             PL_tokenbuf[0] = '@';
5588     }
5589     PL_expect = XOPERATOR;
5590     force_ident_maybe_lex('%');
5591     TERM('%');
5592 }
5593
5594 static int
5595 yyl_caret(pTHX_ char *s)
5596 {
5597     char *d = s;
5598     const bool bof = cBOOL(FEATURE_BITWISE_IS_ENABLED);
5599     if (bof && s[1] == '.')
5600         s++;
5601     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
5602             (s[1] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE))
5603     {
5604         s = d;
5605         TOKEN(0);
5606     }
5607     s++;
5608     BOop(bof ? d == s-2 ? OP_SBIT_XOR : OP_NBIT_XOR : OP_BIT_XOR);
5609 }
5610
5611 static int
5612 yyl_colon(pTHX_ char *s)
5613 {
5614     OP *attrs;
5615
5616     switch (PL_expect) {
5617     case XOPERATOR:
5618         if (!PL_in_my || (PL_lex_state != LEX_NORMAL && !PL_lex_brackets))
5619             break;
5620         PL_bufptr = s;  /* update in case we back off */
5621         if (*s == '=') {
5622             Perl_croak(aTHX_
5623                        "Use of := for an empty attribute list is not allowed");
5624         }
5625         goto grabattrs;
5626     case XATTRBLOCK:
5627         PL_expect = XBLOCK;
5628         goto grabattrs;
5629     case XATTRTERM:
5630         PL_expect = XTERMBLOCK;
5631      grabattrs:
5632         /* NB: as well as parsing normal attributes, we also end up
5633          * here if there is something looking like attributes
5634          * following a signature (which is illegal, but used to be
5635          * legal in 5.20..5.26). If the latter, we still parse the
5636          * attributes so that error messages(s) are less confusing,
5637          * but ignore them (parser->sig_seen).
5638          */
5639         s = skipspace(s);
5640         attrs = NULL;
5641         while (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5642             bool sig = PL_parser->sig_seen;
5643             I32 tmp;
5644             SV *sv;
5645             STRLEN len;
5646             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
5647             if (isLOWER(*s) && (tmp = keyword(PL_tokenbuf, len, 0))) {
5648                 if (tmp < 0) tmp = -tmp;
5649                 switch (tmp) {
5650                 case KEY_or:
5651                 case KEY_and:
5652                 case KEY_for:
5653                 case KEY_foreach:
5654                 case KEY_unless:
5655                 case KEY_if:
5656                 case KEY_while:
5657                 case KEY_until:
5658                     goto got_attrs;
5659                 default:
5660                     break;
5661                 }
5662             }
5663             sv = newSVpvn_flags(s, len, UTF ? SVf_UTF8 : 0);
5664             if (*d == '(') {
5665                 d = scan_str(d,TRUE,TRUE,FALSE,NULL);
5666                 if (!d) {
5667                     if (attrs)
5668                         op_free(attrs);
5669                     sv_free(sv);
5670                     Perl_croak(aTHX_ "Unterminated attribute parameter in attribute list");
5671                 }
5672                 COPLINE_SET_FROM_MULTI_END;
5673             }
5674             if (PL_lex_stuff) {
5675                 sv_catsv(sv, PL_lex_stuff);
5676                 attrs = op_append_elem(OP_LIST, attrs,
5677                                     newSVOP(OP_CONST, 0, sv));
5678                 SvREFCNT_dec_NN(PL_lex_stuff);
5679                 PL_lex_stuff = NULL;
5680             }
5681             else {
5682                 /* NOTE: any CV attrs applied here need to be part of
5683                    the CVf_BUILTIN_ATTRS define in cv.h! */
5684                 if (!PL_in_my && memEQs(SvPVX(sv), len, "lvalue")) {
5685                     sv_free(sv);
5686                     if (!sig)
5687                         CvLVALUE_on(PL_compcv);
5688                 }
5689                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "method")) {
5690                     sv_free(sv);
5691                     if (!sig)
5692                         CvMETHOD_on(PL_compcv);
5693                 }
5694                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "const")) {
5695                     sv_free(sv);
5696                     if (!sig) {
5697                         Perl_ck_warner_d(aTHX_
5698                             packWARN(WARN_EXPERIMENTAL__CONST_ATTR),
5699                            ":const is experimental"
5700                         );
5701                         CvANONCONST_on(PL_compcv);
5702                         if (!CvANON(PL_compcv))
5703                             yyerror(":const is not permitted on named "
5704                                     "subroutines");
5705                     }
5706                 }
5707                 /* After we've set the flags, it could be argued that
5708                    we don't need to do the attributes.pm-based setting
5709                    process, and shouldn't bother appending recognized
5710                    flags.  To experiment with that, uncomment the
5711                    following "else".  (Note that's already been
5712                    uncommented.  That keeps the above-applied built-in
5713                    attributes from being intercepted (and possibly
5714                    rejected) by a package's attribute routines, but is
5715                    justified by the performance win for the common case
5716                    of applying only built-in attributes.) */
5717                 else
5718                     attrs = op_append_elem(OP_LIST, attrs,
5719                                         newSVOP(OP_CONST, 0,
5720                                                 sv));
5721             }
5722             s = skipspace(d);
5723             if (*s == ':' && s[1] != ':')
5724                 s = skipspace(s+1);
5725             else if (s == d)
5726                 break;  /* require real whitespace or :'s */
5727             /* XXX losing whitespace on sequential attributes here */
5728         }
5729
5730         if (*s != ';'
5731             && *s != '}'
5732             && !(PL_expect == XOPERATOR
5733                  ? (*s == '=' ||  *s == ')')
5734                  : (*s == '{' ||  *s == '(')))
5735         {
5736             const char q = ((*s == '\'') ? '"' : '\'');
5737             /* If here for an expression, and parsed no attrs, back off. */
5738             if (PL_expect == XOPERATOR && !attrs) {
5739                 s = PL_bufptr;
5740                 break;
5741             }
5742             /* MUST advance bufptr here to avoid bogus "at end of line"
5743                context messages from yyerror().
5744             */
5745             PL_bufptr = s;
5746             yyerror( (const char *)
5747                      (*s
5748                       ? Perl_form(aTHX_ "Invalid separator character "
5749                                   "%c%c%c in attribute list", q, *s, q)
5750                       : "Unterminated attribute list" ) );
5751             if (attrs)
5752                 op_free(attrs);
5753             OPERATOR(':');
5754         }
5755
5756     got_attrs:
5757         if (PL_parser->sig_seen) {
5758             /* see comment about about sig_seen and parser error
5759              * handling */
5760             if (attrs)
5761                 op_free(attrs);
5762             Perl_croak(aTHX_ "Subroutine attributes must come "
5763                              "before the signature");
5764         }
5765         if (attrs) {
5766             NEXTVAL_NEXTTOKE.opval = attrs;
5767             force_next(THING);
5768         }
5769         TOKEN(COLONATTR);
5770     }
5771
5772     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING) {
5773         s--;
5774         TOKEN(0);
5775     }
5776
5777     PL_lex_allbrackets--;
5778     OPERATOR(':');
5779 }
5780
5781 static int
5782 yyl_subproto(pTHX_ char *s, CV *cv)
5783 {
5784     STRLEN protolen = CvPROTOLEN(cv);
5785     const char *proto = CvPROTO(cv);
5786     bool optional;
5787
5788     proto = S_strip_spaces(aTHX_ proto, &protolen);
5789     if (!protolen)
5790         TERM(FUNC0SUB);
5791     if ((optional = *proto == ';')) {
5792         do {
5793             proto++;
5794         } while (*proto == ';');
5795     }
5796
5797     if (
5798         (
5799             (
5800                 *proto == '$' || *proto == '_'
5801              || *proto == '*' || *proto == '+'
5802             )
5803          && proto[1] == '\0'
5804         )
5805      || (
5806          *proto == '\\' && proto[1] && proto[2] == '\0'
5807         )
5808     ) {
5809         UNIPROTO(UNIOPSUB,optional);
5810     }
5811
5812     if (*proto == '\\' && proto[1] == '[') {
5813         const char *p = proto + 2;
5814         while(*p && *p != ']')
5815             ++p;
5816         if(*p == ']' && !p[1])
5817             UNIPROTO(UNIOPSUB,optional);
5818     }
5819
5820     if (*proto == '&' && *s == '{') {
5821         if (PL_curstash)
5822             sv_setpvs(PL_subname, "__ANON__");
5823         else
5824             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5825         if (!PL_lex_allbrackets
5826             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
5827         {
5828             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
5829         }
5830         PREBLOCK(LSTOPSUB);
5831     }
5832
5833     return KEY_NULL;
5834 }
5835
5836 static int
5837 yyl_leftcurly(pTHX_ char *s, const U8 formbrack)
5838 {
5839     char *d;
5840     if (PL_lex_brackets > 100) {
5841         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
5842     }
5843
5844     switch (PL_expect) {
5845     case XTERM:
5846     case XTERMORDORDOR:
5847         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5848         PL_lex_allbrackets++;
5849         OPERATOR(HASHBRACK);
5850     case XOPERATOR:
5851         while (s < PL_bufend && SPACE_OR_TAB(*s))
5852             s++;
5853         d = s;
5854         PL_tokenbuf[0] = '\0';
5855         if (d < PL_bufend && *d == '-') {
5856             PL_tokenbuf[0] = '-';
5857             d++;
5858             while (d < PL_bufend && SPACE_OR_TAB(*d))
5859                 d++;
5860         }
5861         if (d < PL_bufend && isIDFIRST_lazy_if_safe(d, PL_bufend, UTF)) {
5862             STRLEN len;
5863             d = scan_word(d, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
5864                           FALSE, &len);
5865             while (d < PL_bufend && SPACE_OR_TAB(*d))
5866                 d++;
5867             if (*d == '}') {
5868                 const char minus = (PL_tokenbuf[0] == '-');
5869                 s = force_word(s + minus, BAREWORD, FALSE, TRUE);
5870                 if (minus)
5871                     force_next('-');
5872             }
5873         }
5874         /* FALLTHROUGH */
5875     case XATTRTERM:
5876     case XTERMBLOCK:
5877         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5878         PL_lex_allbrackets++;
5879         PL_expect = XSTATE;
5880         break;
5881     case XATTRBLOCK:
5882     case XBLOCK:
5883         PL_lex_brackstack[PL_lex_brackets++] = XSTATE;
5884         PL_lex_allbrackets++;
5885         PL_expect = XSTATE;
5886         break;
5887     case XBLOCKTERM:
5888         PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5889         PL_lex_allbrackets++;
5890         PL_expect = XSTATE;
5891         break;
5892     default: {
5893             const char *t;
5894             if (PL_oldoldbufptr == PL_last_lop)
5895                 PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5896             else
5897                 PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5898             PL_lex_allbrackets++;
5899             s = skipspace(s);
5900             if (*s == '}') {
5901                 if (PL_expect == XREF && PL_lex_state == LEX_INTERPNORMAL) {
5902                     PL_expect = XTERM;
5903                     /* This hack is to get the ${} in the message. */
5904                     PL_bufptr = s+1;
5905                     yyerror("syntax error");
5906                     break;
5907                 }
5908                 OPERATOR(HASHBRACK);
5909             }
5910             if (PL_expect == XREF && PL_oldoldbufptr != PL_last_lop) {
5911                 /* ${...} or @{...} etc., but not print {...}
5912                  * Skip the disambiguation and treat this as a block.
5913                  */
5914                 goto block_expectation;
5915             }
5916             /* This hack serves to disambiguate a pair of curlies
5917              * as being a block or an anon hash.  Normally, expectation
5918              * determines that, but in cases where we're not in a
5919              * position to expect anything in particular (like inside
5920              * eval"") we have to resolve the ambiguity.  This code
5921              * covers the case where the first term in the curlies is a
5922              * quoted string.  Most other cases need to be explicitly
5923              * disambiguated by prepending a "+" before the opening
5924              * curly in order to force resolution as an anon hash.
5925              *
5926              * XXX should probably propagate the outer expectation
5927              * into eval"" to rely less on this hack, but that could
5928              * potentially break current behavior of eval"".
5929              * GSAR 97-07-21
5930              */
5931             t = s;
5932             if (*s == '\'' || *s == '"' || *s == '`') {
5933                 /* common case: get past first string, handling escapes */
5934                 for (t++; t < PL_bufend && *t != *s;)
5935                     if (*t++ == '\\')
5936                         t++;
5937                 t++;
5938             }
5939             else if (*s == 'q') {
5940                 if (++t < PL_bufend
5941                     && (!isWORDCHAR(*t)
5942                         || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
5943                             && !isWORDCHAR(*t))))
5944                 {
5945                     /* skip q//-like construct */
5946                     const char *tmps;
5947                     char open, close, term;
5948                     I32 brackets = 1;
5949
5950                     while (t < PL_bufend && isSPACE(*t))
5951                         t++;
5952                     /* check for q => */
5953                     if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
5954                         OPERATOR(HASHBRACK);
5955                     }
5956                     term = *t;
5957                     open = term;
5958                     if (term && (tmps = strchr("([{< )]}> )]}>",term)))
5959                         term = tmps[5];
5960                     close = term;
5961                     if (open == close)
5962                         for (t++; t < PL_bufend; t++) {
5963                             if (*t == '\\' && t+1 < PL_bufend && open != '\\')
5964                                 t++;
5965                             else if (*t == open)
5966                                 break;
5967                         }
5968                     else {
5969                         for (t++; t < PL_bufend; t++) {
5970                             if (*t == '\\' && t+1 < PL_bufend)
5971                                 t++;
5972                             else if (*t == close && --brackets <= 0)
5973                                 break;
5974                             else if (*t == open)
5975                                 brackets++;
5976                         }
5977                     }
5978                     t++;
5979                 }
5980                 else
5981                     /* skip plain q word */
5982                     while (   t < PL_bufend
5983                            && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
5984                     {
5985                         t += UTF ? UTF8SKIP(t) : 1;
5986                     }
5987             }
5988             else if (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)) {
5989                 t += UTF ? UTF8SKIP(t) : 1;
5990                 while (   t < PL_bufend
5991                        && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
5992                 {
5993                     t += UTF ? UTF8SKIP(t) : 1;
5994                 }
5995             }
5996             while (t < PL_bufend && isSPACE(*t))
5997                 t++;
5998             /* if comma follows first term, call it an anon hash */
5999             /* XXX it could be a comma expression with loop modifiers */
6000             if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
6001                                || (*t == '=' && t[1] == '>')))
6002                 OPERATOR(HASHBRACK);
6003             if (PL_expect == XREF) {
6004               block_expectation:
6005                 /* If there is an opening brace or 'sub:', treat it
6006                    as a term to make ${{...}}{k} and &{sub:attr...}
6007                    dwim.  Otherwise, treat it as a statement, so
6008                    map {no strict; ...} works.
6009                  */
6010                 s = skipspace(s);
6011                 if (*s == '{') {
6012                     PL_expect = XTERM;
6013                     break;
6014                 }
6015                 if (memBEGINs(s, (STRLEN) (PL_bufend - s), "sub")) {
6016                     PL_bufptr = s;
6017                     d = s + 3;
6018                     d = skipspace(d);
6019                     s = PL_bufptr;
6020                     if (*d == ':') {
6021                         PL_expect = XTERM;
6022                         break;
6023                     }
6024                 }
6025                 PL_expect = XSTATE;
6026             }
6027             else {
6028                 PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
6029                 PL_expect = XSTATE;
6030             }
6031         }
6032         break;
6033     }
6034
6035     pl_yylval.ival = CopLINE(PL_curcop);
6036     PL_copline = NOLINE;   /* invalidate current command line number */
6037     TOKEN(formbrack ? '=' : '{');
6038 }
6039
6040 static int
6041 yyl_rightcurly(pTHX_ char *s, const U8 formbrack)
6042 {
6043     assert(s != PL_bufend);
6044     s++;
6045
6046     if (PL_lex_brackets <= 0)
6047         /* diag_listed_as: Unmatched right %s bracket */
6048         yyerror("Unmatched right curly bracket");
6049     else
6050         PL_expect = (expectation)PL_lex_brackstack[--PL_lex_brackets];
6051
6052     PL_lex_allbrackets--;
6053
6054     if (PL_lex_state == LEX_INTERPNORMAL) {
6055         if (PL_lex_brackets == 0) {
6056             if (PL_expect & XFAKEBRACK) {
6057                 PL_expect &= XENUMMASK;
6058                 PL_lex_state = LEX_INTERPEND;
6059                 PL_bufptr = s;
6060                 return yylex(); /* ignore fake brackets */
6061             }
6062             if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6063              && SvEVALED(PL_lex_repl))
6064                 PL_lex_state = LEX_INTERPEND;
6065             else if (*s == '-' && s[1] == '>')
6066                 PL_lex_state = LEX_INTERPENDMAYBE;
6067             else if (*s != '[' && *s != '{')
6068                 PL_lex_state = LEX_INTERPEND;
6069         }
6070     }
6071
6072     if (PL_expect & XFAKEBRACK) {
6073         PL_expect &= XENUMMASK;
6074         PL_bufptr = s;
6075         return yylex();         /* ignore fake brackets */
6076     }
6077
6078     force_next(formbrack ? '.' : '}');
6079     if (formbrack) LEAVE_with_name("lex_format");
6080     if (formbrack == 2) { /* means . where arguments were expected */
6081         force_next(';');
6082         TOKEN(FORMRBRACK);
6083     }
6084
6085     TOKEN(';');
6086 }
6087
6088 static int
6089 yyl_ampersand(pTHX_ char *s)
6090 {
6091     if (PL_expect == XPOSTDEREF)
6092         POSTDEREF('&');
6093
6094     s++;
6095     if (*s++ == '&') {
6096         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6097                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6098             s -= 2;
6099             TOKEN(0);
6100         }
6101         AOPERATOR(ANDAND);
6102     }
6103     s--;
6104
6105     if (PL_expect == XOPERATOR) {
6106         char *d;
6107         bool bof;
6108         if (   PL_bufptr == PL_linestart
6109             && ckWARN(WARN_SEMICOLON)
6110             && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
6111         {
6112             CopLINE_dec(PL_curcop);
6113             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6114             CopLINE_inc(PL_curcop);
6115         }
6116         d = s;
6117         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6118             s++;
6119         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6120                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6121             s = d;
6122             s--;
6123             TOKEN(0);
6124         }
6125         if (d == s)
6126             BAop(bof ? OP_NBIT_AND : OP_BIT_AND);
6127         else
6128             BAop(OP_SBIT_AND);
6129     }
6130
6131     PL_tokenbuf[0] = '&';
6132     s = scan_ident(s - 1, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, TRUE);
6133     pl_yylval.ival = (OPpENTERSUB_AMPER<<8);
6134
6135     if (PL_tokenbuf[1])
6136         force_ident_maybe_lex('&');
6137     else
6138         PREREF('&');
6139
6140     TERM('&');
6141 }
6142
6143 static int
6144 yyl_verticalbar(pTHX_ char *s)
6145 {
6146     char *d;
6147     bool bof;
6148
6149     s++;
6150     if (*s++ == '|') {
6151         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6152                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6153             s -= 2;
6154             TOKEN(0);
6155         }
6156         AOPERATOR(OROR);
6157     }
6158
6159     s--;
6160     d = s;
6161     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6162         s++;
6163
6164     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6165             (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6166         s = d - 1;
6167         TOKEN(0);
6168     }
6169
6170     BOop(bof ? s == d ? OP_NBIT_OR : OP_SBIT_OR : OP_BIT_OR);
6171 }
6172
6173 static int
6174 yyl_bang(pTHX_ char *s)
6175 {
6176     const char tmp = *s++;
6177     if (tmp == '=') {
6178         /* was this !=~ where !~ was meant?
6179          * warn on m:!=~\s+([/?]|[msy]\W|tr\W): */
6180
6181         if (*s == '~' && ckWARN(WARN_SYNTAX)) {
6182             const char *t = s+1;
6183
6184             while (t < PL_bufend && isSPACE(*t))
6185                 ++t;
6186
6187             if (*t == '/' || *t == '?'
6188                 || ((*t == 'm' || *t == 's' || *t == 'y')
6189                     && !isWORDCHAR(t[1]))
6190                 || (*t == 't' && t[1] == 'r' && !isWORDCHAR(t[2])))
6191                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6192                             "!=~ should be !~");
6193         }
6194
6195         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6196             s -= 2;
6197             TOKEN(0);
6198         }
6199
6200         Eop(OP_NE);
6201     }
6202
6203     if (tmp == '~')
6204         PMop(OP_NOT);
6205
6206     s--;
6207     OPERATOR('!');
6208 }
6209
6210 static int
6211 yyl_snail(pTHX_ char *s)
6212 {
6213     if (PL_expect == XPOSTDEREF)
6214         POSTDEREF('@');
6215     PL_tokenbuf[0] = '@';
6216     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6217     if (PL_expect == XOPERATOR) {
6218         char *d = s;
6219         if (PL_bufptr > s) {
6220             d = PL_bufptr-1;
6221             PL_bufptr = PL_oldbufptr;
6222         }
6223         no_op("Array", d);
6224     }
6225     pl_yylval.ival = 0;
6226     if (!PL_tokenbuf[1]) {
6227         PREREF('@');
6228     }
6229     if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
6230         s = skipspace(s);
6231     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6232         && intuit_more(s, PL_bufend))
6233     {
6234         if (*s == '{')
6235             PL_tokenbuf[0] = '%';
6236
6237         /* Warn about @ where they meant $. */
6238         if (*s == '[' || *s == '{') {
6239             if (ckWARN(WARN_SYNTAX)) {
6240                 S_check_scalar_slice(aTHX_ s);
6241             }
6242         }
6243     }
6244     PL_expect = XOPERATOR;
6245     force_ident_maybe_lex('@');
6246     TERM('@');
6247 }
6248
6249 static int
6250 yyl_slash(pTHX_ char *s)
6251 {
6252     if ((PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR) && s[1] == '/') {
6253         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6254                 (s[2] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC))
6255             TOKEN(0);
6256         s += 2;
6257         AOPERATOR(DORDOR);
6258     }
6259     else if (PL_expect == XOPERATOR) {
6260         s++;
6261         if (*s == '=' && !PL_lex_allbrackets
6262             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6263         {
6264             s--;
6265             TOKEN(0);
6266         }
6267         Mop(OP_DIVIDE);
6268     }
6269     else {
6270         /* Disable warning on "study /blah/" */
6271         if (    PL_oldoldbufptr == PL_last_uni
6272             && (   *PL_last_uni != 's' || s - PL_last_uni < 5
6273                 || memNE(PL_last_uni, "study", 5)
6274                 || isWORDCHAR_lazy_if_safe(PL_last_uni+5, PL_bufend, UTF)
6275          ))
6276             check_uni();
6277         s = scan_pat(s,OP_MATCH);
6278         TERM(sublex_start());
6279     }
6280 }
6281
6282 static int
6283 yyl_leftsquare(pTHX_ char *s)
6284 {
6285     char tmp;
6286
6287     if (PL_lex_brackets > 100)
6288         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
6289     PL_lex_brackstack[PL_lex_brackets++] = 0;
6290     PL_lex_allbrackets++;
6291     tmp = *s++;
6292     OPERATOR(tmp);
6293 }
6294
6295 static int
6296 yyl_rightsquare(pTHX_ char *s)
6297 {
6298     if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
6299         TOKEN(0);
6300     s++;
6301     if (PL_lex_brackets <= 0)
6302         /* diag_listed_as: Unmatched right %s bracket */
6303         yyerror("Unmatched right square bracket");
6304     else
6305         --PL_lex_brackets;
6306     PL_lex_allbrackets--;
6307     if (PL_lex_state == LEX_INTERPNORMAL) {
6308         if (PL_lex_brackets == 0) {
6309             if (*s == '-' && s[1] == '>')
6310                 PL_lex_state = LEX_INTERPENDMAYBE;
6311             else if (*s != '[' && *s != '{')
6312                 PL_lex_state = LEX_INTERPEND;
6313         }
6314     }
6315     TERM(']');
6316 }
6317
6318 static int
6319 yyl_tilde(pTHX_ char *s)
6320 {
6321     bool bof;
6322     if (s[1] == '~' && (PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR)) {
6323         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6324             TOKEN(0);
6325         s += 2;
6326         Perl_ck_warner_d(aTHX_
6327             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
6328             "Smartmatch is experimental");
6329         Eop(OP_SMARTMATCH);
6330     }
6331     s++;
6332     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.') {
6333         s++;
6334         BCop(OP_SCOMPLEMENT);
6335     }
6336     BCop(bof ? OP_NCOMPLEMENT : OP_COMPLEMENT);
6337 }
6338
6339 static int
6340 yyl_leftparen(pTHX_ char *s)
6341 {
6342     if (PL_last_lop == PL_oldoldbufptr || PL_last_uni == PL_oldoldbufptr)
6343         PL_oldbufptr = PL_oldoldbufptr;         /* allow print(STDOUT 123) */
6344     else
6345         PL_expect = XTERM;
6346     s = skipspace(s);
6347     PL_lex_allbrackets++;
6348     TOKEN('(');
6349 }
6350
6351 static int
6352 yyl_rightparen(pTHX_ char *s)
6353 {
6354     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING)
6355         TOKEN(0);
6356     s++;
6357     PL_lex_allbrackets--;
6358     s = skipspace(s);
6359     if (*s == '{')
6360         PREBLOCK(')');
6361     TERM(')');
6362 }
6363
6364 static int
6365 yyl_leftpointy(pTHX_ char *s)
6366 {
6367     char tmp;
6368
6369     if (PL_expect != XOPERATOR) {
6370         if (s[1] != '<' && !memchr(s,'>', PL_bufend - s))
6371             check_uni();
6372         if (s[1] == '<' && s[2] != '>')
6373             s = scan_heredoc(s);
6374         else
6375             s = scan_inputsymbol(s);
6376         PL_expect = XOPERATOR;
6377         TOKEN(sublex_start());
6378     }
6379
6380     s++;
6381
6382     tmp = *s++;
6383     if (tmp == '<') {
6384         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6385             s -= 2;
6386             TOKEN(0);
6387         }
6388         SHop(OP_LEFT_SHIFT);
6389     }
6390     if (tmp == '=') {
6391         tmp = *s++;
6392         if (tmp == '>') {
6393             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6394                 s -= 3;
6395                 TOKEN(0);
6396             }
6397             Eop(OP_NCMP);
6398         }
6399         s--;
6400         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6401             s -= 2;
6402             TOKEN(0);
6403         }
6404         Rop(OP_LE);
6405     }
6406
6407     s--;
6408     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6409         s--;
6410         TOKEN(0);
6411     }
6412
6413     Rop(OP_LT);
6414 }
6415
6416 static int
6417 yyl_rightpointy(pTHX_ char *s)
6418 {
6419     const char tmp = *s++;
6420
6421     if (tmp == '>') {
6422         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6423             s -= 2;
6424             TOKEN(0);
6425         }
6426         SHop(OP_RIGHT_SHIFT);
6427     }
6428     else if (tmp == '=') {
6429         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6430             s -= 2;
6431             TOKEN(0);
6432         }
6433         Rop(OP_GE);
6434     }
6435
6436     s--;
6437     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6438         s--;
6439         TOKEN(0);
6440     }
6441
6442     Rop(OP_GT);
6443 }
6444
6445 static int
6446 yyl_sglquote(pTHX_ char *s)
6447 {
6448     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6449     if (!s)
6450         missingterm(NULL, 0);
6451     COPLINE_SET_FROM_MULTI_END;
6452     DEBUG_T( { printbuf("### Saw string before %s\n", s); } );
6453     if (PL_expect == XOPERATOR) {
6454         no_op("String",s);
6455     }
6456     pl_yylval.ival = OP_CONST;
6457     TERM(sublex_start());
6458 }
6459
6460 static int
6461 yyl_dblquote(pTHX_ char *s, STRLEN len)
6462 {
6463     char *d;
6464     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6465     DEBUG_T( {
6466         if (s)
6467             printbuf("### Saw string before %s\n", s);
6468         else
6469             PerlIO_printf(Perl_debug_log,
6470                          "### Saw unterminated string\n");
6471     } );
6472     if (PL_expect == XOPERATOR) {
6473             no_op("String",s);
6474     }
6475     if (!s)
6476         missingterm(NULL, 0);
6477     pl_yylval.ival = OP_CONST;
6478     /* FIXME. I think that this can be const if char *d is replaced by
6479        more localised variables.  */
6480     for (d = SvPV(PL_lex_stuff, len); len; len--, d++) {
6481         if (*d == '$' || *d == '@' || *d == '\\' || !UTF8_IS_INVARIANT((U8)*d)) {
6482             pl_yylval.ival = OP_STRINGIFY;
6483             break;
6484         }
6485     }
6486     if (pl_yylval.ival == OP_CONST)
6487         COPLINE_SET_FROM_MULTI_END;
6488     TERM(sublex_start());
6489 }
6490
6491 static int
6492 yyl_backtick(pTHX_ char *s)
6493 {
6494     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6495     DEBUG_T( {
6496         if (s)
6497             printbuf("### Saw backtick string before %s\n", s);
6498         else
6499             PerlIO_printf(Perl_debug_log,
6500                          "### Saw unterminated backtick string\n");
6501     } );
6502     if (PL_expect == XOPERATOR)
6503         no_op("Backticks",s);
6504     if (!s)
6505         missingterm(NULL, 0);
6506     pl_yylval.ival = OP_BACKTICK;
6507     TERM(sublex_start());
6508 }
6509
6510 static int
6511 yyl_backslash(pTHX_ char *s)
6512 {
6513     if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr && isDIGIT(*s))
6514         Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),"Can't use \\%c to mean $%c in expression",
6515                        *s, *s);
6516     if (PL_expect == XOPERATOR)
6517         no_op("Backslash",s);
6518     OPERATOR(REFGEN);
6519 }
6520
6521 static void
6522 yyl_data_handle(pTHX)
6523 {
6524     HV * const stash = PL_tokenbuf[2] == 'D' && PL_curstash
6525                             ? PL_curstash
6526                             : PL_defstash;
6527     GV *gv = (GV *)*hv_fetchs(stash, "DATA", 1);
6528
6529     if (!isGV(gv))
6530         gv_init(gv,stash,"DATA",4,0);
6531
6532     GvMULTI_on(gv);
6533     if (!GvIO(gv))
6534         GvIOp(gv) = newIO();
6535     IoIFP(GvIOp(gv)) = PL_rsfp;
6536
6537     /* Mark this internal pseudo-handle as clean */
6538     IoFLAGS(GvIOp(gv)) |= IOf_UNTAINT;
6539     if ((PerlIO*)PL_rsfp == PerlIO_stdin())
6540         IoTYPE(GvIOp(gv)) = IoTYPE_STD;
6541     else
6542         IoTYPE(GvIOp(gv)) = IoTYPE_RDONLY;
6543
6544 #if defined(WIN32) && !defined(PERL_TEXTMODE_SCRIPTS)
6545     /* if the script was opened in binmode, we need to revert
6546      * it to text mode for compatibility; but only iff it has CRs
6547      * XXX this is a questionable hack at best. */
6548     if (PL_bufend-PL_bufptr > 2
6549         && PL_bufend[-1] == '\n' && PL_bufend[-2] == '\r')
6550     {
6551         Off_t loc = 0;
6552         if (IoTYPE(GvIOp(gv)) == IoTYPE_RDONLY) {
6553             loc = PerlIO_tell(PL_rsfp);
6554             (void)PerlIO_seek(PL_rsfp, 0L, 0);
6555         }
6556         if (PerlLIO_setmode(RSFP_FILENO, O_TEXT) != -1) {
6557             if (loc > 0)
6558                 PerlIO_seek(PL_rsfp, loc, 0);
6559         }
6560     }
6561 #endif
6562
6563 #ifdef PERLIO_LAYERS
6564     if (!IN_BYTES) {
6565         if (UTF)
6566             PerlIO_apply_layers(aTHX_ PL_rsfp, NULL, ":utf8");
6567     }
6568 #endif
6569
6570     PL_rsfp = NULL;
6571 }
6572
6573 PERL_STATIC_NO_RET void yyl_croak_unrecognised(pTHX_ char*)
6574     __attribute__noreturn__;
6575
6576 PERL_STATIC_NO_RET void
6577 yyl_croak_unrecognised(pTHX_ char *s)
6578 {
6579     SV *dsv = newSVpvs_flags("", SVs_TEMP);
6580     const char *c;
6581     char *d;
6582     STRLEN len;
6583
6584     if (UTF) {
6585         STRLEN skiplen = UTF8SKIP(s);
6586         STRLEN stravail = PL_bufend - s;
6587         c = sv_uni_display(dsv, newSVpvn_flags(s,
6588                                                skiplen > stravail ? stravail : skiplen,
6589                                                SVs_TEMP | SVf_UTF8),
6590                            10, UNI_DISPLAY_ISPRINT);
6591     }
6592     else {
6593         c = Perl_form(aTHX_ "\\x%02X", (unsigned char)*s);
6594     }
6595
6596     if (s >= PL_linestart) {
6597         d = PL_linestart;
6598     }
6599     else {
6600         /* somehow (probably due to a parse failure), PL_linestart has advanced
6601          * pass PL_bufptr, get a reasonable beginning of line
6602          */
6603         d = s;
6604         while (d > SvPVX(PL_linestr) && d[-1] && d[-1] != '\n')
6605             --d;
6606     }
6607     len = UTF ? Perl_utf8_length(aTHX_ (U8 *) d, (U8 *) s) : (STRLEN) (s - d);
6608     if (len > UNRECOGNIZED_PRECEDE_COUNT) {
6609         d = UTF ? (char *) utf8_hop_back((U8 *) s, -UNRECOGNIZED_PRECEDE_COUNT, (U8 *)d) : s - UNRECOGNIZED_PRECEDE_COUNT;
6610     }
6611
6612     Perl_croak(aTHX_  "Unrecognized character %s; marked by <-- HERE after %" UTF8f "<-- HERE near column %d", c,
6613                       UTF8fARG(UTF, (s - d), d),
6614                      (int) len + 1);
6615 }
6616
6617 static int
6618 yyl_require(pTHX_ char *s, I32 orig_keyword)
6619 {
6620     s = skipspace(s);
6621     if (isDIGIT(*s)) {
6622         s = force_version(s, FALSE);
6623     }
6624     else if (*s != 'v' || !isDIGIT(s[1])
6625             || (s = force_version(s, TRUE), *s == 'v'))
6626     {
6627         *PL_tokenbuf = '\0';
6628         s = force_word(s,BAREWORD,TRUE,TRUE);
6629         if (isIDFIRST_lazy_if_safe(PL_tokenbuf,
6630                                    PL_tokenbuf + sizeof(PL_tokenbuf),
6631                                    UTF))
6632         {
6633             gv_stashpvn(PL_tokenbuf, strlen(PL_tokenbuf),
6634                         GV_ADD | (UTF ? SVf_UTF8 : 0));
6635         }
6636         else if (*s == '<')
6637             yyerror("<> at require-statement should be quotes");
6638     }
6639
6640     if (orig_keyword == KEY_require)
6641         pl_yylval.ival = 1;
6642     else
6643         pl_yylval.ival = 0;
6644
6645     PL_expect = PL_nexttoke ? XOPERATOR : XTERM;
6646     PL_bufptr = s;
6647     PL_last_uni = PL_oldbufptr;
6648     PL_last_lop_op = OP_REQUIRE;
6649     s = skipspace(s);
6650     return REPORT( (int)REQUIRE );
6651 }
6652
6653 static int
6654 yyl_foreach(pTHX_ char *s)
6655 {
6656     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
6657         return REPORT(0);
6658     pl_yylval.ival = CopLINE(PL_curcop);
6659     s = skipspace(s);
6660     if (PL_expect == XSTATE && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6661         char *p = s;
6662         SSize_t s_off = s - SvPVX(PL_linestr);
6663         STRLEN len;
6664
6665         if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "my") && isSPACE(p[2])) {
6666             p += 2;
6667         }
6668         else if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "our") && isSPACE(p[3])) {
6669             p += 3;
6670         }
6671
6672         p = skipspace(p);
6673         /* skip optional package name, as in "for my abc $x (..)" */
6674         if (isIDFIRST_lazy_if_safe(p, PL_bufend, UTF)) {
6675             p = scan_word(p, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6676             p = skipspace(p);
6677         }
6678         if (*p != '$' && *p != '\\')
6679             Perl_croak(aTHX_ "Missing $ on loop variable");
6680
6681         /* The buffer may have been reallocated, update s */
6682         s = SvPVX(PL_linestr) + s_off;
6683     }
6684     OPERATOR(FOR);
6685 }
6686
6687 static int
6688 yyl_do(pTHX_ char *s, I32 orig_keyword)
6689 {
6690     s = skipspace(s);
6691     if (*s == '{')
6692         PRETERMBLOCK(DO);
6693     if (*s != '\'') {
6694         char *d;
6695         STRLEN len;
6696         *PL_tokenbuf = '&';
6697         d = scan_word(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
6698                       1, &len);
6699         if (len && memNEs(PL_tokenbuf+1, len, "CORE")
6700          && !keyword(PL_tokenbuf + 1, len, 0)) {
6701             SSize_t off = s-SvPVX(PL_linestr);
6702             d = skipspace(d);
6703             s = SvPVX(PL_linestr)+off;
6704             if (*d == '(') {
6705                 force_ident_maybe_lex('&');
6706                 s = d;
6707             }
6708         }
6709     }
6710     if (orig_keyword == KEY_do)
6711         pl_yylval.ival = 1;
6712     else
6713         pl_yylval.ival = 0;
6714     OPERATOR(DO);
6715 }
6716
6717 static int
6718 yyl_my(pTHX_ char *s, I32 my)
6719 {
6720     if (PL_in_my) {
6721         PL_bufptr = s;
6722         yyerror(Perl_form(aTHX_
6723                           "Can't redeclare \"%s\" in \"%s\"",
6724                            my       == KEY_my    ? "my" :
6725                            my       == KEY_state ? "state" : "our",
6726                            PL_in_my == KEY_my    ? "my" :
6727                            PL_in_my == KEY_state ? "state" : "our"));
6728     }
6729     PL_in_my = (U16)my;
6730     s = skipspace(s);
6731     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6732         STRLEN len;
6733         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6734         if (memEQs(PL_tokenbuf, len, "sub"))
6735             return yyl_sub(aTHX_ s, my);
6736         PL_in_my_stash = find_in_my_stash(PL_tokenbuf, len);
6737         if (!PL_in_my_stash) {
6738             char tmpbuf[1024];
6739             int i;
6740             PL_bufptr = s;
6741             i = my_snprintf(tmpbuf, sizeof(tmpbuf), "No such class %.1000s", PL_tokenbuf);
6742             PERL_MY_SNPRINTF_POST_GUARD(i, sizeof(tmpbuf));
6743             yyerror_pv(tmpbuf, UTF ? SVf_UTF8 : 0);
6744         }
6745     }
6746     else if (*s == '\\') {
6747         if (!FEATURE_MYREF_IS_ENABLED)
6748             Perl_croak(aTHX_ "The experimental declared_refs "
6749                              "feature is not enabled");
6750         Perl_ck_warner_d(aTHX_
6751              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
6752             "Declaring references is experimental");
6753     }
6754     OPERATOR(MY);
6755 }
6756
6757 static int yyl_try(pTHX_ char*, STRLEN);
6758
6759 static bool
6760 yyl_eol_needs_semicolon(pTHX_ char **ps)
6761 {
6762     char *s = *ps;
6763     if (PL_lex_state != LEX_NORMAL
6764         || (PL_in_eval && !PL_rsfp && !PL_parser->filtered))
6765     {
6766         const bool in_comment = *s == '#';
6767         char *d;
6768         if (*s == '#' && s == PL_linestart && PL_in_eval
6769          && !PL_rsfp && !PL_parser->filtered) {
6770             /* handle eval qq[#line 1 "foo"\n ...] */
6771             CopLINE_dec(PL_curcop);
6772             incline(s, PL_bufend);
6773         }
6774         d = s;
6775         while (d < PL_bufend && *d != '\n')
6776             d++;
6777         if (d < PL_bufend)
6778             d++;
6779         s = d;
6780         if (in_comment && d == PL_bufend
6781             && PL_lex_state == LEX_INTERPNORMAL
6782             && PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6783             && SvEVALED(PL_lex_repl) && d[-1] == '}') s--;
6784         else
6785             incline(s, PL_bufend);
6786         if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
6787             PL_lex_state = LEX_FORMLINE;
6788             force_next(FORMRBRACK);
6789             *ps = s;
6790             return TRUE;
6791         }
6792     }
6793     else {
6794         while (s < PL_bufend && *s != '\n')
6795             s++;
6796         if (s < PL_bufend) {
6797             s++;
6798             if (s < PL_bufend)
6799                 incline(s, PL_bufend);
6800         }
6801     }
6802     *ps = s;
6803     return FALSE;
6804 }
6805
6806 static int
6807 yyl_fake_eof(pTHX_ U32 fake_eof, bool bof, char *s, STRLEN len)
6808 {
6809     char *d;
6810
6811     goto start;
6812
6813     do {
6814         fake_eof = 0;
6815         bof = cBOOL(PL_rsfp);
6816       start:
6817
6818         PL_bufptr = PL_bufend;
6819         COPLINE_INC_WITH_HERELINES;
6820         if (!lex_next_chunk(fake_eof)) {
6821             CopLINE_dec(PL_curcop);
6822             s = PL_bufptr;
6823             TOKEN(';'); /* not infinite loop because rsfp is NULL now */
6824         }
6825         CopLINE_dec(PL_curcop);
6826         s = PL_bufptr;
6827         /* If it looks like the start of a BOM or raw UTF-16,
6828          * check if it in fact is. */
6829         if (bof && PL_rsfp
6830             && (   *s == 0
6831                 || *(U8*)s == BOM_UTF8_FIRST_BYTE
6832                 || *(U8*)s >= 0xFE
6833                 || s[1] == 0))
6834         {
6835             Off_t offset = (IV)PerlIO_tell(PL_rsfp);
6836             bof = (offset == (Off_t)SvCUR(PL_linestr));
6837 #if defined(PERLIO_USING_CRLF) && defined(PERL_TEXTMODE_SCRIPTS)
6838             /* offset may include swallowed CR */
6839             if (!bof)
6840                 bof = (offset == (Off_t)SvCUR(PL_linestr)+1);
6841 #endif
6842             if (bof) {
6843                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6844                 s = swallow_bom((U8*)s);
6845             }
6846         }
6847         if (PL_parser->in_pod) {
6848             /* Incest with pod. */
6849             if (    memBEGINPs(s, (STRLEN) (PL_bufend - s), "=cut")
6850                 && !isALPHA(s[4]))
6851             {
6852                 SvPVCLEAR(PL_linestr);
6853                 PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
6854                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6855                 PL_last_lop = PL_last_uni = NULL;
6856                 PL_parser->in_pod = 0;
6857             }
6858         }
6859         if (PL_rsfp || PL_parser->filtered)
6860             incline(s, PL_bufend);
6861     } while (PL_parser->in_pod);
6862
6863     PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = PL_linestart = s;
6864     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6865     PL_last_lop = PL_last_uni = NULL;
6866     if (CopLINE(PL_curcop) == 1) {
6867         while (s < PL_bufend && isSPACE(*s))
6868             s++;
6869         if (*s == ':' && s[1] != ':') /* for csh execing sh scripts */
6870             s++;
6871         d = NULL;
6872         if (!PL_in_eval) {
6873             if (*s == '#' && *(s+1) == '!')
6874                 d = s + 2;
6875 #ifdef ALTERNATE_SHEBANG
6876             else {
6877                 static char const as[] = ALTERNATE_SHEBANG;
6878                 if (*s == as[0] && strnEQ(s, as, sizeof(as) - 1))
6879                     d = s + (sizeof(as) - 1);
6880             }
6881 #endif /* ALTERNATE_SHEBANG */
6882         }
6883         if (d) {
6884             char *ipath;
6885             char *ipathend;
6886
6887             while (isSPACE(*d))
6888                 d++;
6889             ipath = d;
6890             while (*d && !isSPACE(*d))
6891                 d++;
6892             ipathend = d;
6893
6894 #ifdef ARG_ZERO_IS_SCRIPT
6895             if (ipathend > ipath) {
6896                 /*
6897                  * HP-UX (at least) sets argv[0] to the script name,
6898                  * which makes $^X incorrect.  And Digital UNIX and Linux,
6899                  * at least, set argv[0] to the basename of the Perl
6900                  * interpreter. So, having found "#!", we'll set it right.
6901                  */
6902                 SV* copfilesv = CopFILESV(PL_curcop);
6903                 if (copfilesv) {
6904                     SV * const x =
6905                         GvSV(gv_fetchpvs("\030", GV_ADD|GV_NOTQUAL,
6906                                          SVt_PV)); /* $^X */
6907                     assert(SvPOK(x) || SvGMAGICAL(x));
6908                     if (sv_eq(x, copfilesv)) {
6909                         sv_setpvn(x, ipath, ipathend - ipath);
6910                         SvSETMAGIC(x);
6911                     }
6912                     else {
6913                         STRLEN blen;
6914                         STRLEN llen;
6915                         const char *bstart = SvPV_const(copfilesv, blen);
6916                         const char * const lstart = SvPV_const(x, llen);
6917                         if (llen < blen) {
6918                             bstart += blen - llen;
6919                             if (strnEQ(bstart, lstart, llen) && bstart[-1] == '/') {
6920                                 sv_setpvn(x, ipath, ipathend - ipath);
6921                                 SvSETMAGIC(x);
6922                             }
6923                         }
6924                     }
6925                 }
6926                 else {
6927                     /* Anything to do if no copfilesv? */
6928                 }
6929                 TAINT_NOT;      /* $^X is always tainted, but that's OK */
6930             }
6931 #endif /* ARG_ZERO_IS_SCRIPT */
6932
6933             /*
6934              * Look for options.
6935              */
6936             d = instr(s,"perl -");
6937             if (!d) {
6938                 d = instr(s,"perl");
6939 #if defined(DOSISH)
6940                 /* avoid getting into infinite loops when shebang
6941                  * line contains "Perl" rather than "perl" */
6942                 if (!d) {
6943                     for (d = ipathend-4; d >= ipath; --d) {
6944                         if (isALPHA_FOLD_EQ(*d, 'p')
6945                             && !ibcmp(d, "perl", 4))
6946                         {
6947                             break;
6948                         }
6949                     }
6950                     if (d < ipath)
6951                         d = NULL;
6952                 }
6953 #endif
6954             }
6955 #ifdef ALTERNATE_SHEBANG
6956             /*
6957              * If the ALTERNATE_SHEBANG on this system starts with a
6958              * character that can be part of a Perl expression, then if
6959              * we see it but not "perl", we're probably looking at the
6960              * start of Perl code, not a request to hand off to some
6961              * other interpreter.  Similarly, if "perl" is there, but
6962              * not in the first 'word' of the line, we assume the line
6963              * contains the start of the Perl program.
6964              */
6965             if (d && *s != '#') {
6966                 const char *c = ipath;
6967                 while (*c && !strchr("; \t\r\n\f\v#", *c))
6968                     c++;
6969                 if (c < d)
6970                     d = NULL;   /* "perl" not in first word; ignore */
6971                 else
6972                     *s = '#';   /* Don't try to parse shebang line */
6973             }
6974 #endif /* ALTERNATE_SHEBANG */
6975             if (!d
6976                 && *s == '#'
6977                 && ipathend > ipath
6978                 && !PL_minus_c
6979                 && !instr(s,"indir")
6980                 && instr(PL_origargv[0],"perl"))
6981             {
6982                 dVAR;
6983                 char **newargv;
6984
6985                 *ipathend = '\0';
6986                 s = ipathend + 1;
6987                 while (s < PL_bufend && isSPACE(*s))
6988                     s++;
6989                 if (s < PL_bufend) {
6990                     Newx(newargv,PL_origargc+3,char*);
6991                     newargv[1] = s;
6992                     while (s < PL_bufend && !isSPACE(*s))
6993                         s++;
6994                     *s = '\0';
6995                     Copy(PL_origargv+1, newargv+2, PL_origargc+1, char*);
6996                 }
6997                 else
6998                     newargv = PL_origargv;
6999                 newargv[0] = ipath;
7000                 PERL_FPU_PRE_EXEC
7001                 PerlProc_execv(ipath, EXEC_ARGV_CAST(newargv));
7002                 PERL_FPU_POST_EXEC
7003                 Perl_croak(aTHX_ "Can't exec %s", ipath);
7004             }
7005             if (d) {
7006                 while (*d && !isSPACE(*d))
7007                     d++;
7008                 while (SPACE_OR_TAB(*d))
7009                     d++;
7010
7011                 if (*d++ == '-') {
7012                     const bool switches_done = PL_doswitches;
7013                     const U32 oldpdb = PL_perldb;
7014                     const bool oldn = PL_minus_n;
7015                     const bool oldp = PL_minus_p;
7016                     const char *d1 = d;
7017
7018                     do {
7019                         bool baduni = FALSE;
7020                         if (*d1 == 'C') {
7021                             const char *d2 = d1 + 1;
7022                             if (parse_unicode_opts((const char **)&d2)
7023                                 != PL_unicode)
7024                                 baduni = TRUE;
7025                         }
7026                         if (baduni || isALPHA_FOLD_EQ(*d1, 'M')) {
7027                             const char * const m = d1;
7028                             while (*d1 && !isSPACE(*d1))
7029                                 d1++;
7030                             Perl_croak(aTHX_ "Too late for \"-%.*s\" option",
7031                                   (int)(d1 - m), m);
7032                         }
7033                         d1 = moreswitches(d1);
7034                     } while (d1);
7035                     if (PL_doswitches && !switches_done) {
7036                         int argc = PL_origargc;
7037                         char **argv = PL_origargv;
7038                         do {
7039                             argc--,argv++;
7040                         } while (argc && argv[0][0] == '-' && argv[0][1]);
7041                         init_argv_symbols(argc,argv);
7042                     }
7043                     if (   (PERLDB_LINE_OR_SAVESRC && !oldpdb)
7044                         || ((PL_minus_n || PL_minus_p) && !(oldn || oldp)))
7045                           /* if we have already added "LINE: while (<>) {",
7046                              we must not do it again */
7047                     {
7048                         SvPVCLEAR(PL_linestr);
7049                         PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
7050                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7051                         PL_last_lop = PL_last_uni = NULL;
7052                         PL_preambled = FALSE;
7053                         if (PERLDB_LINE_OR_SAVESRC)
7054                             (void)gv_fetchfile(PL_origfilename);
7055                         return yyl_try(aTHX_ s, len);
7056                     }
7057                 }
7058             }
7059         }
7060     }
7061
7062     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
7063         PL_lex_state = LEX_FORMLINE;
7064         force_next(FORMRBRACK);
7065         TOKEN(';');
7066     }
7067
7068     return yyl_try(aTHX_ s, len);
7069 }
7070
7071 static int
7072 yyl_fatcomma(pTHX_ char *s, STRLEN len)
7073 {
7074     CLINE;
7075     pl_yylval.opval
7076         = newSVOP(OP_CONST, 0,
7077                        S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
7078     pl_yylval.opval->op_private = OPpCONST_BARE;
7079     TERM(BAREWORD);
7080 }
7081
7082 static int
7083 yyl_safe_bareword(pTHX_ char *s, const char lastchar)
7084 {
7085     if ((lastchar == '*' || lastchar == '%' || lastchar == '&')
7086         && PL_parser->saw_infix_sigil)
7087     {
7088         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7089                          "Operator or semicolon missing before %c%" UTF8f,
7090                          lastchar,
7091                          UTF8fARG(UTF, strlen(PL_tokenbuf),
7092                                   PL_tokenbuf));
7093         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7094                          "Ambiguous use of %c resolved as operator %c",
7095                          lastchar, lastchar);
7096     }
7097     TOKEN(BAREWORD);
7098 }
7099
7100 static int
7101 yyl_constant_op(pTHX_ char *s, SV *sv, CV *cv, OP *rv2cv_op, PADOFFSET off)
7102 {
7103     if (sv) {
7104         op_free(rv2cv_op);
7105         SvREFCNT_dec(((SVOP*)pl_yylval.opval)->op_sv);
7106         ((SVOP*)pl_yylval.opval)->op_sv = SvREFCNT_inc_simple(sv);
7107         if (SvTYPE(sv) == SVt_PVAV)
7108             pl_yylval.opval = newUNOP(OP_RV2AV, OPf_PARENS,
7109                                       pl_yylval.opval);
7110         else {
7111             pl_yylval.opval->op_private = 0;
7112             pl_yylval.opval->op_folded = 1;
7113             pl_yylval.opval->op_flags |= OPf_SPECIAL;
7114         }
7115         TOKEN(BAREWORD);
7116     }
7117
7118     op_free(pl_yylval.opval);
7119     pl_yylval.opval =
7120         off ? newCVREF(0, rv2cv_op) : rv2cv_op;
7121     pl_yylval.opval->op_private |= OPpENTERSUB_NOPAREN;
7122     PL_last_lop = PL_oldbufptr;
7123     PL_last_lop_op = OP_ENTERSUB;
7124
7125     /* Is there a prototype? */
7126     if (SvPOK(cv)) {
7127         int k = yyl_subproto(aTHX_ s, cv);
7128         if (k != KEY_NULL)
7129             return k;
7130     }
7131
7132     NEXTVAL_NEXTTOKE.opval = pl_yylval.opval;
7133     PL_expect = XTERM;
7134     force_next(off ? PRIVATEREF : BAREWORD);
7135     if (!PL_lex_allbrackets
7136         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7137     {
7138         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7139     }
7140
7141     TOKEN(NOAMP);
7142 }
7143
7144 /* Honour "reserved word" warnings, and enforce strict subs */
7145 static void
7146 yyl_strictwarn_bareword(pTHX_ const char lastchar)
7147 {
7148     /* after "print" and similar functions (corresponding to
7149      * "F? L" in opcode.pl), whatever wasn't already parsed as
7150      * a filehandle should be subject to "strict subs".
7151      * Likewise for the optional indirect-object argument to system
7152      * or exec, which can't be a bareword */
7153     if ((PL_last_lop_op == OP_PRINT
7154             || PL_last_lop_op == OP_PRTF
7155             || PL_last_lop_op == OP_SAY
7156             || PL_last_lop_op == OP_SYSTEM
7157             || PL_last_lop_op == OP_EXEC)
7158         && (PL_hints & HINT_STRICT_SUBS))
7159     {
7160         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7161     }
7162
7163     if (lastchar != '-' && ckWARN(WARN_RESERVED)) {
7164         char *d = PL_tokenbuf;
7165         while (isLOWER(*d))
7166             d++;
7167         if (!*d && !gv_stashpv(PL_tokenbuf, UTF ? SVf_UTF8 : 0)) {
7168             /* PL_warn_reserved is constant */
7169             GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
7170             Perl_warner(aTHX_ packWARN(WARN_RESERVED), PL_warn_reserved,
7171                         PL_tokenbuf);
7172             GCC_DIAG_RESTORE_STMT;
7173         }
7174     }
7175 }
7176
7177 static int
7178 yyl_just_a_word(pTHX_ char *s, STRLEN len, I32 orig_keyword, struct code c)
7179 {
7180     int pkgname = 0;
7181     const char lastchar = (PL_bufptr == PL_oldoldbufptr ? 0 : PL_bufptr[-1]);
7182     bool safebw;
7183     bool no_op_error = FALSE;
7184     /* Use this var to track whether intuit_method has been
7185        called.  intuit_method returns 0 or > 255.  */
7186     int key = 1;
7187
7188     if (PL_expect == XOPERATOR) {
7189         if (PL_bufptr == PL_linestart) {
7190             CopLINE_dec(PL_curcop);
7191             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
7192             CopLINE_inc(PL_curcop);
7193         }
7194         else
7195             /* We want to call no_op with s pointing after the
7196                bareword, so defer it.  But we want it to come
7197                before the Bad name croak.  */
7198             no_op_error = TRUE;
7199     }
7200
7201     /* Get the rest if it looks like a package qualifier */
7202
7203     if (*s == '\'' || (*s == ':' && s[1] == ':')) {
7204         STRLEN morelen;
7205         s = scan_word(s, PL_tokenbuf + len, sizeof PL_tokenbuf - len,
7206                       TRUE, &morelen);
7207         if (no_op_error) {
7208             no_op("Bareword",s);
7209             no_op_error = FALSE;
7210         }
7211         if (!morelen)
7212             Perl_croak(aTHX_ "Bad name after %" UTF8f "%s",
7213                     UTF8fARG(UTF, len, PL_tokenbuf),
7214                     *s == '\'' ? "'" : "::");
7215         len += morelen;
7216         pkgname = 1;
7217     }
7218
7219     if (no_op_error)
7220         no_op("Bareword",s);
7221
7222     /* See if the name is "Foo::",
7223        in which case Foo is a bareword
7224        (and a package name). */
7225
7226     if (len > 2 && PL_tokenbuf[len - 2] == ':' && PL_tokenbuf[len - 1] == ':') {
7227         if (ckWARN(WARN_BAREWORD)
7228             && ! gv_fetchpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0, SVt_PVHV))
7229             Perl_warner(aTHX_ packWARN(WARN_BAREWORD),
7230                         "Bareword \"%" UTF8f
7231                         "\" refers to nonexistent package",
7232                         UTF8fARG(UTF, len, PL_tokenbuf));
7233         len -= 2;
7234         PL_tokenbuf[len] = '\0';
7235         c.gv = NULL;
7236         c.gvp = 0;
7237         safebw = TRUE;
7238     }
7239     else {
7240         safebw = FALSE;
7241     }
7242
7243     /* if we saw a global override before, get the right name */
7244
7245     if (!c.sv)
7246         c.sv = S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len);
7247     if (c.gvp) {
7248         SV *sv = newSVpvs("CORE::GLOBAL::");
7249         sv_catsv(sv, c.sv);
7250         SvREFCNT_dec(c.sv);
7251         c.sv = sv;
7252     }
7253
7254     /* Presume this is going to be a bareword of some sort. */
7255     CLINE;
7256     pl_yylval.opval = newSVOP(OP_CONST, 0, c.sv);
7257     pl_yylval.opval->op_private = OPpCONST_BARE;
7258
7259     /* And if "Foo::", then that's what it certainly is. */
7260     if (safebw)
7261         return yyl_safe_bareword(aTHX_ s, lastchar);
7262
7263     if (!c.off) {
7264         OP *const_op = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(c.sv));
7265         const_op->op_private = OPpCONST_BARE;
7266         c.rv2cv_op = newCVREF(OPpMAY_RETURN_CONSTANT<<8, const_op);
7267         c.cv = c.lex
7268             ? isGV(c.gv)
7269                 ? GvCV(c.gv)
7270                 : SvROK(c.gv) && SvTYPE(SvRV(c.gv)) == SVt_PVCV
7271                     ? (CV *)SvRV(c.gv)
7272                     : ((CV *)c.gv)
7273             : rv2cv_op_cv(c.rv2cv_op, RV2CVOPCV_RETURN_STUB);
7274     }
7275
7276     /* See if it's the indirect object for a list operator. */
7277
7278     if (PL_oldoldbufptr
7279         && PL_oldoldbufptr < PL_bufptr
7280         && (PL_oldoldbufptr == PL_last_lop
7281             || PL_oldoldbufptr == PL_last_uni)
7282         && /* NO SKIPSPACE BEFORE HERE! */
7283            (PL_expect == XREF
7284             || ((PL_opargs[PL_last_lop_op] >> OASHIFT)& 7)
7285                                                    == OA_FILEREF))
7286     {
7287         bool immediate_paren = *s == '(';
7288         SSize_t s_off;
7289
7290         /* (Now we can afford to cross potential line boundary.) */
7291         s = skipspace(s);
7292
7293         /* intuit_method() can indirectly call lex_next_chunk(),
7294          * invalidating s
7295          */
7296         s_off = s - SvPVX(PL_linestr);
7297         /* Two barewords in a row may indicate method call. */
7298         if (   (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
7299                 || *s == '$')
7300             && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7301         {
7302             /* the code at method: doesn't use s */
7303             goto method;
7304         }
7305         s = SvPVX(PL_linestr) + s_off;
7306
7307         /* If not a declared subroutine, it's an indirect object. */
7308         /* (But it's an indir obj regardless for sort.) */
7309         /* Also, if "_" follows a filetest operator, it's a bareword */
7310
7311         if (
7312             ( !immediate_paren && (PL_last_lop_op == OP_SORT
7313              || (!c.cv
7314                  && (PL_last_lop_op != OP_MAPSTART
7315                      && PL_last_lop_op != OP_GREPSTART))))
7316            || (PL_tokenbuf[0] == '_' && PL_tokenbuf[1] == '\0'
7317                 && ((PL_opargs[PL_last_lop_op] & OA_CLASS_MASK)
7318                                                 == OA_FILESTATOP))
7319            )
7320         {
7321             PL_expect = (PL_last_lop == PL_oldoldbufptr) ? XTERM : XOPERATOR;
7322             yyl_strictwarn_bareword(aTHX_ lastchar);
7323             op_free(c.rv2cv_op);
7324             return yyl_safe_bareword(aTHX_ s, lastchar);
7325         }
7326     }
7327
7328     PL_expect = XOPERATOR;
7329     s = skipspace(s);
7330
7331     /* Is this a word before a => operator? */
7332     if (*s == '=' && s[1] == '>' && !pkgname) {
7333         op_free(c.rv2cv_op);
7334         CLINE;
7335         if (c.gvp || (c.lex && !c.off)) {
7336             assert (cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7337             /* This is our own scalar, created a few lines
7338                above, so this is safe. */
7339             SvREADONLY_off(c.sv);
7340             sv_setpv(c.sv, PL_tokenbuf);
7341             if (UTF && !IN_BYTES
7342              && is_utf8_string((U8*)PL_tokenbuf, len))
7343                   SvUTF8_on(c.sv);
7344             SvREADONLY_on(c.sv);
7345         }
7346         TERM(BAREWORD);
7347     }
7348
7349     /* If followed by a paren, it's certainly a subroutine. */
7350     if (*s == '(') {
7351         CLINE;
7352         if (c.cv) {
7353             char *d = s + 1;
7354             while (SPACE_OR_TAB(*d))
7355                 d++;
7356             if (*d == ')' && (c.sv = cv_const_sv_or_av(c.cv)))
7357                 return yyl_constant_op(aTHX_ d + 1, c.sv, c.cv, c.rv2cv_op, c.off);
7358         }
7359         NEXTVAL_NEXTTOKE.opval =
7360             c.off ? c.rv2cv_op : pl_yylval.opval;
7361         if (c.off)
7362              op_free(pl_yylval.opval), force_next(PRIVATEREF);
7363         else op_free(c.rv2cv_op),      force_next(BAREWORD);
7364         pl_yylval.ival = 0;
7365         TOKEN('&');
7366     }
7367
7368     /* If followed by var or block, call it a method (unless sub) */
7369
7370     if ((*s == '$' || *s == '{') && !c.cv) {
7371         op_free(c.rv2cv_op);
7372         PL_last_lop = PL_oldbufptr;
7373         PL_last_lop_op = OP_METHOD;
7374         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7375             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7376         PL_expect = XBLOCKTERM;
7377         PL_bufptr = s;
7378         return REPORT(METHOD);
7379     }
7380
7381     /* If followed by a bareword, see if it looks like indir obj. */
7382
7383     if (   key == 1
7384         && !orig_keyword
7385         && (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF) || *s == '$')
7386         && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7387     {
7388       method:
7389         if (c.lex && !c.off) {
7390             assert(cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7391             SvREADONLY_off(c.sv);
7392             sv_setpvn(c.sv, PL_tokenbuf, len);
7393             if (UTF && !IN_BYTES
7394              && is_utf8_string((U8*)PL_tokenbuf, len))
7395                 SvUTF8_on(c.sv);
7396             else SvUTF8_off(c.sv);
7397         }
7398         op_free(c.rv2cv_op);
7399         if (key == METHOD && !PL_lex_allbrackets
7400             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7401         {
7402             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7403         }
7404         return REPORT(key);
7405     }
7406
7407     /* Not a method, so call it a subroutine (if defined) */
7408
7409     if (c.cv) {
7410         /* Check for a constant sub */
7411         c.sv = cv_const_sv_or_av(c.cv);
7412         return yyl_constant_op(aTHX_ s, c.sv, c.cv, c.rv2cv_op, c.off);
7413     }
7414
7415     /* Call it a bare word */
7416
7417     if (PL_hints & HINT_STRICT_SUBS)
7418         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7419     else
7420         yyl_strictwarn_bareword(aTHX_ lastchar);
7421
7422     op_free(c.rv2cv_op);
7423
7424     return yyl_safe_bareword(aTHX_ s, lastchar);
7425 }
7426
7427 static int
7428 yyl_word_or_keyword(pTHX_ char *s, STRLEN len, I32 key, I32 orig_keyword, struct code c)
7429 {
7430     switch (key) {
7431     default:                    /* not a keyword */
7432         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7433
7434     case KEY___FILE__:
7435         FUN0OP( newSVOP(OP_CONST, 0, newSVpv(CopFILE(PL_curcop),0)) );
7436
7437     case KEY___LINE__:
7438         FUN0OP(
7439             newSVOP(OP_CONST, 0,
7440                 Perl_newSVpvf(aTHX_ "%" IVdf, (IV)CopLINE(PL_curcop)))
7441         );
7442
7443     case KEY___PACKAGE__:
7444         FUN0OP(
7445             newSVOP(OP_CONST, 0, (PL_curstash
7446                                      ? newSVhek(HvNAME_HEK(PL_curstash))
7447                                      : &PL_sv_undef))
7448         );
7449
7450     case KEY___DATA__:
7451     case KEY___END__:
7452         if (PL_rsfp && (!PL_in_eval || PL_tokenbuf[2] == 'D'))
7453             yyl_data_handle(aTHX);
7454         return yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s, len);
7455
7456     case KEY___SUB__:
7457         FUN0OP(CvCLONE(PL_compcv)
7458                     ? newOP(OP_RUNCV, 0)
7459                     : newPVOP(OP_RUNCV,0,NULL));
7460
7461     case KEY_AUTOLOAD:
7462     case KEY_DESTROY:
7463     case KEY_BEGIN:
7464     case KEY_UNITCHECK:
7465     case KEY_CHECK:
7466     case KEY_INIT:
7467     case KEY_END:
7468         if (PL_expect == XSTATE)
7469             return yyl_sub(aTHX_ PL_bufptr, key);
7470         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7471
7472     case KEY_abs:
7473         UNI(OP_ABS);
7474
7475     case KEY_alarm:
7476         UNI(OP_ALARM);
7477
7478     case KEY_accept:
7479         LOP(OP_ACCEPT,XTERM);
7480
7481     case KEY_and:
7482         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7483             return REPORT(0);
7484         OPERATOR(ANDOP);
7485
7486     case KEY_atan2:
7487         LOP(OP_ATAN2,XTERM);
7488
7489     case KEY_bind:
7490         LOP(OP_BIND,XTERM);
7491
7492     case KEY_binmode:
7493         LOP(OP_BINMODE,XTERM);
7494
7495     case KEY_bless:
7496         LOP(OP_BLESS,XTERM);
7497
7498     case KEY_break:
7499         FUN0(OP_BREAK);
7500
7501     case KEY_chop:
7502         UNI(OP_CHOP);
7503
7504     case KEY_continue:
7505         /* We have to disambiguate the two senses of
7506           "continue". If the next token is a '{' then
7507           treat it as the start of a continue block;
7508           otherwise treat it as a control operator.
7509          */
7510         s = skipspace(s);
7511         if (*s == '{')
7512             PREBLOCK(CONTINUE);
7513         else
7514             FUN0(OP_CONTINUE);
7515
7516     case KEY_chdir:
7517         /* may use HOME */
7518         (void)gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV);
7519         UNI(OP_CHDIR);
7520
7521     case KEY_close:
7522         UNI(OP_CLOSE);
7523
7524     case KEY_closedir:
7525         UNI(OP_CLOSEDIR);
7526
7527     case KEY_cmp:
7528         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7529             return REPORT(0);
7530         Eop(OP_SCMP);
7531
7532     case KEY_caller:
7533         UNI(OP_CALLER);
7534
7535     case KEY_crypt:
7536 #ifdef FCRYPT
7537         if (!PL_cryptseen) {
7538             PL_cryptseen = TRUE;
7539             init_des();
7540         }
7541 #endif
7542         LOP(OP_CRYPT,XTERM);
7543
7544     case KEY_chmod:
7545         LOP(OP_CHMOD,XTERM);
7546
7547     case KEY_chown:
7548         LOP(OP_CHOWN,XTERM);
7549
7550     case KEY_connect:
7551         LOP(OP_CONNECT,XTERM);
7552
7553     case KEY_chr:
7554         UNI(OP_CHR);
7555
7556     case KEY_cos:
7557         UNI(OP_COS);
7558
7559     case KEY_chroot:
7560         UNI(OP_CHROOT);
7561
7562     case KEY_default:
7563         PREBLOCK(DEFAULT);
7564
7565     case KEY_do:
7566         return yyl_do(aTHX_ s, orig_keyword);
7567
7568     case KEY_die:
7569         PL_hints |= HINT_BLOCK_SCOPE;
7570         LOP(OP_DIE,XTERM);
7571
7572     case KEY_defined:
7573         UNI(OP_DEFINED);
7574
7575     case KEY_delete:
7576         UNI(OP_DELETE);
7577
7578     case KEY_dbmopen:
7579         Perl_populate_isa(aTHX_ STR_WITH_LEN("AnyDBM_File::ISA"),
7580                           STR_WITH_LEN("NDBM_File::"),
7581                           STR_WITH_LEN("DB_File::"),
7582                           STR_WITH_LEN("GDBM_File::"),
7583                           STR_WITH_LEN("SDBM_File::"),
7584                           STR_WITH_LEN("ODBM_File::"),
7585                           NULL);
7586         LOP(OP_DBMOPEN,XTERM);
7587
7588     case KEY_dbmclose:
7589         UNI(OP_DBMCLOSE);
7590
7591     case KEY_dump:
7592         LOOPX(OP_DUMP);
7593
7594     case KEY_else:
7595         PREBLOCK(ELSE);
7596
7597     case KEY_elsif:
7598         pl_yylval.ival = CopLINE(PL_curcop);
7599         OPERATOR(ELSIF);
7600
7601     case KEY_eq:
7602         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7603             return REPORT(0);
7604         Eop(OP_SEQ);
7605
7606     case KEY_exists:
7607         UNI(OP_EXISTS);
7608
7609     case KEY_exit:
7610         UNI(OP_EXIT);
7611
7612     case KEY_eval:
7613         s = skipspace(s);
7614         if (*s == '{') { /* block eval */
7615             PL_expect = XTERMBLOCK;
7616             UNIBRACK(OP_ENTERTRY);
7617         }
7618         else { /* string eval */
7619             PL_expect = XTERM;
7620             UNIBRACK(OP_ENTEREVAL);
7621         }
7622
7623     case KEY_evalbytes:
7624         PL_expect = XTERM;
7625         UNIBRACK(-OP_ENTEREVAL);
7626
7627     case KEY_eof:
7628         UNI(OP_EOF);
7629
7630     case KEY_exp:
7631         UNI(OP_EXP);
7632
7633     case KEY_each:
7634         UNI(OP_EACH);
7635
7636     case KEY_exec:
7637         LOP(OP_EXEC,XREF);
7638
7639     case KEY_endhostent:
7640         FUN0(OP_EHOSTENT);
7641
7642     case KEY_endnetent:
7643         FUN0(OP_ENETENT);
7644
7645     case KEY_endservent:
7646         FUN0(OP_ESERVENT);
7647
7648     case KEY_endprotoent:
7649         FUN0(OP_EPROTOENT);
7650
7651     case KEY_endpwent:
7652         FUN0(OP_EPWENT);
7653
7654     case KEY_endgrent:
7655         FUN0(OP_EGRENT);
7656
7657     case KEY_for:
7658     case KEY_foreach:
7659         return yyl_foreach(aTHX_ s);
7660
7661     case KEY_formline:
7662         LOP(OP_FORMLINE,XTERM);
7663
7664     case KEY_fork:
7665         FUN0(OP_FORK);
7666
7667     case KEY_fc:
7668         UNI(OP_FC);
7669
7670     case KEY_fcntl:
7671         LOP(OP_FCNTL,XTERM);
7672
7673     case KEY_fileno:
7674         UNI(OP_FILENO);
7675
7676     case KEY_flock:
7677         LOP(OP_FLOCK,XTERM);
7678
7679     case KEY_gt:
7680         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7681             return REPORT(0);
7682         Rop(OP_SGT);
7683
7684     case KEY_ge:
7685         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7686             return REPORT(0);
7687         Rop(OP_SGE);
7688
7689     case KEY_grep:
7690         LOP(OP_GREPSTART, XREF);
7691
7692     case KEY_goto:
7693         LOOPX(OP_GOTO);
7694
7695     case KEY_gmtime:
7696         UNI(OP_GMTIME);
7697
7698     case KEY_getc:
7699         UNIDOR(OP_GETC);
7700
7701     case KEY_getppid:
7702         FUN0(OP_GETPPID);
7703
7704     case KEY_getpgrp:
7705         UNI(OP_GETPGRP);
7706
7707     case KEY_getpriority:
7708         LOP(OP_GETPRIORITY,XTERM);
7709
7710     case KEY_getprotobyname:
7711         UNI(OP_GPBYNAME);
7712
7713     case KEY_getprotobynumber:
7714         LOP(OP_GPBYNUMBER,XTERM);
7715
7716     case KEY_getprotoent:
7717         FUN0(OP_GPROTOENT);
7718
7719     case KEY_getpwent:
7720         FUN0(OP_GPWENT);
7721
7722     case KEY_getpwnam:
7723         UNI(OP_GPWNAM);
7724
7725     case KEY_getpwuid:
7726         UNI(OP_GPWUID);
7727
7728     case KEY_getpeername:
7729         UNI(OP_GETPEERNAME);
7730
7731     case KEY_gethostbyname:
7732         UNI(OP_GHBYNAME);
7733
7734     case KEY_gethostbyaddr:
7735         LOP(OP_GHBYADDR,XTERM);
7736
7737     case KEY_gethostent:
7738         FUN0(OP_GHOSTENT);
7739
7740     case KEY_getnetbyname:
7741         UNI(OP_GNBYNAME);
7742
7743     case KEY_getnetbyaddr:
7744         LOP(OP_GNBYADDR,XTERM);
7745
7746     case KEY_getnetent:
7747         FUN0(OP_GNETENT);
7748
7749     case KEY_getservbyname:
7750         LOP(OP_GSBYNAME,XTERM);
7751
7752     case KEY_getservbyport:
7753         LOP(OP_GSBYPORT,XTERM);
7754
7755     case KEY_getservent:
7756         FUN0(OP_GSERVENT);
7757
7758     case KEY_getsockname:
7759         UNI(OP_GETSOCKNAME);
7760
7761     case KEY_getsockopt:
7762         LOP(OP_GSOCKOPT,XTERM);
7763
7764     case KEY_getgrent:
7765         FUN0(OP_GGRENT);
7766
7767     case KEY_getgrnam:
7768         UNI(OP_GGRNAM);
7769
7770     case KEY_getgrgid:
7771         UNI(OP_GGRGID);
7772
7773     case KEY_getlogin:
7774         FUN0(OP_GETLOGIN);
7775
7776     case KEY_given:
7777         pl_yylval.ival = CopLINE(PL_curcop);
7778         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
7779                          "given is experimental");
7780         OPERATOR(GIVEN);
7781
7782     case KEY_glob:
7783         LOP( orig_keyword==KEY_glob ? -OP_GLOB : OP_GLOB, XTERM );
7784
7785     case KEY_hex:
7786         UNI(OP_HEX);
7787
7788     case KEY_if:
7789         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7790             return REPORT(0);
7791         pl_yylval.ival = CopLINE(PL_curcop);
7792         OPERATOR(IF);
7793
7794     case KEY_index:
7795         LOP(OP_INDEX,XTERM);
7796
7797     case KEY_int:
7798         UNI(OP_INT);
7799
7800     case KEY_ioctl:
7801         LOP(OP_IOCTL,XTERM);
7802
7803     case KEY_join:
7804         LOP(OP_JOIN,XTERM);
7805
7806     case KEY_keys:
7807         UNI(OP_KEYS);
7808
7809     case KEY_kill:
7810         LOP(OP_KILL,XTERM);
7811
7812     case KEY_last:
7813         LOOPX(OP_LAST);
7814
7815     case KEY_lc:
7816         UNI(OP_LC);
7817
7818     case KEY_lcfirst:
7819         UNI(OP_LCFIRST);
7820
7821     case KEY_local:
7822         OPERATOR(LOCAL);
7823
7824     case KEY_length:
7825         UNI(OP_LENGTH);
7826
7827     case KEY_lt:
7828         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7829             return REPORT(0);
7830         Rop(OP_SLT);
7831
7832     case KEY_le:
7833         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7834             return REPORT(0);
7835         Rop(OP_SLE);
7836
7837     case KEY_localtime:
7838         UNI(OP_LOCALTIME);
7839
7840     case KEY_log:
7841         UNI(OP_LOG);
7842
7843     case KEY_link:
7844         LOP(OP_LINK,XTERM);
7845
7846     case KEY_listen:
7847         LOP(OP_LISTEN,XTERM);
7848
7849     case KEY_lock:
7850         UNI(OP_LOCK);
7851
7852     case KEY_lstat:
7853         UNI(OP_LSTAT);
7854
7855     case KEY_m:
7856         s = scan_pat(s,OP_MATCH);
7857         TERM(sublex_start());
7858
7859     case KEY_map:
7860         LOP(OP_MAPSTART, XREF);
7861
7862     case KEY_mkdir:
7863         LOP(OP_MKDIR,XTERM);
7864
7865     case KEY_msgctl:
7866         LOP(OP_MSGCTL,XTERM);
7867
7868     case KEY_msgget:
7869         LOP(OP_MSGGET,XTERM);
7870
7871     case KEY_msgrcv:
7872         LOP(OP_MSGRCV,XTERM);
7873
7874     case KEY_msgsnd:
7875         LOP(OP_MSGSND,XTERM);
7876
7877     case KEY_our:
7878     case KEY_my:
7879     case KEY_state:
7880         return yyl_my(aTHX_ s, key);
7881
7882     case KEY_next:
7883         LOOPX(OP_NEXT);
7884
7885     case KEY_ne:
7886         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7887             return REPORT(0);
7888         Eop(OP_SNE);
7889
7890     case KEY_no:
7891         s = tokenize_use(0, s);
7892         TOKEN(USE);
7893
7894     case KEY_not:
7895         if (*s == '(' || (s = skipspace(s), *s == '('))
7896             FUN1(OP_NOT);
7897         else {
7898             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7899                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7900             OPERATOR(NOTOP);
7901         }
7902
7903     case KEY_open:
7904         s = skipspace(s);
7905         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
7906             const char *t;
7907             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
7908             for (t=d; isSPACE(*t);)
7909                 t++;
7910             if ( *t && strchr("|&*+-=!?:.", *t) && ckWARN_d(WARN_PRECEDENCE)
7911                 /* [perl #16184] */
7912                 && !(t[0] == '=' && t[1] == '>')
7913                 && !(t[0] == ':' && t[1] == ':')
7914                 && !keyword(s, d-s, 0)
7915             ) {
7916                 Perl_warner(aTHX_ packWARN(WARN_PRECEDENCE),
7917                    "Precedence problem: open %" UTF8f " should be open(%" UTF8f ")",
7918                     UTF8fARG(UTF, d-s, s), UTF8fARG(UTF, d-s, s));
7919             }
7920         }
7921         LOP(OP_OPEN,XTERM);
7922
7923     case KEY_or:
7924         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7925             return REPORT(0);
7926         pl_yylval.ival = OP_OR;
7927         OPERATOR(OROP);
7928
7929     case KEY_ord:
7930         UNI(OP_ORD);
7931
7932     case KEY_oct:
7933         UNI(OP_OCT);
7934
7935     case KEY_opendir:
7936         LOP(OP_OPEN_DIR,XTERM);
7937
7938     case KEY_print:
7939         checkcomma(s,PL_tokenbuf,"filehandle");
7940         LOP(OP_PRINT,XREF);
7941
7942     case KEY_printf:
7943         checkcomma(s,PL_tokenbuf,"filehandle");
7944         LOP(OP_PRTF,XREF);
7945
7946     case KEY_prototype:
7947         UNI(OP_PROTOTYPE);
7948
7949     case KEY_push:
7950         LOP(OP_PUSH,XTERM);
7951
7952     case KEY_pop:
7953         UNIDOR(OP_POP);
7954
7955     case KEY_pos:
7956         UNIDOR(OP_POS);
7957
7958     case KEY_pack:
7959         LOP(OP_PACK,XTERM);
7960
7961     case KEY_package:
7962         s = force_word(s,BAREWORD,FALSE,TRUE);
7963         s = skipspace(s);
7964         s = force_strict_version(s);
7965         PREBLOCK(PACKAGE);
7966
7967     case KEY_pipe:
7968         LOP(OP_PIPE_OP,XTERM);
7969
7970     case KEY_q:
7971         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
7972         if (!s)
7973             missingterm(NULL, 0);
7974         COPLINE_SET_FROM_MULTI_END;
7975         pl_yylval.ival = OP_CONST;
7976         TERM(sublex_start());
7977
7978     case KEY_quotemeta:
7979         UNI(OP_QUOTEMETA);
7980
7981     case KEY_qw:
7982         return yyl_qw(aTHX_ s, len);
7983
7984     case KEY_qq:
7985         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
7986         if (!s)
7987             missingterm(NULL, 0);
7988         pl_yylval.ival = OP_STRINGIFY;
7989         if (SvIVX(PL_lex_stuff) == '\'')
7990             SvIV_set(PL_lex_stuff, 0);  /* qq'$foo' should interpolate */
7991         TERM(sublex_start());
7992
7993     case KEY_qr:
7994         s = scan_pat(s,OP_QR);
7995         TERM(sublex_start());
7996
7997     case KEY_qx:
7998         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
7999         if (!s)
8000             missingterm(NULL, 0);
8001         pl_yylval.ival = OP_BACKTICK;
8002         TERM(sublex_start());
8003
8004     case KEY_return:
8005         OLDLOP(OP_RETURN);
8006
8007     case KEY_require:
8008         return yyl_require(aTHX_ s, orig_keyword);
8009
8010     case KEY_reset:
8011         UNI(OP_RESET);
8012
8013     case KEY_redo:
8014         LOOPX(OP_REDO);
8015
8016     case KEY_rename:
8017         LOP(OP_RENAME,XTERM);
8018
8019     case KEY_rand:
8020         UNI(OP_RAND);
8021
8022     case KEY_rmdir:
8023         UNI(OP_RMDIR);
8024
8025     case KEY_rindex:
8026         LOP(OP_RINDEX,XTERM);
8027
8028     case KEY_read:
8029         LOP(OP_READ,XTERM);
8030
8031     case KEY_readdir:
8032         UNI(OP_READDIR);
8033
8034     case KEY_readline:
8035         UNIDOR(OP_READLINE);
8036
8037     case KEY_readpipe:
8038         UNIDOR(OP_BACKTICK);
8039
8040     case KEY_rewinddir:
8041         UNI(OP_REWINDDIR);
8042
8043     case KEY_recv:
8044         LOP(OP_RECV,XTERM);
8045
8046     case KEY_reverse:
8047         LOP(OP_REVERSE,XTERM);
8048
8049     case KEY_readlink:
8050         UNIDOR(OP_READLINK);
8051
8052     case KEY_ref:
8053         UNI(OP_REF);
8054
8055     case KEY_s:
8056         s = scan_subst(s);
8057         if (pl_yylval.opval)
8058             TERM(sublex_start());
8059         else
8060             TOKEN(1);   /* force error */
8061
8062     case KEY_say:
8063         checkcomma(s,PL_tokenbuf,"filehandle");
8064         LOP(OP_SAY,XREF);
8065
8066     case KEY_chomp:
8067         UNI(OP_CHOMP);
8068
8069     case KEY_scalar:
8070         UNI(OP_SCALAR);
8071
8072     case KEY_select:
8073         LOP(OP_SELECT,XTERM);
8074
8075     case KEY_seek:
8076         LOP(OP_SEEK,XTERM);
8077
8078     case KEY_semctl:
8079         LOP(OP_SEMCTL,XTERM);
8080
8081     case KEY_semget:
8082         LOP(OP_SEMGET,XTERM);
8083
8084     case KEY_semop:
8085         LOP(OP_SEMOP,XTERM);
8086
8087     case KEY_send:
8088         LOP(OP_SEND,XTERM);
8089
8090     case KEY_setpgrp:
8091         LOP(OP_SETPGRP,XTERM);
8092
8093     case KEY_setpriority:
8094         LOP(OP_SETPRIORITY,XTERM);
8095
8096     case KEY_sethostent:
8097         UNI(OP_SHOSTENT);
8098
8099     case KEY_setnetent:
8100         UNI(OP_SNETENT);
8101
8102     case KEY_setservent:
8103         UNI(OP_SSERVENT);
8104
8105     case KEY_setprotoent:
8106         UNI(OP_SPROTOENT);
8107
8108     case KEY_setpwent:
8109         FUN0(OP_SPWENT);
8110
8111     case KEY_setgrent:
8112         FUN0(OP_SGRENT);
8113
8114     case KEY_seekdir:
8115         LOP(OP_SEEKDIR,XTERM);
8116
8117     case KEY_setsockopt:
8118         LOP(OP_SSOCKOPT,XTERM);
8119
8120     case KEY_shift:
8121         UNIDOR(OP_SHIFT);
8122
8123     case KEY_shmctl:
8124         LOP(OP_SHMCTL,XTERM);
8125
8126     case KEY_shmget:
8127         LOP(OP_SHMGET,XTERM);
8128
8129     case KEY_shmread:
8130         LOP(OP_SHMREAD,XTERM);
8131
8132     case KEY_shmwrite:
8133         LOP(OP_SHMWRITE,XTERM);
8134
8135     case KEY_shutdown:
8136         LOP(OP_SHUTDOWN,XTERM);
8137
8138     case KEY_sin:
8139         UNI(OP_SIN);
8140
8141     case KEY_sleep:
8142         UNI(OP_SLEEP);
8143
8144     case KEY_socket:
8145         LOP(OP_SOCKET,XTERM);
8146
8147     case KEY_socketpair:
8148         LOP(OP_SOCKPAIR,XTERM);
8149
8150     case KEY_sort:
8151         checkcomma(s,PL_tokenbuf,"subroutine name");
8152         s = skipspace(s);
8153         PL_expect = XTERM;
8154         s = force_word(s,BAREWORD,TRUE,TRUE);
8155         LOP(OP_SORT,XREF);
8156
8157     case KEY_split:
8158         LOP(OP_SPLIT,XTERM);
8159
8160     case KEY_sprintf:
8161         LOP(OP_SPRINTF,XTERM);
8162
8163     case KEY_splice:
8164         LOP(OP_SPLICE,XTERM);
8165
8166     case KEY_sqrt:
8167         UNI(OP_SQRT);
8168
8169     case KEY_srand:
8170         UNI(OP_SRAND);
8171
8172     case KEY_stat:
8173         UNI(OP_STAT);
8174
8175     case KEY_study:
8176         UNI(OP_STUDY);
8177
8178     case KEY_substr:
8179         LOP(OP_SUBSTR,XTERM);
8180
8181     case KEY_format:
8182     case KEY_sub:
8183         return yyl_sub(aTHX_ s, key);
8184
8185     case KEY_system:
8186         LOP(OP_SYSTEM,XREF);
8187
8188     case KEY_symlink:
8189         LOP(OP_SYMLINK,XTERM);
8190
8191     case KEY_syscall:
8192         LOP(OP_SYSCALL,XTERM);
8193
8194     case KEY_sysopen:
8195         LOP(OP_SYSOPEN,XTERM);
8196
8197     case KEY_sysseek:
8198         LOP(OP_SYSSEEK,XTERM);
8199
8200     case KEY_sysread:
8201         LOP(OP_SYSREAD,XTERM);
8202
8203     case KEY_syswrite:
8204         LOP(OP_SYSWRITE,XTERM);
8205
8206     case KEY_tr:
8207     case KEY_y:
8208         s = scan_trans(s);
8209         TERM(sublex_start());
8210
8211     case KEY_tell:
8212         UNI(OP_TELL);
8213
8214     case KEY_telldir:
8215         UNI(OP_TELLDIR);
8216
8217     case KEY_tie:
8218         LOP(OP_TIE,XTERM);
8219
8220     case KEY_tied:
8221         UNI(OP_TIED);
8222
8223     case KEY_time:
8224         FUN0(OP_TIME);
8225
8226     case KEY_times:
8227         FUN0(OP_TMS);
8228
8229     case KEY_truncate:
8230         LOP(OP_TRUNCATE,XTERM);
8231
8232     case KEY_uc:
8233         UNI(OP_UC);
8234
8235     case KEY_ucfirst:
8236         UNI(OP_UCFIRST);
8237
8238     case KEY_untie:
8239         UNI(OP_UNTIE);
8240
8241     case KEY_until:
8242         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8243             return REPORT(0);
8244         pl_yylval.ival = CopLINE(PL_curcop);
8245         OPERATOR(UNTIL);
8246
8247     case KEY_unless:
8248         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8249             return REPORT(0);
8250         pl_yylval.ival = CopLINE(PL_curcop);
8251         OPERATOR(UNLESS);
8252
8253     case KEY_unlink:
8254         LOP(OP_UNLINK,XTERM);
8255
8256     case KEY_undef:
8257         UNIDOR(OP_UNDEF);
8258
8259     case KEY_unpack:
8260         LOP(OP_UNPACK,XTERM);
8261
8262     case KEY_utime:
8263         LOP(OP_UTIME,XTERM);
8264
8265     case KEY_umask:
8266         UNIDOR(OP_UMASK);
8267
8268     case KEY_unshift:
8269         LOP(OP_UNSHIFT,XTERM);
8270
8271     case KEY_use:
8272         s = tokenize_use(1, s);
8273         TOKEN(USE);
8274
8275     case KEY_values:
8276         UNI(OP_VALUES);
8277
8278     case KEY_vec:
8279         LOP(OP_VEC,XTERM);
8280
8281     case KEY_when:
8282         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8283             return REPORT(0);
8284         pl_yylval.ival = CopLINE(PL_curcop);
8285         Perl_ck_warner_d(aTHX_
8286             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8287             "when is experimental");
8288         OPERATOR(WHEN);
8289
8290     case KEY_while:
8291         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8292             return REPORT(0);
8293         pl_yylval.ival = CopLINE(PL_curcop);
8294         OPERATOR(WHILE);
8295
8296     case KEY_warn:
8297         PL_hints |= HINT_BLOCK_SCOPE;
8298         LOP(OP_WARN,XTERM);
8299
8300     case KEY_wait:
8301         FUN0(OP_WAIT);
8302
8303     case KEY_waitpid:
8304         LOP(OP_WAITPID,XTERM);
8305
8306     case KEY_wantarray:
8307         FUN0(OP_WANTARRAY);
8308
8309     case KEY_write:
8310         /* Make sure $^L is defined. 0x0C is CTRL-L on ASCII platforms, and
8311          * we use the same number on EBCDIC */
8312         gv_fetchpvs("\x0C", GV_ADD|GV_NOTQUAL, SVt_PV);
8313         UNI(OP_ENTERWRITE);
8314
8315     case KEY_x:
8316         if (PL_expect == XOPERATOR) {
8317             if (*s == '=' && !PL_lex_allbrackets
8318                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8319             {
8320                 return REPORT(0);
8321             }
8322             Mop(OP_REPEAT);
8323         }
8324         check_uni();
8325         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
8326
8327     case KEY_xor:
8328         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8329             return REPORT(0);
8330         pl_yylval.ival = OP_XOR;
8331         OPERATOR(OROP);
8332     }
8333 }
8334
8335 static int
8336 yyl_key_core(pTHX_ char *s, STRLEN len, struct code c)
8337 {
8338     I32 key = 0;
8339     I32 orig_keyword = 0;
8340     STRLEN olen = len;
8341     char *d = s;
8342     s += 2;
8343     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8344     if ((*s == ':' && s[1] == ':')
8345         || (!(key = keyword(PL_tokenbuf, len, 1)) && *s == '\''))
8346     {
8347         Copy(PL_bufptr, PL_tokenbuf, olen, char);
8348         return yyl_just_a_word(aTHX_ d, olen, 0, c);
8349     }
8350     if (!key)
8351         Perl_croak(aTHX_ "CORE::%" UTF8f " is not a keyword",
8352                           UTF8fARG(UTF, len, PL_tokenbuf));
8353     if (key < 0)
8354         key = -key;
8355     else if (key == KEY_require || key == KEY_do
8356           || key == KEY_glob)
8357         /* that's a way to remember we saw "CORE::" */
8358         orig_keyword = key;
8359
8360     /* Known to be a reserved word at this point */
8361     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8362 }
8363
8364 static int
8365 yyl_keylookup(pTHX_ char *s, GV *gv)
8366 {
8367     dVAR;
8368     STRLEN len;
8369     bool anydelim;
8370     I32 key;
8371     struct code c = no_code;
8372     I32 orig_keyword = 0;
8373     char *d;
8374
8375     c.gv = gv;
8376
8377     PL_bufptr = s;
8378     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8379
8380     /* Some keywords can be followed by any delimiter, including ':' */
8381     anydelim = word_takes_any_delimiter(PL_tokenbuf, len);
8382
8383     /* x::* is just a word, unless x is "CORE" */
8384     if (!anydelim && *s == ':' && s[1] == ':') {
8385         if (memEQs(PL_tokenbuf, len, "CORE"))
8386             return yyl_key_core(aTHX_ s, len, c);
8387         return yyl_just_a_word(aTHX_ s, len, 0, c);
8388     }
8389
8390     d = s;
8391     while (d < PL_bufend && isSPACE(*d))
8392             d++;        /* no comments skipped here, or s### is misparsed */
8393
8394     /* Is this a word before a => operator? */
8395     if (*d == '=' && d[1] == '>') {
8396         return yyl_fatcomma(aTHX_ s, len);
8397     }
8398
8399     /* Check for plugged-in keyword */
8400     {
8401         OP *o;
8402         int result;
8403         char *saved_bufptr = PL_bufptr;
8404         PL_bufptr = s;
8405         result = PL_keyword_plugin(aTHX_ PL_tokenbuf, len, &o);
8406         s = PL_bufptr;
8407         if (result == KEYWORD_PLUGIN_DECLINE) {
8408             /* not a plugged-in keyword */
8409             PL_bufptr = saved_bufptr;
8410         } else if (result == KEYWORD_PLUGIN_STMT) {
8411             pl_yylval.opval = o;
8412             CLINE;
8413             if (!PL_nexttoke) PL_expect = XSTATE;
8414             return REPORT(PLUGSTMT);
8415         } else if (result == KEYWORD_PLUGIN_EXPR) {
8416             pl_yylval.opval = o;
8417             CLINE;
8418             if (!PL_nexttoke) PL_expect = XOPERATOR;
8419             return REPORT(PLUGEXPR);
8420         } else {
8421             Perl_croak(aTHX_ "Bad plugin affecting keyword '%s'", PL_tokenbuf);
8422         }
8423     }
8424
8425     /* Is this a label? */
8426     if (!anydelim && PL_expect == XSTATE
8427           && d < PL_bufend && *d == ':' && *(d + 1) != ':') {
8428         s = d + 1;
8429         pl_yylval.opval =
8430             newSVOP(OP_CONST, 0,
8431                 newSVpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0));
8432         CLINE;
8433         TOKEN(LABEL);
8434     }
8435
8436     /* Check for lexical sub */
8437     if (PL_expect != XOPERATOR) {
8438         char tmpbuf[sizeof PL_tokenbuf + 1];
8439         *tmpbuf = '&';
8440         Copy(PL_tokenbuf, tmpbuf+1, len, char);
8441         c.off = pad_findmy_pvn(tmpbuf, len+1, 0);
8442         if (c.off != NOT_IN_PAD) {
8443             assert(c.off); /* we assume this is boolean-true below */
8444             if (PAD_COMPNAME_FLAGS_isOUR(c.off)) {
8445                 HV *  const stash = PAD_COMPNAME_OURSTASH(c.off);
8446                 HEK * const stashname = HvNAME_HEK(stash);
8447                 c.sv = newSVhek(stashname);
8448                 sv_catpvs(c.sv, "::");
8449                 sv_catpvn_flags(c.sv, PL_tokenbuf, len,
8450                                 (UTF ? SV_CATUTF8 : SV_CATBYTES));
8451                 c.gv = gv_fetchsv(c.sv, GV_NOADD_NOINIT | SvUTF8(c.sv),
8452                                   SVt_PVCV);
8453                 c.off = 0;
8454                 if (!c.gv) {
8455                     sv_free(c.sv);
8456                     c.sv = NULL;
8457                     return yyl_just_a_word(aTHX_ s, len, 0, c);
8458                 }
8459             }
8460             else {
8461                 c.rv2cv_op = newOP(OP_PADANY, 0);
8462                 c.rv2cv_op->op_targ = c.off;
8463                 c.cv = find_lexical_cv(c.off);
8464             }
8465             c.lex = TRUE;
8466             return yyl_just_a_word(aTHX_ s, len, 0, c);
8467         }
8468         c.off = 0;
8469     }
8470
8471     /* Check for built-in keyword */
8472     key = keyword(PL_tokenbuf, len, 0);
8473
8474     if (key < 0)
8475         key = yyl_secondclass_keyword(aTHX_ s, len, key, &orig_keyword, &c.gv, &c.gvp);
8476
8477     if (key && key != KEY___DATA__ && key != KEY___END__
8478      && (!anydelim || *s != '#')) {
8479         /* no override, and not s### either; skipspace is safe here
8480          * check for => on following line */
8481         bool arrow;
8482         STRLEN bufoff = PL_bufptr - SvPVX(PL_linestr);
8483         STRLEN   soff = s         - SvPVX(PL_linestr);
8484         s = peekspace(s);
8485         arrow = *s == '=' && s[1] == '>';
8486         PL_bufptr = SvPVX(PL_linestr) + bufoff;
8487         s         = SvPVX(PL_linestr) +   soff;
8488         if (arrow)
8489             return yyl_fatcomma(aTHX_ s, len);
8490     }
8491
8492     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8493 }
8494
8495 static int
8496 yyl_try(pTHX_ char *s, STRLEN len)
8497 {
8498     char *d;
8499     GV *gv = NULL;
8500
8501   retry:
8502     switch (*s) {
8503     default:
8504         if (UTF ? isIDFIRST_utf8_safe(s, PL_bufend) : isALNUMC(*s))
8505             return yyl_keylookup(aTHX_ s, gv);
8506         yyl_croak_unrecognised(aTHX_ s);
8507
8508     case 4:
8509     case 26:
8510         /* emulate EOF on ^D or ^Z */
8511         return yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s, len);
8512
8513     case 0:
8514         if ((!PL_rsfp || PL_lex_inwhat)
8515          && (!PL_parser->filtered || s+1 < PL_bufend)) {
8516             PL_last_uni = 0;
8517             PL_last_lop = 0;
8518             if (PL_lex_brackets
8519                 && PL_lex_brackstack[PL_lex_brackets-1] != XFAKEEOF)
8520             {
8521                 yyerror((const char *)
8522                         (PL_lex_formbrack
8523                          ? "Format not terminated"
8524                          : "Missing right curly or square bracket"));
8525             }
8526             DEBUG_T({
8527                 PerlIO_printf(Perl_debug_log, "### Tokener got EOF\n");
8528             });
8529             TOKEN(0);
8530         }
8531         if (s++ < PL_bufend)
8532             goto retry;  /* ignore stray nulls */
8533         PL_last_uni = 0;
8534         PL_last_lop = 0;
8535         if (!PL_in_eval && !PL_preambled) {
8536             PL_preambled = TRUE;
8537             if (PL_perldb) {
8538                 /* Generate a string of Perl code to load the debugger.
8539                  * If PERL5DB is set, it will return the contents of that,
8540                  * otherwise a compile-time require of perl5db.pl.  */
8541
8542                 const char * const pdb = PerlEnv_getenv("PERL5DB");
8543
8544                 if (pdb) {
8545                     sv_setpv(PL_linestr, pdb);
8546                     sv_catpvs(PL_linestr,";");
8547                 } else {
8548                     SETERRNO(0,SS_NORMAL);
8549                     sv_setpvs(PL_linestr, "BEGIN { require 'perl5db.pl' };");
8550                 }
8551                 PL_parser->preambling = CopLINE(PL_curcop);
8552             } else
8553                 SvPVCLEAR(PL_linestr);
8554             if (PL_preambleav) {
8555                 SV **svp = AvARRAY(PL_preambleav);
8556                 SV **const end = svp + AvFILLp(PL_preambleav);
8557                 while(svp <= end) {
8558                     sv_catsv(PL_linestr, *svp);
8559                     ++svp;
8560                     sv_catpvs(PL_linestr, ";");
8561                 }
8562                 sv_free(MUTABLE_SV(PL_preambleav));
8563                 PL_preambleav = NULL;
8564             }
8565             if (PL_minus_E)
8566                 sv_catpvs(PL_linestr,
8567                           "use feature ':5." STRINGIFY(PERL_VERSION) "';");
8568             if (PL_minus_n || PL_minus_p) {
8569                 sv_catpvs(PL_linestr, "LINE: while (<>) {"/*}*/);
8570                 if (PL_minus_l)
8571                     sv_catpvs(PL_linestr,"chomp;");
8572                 if (PL_minus_a) {
8573                     if (PL_minus_F) {
8574                         if (   (   *PL_splitstr == '/'
8575                                 || *PL_splitstr == '\''
8576                                 || *PL_splitstr == '"')
8577                             && strchr(PL_splitstr + 1, *PL_splitstr))
8578                         {
8579                             /* strchr is ok, because -F pattern can't contain
8580                              * embeddded NULs */
8581                             Perl_sv_catpvf(aTHX_ PL_linestr, "our @F=split(%s);", PL_splitstr);
8582                         }
8583                         else {
8584                             /* "q\0${splitstr}\0" is legal perl. Yes, even NUL
8585                                bytes can be used as quoting characters.  :-) */
8586                             const char *splits = PL_splitstr;
8587                             sv_catpvs(PL_linestr, "our @F=split(q\0");
8588                             do {
8589                                 /* Need to \ \s  */
8590                                 if (*splits == '\\')
8591                                     sv_catpvn(PL_linestr, splits, 1);
8592                                 sv_catpvn(PL_linestr, splits, 1);
8593                             } while (*splits++);
8594                             /* This loop will embed the trailing NUL of
8595                                PL_linestr as the last thing it does before
8596                                terminating.  */
8597                             sv_catpvs(PL_linestr, ");");
8598                         }
8599                     }
8600                     else
8601                         sv_catpvs(PL_linestr,"our @F=split(' ');");
8602                 }
8603             }
8604             sv_catpvs(PL_linestr, "\n");
8605             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
8606             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
8607             PL_last_lop = PL_last_uni = NULL;
8608             if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
8609                 update_debugger_info(PL_linestr, NULL, 0);
8610             goto retry;
8611         }
8612         return yyl_fake_eof(aTHX_ 0, cBOOL(PL_rsfp), s, len);
8613
8614     case '\r':
8615 #ifdef PERL_STRICT_CR
8616         Perl_warn(aTHX_ "Illegal character \\%03o (carriage return)", '\r');
8617         Perl_croak(aTHX_
8618       "\t(Maybe you didn't strip carriage returns after a network transfer?)\n");
8619 #endif
8620     case ' ': case '\t': case '\f': case '\v':
8621         s++;
8622         goto retry;
8623
8624     case '#':
8625     case '\n': {
8626         const bool needs_semicolon = yyl_eol_needs_semicolon(aTHX_ &s);
8627         if (needs_semicolon)
8628             TOKEN(';');
8629         else
8630             goto retry;
8631     }
8632
8633     case '-':
8634         return yyl_hyphen(aTHX_ s);
8635
8636     case '+':
8637         return yyl_plus(aTHX_ s);
8638
8639     case '*':
8640         return yyl_star(aTHX_ s);
8641
8642     case '%':
8643         return yyl_percent(aTHX_ s);
8644
8645     case '^':
8646         return yyl_caret(aTHX_ s);
8647
8648     case '[':
8649         return yyl_leftsquare(aTHX_ s);
8650
8651     case '~':
8652         return yyl_tilde(aTHX_ s);
8653
8654     case ',':
8655         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8656             TOKEN(0);
8657         s++;
8658         OPERATOR(',');
8659     case ':':
8660         if (s[1] == ':')
8661             return yyl_just_a_word(aTHX_ s, 0, 0, no_code);
8662         return yyl_colon(aTHX_ s + 1);
8663
8664     case '(':
8665         return yyl_leftparen(aTHX_ s + 1);
8666
8667     case ';':
8668         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8669             TOKEN(0);
8670         CLINE;
8671         s++;
8672         PL_expect = XSTATE;
8673         TOKEN(';');
8674
8675     case ')':
8676         return yyl_rightparen(aTHX_ s);
8677
8678     case ']':
8679         return yyl_rightsquare(aTHX_ s);
8680
8681     case '{':
8682         return yyl_leftcurly(aTHX_ s + 1, 0);
8683
8684     case '}':
8685         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
8686             TOKEN(0);
8687         return yyl_rightcurly(aTHX_ s, 0);
8688
8689     case '&':
8690         return yyl_ampersand(aTHX_ s);
8691
8692     case '|':
8693         return yyl_verticalbar(aTHX_ s);
8694
8695     case '=':
8696         if (s[1] == '=' && (s == PL_linestart || s[-1] == '\n')
8697             && memBEGINs(s + 2, (STRLEN) (PL_bufend - s + 2), "====="))
8698         {
8699             s = vcs_conflict_marker(s + 7);
8700             goto retry;
8701         }
8702
8703         s++;
8704         {
8705             const char tmp = *s++;
8706             if (tmp == '=') {
8707                 if (!PL_lex_allbrackets
8708                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8709                 {
8710                     s -= 2;
8711                     TOKEN(0);
8712                 }
8713                 Eop(OP_EQ);
8714             }
8715             if (tmp == '>') {
8716                 if (!PL_lex_allbrackets
8717                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8718                 {
8719                     s -= 2;
8720                     TOKEN(0);
8721                 }
8722                 OPERATOR(',');
8723             }
8724             if (tmp == '~')
8725                 PMop(OP_MATCH);
8726             if (tmp && isSPACE(*s) && ckWARN(WARN_SYNTAX)
8727                 && strchr("+-*/%.^&|<",tmp))
8728                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
8729                             "Reversed %c= operator",(int)tmp);
8730             s--;
8731             if (PL_expect == XSTATE
8732                 && isALPHA(tmp)
8733                 && (s == PL_linestart+1 || s[-2] == '\n') )
8734             {
8735                 if (   (PL_in_eval && !PL_rsfp && !PL_parser->filtered)
8736                     || PL_lex_state != LEX_NORMAL)
8737                 {
8738                     d = PL_bufend;
8739                     while (s < d) {
8740                         if (*s++ == '\n') {
8741                             incline(s, PL_bufend);
8742                             if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=cut"))
8743                             {
8744                                 s = (char *) memchr(s,'\n', d - s);
8745                                 if (s)
8746                                     s++;
8747                                 else
8748                                     s = d;
8749                                 incline(s, PL_bufend);
8750                                 goto retry;
8751                             }
8752                         }
8753                     }
8754                     goto retry;
8755                 }
8756                 s = PL_bufend;
8757                 PL_parser->in_pod = 1;
8758                 goto retry;
8759             }
8760         }
8761         if (PL_expect == XBLOCK) {
8762             const char *t = s;
8763 #ifdef PERL_STRICT_CR
8764             while (SPACE_OR_TAB(*t))
8765 #else
8766             while (SPACE_OR_TAB(*t) || *t == '\r')
8767 #endif
8768                 t++;
8769             if (*t == '\n' || *t == '#') {
8770                 ENTER_with_name("lex_format");
8771                 SAVEI8(PL_parser->form_lex_state);
8772                 SAVEI32(PL_lex_formbrack);
8773                 PL_parser->form_lex_state = PL_lex_state;
8774                 PL_lex_formbrack = PL_lex_brackets + 1;
8775                 PL_parser->sub_error_count = PL_error_count;
8776                 return yyl_leftcurly(aTHX_ s, 1);
8777             }
8778         }
8779         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
8780             s--;
8781             TOKEN(0);
8782         }
8783         pl_yylval.ival = 0;
8784         OPERATOR(ASSIGNOP);
8785
8786     case '!':
8787         return yyl_bang(aTHX_ s + 1);
8788
8789     case '<':
8790         if (s[1] == '<' && (s == PL_linestart || s[-1] == '\n')
8791             && memBEGINs(s+2, (STRLEN) (PL_bufend - (s+2)), "<<<<<"))
8792         {
8793             s = vcs_conflict_marker(s + 7);
8794             goto retry;
8795         }
8796         return yyl_leftpointy(aTHX_ s);
8797
8798     case '>':
8799         if (s[1] == '>' && (s == PL_linestart || s[-1] == '\n')
8800             && memBEGINs(s + 2, (STRLEN) (PL_bufend - s + 2), ">>>>>"))
8801         {
8802             s = vcs_conflict_marker(s + 7);
8803             goto retry;
8804         }
8805         return yyl_rightpointy(aTHX_ s + 1);
8806
8807     case '$':
8808         return yyl_dollar(aTHX_ s);
8809
8810     case '@':
8811         return yyl_snail(aTHX_ s);
8812
8813     case '/':                   /* may be division, defined-or, or pattern */
8814         return yyl_slash(aTHX_ s);
8815
8816      case '?':                  /* conditional */
8817         s++;
8818         if (!PL_lex_allbrackets
8819             && PL_lex_fakeeof >= LEX_FAKEEOF_IFELSE)
8820         {
8821             s--;
8822             TOKEN(0);
8823         }
8824         PL_lex_allbrackets++;
8825         OPERATOR('?');
8826
8827     case '.':
8828         if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack
8829 #ifdef PERL_STRICT_CR
8830             && s[1] == '\n'
8831 #else
8832             && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n'))
8833 #endif
8834             && (s == PL_linestart || s[-1] == '\n') )
8835         {
8836             PL_expect = XSTATE;
8837             /* formbrack==2 means dot seen where arguments expected */
8838             return yyl_rightcurly(aTHX_ s, 2);
8839         }
8840         if (PL_expect == XSTATE && s[1] == '.' && s[2] == '.') {
8841             s += 3;
8842             OPERATOR(YADAYADA);
8843         }
8844         if (PL_expect == XOPERATOR || !isDIGIT(s[1])) {
8845             char tmp = *s++;
8846             if (*s == tmp) {
8847                 if (!PL_lex_allbrackets
8848                     && PL_lex_fakeeof >= LEX_FAKEEOF_RANGE)
8849                 {
8850                     s--;
8851                     TOKEN(0);
8852                 }
8853                 s++;
8854                 if (*s == tmp) {
8855                     s++;
8856                     pl_yylval.ival = OPf_SPECIAL;
8857                 }
8858                 else
8859                     pl_yylval.ival = 0;
8860                 OPERATOR(DOTDOT);
8861             }
8862             if (*s == '=' && !PL_lex_allbrackets
8863                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8864             {
8865                 s--;
8866                 TOKEN(0);
8867             }
8868             Aop(OP_CONCAT);
8869         }
8870         /* FALLTHROUGH */
8871     case '0': case '1': case '2': case '3': case '4':
8872     case '5': case '6': case '7': case '8': case '9':
8873         s = scan_num(s, &pl_yylval);
8874         DEBUG_T( { printbuf("### Saw number in %s\n", s); } );
8875         if (PL_expect == XOPERATOR)
8876             no_op("Number",s);
8877         TERM(THING);
8878
8879     case '\'':
8880         return yyl_sglquote(aTHX_ s);
8881
8882     case '"':
8883         return yyl_dblquote(aTHX_ s, len);
8884
8885     case '`':
8886         return yyl_backtick(aTHX_ s);
8887
8888     case '\\':
8889         return yyl_backslash(aTHX_ s + 1);
8890
8891     case 'v':
8892         if (isDIGIT(s[1]) && PL_expect != XOPERATOR) {
8893             char *start = s + 2;
8894             while (isDIGIT(*start) || *start == '_')
8895                 start++;
8896             if (*start == '.' && isDIGIT(start[1])) {
8897                 s = scan_num(s, &pl_yylval);
8898                 TERM(THING);
8899             }
8900             else if ((*start == ':' && start[1] == ':')
8901                   || (PL_expect == XSTATE && *start == ':'))
8902                 return yyl_keylookup(aTHX_ s, gv);
8903             else if (PL_expect == XSTATE) {
8904                 d = start;
8905                 while (d < PL_bufend && isSPACE(*d)) d++;
8906                 if (*d == ':')
8907                     return yyl_keylookup(aTHX_ s, gv);
8908             }
8909             /* avoid v123abc() or $h{v1}, allow C<print v10;> */
8910             if (!isALPHA(*start) && (PL_expect == XTERM
8911                         || PL_expect == XREF || PL_expect == XSTATE
8912                         || PL_expect == XTERMORDORDOR)) {
8913                 GV *const gv = gv_fetchpvn_flags(s, start - s,
8914                                                     UTF ? SVf_UTF8 : 0, SVt_PVCV);
8915                 if (!gv) {
8916                     s = scan_num(s, &pl_yylval);
8917                     TERM(THING);
8918                 }
8919             }
8920         }
8921         return yyl_keylookup(aTHX_ s, gv);
8922
8923     case 'x':
8924         if (isDIGIT(s[1]) && PL_expect == XOPERATOR) {
8925             s++;
8926             Mop(OP_REPEAT);
8927         }
8928         return yyl_keylookup(aTHX_ s, gv);
8929
8930     case '_':
8931     case 'a': case 'A':
8932     case 'b': case 'B':
8933     case 'c': case 'C':
8934     case 'd': case 'D':
8935     case 'e': case 'E':
8936     case 'f': case 'F':
8937     case 'g': case 'G':
8938     case 'h': case 'H':
8939     case 'i': case 'I':
8940     case 'j': case 'J':
8941     case 'k': case 'K':
8942     case 'l': case 'L':
8943     case 'm': case 'M':
8944     case 'n': case 'N':
8945     case 'o': case 'O':
8946     case 'p': case 'P':
8947     case 'q': case 'Q':
8948     case 'r': case 'R':
8949     case 's': case 'S':
8950     case 't': case 'T':
8951     case 'u': case 'U':
8952               case 'V':
8953     case 'w': case 'W':
8954               case 'X':
8955     case 'y': case 'Y':
8956     case 'z': case 'Z':
8957         return yyl_keylookup(aTHX_ s, gv);
8958     }
8959 }
8960
8961
8962 /*
8963   yylex
8964
8965   Works out what to call the token just pulled out of the input
8966   stream.  The yacc parser takes care of taking the ops we return and
8967   stitching them into a tree.
8968
8969   Returns:
8970     The type of the next token
8971
8972   Structure:
8973       Check if we have already built the token; if so, use it.
8974       Switch based on the current state:
8975           - if we have a case modifier in a string, deal with that
8976           - handle other cases of interpolation inside a string
8977           - scan the next line if we are inside a format
8978       In the normal state, switch on the next character:
8979           - default:
8980             if alphabetic, go to key lookup
8981             unrecognized character - croak
8982           - 0/4/26: handle end-of-line or EOF
8983           - cases for whitespace
8984           - \n and #: handle comments and line numbers
8985           - various operators, brackets and sigils
8986           - numbers
8987           - quotes
8988           - 'v': vstrings (or go to key lookup)
8989           - 'x' repetition operator (or go to key lookup)
8990           - other ASCII alphanumerics (key lookup begins here):
8991               word before => ?
8992               keyword plugin
8993               scan built-in keyword (but do nothing with it yet)
8994               check for statement label
8995               check for lexical subs
8996                   return yyl_just_a_word if there is one
8997               see whether built-in keyword is overridden
8998               switch on keyword number:
8999                   - default: return yyl_just_a_word:
9000                       not a built-in keyword; handle bareword lookup
9001                       disambiguate between method and sub call
9002                       fall back to bareword
9003                   - cases for built-in keywords
9004 */
9005
9006 #ifdef NETWARE
9007 #define RSFP_FILENO (PL_rsfp)
9008 #else
9009 #define RSFP_FILENO (PerlIO_fileno(PL_rsfp))
9010 #endif
9011
9012
9013 int
9014 Perl_yylex(pTHX)
9015 {
9016     dVAR;
9017     char *s = PL_bufptr;
9018
9019     if (UNLIKELY(PL_parser->recheck_utf8_validity)) {
9020         const U8* first_bad_char_loc;
9021         if (UTF && UNLIKELY(! is_utf8_string_loc((U8 *) PL_bufptr,
9022                                                         PL_bufend - PL_bufptr,
9023                                                         &first_bad_char_loc)))
9024         {
9025             _force_out_malformed_utf8_message(first_bad_char_loc,
9026                                               (U8 *) PL_bufend,
9027                                               0,
9028                                               1 /* 1 means die */ );
9029             NOT_REACHED; /* NOTREACHED */
9030         }
9031         PL_parser->recheck_utf8_validity = FALSE;
9032     }
9033     DEBUG_T( {
9034         SV* tmp = newSVpvs("");
9035         PerlIO_printf(Perl_debug_log, "### %" IVdf ":LEX_%s/X%s %s\n",
9036             (IV)CopLINE(PL_curcop),
9037             lex_state_names[PL_lex_state],
9038             exp_name[PL_expect],
9039             pv_display(tmp, s, strlen(s), 0, 60));
9040         SvREFCNT_dec(tmp);
9041     } );
9042
9043     /* when we've already built the next token, just pull it out of the queue */
9044     if (PL_nexttoke) {
9045         PL_nexttoke--;
9046         pl_yylval = PL_nextval[PL_nexttoke];
9047         {
9048             I32 next_type;
9049             next_type = PL_nexttype[PL_nexttoke];
9050             if (next_type & (7<<24)) {
9051                 if (next_type & (1<<24)) {
9052                     if (PL_lex_brackets > 100)
9053                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
9054                     PL_lex_brackstack[PL_lex_brackets++] =
9055                         (char) ((next_type >> 16) & 0xff);
9056                 }
9057                 if (next_type & (2<<24))
9058                     PL_lex_allbrackets++;
9059                 if (next_type & (4<<24))
9060                     PL_lex_allbrackets--;
9061                 next_type &= 0xffff;
9062             }
9063             return REPORT(next_type == 'p' ? pending_ident() : next_type);
9064         }
9065     }
9066
9067     switch (PL_lex_state) {
9068     case LEX_NORMAL:
9069     case LEX_INTERPNORMAL:
9070         break;
9071
9072     /* interpolated case modifiers like \L \U, including \Q and \E.
9073        when we get here, PL_bufptr is at the \
9074     */
9075     case LEX_INTERPCASEMOD:
9076         /* handle \E or end of string */
9077         return yyl_interpcasemod(aTHX_ s);
9078
9079     case LEX_INTERPPUSH:
9080         return REPORT(sublex_push());
9081
9082     case LEX_INTERPSTART:
9083         if (PL_bufptr == PL_bufend)
9084             return REPORT(sublex_done());
9085         DEBUG_T({
9086             if(*PL_bufptr != '(')
9087                 PerlIO_printf(Perl_debug_log, "### Interpolated variable\n");
9088         });
9089         PL_expect = XTERM;
9090         /* for /@a/, we leave the joining for the regex engine to do
9091          * (unless we're within \Q etc) */
9092         PL_lex_dojoin = (*PL_bufptr == '@'
9093                             && (!PL_lex_inpat || PL_lex_casemods));
9094         PL_lex_state = LEX_INTERPNORMAL;
9095         if (PL_lex_dojoin) {
9096             NEXTVAL_NEXTTOKE.ival = 0;
9097             force_next(',');
9098             force_ident("\"", '$');
9099             NEXTVAL_NEXTTOKE.ival = 0;
9100             force_next('$');
9101             NEXTVAL_NEXTTOKE.ival = 0;
9102             force_next((2<<24)|'(');
9103             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
9104             force_next(FUNC);
9105         }
9106         /* Convert (?{...}) and friends to 'do {...}' */
9107         if (PL_lex_inpat && *PL_bufptr == '(') {
9108             PL_parser->lex_shared->re_eval_start = PL_bufptr;
9109             PL_bufptr += 2;
9110             if (*PL_bufptr != '{')
9111                 PL_bufptr++;
9112             PL_expect = XTERMBLOCK;
9113             force_next(DO);
9114         }
9115
9116         if (PL_lex_starts++) {
9117             s = PL_bufptr;
9118             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9119             if (!PL_lex_casemods && PL_lex_inpat)
9120                 TOKEN(',');
9121             else
9122                 AopNOASSIGN(OP_CONCAT);
9123         }
9124         return yylex();
9125
9126     case LEX_INTERPENDMAYBE:
9127         if (intuit_more(PL_bufptr, PL_bufend)) {
9128             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
9129             break;
9130         }
9131         /* FALLTHROUGH */
9132
9133     case LEX_INTERPEND:
9134         if (PL_lex_dojoin) {
9135             const U8 dojoin_was = PL_lex_dojoin;
9136             PL_lex_dojoin = FALSE;
9137             PL_lex_state = LEX_INTERPCONCAT;
9138             PL_lex_allbrackets--;
9139             return REPORT(dojoin_was == 1 ? (int)')' : (int)POSTJOIN);
9140         }
9141         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
9142             && SvEVALED(PL_lex_repl))
9143         {
9144             if (PL_bufptr != PL_bufend)
9145                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
9146             PL_lex_repl = NULL;
9147         }
9148         /* Paranoia.  re_eval_start is adjusted when S_scan_heredoc sets
9149            re_eval_str.  If the here-doc body’s length equals the previous
9150            value of re_eval_start, re_eval_start will now be null.  So
9151            check re_eval_str as well. */
9152         if (PL_parser->lex_shared->re_eval_start
9153          || PL_parser->lex_shared->re_eval_str) {
9154             SV *sv;
9155             if (*PL_bufptr != ')')
9156                 Perl_croak(aTHX_ "Sequence (?{...}) not terminated with ')'");
9157             PL_bufptr++;
9158             /* having compiled a (?{..}) expression, return the original
9159              * text too, as a const */
9160             if (PL_parser->lex_shared->re_eval_str) {
9161                 sv = PL_parser->lex_shared->re_eval_str;
9162                 PL_parser->lex_shared->re_eval_str = NULL;
9163                 SvCUR_set(sv,
9164                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9165                 SvPV_shrink_to_cur(sv);
9166             }
9167             else sv = newSVpvn(PL_parser->lex_shared->re_eval_start,
9168                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9169             NEXTVAL_NEXTTOKE.opval =
9170                     newSVOP(OP_CONST, 0,
9171                                  sv);
9172             force_next(THING);
9173             PL_parser->lex_shared->re_eval_start = NULL;
9174             PL_expect = XTERM;
9175             return REPORT(',');
9176         }
9177
9178         /* FALLTHROUGH */
9179     case LEX_INTERPCONCAT:
9180 #ifdef DEBUGGING
9181         if (PL_lex_brackets)
9182             Perl_croak(aTHX_ "panic: INTERPCONCAT, lex_brackets=%ld",
9183                        (long) PL_lex_brackets);
9184 #endif
9185         if (PL_bufptr == PL_bufend)
9186             return REPORT(sublex_done());
9187
9188         /* m'foo' still needs to be parsed for possible (?{...}) */
9189         if (SvIVX(PL_linestr) == '\'' && !PL_lex_inpat) {
9190             SV *sv = newSVsv(PL_linestr);
9191             sv = tokeq(sv);
9192             pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
9193             s = PL_bufend;
9194         }
9195         else {
9196             int save_error_count = PL_error_count;
9197
9198             s = scan_const(PL_bufptr);
9199
9200             /* Set flag if this was a pattern and there were errors.  op.c will
9201              * refuse to compile a pattern with this flag set.  Otherwise, we
9202              * could get segfaults, etc. */
9203             if (PL_lex_inpat && PL_error_count > save_error_count) {
9204                 ((PMOP*)PL_lex_inpat)->op_pmflags |= PMf_HAS_ERROR;
9205             }
9206             if (*s == '\\')
9207                 PL_lex_state = LEX_INTERPCASEMOD;
9208             else
9209                 PL_lex_state = LEX_INTERPSTART;
9210         }
9211
9212         if (s != PL_bufptr) {
9213             NEXTVAL_NEXTTOKE = pl_yylval;
9214             PL_expect = XTERM;
9215             force_next(THING);
9216             if (PL_lex_starts++) {
9217                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9218                 if (!PL_lex_casemods && PL_lex_inpat)
9219                     TOKEN(',');
9220                 else
9221                     AopNOASSIGN(OP_CONCAT);
9222             }
9223             else {
9224                 PL_bufptr = s;
9225                 return yylex();
9226             }
9227         }
9228
9229         return yylex();
9230     case LEX_FORMLINE:
9231         if (PL_parser->sub_error_count != PL_error_count) {
9232             /* There was an error parsing a formline, which tends to
9233                mess up the parser.
9234                Unlike interpolated sub-parsing, we can't treat any of
9235                these as recoverable, so no need to check sub_no_recover.
9236             */
9237             yyquit();
9238         }
9239         assert(PL_lex_formbrack);
9240         s = scan_formline(PL_bufptr);
9241         if (!PL_lex_formbrack)
9242             return yyl_rightcurly(aTHX_ s, 1);
9243         PL_bufptr = s;
9244         return yylex();
9245     }
9246
9247     /* We really do *not* want PL_linestr ever becoming a COW. */
9248     assert (!SvIsCOW(PL_linestr));
9249     s = PL_bufptr;
9250     PL_oldoldbufptr = PL_oldbufptr;
9251     PL_oldbufptr = s;
9252
9253     if (PL_in_my == KEY_sigvar) {
9254         PL_parser->saw_infix_sigil = 0;
9255         return yyl_sigvar(aTHX_ s);
9256     }
9257
9258     {
9259         /* yyl_try() and its callees might consult PL_parser->saw_infix_sigil.
9260            On its return, we then need to set it to indicate whether the token
9261            we just encountered was an infix operator that (if we hadn't been
9262            expecting an operator) have been a sigil.
9263         */
9264         bool expected_operator = (PL_expect == XOPERATOR);
9265         int ret = yyl_try(aTHX_ s, 0);
9266         switch (pl_yylval.ival) {
9267         case OP_BIT_AND:
9268         case OP_MODULO:
9269         case OP_MULTIPLY:
9270         case OP_NBIT_AND:
9271             if (expected_operator) {
9272                 PL_parser->saw_infix_sigil = 1;
9273                 break;
9274             }
9275             /* FALLTHROUGH */
9276         default:
9277             PL_parser->saw_infix_sigil = 0;
9278         }
9279         return ret;
9280     }
9281 }
9282
9283
9284 /*
9285   S_pending_ident
9286
9287   Looks up an identifier in the pad or in a package
9288
9289   PL_in_my == KEY_sigvar indicates that this is a subroutine signature variable
9290   rather than a plain pad var.
9291
9292   Returns:
9293     PRIVATEREF if this is a lexical name.
9294     BAREWORD   if this belongs to a package.
9295
9296   Structure:
9297       if we're in a my declaration
9298           croak if they tried to say my($foo::bar)
9299           build the ops for a my() declaration
9300       if it's an access to a my() variable
9301           build ops for access to a my() variable
9302       if in a dq string, and they've said @foo and we can't find @foo
9303           warn
9304       build ops for a bareword
9305 */
9306
9307 static int
9308 S_pending_ident(pTHX)
9309 {
9310     PADOFFSET tmp = 0;
9311     const char pit = (char)pl_yylval.ival;
9312     const STRLEN tokenbuf_len = strlen(PL_tokenbuf);
9313     /* All routes through this function want to know if there is a colon.  */
9314     const char *const has_colon = (const char*) memchr (PL_tokenbuf, ':', tokenbuf_len);
9315
9316     DEBUG_T({ PerlIO_printf(Perl_debug_log,
9317           "### Pending identifier '%s'\n", PL_tokenbuf); });
9318     assert(tokenbuf_len >= 2);
9319
9320     /* if we're in a my(), we can't allow dynamics here.
9321        $foo'bar has already been turned into $foo::bar, so
9322        just check for colons.
9323
9324        if it's a legal name, the OP is a PADANY.
9325     */
9326     if (PL_in_my) {
9327         if (PL_in_my == KEY_our) {      /* "our" is merely analogous to "my" */
9328             if (has_colon)
9329                 /* diag_listed_as: No package name allowed for variable %s
9330                                    in "our" */
9331                 yyerror_pv(Perl_form(aTHX_ "No package name allowed for "
9332                                   "%s %s in \"our\"",
9333                                   *PL_tokenbuf=='&' ? "subroutine" : "variable",
9334                                   PL_tokenbuf), UTF ? SVf_UTF8 : 0);
9335             tmp = allocmy(PL_tokenbuf, tokenbuf_len, UTF ? SVf_UTF8 : 0);
9336         }
9337         else {
9338             OP *o;
9339             if (has_colon) {
9340                 /* "my" variable %s can't be in a package */
9341                 /* PL_no_myglob is constant */
9342                 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
9343                 yyerror_pv(Perl_form(aTHX_ PL_no_myglob,
9344                             PL_in_my == KEY_my ? "my" : "state",
9345                             *PL_tokenbuf == '&' ? "subroutine" : "variable",
9346                             PL_tokenbuf),
9347                             UTF ? SVf_UTF8 : 0);
9348                 GCC_DIAG_RESTORE_STMT;
9349             }
9350
9351             if (PL_in_my == KEY_sigvar) {
9352                 /* A signature 'padop' needs in addition, an op_first to
9353                  * point to a child sigdefelem, and an extra field to hold
9354                  * the signature index. We can achieve both by using an
9355                  * UNOP_AUX and (ab)using the op_aux field to hold the
9356                  * index. If we ever need more fields, use a real malloced
9357                  * aux strut instead.
9358                  */
9359                 o = newUNOP_AUX(OP_ARGELEM, 0, NULL,
9360                                     INT2PTR(UNOP_AUX_item *,
9361                                         (PL_parser->sig_elems)));
9362                 o->op_private |= (  PL_tokenbuf[0] == '$' ? OPpARGELEM_SV
9363                                   : PL_tokenbuf[0] == '@' ? OPpARGELEM_AV
9364                                   :                         OPpARGELEM_HV);
9365             }
9366             else
9367                 o = newOP(OP_PADANY, 0);
9368             o->op_targ = allocmy(PL_tokenbuf, tokenbuf_len,
9369                                                         UTF ? SVf_UTF8 : 0);
9370             if (PL_in_my == KEY_sigvar)
9371                 PL_in_my = 0;
9372
9373             pl_yylval.opval = o;
9374             return PRIVATEREF;
9375         }
9376     }
9377
9378     /*
9379        build the ops for accesses to a my() variable.
9380     */
9381
9382     if (!has_colon) {
9383         if (!PL_in_my)
9384             tmp = pad_findmy_pvn(PL_tokenbuf, tokenbuf_len,
9385                                  0);
9386         if (tmp != NOT_IN_PAD) {
9387             /* might be an "our" variable" */
9388             if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
9389                 /* build ops for a bareword */
9390                 HV *  const stash = PAD_COMPNAME_OURSTASH(tmp);
9391                 HEK * const stashname = HvNAME_HEK(stash);
9392                 SV *  const sym = newSVhek(stashname);
9393                 sv_catpvs(sym, "::");
9394                 sv_catpvn_flags(sym, PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0, (UTF ? SV_CATUTF8 : SV_CATBYTES ));
9395                 pl_yylval.opval = newSVOP(OP_CONST, 0, sym);
9396                 pl_yylval.opval->op_private = OPpCONST_ENTERED;
9397                 if (pit != '&')
9398                   gv_fetchsv(sym,
9399                     GV_ADDMULTI,
9400                     ((PL_tokenbuf[0] == '$') ? SVt_PV
9401                      : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9402                      : SVt_PVHV));
9403                 return BAREWORD;
9404             }
9405
9406             pl_yylval.opval = newOP(OP_PADANY, 0);
9407             pl_yylval.opval->op_targ = tmp;
9408             return PRIVATEREF;
9409         }
9410     }
9411
9412     /*
9413        Whine if they've said @foo or @foo{key} in a doublequoted string,
9414        and @foo (or %foo) isn't a variable we can find in the symbol
9415        table.
9416     */
9417     if (ckWARN(WARN_AMBIGUOUS)
9418         && pit == '@'
9419         && PL_lex_state != LEX_NORMAL
9420         && !PL_lex_brackets)
9421     {
9422         GV *const gv = gv_fetchpvn_flags(PL_tokenbuf + 1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9423                                          ( UTF ? SVf_UTF8 : 0 ) | GV_ADDMG,
9424                                          SVt_PVAV);
9425         if ((!gv || ((PL_tokenbuf[0] == '@') ? !GvAV(gv) : !GvHV(gv)))
9426            )
9427         {
9428             /* Downgraded from fatal to warning 20000522 mjd */
9429             Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9430                         "Possible unintended interpolation of %" UTF8f
9431                         " in string",
9432                         UTF8fARG(UTF, tokenbuf_len, PL_tokenbuf));
9433         }
9434     }
9435
9436     /* build ops for a bareword */
9437     pl_yylval.opval = newSVOP(OP_CONST, 0,
9438                                    newSVpvn_flags(PL_tokenbuf + 1,
9439                                                       tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9440                                                       UTF ? SVf_UTF8 : 0 ));
9441     pl_yylval.opval->op_private = OPpCONST_ENTERED;
9442     if (pit != '&')
9443         gv_fetchpvn_flags(PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9444                      (PL_in_eval ? GV_ADDMULTI : GV_ADD)
9445                      | ( UTF ? SVf_UTF8 : 0 ),
9446                      ((PL_tokenbuf[0] == '$') ? SVt_PV
9447                       : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9448                       : SVt_PVHV));
9449     return BAREWORD;
9450 }
9451
9452 STATIC void
9453 S_checkcomma(pTHX_ const char *s, const char *name, const char *what)
9454 {
9455     PERL_ARGS_ASSERT_CHECKCOMMA;
9456
9457     if (*s == ' ' && s[1] == '(') {     /* XXX gotta be a better way */
9458         if (ckWARN(WARN_SYNTAX)) {
9459             int level = 1;
9460             const char *w;
9461             for (w = s+2; *w && level; w++) {
9462                 if (*w == '(')
9463                     ++level;
9464                 else if (*w == ')')
9465                     --level;
9466             }
9467             while (isSPACE(*w))
9468                 ++w;
9469             /* the list of chars below is for end of statements or
9470              * block / parens, boolean operators (&&, ||, //) and branch
9471              * constructs (or, and, if, until, unless, while, err, for).
9472              * Not a very solid hack... */
9473             if (!*w || !strchr(";&/|})]oaiuwef!=", *w))
9474                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9475                             "%s (...) interpreted as function",name);
9476         }
9477     }
9478     while (s < PL_bufend && isSPACE(*s))
9479         s++;
9480     if (*s == '(')
9481         s++;
9482     while (s < PL_bufend && isSPACE(*s))
9483         s++;
9484     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
9485         const char * const w = s;
9486         s += UTF ? UTF8SKIP(s) : 1;
9487         while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
9488             s += UTF ? UTF8SKIP(s) : 1;
9489         while (s < PL_bufend && isSPACE(*s))
9490             s++;
9491         if (*s == ',') {
9492             GV* gv;
9493             if (keyword(w, s - w, 0))
9494                 return;
9495
9496             gv = gv_fetchpvn_flags(w, s - w, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
9497             if (gv && GvCVu(gv))
9498                 return;
9499             if (s - w <= 254) {
9500                 PADOFFSET off;
9501                 char tmpbuf[256];
9502                 Copy(w, tmpbuf+1, s - w, char);
9503                 *tmpbuf = '&';
9504                 off = pad_findmy_pvn(tmpbuf, s-w+1, 0);
9505                 if (off != NOT_IN_PAD) return;
9506             }
9507             Perl_croak(aTHX_ "No comma allowed after %s", what);
9508         }
9509     }
9510 }
9511
9512 /* S_new_constant(): do any overload::constant lookup.
9513
9514    Either returns sv, or mortalizes/frees sv and returns a new SV*.
9515    Best used as sv=new_constant(..., sv, ...).
9516    If s, pv are NULL, calls subroutine with one argument,
9517    and <type> is used with error messages only.
9518    <type> is assumed to be well formed UTF-8.
9519
9520    If error_msg is not NULL, *error_msg will be set to any error encountered.
9521    Otherwise yyerror() will be used to output it */
9522
9523 STATIC SV *
9524 S_new_constant(pTHX_ const char *s, STRLEN len, const char *key, STRLEN keylen,
9525                SV *sv, SV *pv, const char *type, STRLEN typelen,
9526                const char ** error_msg)
9527 {
9528     dSP;
9529     HV * table = GvHV(PL_hintgv);                /* ^H */
9530     SV *res;
9531     SV *errsv = NULL;
9532     SV **cvp;
9533     SV *cv, *typesv;
9534     const char *why1 = "", *why2 = "", *why3 = "";
9535
9536     PERL_ARGS_ASSERT_NEW_CONSTANT;
9537     /* We assume that this is true: */
9538     if (*key == 'c') { assert (strEQ(key, "charnames")); }
9539     assert(type || s);
9540
9541     sv_2mortal(sv);                     /* Parent created it permanently */
9542     if (!table
9543         || ! (PL_hints & HINT_LOCALIZE_HH)
9544         || ! (cvp = hv_fetch(table, key, keylen, FALSE))
9545         || ! SvOK(*cvp))
9546     {
9547         char *msg;
9548
9549         /* Here haven't found what we're looking for.  If it is charnames,
9550          * perhaps it needs to be loaded.  Try doing that before giving up */
9551         if (*key == 'c') {
9552             Perl_load_module(aTHX_
9553                             0,
9554                             newSVpvs("_charnames"),
9555                              /* version parameter; no need to specify it, as if
9556                               * we get too early a version, will fail anyway,
9557                               * not being able to find '_charnames' */
9558                             NULL,
9559                             newSVpvs(":full"),
9560                             newSVpvs(":short"),
9561                             NULL);
9562             assert(sp == PL_stack_sp);
9563             table = GvHV(PL_hintgv);
9564             if (table
9565                 && (PL_hints & HINT_LOCALIZE_HH)
9566                 && (cvp = hv_fetch(table, key, keylen, FALSE))
9567                 && SvOK(*cvp))
9568             {
9569                 goto now_ok;
9570             }
9571         }
9572         if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
9573             msg = Perl_form(aTHX_
9574                                "Constant(%.*s) unknown",
9575                                 (int)(type ? typelen : len),
9576                                 (type ? type: s));
9577         }
9578         else {
9579             why1 = "$^H{";
9580             why2 = key;
9581             why3 = "} is not defined";
9582         report:
9583             if (*key == 'c') {
9584                 msg = Perl_form(aTHX_
9585                             /* The +3 is for '\N{'; -4 for that, plus '}' */
9586                             "Unknown charname '%.*s'", (int)typelen - 4, type + 3
9587                       );
9588             }
9589             else {
9590                 msg = Perl_form(aTHX_ "Constant(%.*s): %s%s%s",
9591                                     (int)(type ? typelen : len),
9592                                     (type ? type: s), why1, why2, why3);
9593             }
9594         }
9595         if (error_msg) {
9596             *error_msg = msg;
9597         }
9598         else {
9599             yyerror_pv(msg, UTF ? SVf_UTF8 : 0);
9600         }
9601         return SvREFCNT_inc_simple_NN(sv);
9602     }
9603   now_ok:
9604     cv = *cvp;
9605     if (!pv && s)
9606         pv = newSVpvn_flags(s, len, SVs_TEMP);
9607     if (type && pv)
9608         typesv = newSVpvn_flags(type, typelen, SVs_TEMP);
9609     else
9610         typesv = &PL_sv_undef;
9611
9612     PUSHSTACKi(PERLSI_OVERLOAD);
9613     ENTER ;
9614     SAVETMPS;
9615
9616     PUSHMARK(SP) ;
9617     EXTEND(sp, 3);
9618     if (pv)
9619         PUSHs(pv);
9620     PUSHs(sv);
9621     if (pv)
9622         PUSHs(typesv);
9623     PUTBACK;
9624     call_sv(cv, G_SCALAR | ( PL_in_eval ? 0 : G_EVAL));
9625
9626     SPAGAIN ;
9627
9628     /* Check the eval first */
9629     if (!PL_in_eval && ((errsv = ERRSV), SvTRUE_NN(errsv))) {
9630         STRLEN errlen;
9631         const char * errstr;
9632         sv_catpvs(errsv, "Propagated");
9633         errstr = SvPV_const(errsv, errlen);
9634         yyerror_pvn(errstr, errlen, 0); /* Duplicates the message inside eval */
9635         (void)POPs;
9636         res = SvREFCNT_inc_simple_NN(sv);
9637     }
9638     else {
9639         res = POPs;
9640         SvREFCNT_inc_simple_void_NN(res);
9641     }
9642
9643     PUTBACK ;
9644     FREETMPS ;
9645     LEAVE ;
9646     POPSTACK;
9647
9648     if (!SvOK(res)) {
9649         why1 = "Call to &{$^H{";
9650         why2 = key;
9651         why3 = "}} did not return a defined value";
9652         sv = res;
9653         (void)sv_2mortal(sv);
9654         goto report;
9655     }
9656
9657     return res;
9658 }
9659
9660 PERL_STATIC_INLINE void
9661 S_parse_ident(pTHX_ char **s, char **d, char * const e, int allow_package,
9662                     bool is_utf8, bool check_dollar, bool tick_warn)
9663 {
9664     int saw_tick = 0;
9665     const char *olds = *s;
9666     PERL_ARGS_ASSERT_PARSE_IDENT;
9667
9668     while (*s < PL_bufend) {
9669         if (*d >= e)
9670             Perl_croak(aTHX_ "%s", ident_too_long);
9671         if (is_utf8 && isIDFIRST_utf8_safe(*s, PL_bufend)) {
9672              /* The UTF-8 case must come first, otherwise things
9673              * like c\N{COMBINING TILDE} would start failing, as the
9674              * isWORDCHAR_A case below would gobble the 'c' up.
9675              */
9676
9677             char *t = *s + UTF8SKIP(*s);
9678             while (isIDCONT_utf8_safe((const U8*) t, (const U8*) PL_bufend)) {
9679                 t += UTF8SKIP(t);
9680             }
9681             if (*d + (t - *s) > e)
9682                 Perl_croak(aTHX_ "%s", ident_too_long);
9683             Copy(*s, *d, t - *s, char);
9684             *d += t - *s;
9685             *s = t;
9686         }
9687         else if ( isWORDCHAR_A(**s) ) {
9688             do {
9689                 *(*d)++ = *(*s)++;
9690             } while (isWORDCHAR_A(**s) && *d < e);
9691         }
9692         else if (   allow_package
9693                  && **s == '\''
9694                  && isIDFIRST_lazy_if_safe((*s)+1, PL_bufend, is_utf8))
9695         {
9696             *(*d)++ = ':';
9697             *(*d)++ = ':';
9698             (*s)++;
9699             saw_tick++;
9700         }
9701         else if (allow_package && **s == ':' && (*s)[1] == ':'
9702            /* Disallow things like Foo::$bar. For the curious, this is
9703             * the code path that triggers the "Bad name after" warning
9704             * when looking for barewords.
9705             */
9706            && !(check_dollar && (*s)[2] == '$')) {
9707             *(*d)++ = *(*s)++;
9708             *(*d)++ = *(*s)++;
9709         }
9710         else
9711             break;
9712     }
9713     if (UNLIKELY(tick_warn && saw_tick && PL_lex_state == LEX_INTERPNORMAL
9714               && !PL_lex_brackets && ckWARN(WARN_SYNTAX))) {
9715         char *this_d;
9716         char *d2;
9717         Newx(this_d, *s - olds + saw_tick + 2, char); /* +2 for $# */
9718         d2 = this_d;
9719         SAVEFREEPV(this_d);
9720         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9721                          "Old package separator used in string");
9722         if (olds[-1] == '#')
9723             *d2++ = olds[-2];
9724         *d2++ = olds[-1];
9725         while (olds < *s) {
9726             if (*olds == '\'') {
9727                 *d2++ = '\\';
9728                 *d2++ = *olds++;
9729             }
9730             else
9731                 *d2++ = *olds++;
9732         }
9733         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9734                          "\t(Did you mean \"%" UTF8f "\" instead?)\n",
9735                           UTF8fARG(is_utf8, d2-this_d, this_d));
9736     }
9737     return;
9738 }
9739
9740 /* Returns a NUL terminated string, with the length of the string written to
9741    *slp
9742    */
9743 char *
9744 Perl_scan_word(pTHX_ char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
9745 {
9746     char *d = dest;
9747     char * const e = d + destlen - 3;  /* two-character token, ending NUL */
9748     bool is_utf8 = cBOOL(UTF);
9749
9750     PERL_ARGS_ASSERT_SCAN_WORD;
9751
9752     parse_ident(&s, &d, e, allow_package, is_utf8, TRUE, FALSE);
9753     *d = '\0';
9754     *slp = d - dest;
9755     return s;
9756 }
9757
9758 /* Is the byte 'd' a legal single character identifier name?  'u' is true
9759  * iff Unicode semantics are to be used.  The legal ones are any of:
9760  *  a) all ASCII characters except:
9761  *          1) control and space-type ones, like NUL, SOH, \t, and SPACE;
9762  *          2) '{'
9763  *     The final case currently doesn't get this far in the program, so we
9764  *     don't test for it.  If that were to change, it would be ok to allow it.
9765  *  b) When not under Unicode rules, any upper Latin1 character
9766  *  c) Otherwise, when unicode rules are used, all XIDS characters.
9767  *
9768  *      Because all ASCII characters have the same representation whether
9769  *      encoded in UTF-8 or not, we can use the foo_A macros below and '\0' and
9770  *      '{' without knowing if is UTF-8 or not. */
9771 #define VALID_LEN_ONE_IDENT(s, e, is_utf8)                                  \
9772     (isGRAPH_A(*(s)) || ((is_utf8)                                          \
9773                          ? isIDFIRST_utf8_safe(s, e)                        \
9774                          : (isGRAPH_L1(*s)                                  \
9775                             && LIKELY((U8) *(s) != LATIN1_TO_NATIVE(0xAD)))))
9776
9777 STATIC char *
9778 S_scan_ident(pTHX_ char *s, char *dest, STRLEN destlen, I32 ck_uni)
9779 {
9780     I32 herelines = PL_parser->herelines;
9781     SSize_t bracket = -1;
9782     char funny = *s++;
9783     char *d = dest;
9784     char * const e = d + destlen - 3;    /* two-character token, ending NUL */
9785     bool is_utf8 = cBOOL(UTF);
9786     I32 orig_copline = 0, tmp_copline = 0;
9787
9788     PERL_ARGS_ASSERT_SCAN_IDENT;
9789
9790     if (isSPACE(*s) || !*s)
9791         s = skipspace(s);
9792     if (isDIGIT(*s)) {
9793         while (isDIGIT(*s)) {
9794             if (d >= e)
9795                 Perl_croak(aTHX_ "%s", ident_too_long);
9796             *d++ = *s++;
9797         }
9798     }
9799     else {  /* See if it is a "normal" identifier */
9800         parse_ident(&s, &d, e, 1, is_utf8, FALSE, TRUE);
9801     }
9802     *d = '\0';
9803     d = dest;
9804     if (*d) {
9805         /* Either a digit variable, or parse_ident() found an identifier
9806            (anything valid as a bareword), so job done and return.  */
9807         if (PL_lex_state != LEX_NORMAL)
9808             PL_lex_state = LEX_INTERPENDMAYBE;
9809         return s;
9810     }
9811
9812     /* Here, it is not a run-of-the-mill identifier name */
9813
9814     if (*s == '$' && s[1]
9815         && (   isIDFIRST_lazy_if_safe(s+1, PL_bufend, is_utf8)
9816             || isDIGIT_A((U8)s[1])
9817             || s[1] == '$'
9818             || s[1] == '{'
9819             || memBEGINs(s+1, (STRLEN) (PL_bufend - (s+1)), "::")) )
9820     {
9821         /* Dereferencing a value in a scalar variable.
9822            The alternatives are different syntaxes for a scalar variable.
9823            Using ' as a leading package separator isn't allowed. :: is.   */
9824         return s;
9825     }
9826     /* Handle the opening { of @{...}, &{...}, *{...}, %{...}, ${...}  */
9827     if (*s == '{') {
9828         bracket = s - SvPVX(PL_linestr);
9829         s++;
9830         orig_copline = CopLINE(PL_curcop);
9831         if (s < PL_bufend && isSPACE(*s)) {
9832             s = skipspace(s);
9833         }
9834     }
9835     if ((s <= PL_bufend - ((is_utf8)
9836                           ? UTF8SKIP(s)
9837                           : 1))
9838         && VALID_LEN_ONE_IDENT(s, PL_bufend, is_utf8))
9839     {
9840         if (is_utf8) {
9841             const STRLEN skip = UTF8SKIP(s);
9842             STRLEN i;
9843             d[skip] = '\0';
9844             for ( i = 0; i < skip; i++ )
9845                 d[i] = *s++;
9846         }
9847         else {
9848             *d = *s++;
9849             d[1] = '\0';
9850         }
9851     }
9852     /* Convert $^F, ${^F} and the ^F of ${^FOO} to control characters */
9853     if (*d == '^' && *s && isCONTROLVAR(*s)) {
9854         *d = toCTRL(*s);
9855         s++;
9856     }
9857     /* Warn about ambiguous code after unary operators if {...} notation isn't
9858        used.  There's no difference in ambiguity; it's merely a heuristic
9859        about when not to warn.  */
9860     else if (ck_uni && bracket == -1)
9861         check_uni();
9862     if (bracket != -1) {
9863         bool skip;
9864         char *s2;
9865         /* If we were processing {...} notation then...  */
9866         if (isIDFIRST_lazy_if_safe(d, e, is_utf8)
9867             || (!isPRINT(*d) /* isCNTRL(d), plus all non-ASCII */
9868                  && isWORDCHAR(*s))
9869         ) {
9870             /* note we have to check for a normal identifier first,
9871              * as it handles utf8 symbols, and only after that has
9872              * been ruled out can we look at the caret words */
9873             if (isIDFIRST_lazy_if_safe(d, e, is_utf8) ) {
9874                 /* if it starts as a valid identifier, assume that it is one.
9875                    (the later check for } being at the expected point will trap
9876                    cases where this doesn't pan out.)  */
9877                 d += is_utf8 ? UTF8SKIP(d) : 1;
9878                 parse_ident(&s, &d, e, 1, is_utf8, TRUE, TRUE);
9879                 *d = '\0';
9880             }
9881             else { /* caret word: ${^Foo} ${^CAPTURE[0]} */
9882                 d++;
9883                 while (isWORDCHAR(*s) && d < e) {
9884                     *d++ = *s++;
9885                 }
9886                 if (d >= e)
9887                     Perl_croak(aTHX_ "%s", ident_too_long);
9888                 *d = '\0';
9889             }
9890             tmp_copline = CopLINE(PL_curcop);
9891             if (s < PL_bufend && isSPACE(*s)) {
9892                 s = skipspace(s);
9893             }
9894             if ((*s == '[' || (*s == '{' && strNE(dest, "sub")))) {
9895                 /* ${foo[0]} and ${foo{bar}} and ${^CAPTURE[0]} notation.  */
9896                 if (ckWARN(WARN_AMBIGUOUS) && keyword(dest, d - dest, 0)) {
9897                     const char * const brack =
9898                         (const char *)
9899                         ((*s == '[') ? "[...]" : "{...}");
9900                     orig_copline = CopLINE(PL_curcop);
9901                     CopLINE_set(PL_curcop, tmp_copline);
9902    /* diag_listed_as: Ambiguous use of %c{%s[...]} resolved to %c%s[...] */
9903                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9904                         "Ambiguous use of %c{%s%s} resolved to %c%s%s",
9905                         funny, dest, brack, funny, dest, brack);
9906                     CopLINE_set(PL_curcop, orig_copline);
9907                 }
9908                 bracket++;
9909                 PL_lex_brackstack[PL_lex_brackets++] = (char)(XOPERATOR | XFAKEBRACK);
9910                 PL_lex_allbrackets++;
9911                 return s;
9912             }
9913         }
9914
9915         if ( !tmp_copline )
9916             tmp_copline = CopLINE(PL_curcop);
9917         if ((skip = s < PL_bufend && isSPACE(*s))) {
9918             /* Avoid incrementing line numbers or resetting PL_linestart,
9919                in case we have to back up.  */
9920             STRLEN s_off = s - SvPVX(PL_linestr);
9921             s2 = peekspace(s);
9922             s = SvPVX(PL_linestr) + s_off;
9923         }
9924         else
9925             s2 = s;
9926
9927         /* Expect to find a closing } after consuming any trailing whitespace.
9928          */
9929         if (*s2 == '}') {
9930             /* Now increment line numbers if applicable.  */
9931             if (skip)
9932                 s = skipspace(s);
9933             s++;
9934             if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
9935                 PL_lex_state = LEX_INTERPEND;
9936                 PL_expect = XREF;
9937             }
9938             if (PL_lex_state == LEX_NORMAL || PL_lex_brackets) {
9939                 if (ckWARN(WARN_AMBIGUOUS)
9940                     && (keyword(dest, d - dest, 0)
9941                         || get_cvn_flags(dest, d - dest, is_utf8
9942                            ? SVf_UTF8
9943                            : 0)))
9944                 {
9945                     SV *tmp = newSVpvn_flags( dest, d - dest,
9946                                         SVs_TEMP | (is_utf8 ? SVf_UTF8 : 0) );
9947                     if (funny == '#')
9948                         funny = '@';
9949                     orig_copline = CopLINE(PL_curcop);
9950                     CopLINE_set(PL_curcop, tmp_copline);
9951                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9952                         "Ambiguous use of %c{%" SVf "} resolved to %c%" SVf,
9953                         funny, SVfARG(tmp), funny, SVfARG(tmp));
9954                     CopLINE_set(PL_curcop, orig_copline);
9955                 }
9956             }
9957         }
9958         else {
9959             /* Didn't find the closing } at the point we expected, so restore
9960                state such that the next thing to process is the opening { and */
9961             s = SvPVX(PL_linestr) + bracket; /* let the parser handle it */
9962             CopLINE_set(PL_curcop, orig_copline);
9963             PL_parser->herelines = herelines;
9964             *dest = '\0';
9965             PL_parser->sub_no_recover = TRUE;
9966         }
9967     }
9968     else if (   PL_lex_state == LEX_INTERPNORMAL
9969              && !PL_lex_brackets
9970              && !intuit_more(s, PL_bufend))
9971         PL_lex_state = LEX_INTERPEND;
9972     return s;
9973 }
9974
9975 static bool
9976 S_pmflag(pTHX_ const char* const valid_flags, U32 * pmfl, char** s, char* charset, unsigned int * x_mod_count) {
9977
9978     /* Adds, subtracts to/from 'pmfl' based on the next regex modifier flag
9979      * found in the parse starting at 's', based on the subset that are valid
9980      * in this context input to this routine in 'valid_flags'. Advances s.
9981      * Returns TRUE if the input should be treated as a valid flag, so the next
9982      * char may be as well; otherwise FALSE. 'charset' should point to a NUL
9983      * upon first call on the current regex.  This routine will set it to any
9984      * charset modifier found.  The caller shouldn't change it.  This way,
9985      * another charset modifier encountered in the parse can be detected as an
9986      * error, as we have decided to allow only one */
9987
9988     const char c = **s;
9989     STRLEN charlen = UTF ? UTF8SKIP(*s) : 1;
9990
9991     if ( charlen != 1 || ! strchr(valid_flags, c) ) {
9992         if (isWORDCHAR_lazy_if_safe( *s, PL_bufend, UTF)) {
9993             yyerror_pv(Perl_form(aTHX_ "Unknown regexp modifier \"/%.*s\"", (int)charlen, *s),
9994                        UTF ? SVf_UTF8 : 0);
9995             (*s) += charlen;
9996             /* Pretend that it worked, so will continue processing before
9997              * dieing */
9998             return TRUE;
9999         }
10000         return FALSE;
10001     }
10002
10003     switch (c) {
10004
10005         CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, *x_mod_count);
10006         case GLOBAL_PAT_MOD:      *pmfl |= PMf_GLOBAL; break;
10007         case CONTINUE_PAT_MOD:    *pmfl |= PMf_CONTINUE; break;
10008         case ONCE_PAT_MOD:        *pmfl |= PMf_KEEP; break;
10009         case KEEPCOPY_PAT_MOD:    *pmfl |= RXf_PMf_KEEPCOPY; break;
10010         case NONDESTRUCT_PAT_MOD: *pmfl |= PMf_NONDESTRUCT; break;
10011         case LOCALE_PAT_MOD:
10012             if (*charset) {
10013                 goto multiple_charsets;
10014             }
10015             set_regex_charset(pmfl, REGEX_LOCALE_CHARSET);
10016             *charset = c;
10017             break;
10018         case UNICODE_PAT_MOD:
10019             if (*charset) {
10020                 goto multiple_charsets;
10021             }
10022             set_regex_charset(pmfl, REGEX_UNICODE_CHARSET);
10023             *charset = c;
10024             break;
10025         case ASCII_RESTRICT_PAT_MOD:
10026             if (! *charset) {
10027                 set_regex_charset(pmfl, REGEX_ASCII_RESTRICTED_CHARSET);
10028             }
10029             else {
10030
10031                 /* Error if previous modifier wasn't an 'a', but if it was, see
10032                  * if, and accept, a second occurrence (only) */
10033                 if (*charset != 'a'
10034                     || get_regex_charset(*pmfl)
10035                         != REGEX_ASCII_RESTRICTED_CHARSET)
10036                 {
10037                         goto multiple_charsets;
10038                 }
10039                 set_regex_charset(pmfl, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
10040             }
10041             *charset = c;
10042             break;
10043         case DEPENDS_PAT_MOD:
10044             if (*charset) {
10045                 goto multiple_charsets;
10046             }
10047             set_regex_charset(pmfl, REGEX_DEPENDS_CHARSET);
10048             *charset = c;
10049             break;
10050     }
10051
10052     (*s)++;
10053     return TRUE;
10054
10055     multiple_charsets:
10056         if (*charset != c) {
10057             yyerror(Perl_form(aTHX_ "Regexp modifiers \"/%c\" and \"/%c\" are mutually exclusive", *charset, c));
10058         }
10059         else if (c == 'a') {
10060   /* diag_listed_as: Regexp modifier "/%c" may appear a maximum of twice */
10061             yyerror("Regexp modifier \"/a\" may appear a maximum of twice");
10062         }
10063         else {
10064             yyerror(Perl_form(aTHX_ "Regexp modifier \"/%c\" may not appear twice", c));
10065         }
10066
10067         /* Pretend that it worked, so will continue processing before dieing */
10068         (*s)++;
10069         return TRUE;
10070 }
10071
10072 STATIC char *
10073 S_scan_pat(pTHX_ char *start, I32 type)
10074 {
10075     PMOP *pm;
10076     char *s;
10077     const char * const valid_flags =
10078         (const char *)((type == OP_QR) ? QR_PAT_MODS : M_PAT_MODS);
10079     char charset = '\0';    /* character set modifier */
10080     unsigned int x_mod_count = 0;
10081
10082     PERL_ARGS_ASSERT_SCAN_PAT;
10083
10084     s = scan_str(start,TRUE,FALSE, (PL_in_eval & EVAL_RE_REPARSING), NULL);
10085     if (!s)
10086         Perl_croak(aTHX_ "Search pattern not terminated");
10087
10088     pm = (PMOP*)newPMOP(type, 0);
10089     if (PL_multi_open == '?') {
10090         /* This is the only point in the code that sets PMf_ONCE:  */
10091         pm->op_pmflags |= PMf_ONCE;
10092
10093         /* Hence it's safe to do this bit of PMOP book-keeping here, which
10094            allows us to restrict the list needed by reset to just the ??
10095            matches.  */
10096         assert(type != OP_TRANS);
10097         if (PL_curstash) {
10098             MAGIC *mg = mg_find((const SV *)PL_curstash, PERL_MAGIC_symtab);
10099             U32 elements;
10100             if (!mg) {
10101                 mg = sv_magicext(MUTABLE_SV(PL_curstash), 0, PERL_MAGIC_symtab, 0, 0,
10102                                  0);
10103             }
10104             elements = mg->mg_len / sizeof(PMOP**);
10105             Renewc(mg->mg_ptr, elements + 1, PMOP*, char);
10106             ((PMOP**)mg->mg_ptr) [elements++] = pm;
10107             mg->mg_len = elements * sizeof(PMOP**);
10108             PmopSTASH_set(pm,PL_curstash);
10109         }
10110     }
10111
10112     /* if qr/...(?{..}).../, then need to parse the pattern within a new
10113      * anon CV. False positives like qr/[(?{]/ are harmless */
10114
10115     if (type == OP_QR) {
10116         STRLEN len;
10117         char *e, *p = SvPV(PL_lex_stuff, len);
10118         e = p + len;
10119         for (; p < e; p++) {
10120             if (p[0] == '(' && p[1] == '?'
10121                 && (p[2] == '{' || (p[2] == '?' && p[3] == '{')))
10122             {
10123                 pm->op_pmflags |= PMf_HAS_CV;
10124                 break;
10125             }
10126         }
10127         pm->op_pmflags |= PMf_IS_QR;
10128     }
10129
10130     while (*s && S_pmflag(aTHX_ valid_flags, &(pm->op_pmflags),
10131                                 &s, &charset, &x_mod_count))
10132     {};
10133     /* issue a warning if /c is specified,but /g is not */
10134     if ((pm->op_pmflags & PMf_CONTINUE) && !(pm->op_pmflags & PMf_GLOBAL))
10135     {
10136         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10137                        "Use of /c modifier is meaningless without /g" );
10138     }
10139
10140     PL_lex_op = (OP*)pm;
10141     pl_yylval.ival = OP_MATCH;
10142     return s;
10143 }
10144
10145 STATIC char *
10146 S_scan_subst(pTHX_ char *start)
10147 {
10148     char *s;
10149     PMOP *pm;
10150     I32 first_start;
10151     line_t first_line;
10152     line_t linediff = 0;
10153     I32 es = 0;
10154     char charset = '\0';    /* character set modifier */
10155     unsigned int x_mod_count = 0;
10156     char *t;
10157
10158     PERL_ARGS_ASSERT_SCAN_SUBST;
10159
10160     pl_yylval.ival = OP_NULL;
10161
10162     s = scan_str(start, TRUE, FALSE, FALSE, &t);
10163
10164     if (!s)
10165         Perl_croak(aTHX_ "Substitution pattern not terminated");
10166
10167     s = t;
10168
10169     first_start = PL_multi_start;
10170     first_line = CopLINE(PL_curcop);
10171     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10172     if (!s) {
10173         SvREFCNT_dec_NN(PL_lex_stuff);
10174         PL_lex_stuff = NULL;
10175         Perl_croak(aTHX_ "Substitution replacement not terminated");
10176     }
10177     PL_multi_start = first_start;       /* so whole substitution is taken together */
10178
10179     pm = (PMOP*)newPMOP(OP_SUBST, 0);
10180
10181
10182     while (*s) {
10183         if (*s == EXEC_PAT_MOD) {
10184             s++;
10185             es++;
10186         }
10187         else if (! S_pmflag(aTHX_ S_PAT_MODS, &(pm->op_pmflags),
10188                                   &s, &charset, &x_mod_count))
10189         {
10190             break;
10191         }
10192     }
10193
10194     if ((pm->op_pmflags & PMf_CONTINUE)) {
10195         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Use of /c modifier is meaningless in s///" );
10196     }
10197
10198     if (es) {
10199         SV * const repl = newSVpvs("");
10200
10201         PL_multi_end = 0;
10202         pm->op_pmflags |= PMf_EVAL;
10203         for (; es > 1; es--) {
10204             sv_catpvs(repl, "eval ");
10205         }
10206         sv_catpvs(repl, "do {");
10207         sv_catsv(repl, PL_parser->lex_sub_repl);
10208         sv_catpvs(repl, "}");
10209         SvREFCNT_dec(PL_parser->lex_sub_repl);
10210         PL_parser->lex_sub_repl = repl;
10211     }
10212
10213
10214     linediff = CopLINE(PL_curcop) - first_line;
10215     if (linediff)
10216         CopLINE_set(PL_curcop, first_line);
10217
10218     if (linediff || es) {
10219         /* the IVX field indicates that the replacement string is a s///e;
10220          * the NVX field indicates how many src code lines the replacement
10221          * spreads over */
10222         sv_upgrade(PL_parser->lex_sub_repl, SVt_PVNV);
10223         ((XPVNV*)SvANY(PL_parser->lex_sub_repl))->xnv_u.xnv_lines = linediff;
10224         ((XPVIV*)SvANY(PL_parser->lex_sub_repl))->xiv_u.xivu_eval_seen =
10225                                                                     cBOOL(es);
10226     }
10227
10228     PL_lex_op = (OP*)pm;
10229     pl_yylval.ival = OP_SUBST;
10230     return s;
10231 }
10232
10233 STATIC char *
10234 S_scan_trans(pTHX_ char *start)
10235 {
10236     char* s;
10237     OP *o;
10238     U8 squash;
10239     U8 del;
10240     U8 complement;
10241     bool nondestruct = 0;
10242     char *t;
10243
10244     PERL_ARGS_ASSERT_SCAN_TRANS;
10245
10246     pl_yylval.ival = OP_NULL;
10247
10248     s = scan_str(start,FALSE,FALSE,FALSE,&t);
10249     if (!s)
10250         Perl_croak(aTHX_ "Transliteration pattern not terminated");
10251
10252     s = t;
10253
10254     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10255     if (!s) {
10256         SvREFCNT_dec_NN(PL_lex_stuff);
10257         PL_lex_stuff = NULL;
10258         Perl_croak(aTHX_ "Transliteration replacement not terminated");
10259     }
10260
10261     complement = del = squash = 0;
10262     while (1) {
10263         switch (*s) {
10264         case 'c':
10265             complement = OPpTRANS_COMPLEMENT;
10266             break;
10267         case 'd':
10268             del = OPpTRANS_DELETE;
10269             break;
10270         case 's':
10271             squash = OPpTRANS_SQUASH;
10272             break;
10273         case 'r':
10274             nondestruct = 1;
10275             break;
10276         default:
10277             goto no_more;
10278         }
10279         s++;
10280     }
10281   no_more:
10282
10283     o = newPVOP(nondestruct ? OP_TRANSR : OP_TRANS, 0, (char*)NULL);
10284     o->op_private &= ~OPpTRANS_ALL;
10285     o->op_private |= del|squash|complement;
10286
10287     PL_lex_op = o;
10288     pl_yylval.ival = nondestruct ? OP_TRANSR : OP_TRANS;
10289
10290
10291     return s;
10292 }
10293
10294 /* scan_heredoc
10295    Takes a pointer to the first < in <<FOO.
10296    Returns a pointer to the byte following <<FOO.
10297
10298    This function scans a heredoc, which involves different methods
10299    depending on whether we are in a string eval, quoted construct, etc.
10300    This is because PL_linestr could containing a single line of input, or
10301    a whole string being evalled, or the contents of the current quote-
10302    like operator.
10303
10304    The two basic methods are:
10305     - Steal lines from the input stream
10306     - Scan the heredoc in PL_linestr and remove it therefrom
10307
10308    In a file scope or filtered eval, the first method is used; in a
10309    string eval, the second.
10310
10311    In a quote-like operator, we have to choose between the two,
10312    depending on where we can find a newline.  We peek into outer lex-
10313    ing scopes until we find one with a newline in it.  If we reach the
10314    outermost lexing scope and it is a file, we use the stream method.
10315    Otherwise it is treated as an eval.
10316 */
10317
10318 STATIC char *
10319 S_scan_heredoc(pTHX_ char *s)
10320 {
10321     I32 op_type = OP_SCALAR;
10322     I32 len;
10323     SV *tmpstr;
10324     char term;
10325     char *d;
10326     char *e;
10327     char *peek;
10328     char *indent = 0;
10329     I32 indent_len = 0;
10330     bool indented = FALSE;
10331     const bool infile = PL_rsfp || PL_parser->filtered;
10332     const line_t origline = CopLINE(PL_curcop);
10333     LEXSHARED *shared = PL_parser->lex_shared;
10334
10335     PERL_ARGS_ASSERT_SCAN_HEREDOC;
10336
10337     s += 2;
10338     d = PL_tokenbuf + 1;
10339     e = PL_tokenbuf + sizeof PL_tokenbuf - 1;
10340     *PL_tokenbuf = '\n';
10341     peek = s;
10342
10343     if (*peek == '~') {
10344         indented = TRUE;
10345         peek++; s++;
10346     }
10347
10348     while (SPACE_OR_TAB(*peek))
10349         peek++;
10350
10351     if (*peek == '`' || *peek == '\'' || *peek =='"') {
10352         s = peek;
10353         term = *s++;
10354         s = delimcpy(d, e, s, PL_bufend, term, &len);
10355         if (s == PL_bufend)
10356             Perl_croak(aTHX_ "Unterminated delimiter for here document");
10357         d += len;
10358         s++;
10359     }
10360     else {
10361         if (*s == '\\')
10362             /* <<\FOO is equivalent to <<'FOO' */
10363             s++, term = '\'';
10364         else
10365             term = '"';
10366
10367         if (! isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
10368             Perl_croak(aTHX_ "Use of bare << to mean <<\"\" is forbidden");
10369
10370         peek = s;
10371
10372         while (isWORDCHAR_lazy_if_safe(peek, PL_bufend, UTF)) {
10373             peek += UTF ? UTF8SKIP(peek) : 1;
10374         }
10375
10376         len = (peek - s >= e - d) ? (e - d) : (peek - s);
10377         Copy(s, d, len, char);
10378         s += len;
10379         d += len;
10380     }
10381
10382     if (d >= PL_tokenbuf + sizeof PL_tokenbuf - 1)
10383         Perl_croak(aTHX_ "Delimiter for here document is too long");
10384
10385     *d++ = '\n';
10386     *d = '\0';
10387     len = d - PL_tokenbuf;
10388
10389 #ifndef PERL_STRICT_CR
10390     d = (char *) memchr(s, '\r', PL_bufend - s);
10391     if (d) {
10392         char * const olds = s;
10393         s = d;
10394         while (s < PL_bufend) {
10395             if (*s == '\r') {
10396                 *d++ = '\n';
10397                 if (*++s == '\n')
10398                     s++;
10399             }
10400             else if (*s == '\n' && s[1] == '\r') {      /* \015\013 on a mac? */
10401                 *d++ = *s++;
10402                 s++;
10403             }
10404             else
10405                 *d++ = *s++;
10406         }
10407         *d = '\0';
10408         PL_bufend = d;
10409         SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10410         s = olds;
10411     }
10412 #endif
10413
10414     tmpstr = newSV_type(SVt_PVIV);
10415     SvGROW(tmpstr, 80);
10416     if (term == '\'') {
10417         op_type = OP_CONST;
10418         SvIV_set(tmpstr, -1);
10419     }
10420     else if (term == '`') {
10421         op_type = OP_BACKTICK;
10422         SvIV_set(tmpstr, '\\');
10423     }
10424
10425     PL_multi_start = origline + 1 + PL_parser->herelines;
10426     PL_multi_open = PL_multi_close = '<';
10427
10428     /* inside a string eval or quote-like operator */
10429     if (!infile || PL_lex_inwhat) {
10430         SV *linestr;
10431         char *bufend;
10432         char * const olds = s;
10433         PERL_CONTEXT * const cx = CX_CUR();
10434         /* These two fields are not set until an inner lexing scope is
10435            entered.  But we need them set here. */
10436         shared->ls_bufptr  = s;
10437         shared->ls_linestr = PL_linestr;
10438
10439         if (PL_lex_inwhat) {
10440             /* Look for a newline.  If the current buffer does not have one,
10441              peek into the line buffer of the parent lexing scope, going
10442              up as many levels as necessary to find one with a newline
10443              after bufptr.
10444             */
10445             while (!(s = (char *)memchr(
10446                                 (void *)shared->ls_bufptr, '\n',
10447                                 SvEND(shared->ls_linestr)-shared->ls_bufptr
10448                 )))
10449             {
10450                 shared = shared->ls_prev;
10451                 /* shared is only null if we have gone beyond the outermost
10452                    lexing scope.  In a file, we will have broken out of the
10453                    loop in the previous iteration.  In an eval, the string buf-
10454                    fer ends with "\n;", so the while condition above will have
10455                    evaluated to false.  So shared can never be null.  Or so you
10456                    might think.  Odd syntax errors like s;@{<<; can gobble up
10457                    the implicit semicolon at the end of a flie, causing the
10458                    file handle to be closed even when we are not in a string
10459                    eval.  So shared may be null in that case.
10460                    (Closing '>>}' here to balance the earlier open brace for
10461                    editors that look for matched pairs.) */
10462                 if (UNLIKELY(!shared))
10463                     goto interminable;
10464                 /* A LEXSHARED struct with a null ls_prev pointer is the outer-
10465                    most lexing scope.  In a file, shared->ls_linestr at that
10466                    level is just one line, so there is no body to steal. */
10467                 if (infile && !shared->ls_prev) {
10468                     s = olds;
10469                     goto streaming;
10470                 }
10471             }
10472         }
10473         else {  /* eval or we've already hit EOF */
10474             s = (char*)memchr((void*)s, '\n', PL_bufend - s);
10475             if (!s)
10476                 goto interminable;
10477         }
10478
10479         linestr = shared->ls_linestr;
10480         bufend = SvEND(linestr);
10481         d = s;
10482         if (indented) {
10483             char *myolds = s;
10484
10485             while (s < bufend - len + 1) {
10486                 if (*s++ == '\n')
10487                     ++PL_parser->herelines;
10488
10489                 if (memEQ(s, PL_tokenbuf + 1, len - 1)) {
10490                     char *backup = s;
10491                     indent_len = 0;
10492
10493                     /* Only valid if it's preceded by whitespace only */
10494                     while (backup != myolds && --backup >= myolds) {
10495                         if (! SPACE_OR_TAB(*backup)) {
10496                             break;
10497                         }
10498                         indent_len++;
10499                     }
10500
10501                     /* No whitespace or all! */
10502                     if (backup == s || *backup == '\n') {
10503                         Newx(indent, indent_len + 1, char);
10504                         memcpy(indent, backup + 1, indent_len);
10505                         indent[indent_len] = 0;
10506                         s--; /* before our delimiter */
10507                         PL_parser->herelines--; /* this line doesn't count */
10508                         break;
10509                     }
10510                 }
10511             }
10512         }
10513         else {
10514             while (s < bufend - len + 1
10515                    && memNE(s,PL_tokenbuf,len) )
10516             {
10517                 if (*s++ == '\n')
10518                     ++PL_parser->herelines;
10519             }
10520         }
10521
10522         if (s >= bufend - len + 1) {
10523             goto interminable;
10524         }
10525
10526         sv_setpvn(tmpstr,d+1,s-d);
10527         s += len - 1;
10528         /* the preceding stmt passes a newline */
10529         PL_parser->herelines++;
10530
10531         /* s now points to the newline after the heredoc terminator.
10532            d points to the newline before the body of the heredoc.
10533          */
10534
10535         /* We are going to modify linestr in place here, so set
10536            aside copies of the string if necessary for re-evals or
10537            (caller $n)[6]. */
10538         /* See the Paranoia note in case LEX_INTERPEND in yylex, for why we
10539            check shared->re_eval_str. */
10540         if (shared->re_eval_start || shared->re_eval_str) {
10541             /* Set aside the rest of the regexp */
10542             if (!shared->re_eval_str)
10543                 shared->re_eval_str =
10544                        newSVpvn(shared->re_eval_start,
10545                                 bufend - shared->re_eval_start);
10546             shared->re_eval_start -= s-d;
10547         }
10548
10549         if (cxstack_ix >= 0
10550             && CxTYPE(cx) == CXt_EVAL
10551             && CxOLD_OP_TYPE(cx) == OP_ENTEREVAL
10552             && cx->blk_eval.cur_text == linestr)
10553         {
10554             cx->blk_eval.cur_text = newSVsv(linestr);
10555             cx->blk_u16 |= 0x40; /* indicate cur_text is ref counted */
10556         }
10557
10558         /* Copy everything from s onwards back to d. */
10559         Move(s,d,bufend-s + 1,char);
10560         SvCUR_set(linestr, SvCUR(linestr) - (s-d));
10561         /* Setting PL_bufend only applies when we have not dug deeper
10562            into other scopes, because sublex_done sets PL_bufend to
10563            SvEND(PL_linestr). */
10564         if (shared == PL_parser->lex_shared)
10565             PL_bufend = SvEND(linestr);
10566         s = olds;
10567     }
10568     else {
10569         SV *linestr_save;
10570         char *oldbufptr_save;
10571         char *oldoldbufptr_save;
10572       streaming:
10573         SvPVCLEAR(tmpstr);   /* avoid "uninitialized" warning */
10574         term = PL_tokenbuf[1];
10575         len--;
10576         linestr_save = PL_linestr; /* must restore this afterwards */
10577         d = s;                   /* and this */
10578         oldbufptr_save = PL_oldbufptr;
10579         oldoldbufptr_save = PL_oldoldbufptr;
10580         PL_linestr = newSVpvs("");
10581         PL_bufend = SvPVX(PL_linestr);
10582
10583         while (1) {
10584             PL_bufptr = PL_bufend;
10585             CopLINE_set(PL_curcop,
10586                         origline + 1 + PL_parser->herelines);
10587
10588             if (   !lex_next_chunk(LEX_NO_TERM)
10589                 && (!SvCUR(tmpstr) || SvEND(tmpstr)[-1] != '\n'))
10590             {
10591                 /* Simply freeing linestr_save might seem simpler here, as it
10592                    does not matter what PL_linestr points to, since we are
10593                    about to croak; but in a quote-like op, linestr_save
10594                    will have been prospectively freed already, via
10595                    SAVEFREESV(PL_linestr) in sublex_push, so it’s easier to
10596                    restore PL_linestr. */
10597                 SvREFCNT_dec_NN(PL_linestr);
10598                 PL_linestr = linestr_save;
10599                 PL_oldbufptr = oldbufptr_save;
10600                 PL_oldoldbufptr = oldoldbufptr_save;
10601                 goto interminable;
10602             }
10603
10604             CopLINE_set(PL_curcop, origline);
10605
10606             if (!SvCUR(PL_linestr) || PL_bufend[-1] != '\n') {
10607                 s = lex_grow_linestr(SvLEN(PL_linestr) + 3);
10608                 /* ^That should be enough to avoid this needing to grow:  */
10609                 sv_catpvs(PL_linestr, "\n\0");
10610                 assert(s == SvPVX(PL_linestr));
10611                 PL_bufend = SvEND(PL_linestr);
10612             }
10613
10614             s = PL_bufptr;
10615             PL_parser->herelines++;
10616             PL_last_lop = PL_last_uni = NULL;
10617
10618 #ifndef PERL_STRICT_CR
10619             if (PL_bufend - PL_linestart >= 2) {
10620                 if (   (PL_bufend[-2] == '\r' && PL_bufend[-1] == '\n')
10621                     || (PL_bufend[-2] == '\n' && PL_bufend[-1] == '\r'))
10622                 {
10623                     PL_bufend[-2] = '\n';
10624                     PL_bufend--;
10625                     SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10626                 }
10627                 else if (PL_bufend[-1] == '\r')
10628                     PL_bufend[-1] = '\n';
10629             }
10630             else if (PL_bufend - PL_linestart == 1 && PL_bufend[-1] == '\r')
10631                 PL_bufend[-1] = '\n';
10632 #endif
10633
10634             if (indented && (PL_bufend-s) >= len) {
10635                 char * found = ninstr(s, PL_bufend, (PL_tokenbuf + 1), (PL_tokenbuf +1 + len));
10636
10637                 if (found) {
10638                     char *backup = found;
10639                     indent_len = 0;
10640
10641                     /* Only valid if it's preceded by whitespace only */
10642                     while (backup != s && --backup >= s) {
10643                         if (! SPACE_OR_TAB(*backup)) {
10644                             break;
10645                         }
10646                         indent_len++;
10647                     }
10648
10649                     /* All whitespace or none! */
10650                     if (backup == found || SPACE_OR_TAB(*backup)) {
10651                         Newx(indent, indent_len + 1, char);
10652                         memcpy(indent, backup, indent_len);
10653                         indent[indent_len] = 0;
10654                         SvREFCNT_dec(PL_linestr);
10655                         PL_linestr = linestr_save;
10656                         PL_linestart = SvPVX(linestr_save);
10657                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10658                         PL_oldbufptr = oldbufptr_save;
10659                         PL_oldoldbufptr = oldoldbufptr_save;
10660                         s = d;
10661                         break;
10662                     }
10663                 }
10664
10665                 /* Didn't find it */
10666                 sv_catsv(tmpstr,PL_linestr);
10667             }
10668             else {
10669                 if (*s == term && PL_bufend-s >= len
10670                     && memEQ(s,PL_tokenbuf + 1,len))
10671                 {
10672                     SvREFCNT_dec(PL_linestr);
10673                     PL_linestr = linestr_save;
10674                     PL_linestart = SvPVX(linestr_save);
10675                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10676                     PL_oldbufptr = oldbufptr_save;
10677                     PL_oldoldbufptr = oldoldbufptr_save;
10678                     s = d;
10679                     break;
10680                 }
10681                 else {
10682                     sv_catsv(tmpstr,PL_linestr);
10683                 }
10684             }
10685         } /* while (1) */
10686     }
10687
10688     PL_multi_end = origline + PL_parser->herelines;
10689
10690     if (indented && indent) {
10691         STRLEN linecount = 1;
10692         STRLEN herelen = SvCUR(tmpstr);
10693         char *ss = SvPVX(tmpstr);
10694         char *se = ss + herelen;
10695         SV *newstr = newSV(herelen+1);
10696         SvPOK_on(newstr);
10697
10698         /* Trim leading whitespace */
10699         while (ss < se) {
10700             /* newline only? Copy and move on */
10701             if (*ss == '\n') {
10702                 sv_catpvs(newstr,"\n");
10703                 ss++;
10704                 linecount++;
10705
10706             /* Found our indentation? Strip it */
10707             }
10708             else if (se - ss >= indent_len
10709                        && memEQ(ss, indent, indent_len))
10710             {
10711                 STRLEN le = 0;
10712                 ss += indent_len;
10713
10714                 while ((ss + le) < se && *(ss + le) != '\n')
10715                     le++;
10716
10717                 sv_catpvn(newstr, ss, le);
10718                 ss += le;
10719
10720             /* Line doesn't begin with our indentation? Croak */
10721             }
10722             else {
10723                 Safefree(indent);
10724                 Perl_croak(aTHX_
10725                     "Indentation on line %d of here-doc doesn't match delimiter",
10726                     (int)linecount
10727                 );
10728             }
10729         } /* while */
10730
10731         /* avoid sv_setsv() as we dont wan't to COW here */
10732         sv_setpvn(tmpstr,SvPVX(newstr),SvCUR(newstr));
10733         Safefree(indent);
10734         SvREFCNT_dec_NN(newstr);
10735     }
10736
10737     if (SvCUR(tmpstr) + 5 < SvLEN(tmpstr)) {
10738         SvPV_shrink_to_cur(tmpstr);
10739     }
10740
10741     if (!IN_BYTES) {
10742         if (UTF && is_utf8_string((U8*)SvPVX_const(tmpstr), SvCUR(tmpstr)))
10743             SvUTF8_on(tmpstr);
10744     }
10745
10746     PL_lex_stuff = tmpstr;
10747     pl_yylval.ival = op_type;
10748     return s;
10749
10750   interminable:
10751     if (indent)
10752         Safefree(indent);
10753     SvREFCNT_dec(tmpstr);
10754     CopLINE_set(PL_curcop, origline);
10755     missingterm(PL_tokenbuf + 1, sizeof(PL_tokenbuf) - 1);
10756 }
10757
10758
10759 /* scan_inputsymbol
10760    takes: position of first '<' in input buffer
10761    returns: position of first char following the matching '>' in
10762             input buffer
10763    side-effects: pl_yylval and lex_op are set.
10764
10765    This code handles:
10766
10767    <>           read from ARGV
10768    <<>>         read from ARGV without magic open
10769    <FH>         read from filehandle
10770    <pkg::FH>    read from package qualified filehandle
10771    <pkg'FH>     read from package qualified filehandle
10772    <$fh>        read from filehandle in $fh
10773    <*.h>        filename glob
10774
10775 */
10776
10777 STATIC char *
10778 S_scan_inputsymbol(pTHX_ char *start)
10779 {
10780     char *s = start;            /* current position in buffer */
10781     char *end;
10782     I32 len;
10783     bool nomagicopen = FALSE;
10784     char *d = PL_tokenbuf;                                      /* start of temp holding space */
10785     const char * const e = PL_tokenbuf + sizeof PL_tokenbuf;    /* end of temp holding space */
10786
10787     PERL_ARGS_ASSERT_SCAN_INPUTSYMBOL;
10788
10789     end = (char *) memchr(s, '\n', PL_bufend - s);
10790     if (!end)
10791         end = PL_bufend;
10792     if (s[1] == '<' && s[2] == '>' && s[3] == '>') {
10793         nomagicopen = TRUE;
10794         *d = '\0';
10795         len = 0;
10796         s += 3;
10797     }
10798     else
10799         s = delimcpy(d, e, s + 1, end, '>', &len);      /* extract until > */
10800
10801     /* die if we didn't have space for the contents of the <>,
10802        or if it didn't end, or if we see a newline
10803     */
10804
10805     if (len >= (I32)sizeof PL_tokenbuf)
10806         Perl_croak(aTHX_ "Excessively long <> operator");
10807     if (s >= end)
10808         Perl_croak(aTHX_ "Unterminated <> operator");
10809
10810     s++;
10811
10812     /* check for <$fh>
10813        Remember, only scalar variables are interpreted as filehandles by
10814        this code.  Anything more complex (e.g., <$fh{$num}>) will be
10815        treated as a glob() call.
10816        This code makes use of the fact that except for the $ at the front,
10817        a scalar variable and a filehandle look the same.
10818     */
10819     if (*d == '$' && d[1]) d++;
10820
10821     /* allow <Pkg'VALUE> or <Pkg::VALUE> */
10822     while (isWORDCHAR_lazy_if_safe(d, e, UTF) || *d == '\'' || *d == ':') {
10823         d += UTF ? UTF8SKIP(d) : 1;
10824     }
10825
10826     /* If we've tried to read what we allow filehandles to look like, and
10827        there's still text left, then it must be a glob() and not a getline.
10828        Use scan_str to pull out the stuff between the <> and treat it
10829        as nothing more than a string.
10830     */
10831
10832     if (d - PL_tokenbuf != len) {
10833         pl_yylval.ival = OP_GLOB;
10834         s = scan_str(start,FALSE,FALSE,FALSE,NULL);
10835         if (!s)
10836            Perl_croak(aTHX_ "Glob not terminated");
10837         return s;
10838     }
10839     else {
10840         bool readline_overriden = FALSE;
10841         GV *gv_readline;
10842         /* we're in a filehandle read situation */
10843         d = PL_tokenbuf;
10844
10845         /* turn <> into <ARGV> */
10846         if (!len)
10847             Copy("ARGV",d,5,char);
10848
10849         /* Check whether readline() is overriden */
10850         if ((gv_readline = gv_override("readline",8)))
10851             readline_overriden = TRUE;
10852
10853         /* if <$fh>, create the ops to turn the variable into a
10854            filehandle
10855         */
10856         if (*d == '$') {
10857             /* try to find it in the pad for this block, otherwise find
10858                add symbol table ops
10859             */
10860             const PADOFFSET tmp = pad_findmy_pvn(d, len, 0);
10861             if (tmp != NOT_IN_PAD) {
10862                 if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
10863                     HV * const stash = PAD_COMPNAME_OURSTASH(tmp);
10864                     HEK * const stashname = HvNAME_HEK(stash);
10865                     SV * const sym = sv_2mortal(newSVhek(stashname));
10866                     sv_catpvs(sym, "::");
10867                     sv_catpv(sym, d+1);
10868                     d = SvPVX(sym);
10869                     goto intro_sym;
10870                 }
10871                 else {
10872                     OP * const o = newOP(OP_PADSV, 0);
10873                     o->op_targ = tmp;
10874                     PL_lex_op = readline_overriden
10875                         ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10876                                 op_append_elem(OP_LIST, o,
10877                                     newCVREF(0, newGVOP(OP_GV,0,gv_readline))))
10878                         : newUNOP(OP_READLINE, 0, o);
10879                 }
10880             }
10881             else {
10882                 GV *gv;
10883                 ++d;
10884               intro_sym:
10885                 gv = gv_fetchpv(d,
10886                                 GV_ADDMULTI | ( UTF ? SVf_UTF8 : 0 ),
10887                                 SVt_PV);
10888                 PL_lex_op = readline_overriden
10889                     ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10890                             op_append_elem(OP_LIST,
10891                                 newUNOP(OP_RV2SV, 0, newGVOP(OP_GV, 0, gv)),
10892                                 newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10893                     : newUNOP(OP_READLINE, 0,
10894                             newUNOP(OP_RV2SV, 0,
10895                                 newGVOP(OP_GV, 0, gv)));
10896             }
10897             /* we created the ops in PL_lex_op, so make pl_yylval.ival a null op */
10898             pl_yylval.ival = OP_NULL;
10899         }
10900
10901         /* If it's none of the above, it must be a literal filehandle
10902            (<Foo::BAR> or <FOO>) so build a simple readline OP */
10903         else {
10904             GV * const gv = gv_fetchpv(d, GV_ADD | ( UTF ? SVf_UTF8 : 0 ), SVt_PVIO);
10905             PL_lex_op = readline_overriden
10906                 ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10907                         op_append_elem(OP_LIST,
10908                             newGVOP(OP_GV, 0, gv),
10909                             newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10910                 : newUNOP(OP_READLINE, nomagicopen ? OPf_SPECIAL : 0, newGVOP(OP_GV, 0, gv));
10911             pl_yylval.ival = OP_NULL;
10912         }
10913     }
10914
10915     return s;
10916 }
10917
10918
10919 /* scan_str
10920    takes:
10921         start                   position in buffer
10922         keep_bracketed_quoted   preserve \ quoting of embedded delimiters, but
10923                                 only if they are of the open/close form
10924         keep_delims             preserve the delimiters around the string
10925         re_reparse              compiling a run-time /(?{})/:
10926                                    collapse // to /,  and skip encoding src
10927         delimp                  if non-null, this is set to the position of
10928                                 the closing delimiter, or just after it if
10929                                 the closing and opening delimiters differ
10930                                 (i.e., the opening delimiter of a substitu-
10931                                 tion replacement)
10932    returns: position to continue reading from buffer
10933    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
10934         updates the read buffer.
10935
10936    This subroutine pulls a string out of the input.  It is called for:
10937         q               single quotes           q(literal text)
10938         '               single quotes           'literal text'
10939         qq              double quotes           qq(interpolate $here please)
10940         "               double quotes           "interpolate $here please"
10941         qx              backticks               qx(/bin/ls -l)
10942         `               backticks               `/bin/ls -l`
10943         qw              quote words             @EXPORT_OK = qw( func() $spam )
10944         m//             regexp match            m/this/
10945         s///            regexp substitute       s/this/that/
10946         tr///           string transliterate    tr/this/that/
10947         y///            string transliterate    y/this/that/
10948         ($*@)           sub prototypes          sub foo ($)
10949         (stuff)         sub attr parameters     sub foo : attr(stuff)
10950         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
10951
10952    In most of these cases (all but <>, patterns and transliterate)
10953    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
10954    calls scan_str().  s/// makes yylex() call scan_subst() which calls
10955    scan_str().  tr/// and y/// make yylex() call scan_trans() which
10956    calls scan_str().
10957
10958    It skips whitespace before the string starts, and treats the first
10959    character as the delimiter.  If the delimiter is one of ([{< then
10960    the corresponding "close" character )]}> is used as the closing
10961    delimiter.  It allows quoting of delimiters, and if the string has
10962    balanced delimiters ([{<>}]) it allows nesting.
10963
10964    On success, the SV with the resulting string is put into lex_stuff or,
10965    if that is already non-NULL, into lex_repl. The second case occurs only
10966    when parsing the RHS of the special constructs s/// and tr/// (y///).
10967    For convenience, the terminating delimiter character is stuffed into
10968    SvIVX of the SV.
10969 */
10970
10971 char *
10972 Perl_scan_str(pTHX_ char *start, int keep_bracketed_quoted, int keep_delims, int re_reparse,
10973                  char **delimp
10974     )
10975 {
10976     SV *sv;                     /* scalar value: string */
10977     const char *tmps;           /* temp string, used for delimiter matching */
10978     char *s = start;            /* current position in the buffer */
10979     char term;                  /* terminating character */
10980     char *to;                   /* current position in the sv's data */
10981     I32 brackets = 1;           /* bracket nesting level */
10982     bool d_is_utf8 = FALSE;     /* is there any utf8 content? */
10983     IV termcode;                /* terminating char. code */
10984     U8 termstr[UTF8_MAXBYTES+1]; /* terminating string */
10985     STRLEN termlen;             /* length of terminating string */
10986     line_t herelines;
10987
10988     /* The delimiters that have a mirror-image closing one */
10989     const char * opening_delims = "([{<";
10990     const char * closing_delims = ")]}>";
10991
10992     /* The only non-UTF character that isn't a stand alone grapheme is
10993      * white-space, hence can't be a delimiter. */
10994     const char * non_grapheme_msg = "Use of unassigned code point or"
10995                                     " non-standalone grapheme for a delimiter"
10996                                     " is not allowed";
10997     PERL_ARGS_ASSERT_SCAN_STR;
10998
10999     /* skip space before the delimiter */
11000     if (isSPACE(*s)) {
11001         s = skipspace(s);
11002     }
11003
11004     /* mark where we are, in case we need to report errors */
11005     CLINE;
11006
11007     /* after skipping whitespace, the next character is the terminator */
11008     term = *s;
11009     if (!UTF || UTF8_IS_INVARIANT(term)) {
11010         termcode = termstr[0] = term;
11011         termlen = 1;
11012     }
11013     else {
11014         termcode = utf8_to_uvchr_buf((U8*)s, (U8*)PL_bufend, &termlen);
11015         if (UTF && UNLIKELY(! _is_grapheme((U8 *) start,
11016                                            (U8 *) s,
11017                                            (U8 *) PL_bufend,
11018                                                   termcode)))
11019         {
11020             yyerror(non_grapheme_msg);
11021         }
11022
11023         Copy(s, termstr, termlen, U8);
11024     }
11025
11026     /* mark where we are */
11027     PL_multi_start = CopLINE(PL_curcop);
11028     PL_multi_open = termcode;
11029     herelines = PL_parser->herelines;
11030
11031     /* If the delimiter has a mirror-image closing one, get it */
11032     if (term && (tmps = strchr(opening_delims, term))) {
11033         termcode = termstr[0] = term = closing_delims[tmps - opening_delims];
11034     }
11035
11036     PL_multi_close = termcode;
11037
11038     if (PL_multi_open == PL_multi_close) {
11039         keep_bracketed_quoted = FALSE;
11040     }
11041
11042     /* create a new SV to hold the contents.  79 is the SV's initial length.
11043        What a random number. */
11044     sv = newSV_type(SVt_PVIV);
11045     SvGROW(sv, 80);
11046     SvIV_set(sv, termcode);
11047     (void)SvPOK_only(sv);               /* validate pointer */
11048
11049     /* move past delimiter and try to read a complete string */
11050     if (keep_delims)
11051         sv_catpvn(sv, s, termlen);
11052     s += termlen;
11053     for (;;) {
11054         /* extend sv if need be */
11055         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
11056         /* set 'to' to the next character in the sv's string */
11057         to = SvPVX(sv)+SvCUR(sv);
11058
11059         /* if open delimiter is the close delimiter read unbridle */
11060         if (PL_multi_open == PL_multi_close) {
11061             for (; s < PL_bufend; s++,to++) {
11062                 /* embedded newlines increment the current line number */
11063                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11064                     COPLINE_INC_WITH_HERELINES;
11065                 /* handle quoted delimiters */
11066                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
11067                     if (!keep_bracketed_quoted
11068                         && (s[1] == term
11069                             || (re_reparse && s[1] == '\\'))
11070                     )
11071                         s++;
11072                     else /* any other quotes are simply copied straight through */
11073                         *to++ = *s++;
11074                 }
11075                 /* terminate when run out of buffer (the for() condition), or
11076                    have found the terminator */
11077                 else if (*s == term) {  /* First byte of terminator matches */
11078                     if (termlen == 1)   /* If is the only byte, are done */
11079                         break;
11080
11081                     /* If the remainder of the terminator matches, also are
11082                      * done, after checking that is a separate grapheme */
11083                     if (   s + termlen <= PL_bufend
11084                         && memEQ(s + 1, (char*)termstr + 1, termlen - 1))
11085                     {
11086                         if (   UTF
11087                             && UNLIKELY(! _is_grapheme((U8 *) start,
11088                                                        (U8 *) s,
11089                                                        (U8 *) PL_bufend,
11090                                                               termcode)))
11091                         {
11092                             yyerror(non_grapheme_msg);
11093                         }
11094                         break;
11095                     }
11096                 }
11097                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF) {
11098                     d_is_utf8 = TRUE;
11099                 }
11100
11101                 *to = *s;
11102             }
11103         }
11104
11105         /* if the terminator isn't the same as the start character (e.g.,
11106            matched brackets), we have to allow more in the quoting, and
11107            be prepared for nested brackets.
11108         */
11109         else {
11110             /* read until we run out of string, or we find the terminator */
11111             for (; s < PL_bufend; s++,to++) {
11112                 /* embedded newlines increment the line count */
11113                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11114                     COPLINE_INC_WITH_HERELINES;
11115                 /* backslashes can escape the open or closing characters */
11116                 if (*s == '\\' && s+1 < PL_bufend) {
11117                     if (!keep_bracketed_quoted
11118                        && ( ((UV)s[1] == PL_multi_open)
11119                          || ((UV)s[1] == PL_multi_close) ))
11120                     {
11121                         s++;
11122                     }
11123                     else
11124                         *to++ = *s++;
11125                 }
11126                 /* allow nested opens and closes */
11127                 else if ((UV)*s == PL_multi_close && --brackets <= 0)
11128                     break;
11129                 else if ((UV)*s == PL_multi_open)
11130                     brackets++;
11131                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
11132                     d_is_utf8 = TRUE;
11133                 *to = *s;
11134             }
11135         }
11136         /* terminate the copied string and update the sv's end-of-string */
11137         *to = '\0';
11138         SvCUR_set(sv, to - SvPVX_const(sv));
11139
11140         /*
11141          * this next chunk reads more into the buffer if we're not done yet
11142          */
11143
11144         if (s < PL_bufend)
11145             break;              /* handle case where we are done yet :-) */
11146
11147 #ifndef PERL_STRICT_CR
11148         if (to - SvPVX_const(sv) >= 2) {
11149             if (   (to[-2] == '\r' && to[-1] == '\n')
11150                 || (to[-2] == '\n' && to[-1] == '\r'))
11151             {
11152                 to[-2] = '\n';
11153                 to--;
11154                 SvCUR_set(sv, to - SvPVX_const(sv));
11155             }
11156             else if (to[-1] == '\r')
11157                 to[-1] = '\n';
11158         }
11159         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
11160             to[-1] = '\n';
11161 #endif
11162
11163         /* if we're out of file, or a read fails, bail and reset the current
11164            line marker so we can report where the unterminated string began
11165         */
11166         COPLINE_INC_WITH_HERELINES;
11167         PL_bufptr = PL_bufend;
11168         if (!lex_next_chunk(0)) {
11169             sv_free(sv);
11170             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
11171             return NULL;
11172         }
11173         s = start = PL_bufptr;
11174     }
11175
11176     /* at this point, we have successfully read the delimited string */
11177
11178     if (keep_delims)
11179             sv_catpvn(sv, s, termlen);
11180     s += termlen;
11181
11182     if (d_is_utf8)
11183         SvUTF8_on(sv);
11184
11185     PL_multi_end = CopLINE(PL_curcop);
11186     CopLINE_set(PL_curcop, PL_multi_start);
11187     PL_parser->herelines = herelines;
11188
11189     /* if we allocated too much space, give some back */
11190     if (SvCUR(sv) + 5 < SvLEN(sv)) {
11191         SvLEN_set(sv, SvCUR(sv) + 1);
11192         SvPV_renew(sv, SvLEN(sv));
11193     }
11194
11195     /* decide whether this is the first or second quoted string we've read
11196        for this op
11197     */
11198
11199     if (PL_lex_stuff)
11200         PL_parser->lex_sub_repl = sv;
11201     else
11202         PL_lex_stuff = sv;
11203     if (delimp) *delimp = PL_multi_open == PL_multi_close ? s-termlen : s;
11204     return s;
11205 }
11206
11207 /*
11208   scan_num
11209   takes: pointer to position in buffer
11210   returns: pointer to new position in buffer
11211   side-effects: builds ops for the constant in pl_yylval.op
11212
11213   Read a number in any of the formats that Perl accepts:
11214
11215   \d(_?\d)*(\.(\d(_?\d)*)?)?[Ee][\+\-]?(\d(_?\d)*)      12 12.34 12.
11216   \.\d(_?\d)*[Ee][\+\-]?(\d(_?\d)*)                     .34
11217   0b[01](_?[01])*                                       binary integers
11218   0[0-7](_?[0-7])*                                      octal integers
11219   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*                         hexadecimal integers
11220   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*(?:\.\d*)?p[+-]?[0-9]+   hexadecimal floats
11221
11222   Like most scan_ routines, it uses the PL_tokenbuf buffer to hold the
11223   thing it reads.
11224
11225   If it reads a number without a decimal point or an exponent, it will
11226   try converting the number to an integer and see if it can do so
11227   without loss of precision.
11228 */
11229
11230 char *
11231 Perl_scan_num(pTHX_ const char *start, YYSTYPE* lvalp)
11232 {
11233     const char *s = start;      /* current position in buffer */
11234     char *d;                    /* destination in temp buffer */
11235     char *e;                    /* end of temp buffer */
11236     NV nv;                              /* number read, as a double */
11237     SV *sv = NULL;                      /* place to put the converted number */
11238     bool floatit;                       /* boolean: int or float? */
11239     const char *lastub = NULL;          /* position of last underbar */
11240     static const char* const number_too_long = "Number too long";
11241     bool warned_about_underscore = 0;
11242     I32 shift; /* shift per digit for hex/oct/bin, hoisted here for fp */
11243 #define WARN_ABOUT_UNDERSCORE() \
11244         do { \
11245             if (!warned_about_underscore) { \
11246                 warned_about_underscore = 1; \
11247                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), \
11248                                "Misplaced _ in number"); \
11249             } \
11250         } while(0)
11251     /* Hexadecimal floating point.
11252      *
11253      * In many places (where we have quads and NV is IEEE 754 double)
11254      * we can fit the mantissa bits of a NV into an unsigned quad.
11255      * (Note that UVs might not be quads even when we have quads.)
11256      * This will not work everywhere, though (either no quads, or
11257      * using long doubles), in which case we have to resort to NV,
11258      * which will probably mean horrible loss of precision due to
11259      * multiple fp operations. */
11260     bool hexfp = FALSE;
11261     int total_bits = 0;
11262     int significant_bits = 0;
11263 #if NVSIZE == 8 && defined(HAS_QUAD) && defined(Uquad_t)
11264 #  define HEXFP_UQUAD
11265     Uquad_t hexfp_uquad = 0;
11266     int hexfp_frac_bits = 0;
11267 #else
11268 #  define HEXFP_NV
11269     NV hexfp_nv = 0.0;
11270 #endif
11271     NV hexfp_mult = 1.0;
11272     UV high_non_zero = 0; /* highest digit */
11273     int non_zero_integer_digits = 0;
11274
11275     PERL_ARGS_ASSERT_SCAN_NUM;
11276
11277     /* We use the first character to decide what type of number this is */
11278
11279     switch (*s) {
11280     default:
11281         Perl_croak(aTHX_ "panic: scan_num, *s=%d", *s);
11282
11283     /* if it starts with a 0, it could be an octal number, a decimal in
11284        0.13 disguise, or a hexadecimal number, or a binary number. */
11285     case '0':
11286         {
11287           /* variables:
11288              u          holds the "number so far"
11289              overflowed was the number more than we can hold?
11290
11291              Shift is used when we add a digit.  It also serves as an "are
11292              we in octal/hex/binary?" indicator to disallow hex characters
11293              when in octal mode.
11294            */
11295             NV n = 0.0;
11296             UV u = 0;
11297             bool overflowed = FALSE;
11298             bool just_zero  = TRUE;     /* just plain 0 or binary number? */
11299             bool has_digs = FALSE;
11300             static const NV nvshift[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
11301             static const char* const bases[5] =
11302               { "", "binary", "", "octal", "hexadecimal" };
11303             static const char* const Bases[5] =
11304               { "", "Binary", "", "Octal", "Hexadecimal" };
11305             static const char* const maxima[5] =
11306               { "",
11307                 "0b11111111111111111111111111111111",
11308                 "",
11309                 "037777777777",
11310                 "0xffffffff" };
11311             const char *base, *Base, *max;
11312
11313             /* check for hex */
11314             if (isALPHA_FOLD_EQ(s[1], 'x')) {
11315                 shift = 4;
11316                 s += 2;
11317                 just_zero = FALSE;
11318             } else if (isALPHA_FOLD_EQ(s[1], 'b')) {
11319                 shift = 1;
11320                 s += 2;
11321                 just_zero = FALSE;
11322             }
11323             /* check for a decimal in disguise */
11324             else if (s[1] == '.' || isALPHA_FOLD_EQ(s[1], 'e'))
11325                 goto decimal;
11326             /* so it must be octal */
11327             else {
11328                 shift = 3;
11329                 s++;
11330             }
11331
11332             if (*s == '_') {
11333                 WARN_ABOUT_UNDERSCORE();
11334                lastub = s++;
11335             }
11336
11337             base = bases[shift];
11338             Base = Bases[shift];
11339             max  = maxima[shift];
11340
11341             /* read the rest of the number */
11342             for (;;) {
11343                 /* x is used in the overflow test,
11344                    b is the digit we're adding on. */
11345                 UV x, b;
11346
11347                 switch (*s) {
11348
11349                 /* if we don't mention it, we're done */
11350                 default:
11351                     goto out;
11352
11353                 /* _ are ignored -- but warned about if consecutive */
11354                 case '_':
11355                     if (lastub && s == lastub + 1)
11356                         WARN_ABOUT_UNDERSCORE();
11357                     lastub = s++;
11358                     break;
11359
11360                 /* 8 and 9 are not octal */
11361                 case '8': case '9':
11362                     if (shift == 3)
11363                         yyerror(Perl_form(aTHX_ "Illegal octal digit '%c'", *s));
11364                     /* FALLTHROUGH */
11365
11366                 /* octal digits */
11367                 case '2': case '3': case '4':
11368                 case '5': case '6': case '7':
11369                     if (shift == 1)
11370                         yyerror(Perl_form(aTHX_ "Illegal binary digit '%c'", *s));
11371                     /* FALLTHROUGH */
11372
11373                 case '0': case '1':
11374                     b = *s++ & 15;              /* ASCII digit -> value of digit */
11375                     goto digit;
11376
11377                 /* hex digits */
11378                 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
11379                 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
11380                     /* make sure they said 0x */
11381                     if (shift != 4)
11382                         goto out;
11383                     b = (*s++ & 7) + 9;
11384
11385                     /* Prepare to put the digit we have onto the end
11386                        of the number so far.  We check for overflows.
11387                     */
11388
11389                   digit:
11390                     just_zero = FALSE;
11391                     has_digs = TRUE;
11392                     if (!overflowed) {
11393                         assert(shift >= 0);
11394                         x = u << shift; /* make room for the digit */
11395
11396                         total_bits += shift;
11397
11398                         if ((x >> shift) != u
11399                             && !(PL_hints & HINT_NEW_BINARY)) {
11400                             overflowed = TRUE;
11401                             n = (NV) u;
11402                             Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
11403                                              "Integer overflow in %s number",
11404                                              base);
11405                         } else
11406                             u = x | b;          /* add the digit to the end */
11407                     }
11408                     if (overflowed) {
11409                         n *= nvshift[shift];
11410                         /* If an NV has not enough bits in its
11411                          * mantissa to represent an UV this summing of
11412                          * small low-order numbers is a waste of time
11413                          * (because the NV cannot preserve the
11414                          * low-order bits anyway): we could just
11415                          * remember when did we overflow and in the
11416                          * end just multiply n by the right
11417                          * amount. */
11418                         n += (NV) b;
11419                     }
11420
11421                     if (high_non_zero == 0 && b > 0)
11422                         high_non_zero = b;
11423
11424                     if (high_non_zero)
11425                         non_zero_integer_digits++;
11426
11427                     /* this could be hexfp, but peek ahead
11428                      * to avoid matching ".." */
11429                     if (UNLIKELY(HEXFP_PEEK(s))) {
11430                         goto out;
11431                     }
11432
11433                     break;
11434                 }
11435             }
11436
11437           /* if we get here, we had success: make a scalar value from
11438              the number.
11439           */
11440           out:
11441
11442             /* final misplaced underbar check */
11443             if (s[-1] == '_')
11444                 WARN_ABOUT_UNDERSCORE();
11445
11446             if (UNLIKELY(HEXFP_PEEK(s))) {
11447                 /* Do sloppy (on the underbars) but quick detection
11448                  * (and value construction) for hexfp, the decimal
11449                  * detection will shortly be more thorough with the
11450                  * underbar checks. */
11451                 const char* h = s;
11452                 significant_bits = non_zero_integer_digits * shift;
11453 #ifdef HEXFP_UQUAD
11454                 hexfp_uquad = u;
11455 #else /* HEXFP_NV */
11456                 hexfp_nv = u;
11457 #endif
11458                 /* Ignore the leading zero bits of
11459                  * the high (first) non-zero digit. */
11460                 if (high_non_zero) {
11461                     if (high_non_zero < 0x8)
11462                         significant_bits--;
11463                     if (high_non_zero < 0x4)
11464                         significant_bits--;
11465                     if (high_non_zero < 0x2)
11466                         significant_bits--;
11467                 }
11468
11469                 if (*h == '.') {
11470 #ifdef HEXFP_NV
11471                     NV nv_mult = 1.0;
11472 #endif
11473                     bool accumulate = TRUE;
11474                     U8 b;
11475                     int lim = 1 << shift;
11476                     for (h++; ((isXDIGIT(*h) && (b = XDIGIT_VALUE(*h)) < lim) ||
11477                                *h == '_'); h++) {
11478                         if (isXDIGIT(*h)) {
11479                             significant_bits += shift;
11480 #ifdef HEXFP_UQUAD
11481                             if (accumulate) {
11482                                 if (significant_bits < NV_MANT_DIG) {
11483                                     /* We are in the long "run" of xdigits,
11484                                      * accumulate the full four bits. */
11485                                     assert(shift >= 0);
11486                                     hexfp_uquad <<= shift;
11487                                     hexfp_uquad |= b;
11488                                     hexfp_frac_bits += shift;
11489                                 } else if (significant_bits - shift < NV_MANT_DIG) {
11490                                     /* We are at a hexdigit either at,
11491                                      * or straddling, the edge of mantissa.
11492                                      * We will try grabbing as many as
11493                                      * possible bits. */
11494                                     int tail =
11495                                       significant_bits - NV_MANT_DIG;
11496                                     if (tail <= 0)
11497                                        tail += shift;
11498                                     assert(tail >= 0);
11499                                     hexfp_uquad <<= tail;
11500                                     assert((shift - tail) >= 0);
11501                                     hexfp_uquad |= b >> (shift - tail);
11502                                     hexfp_frac_bits += tail;
11503
11504                                     /* Ignore the trailing zero bits
11505                                      * of the last non-zero xdigit.
11506                                      *
11507                                      * The assumption here is that if
11508                                      * one has input of e.g. the xdigit
11509                                      * eight (0x8), there is only one
11510                                      * bit being input, not the full
11511                                      * four bits.  Conversely, if one
11512                                      * specifies a zero xdigit, the
11513                                      * assumption is that one really
11514                                      * wants all those bits to be zero. */
11515                                     if (b) {
11516                                         if ((b & 0x1) == 0x0) {
11517                                             significant_bits--;
11518                                             if ((b & 0x2) == 0x0) {
11519                                                 significant_bits--;
11520                                                 if ((b & 0x4) == 0x0) {
11521                                                     significant_bits--;
11522                                                 }
11523                                             }
11524                                         }
11525                                     }
11526
11527                                     accumulate = FALSE;
11528                                 }
11529                             } else {
11530                                 /* Keep skipping the xdigits, and
11531                                  * accumulating the significant bits,
11532                                  * but do not shift the uquad
11533                                  * (which would catastrophically drop
11534                                  * high-order bits) or accumulate the
11535                                  * xdigits anymore. */
11536                             }
11537 #else /* HEXFP_NV */
11538                             if (accumulate) {
11539                                 nv_mult /= nvshift[shift];
11540                                 if (nv_mult > 0.0)
11541                                     hexfp_nv += b * nv_mult;
11542                                 else
11543                                     accumulate = FALSE;
11544                             }
11545 #endif
11546                         }
11547                         if (significant_bits >= NV_MANT_DIG)
11548                             accumulate = FALSE;
11549                     }
11550                 }
11551
11552                 if ((total_bits > 0 || significant_bits > 0) &&
11553                     isALPHA_FOLD_EQ(*h, 'p')) {
11554                     bool negexp = FALSE;
11555                     h++;
11556                     if (*h == '+')
11557                         h++;
11558                     else if (*h == '-') {
11559                         negexp = TRUE;
11560                         h++;
11561                     }
11562                     if (isDIGIT(*h)) {
11563                         I32 hexfp_exp = 0;
11564                         while (isDIGIT(*h) || *h == '_') {
11565                             if (isDIGIT(*h)) {
11566                                 hexfp_exp *= 10;
11567                                 hexfp_exp += *h - '0';
11568 #ifdef NV_MIN_EXP
11569                                 if (negexp
11570                                     && -hexfp_exp < NV_MIN_EXP - 1) {
11571                                     /* NOTE: this means that the exponent
11572                                      * underflow warning happens for
11573                                      * the IEEE 754 subnormals (denormals),
11574                                      * because DBL_MIN_EXP etc are the lowest
11575                                      * possible binary (or, rather, DBL_RADIX-base)
11576                                      * exponent for normals, not subnormals.
11577                                      *
11578                                      * This may or may not be a good thing. */
11579                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11580                                                    "Hexadecimal float: exponent underflow");
11581                                     break;
11582                                 }
11583 #endif
11584 #ifdef NV_MAX_EXP
11585                                 if (!negexp
11586                                     && hexfp_exp > NV_MAX_EXP - 1) {
11587                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11588                                                    "Hexadecimal float: exponent overflow");
11589                                     break;
11590                                 }
11591 #endif
11592                             }
11593                             h++;
11594                         }
11595                         if (negexp)
11596                             hexfp_exp = -hexfp_exp;
11597 #ifdef HEXFP_UQUAD
11598                         hexfp_exp -= hexfp_frac_bits;
11599 #endif
11600                         hexfp_mult = Perl_pow(2.0, hexfp_exp);
11601                         hexfp = TRUE;
11602                         goto decimal;
11603                     }
11604                 }
11605             }
11606
11607             if (shift != 3 && !has_digs) {
11608                 /* 0x or 0b with no digits, treat it as an error.
11609                    Originally this backed up the parse before the b or
11610                    x, but that has the potential for silent changes in
11611                    behaviour, like for: "0x.3" and "0x+$foo".
11612                 */
11613                 const char *d = s;
11614                 char *oldbp = PL_bufptr;
11615                 if (*d) ++d; /* so the user sees the bad non-digit */
11616                 PL_bufptr = (char *)d; /* so yyerror reports the context */
11617                 yyerror(Perl_form(aTHX_ "No digits found for %s literal",
11618                                   shift == 4 ? "hexadecimal" : "binary"));
11619                 PL_bufptr = oldbp;
11620             }
11621
11622             if (overflowed) {
11623                 if (n > 4294967295.0)
11624                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11625                                    "%s number > %s non-portable",
11626                                    Base, max);
11627                 sv = newSVnv(n);
11628             }
11629             else {
11630 #if UVSIZE > 4
11631                 if (u > 0xffffffff)
11632                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11633                                    "%s number > %s non-portable",
11634                                    Base, max);
11635 #endif
11636                 sv = newSVuv(u);
11637             }
11638             if (just_zero && (PL_hints & HINT_NEW_INTEGER))
11639                 sv = new_constant(start, s - start, "integer",
11640                                   sv, NULL, NULL, 0, NULL);
11641             else if (PL_hints & HINT_NEW_BINARY)
11642                 sv = new_constant(start, s - start, "binary",
11643                                   sv, NULL, NULL, 0, NULL);
11644         }
11645         break;
11646
11647     /*
11648       handle decimal numbers.
11649       we're also sent here when we read a 0 as the first digit
11650     */
11651     case '1': case '2': case '3': case '4': case '5':
11652     case '6': case '7': case '8': case '9': case '.':
11653       decimal:
11654         d = PL_tokenbuf;
11655         e = PL_tokenbuf + sizeof PL_tokenbuf - 6; /* room for various punctuation */
11656         floatit = FALSE;
11657         if (hexfp) {
11658             floatit = TRUE;
11659             *d++ = '0';
11660             switch (shift) {
11661             case 4:
11662                 *d++ = 'x';
11663                 s = start + 2;
11664                 break;
11665             case 3:
11666                 s = start + 1;
11667                 break;
11668             case 1:
11669                 *d++ = 'b';
11670                 s = start + 2;
11671                 break;
11672             default:
11673                 NOT_REACHED; /* NOTREACHED */
11674             }
11675         }
11676
11677         /* read next group of digits and _ and copy into d */
11678         while (isDIGIT(*s)
11679                || *s == '_'
11680                || UNLIKELY(hexfp && isXDIGIT(*s)))
11681         {
11682             /* skip underscores, checking for misplaced ones
11683                if -w is on
11684             */
11685             if (*s == '_') {
11686                 if (lastub && s == lastub + 1)
11687                     WARN_ABOUT_UNDERSCORE();
11688                 lastub = s++;
11689             }
11690             else {
11691                 /* check for end of fixed-length buffer */
11692                 if (d >= e)
11693                     Perl_croak(aTHX_ "%s", number_too_long);
11694                 /* if we're ok, copy the character */
11695                 *d++ = *s++;
11696             }
11697         }
11698
11699         /* final misplaced underbar check */
11700         if (lastub && s == lastub + 1)
11701             WARN_ABOUT_UNDERSCORE();
11702
11703         /* read a decimal portion if there is one.  avoid
11704            3..5 being interpreted as the number 3. followed
11705            by .5
11706         */
11707         if (*s == '.' && s[1] != '.') {
11708             floatit = TRUE;
11709             *d++ = *s++;
11710
11711             if (*s == '_') {
11712                 WARN_ABOUT_UNDERSCORE();
11713                 lastub = s;
11714             }
11715
11716             /* copy, ignoring underbars, until we run out of digits.
11717             */
11718             for (; isDIGIT(*s)
11719                    || *s == '_'
11720                    || UNLIKELY(hexfp && isXDIGIT(*s));
11721                  s++)
11722             {
11723                 /* fixed length buffer check */
11724                 if (d >= e)
11725                     Perl_croak(aTHX_ "%s", number_too_long);
11726                 if (*s == '_') {
11727                    if (lastub && s == lastub + 1)
11728                         WARN_ABOUT_UNDERSCORE();
11729                    lastub = s;
11730                 }
11731                 else
11732                     *d++ = *s;
11733             }
11734             /* fractional part ending in underbar? */
11735             if (s[-1] == '_')
11736                 WARN_ABOUT_UNDERSCORE();
11737             if (*s == '.' && isDIGIT(s[1])) {
11738                 /* oops, it's really a v-string, but without the "v" */
11739                 s = start;
11740                 goto vstring;
11741             }
11742         }
11743
11744         /* read exponent part, if present */
11745         if ((isALPHA_FOLD_EQ(*s, 'e')
11746               || UNLIKELY(hexfp && isALPHA_FOLD_EQ(*s, 'p')))
11747             && strchr("+-0123456789_", s[1]))
11748         {
11749             int exp_digits = 0;
11750             const char *save_s = s;
11751             char * save_d = d;
11752
11753             /* regardless of whether user said 3E5 or 3e5, use lower 'e',
11754                ditto for p (hexfloats) */
11755             if ((isALPHA_FOLD_EQ(*s, 'e'))) {
11756                 /* At least some Mach atof()s don't grok 'E' */
11757                 *d++ = 'e';
11758             }
11759             else if (UNLIKELY(hexfp && (isALPHA_FOLD_EQ(*s, 'p')))) {
11760                 *d++ = 'p';
11761             }
11762
11763             s++;
11764
11765
11766             /* stray preinitial _ */
11767             if (*s == '_') {
11768                 WARN_ABOUT_UNDERSCORE();
11769                 lastub = s++;
11770             }
11771
11772             /* allow positive or negative exponent */
11773             if (*s == '+' || *s == '-')
11774                 *d++ = *s++;
11775
11776             /* stray initial _ */
11777             if (*s == '_') {
11778                 WARN_ABOUT_UNDERSCORE();
11779                 lastub = s++;
11780             }
11781
11782             /* read digits of exponent */
11783             while (isDIGIT(*s) || *s == '_') {
11784                 if (isDIGIT(*s)) {
11785                     ++exp_digits;
11786                     if (d >= e)
11787                         Perl_croak(aTHX_ "%s", number_too_long);
11788                     *d++ = *s++;
11789                 }
11790                 else {
11791                    if (((lastub && s == lastub + 1)
11792                         || (!isDIGIT(s[1]) && s[1] != '_')))
11793                         WARN_ABOUT_UNDERSCORE();
11794                    lastub = s++;
11795                 }
11796             }
11797
11798             if (!exp_digits) {
11799                 /* no exponent digits, the [eEpP] could be for something else,
11800                  * though in practice we don't get here for p since that's preparsed
11801                  * earlier, and results in only the 0xX being consumed, so behave similarly
11802                  * for decimal floats and consume only the D.DD, leaving the [eE] to the
11803                  * next token.
11804                  */
11805                 s = save_s;
11806                 d = save_d;
11807             }
11808             else {
11809                 floatit = TRUE;
11810             }
11811         }
11812
11813
11814         /*
11815            We try to do an integer conversion first if no characters
11816            indicating "float" have been found.
11817          */
11818
11819         if (!floatit) {
11820             UV uv;
11821             const int flags = grok_number (PL_tokenbuf, d - PL_tokenbuf, &uv);
11822
11823             if (flags == IS_NUMBER_IN_UV) {
11824               if (uv <= IV_MAX)
11825                 sv = newSViv(uv); /* Prefer IVs over UVs. */
11826               else
11827                 sv = newSVuv(uv);
11828             } else if (flags == (IS_NUMBER_IN_UV | IS_NUMBER_NEG)) {
11829               if (uv <= (UV) IV_MIN)
11830                 sv = newSViv(-(IV)uv);
11831               else
11832                 floatit = TRUE;
11833             } else
11834               floatit = TRUE;
11835         }
11836         if (floatit) {
11837             /* terminate the string */
11838             *d = '\0';
11839             if (UNLIKELY(hexfp)) {
11840 #  ifdef NV_MANT_DIG
11841                 if (significant_bits > NV_MANT_DIG)
11842                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11843                                    "Hexadecimal float: mantissa overflow");
11844 #  endif
11845 #ifdef HEXFP_UQUAD
11846                 nv = hexfp_uquad * hexfp_mult;
11847 #else /* HEXFP_NV */
11848                 nv = hexfp_nv * hexfp_mult;
11849 #endif
11850             } else {
11851                 nv = Atof(PL_tokenbuf);
11852             }
11853             sv = newSVnv(nv);
11854         }
11855
11856         if ( floatit
11857              ? (PL_hints & HINT_NEW_FLOAT) : (PL_hints & HINT_NEW_INTEGER) ) {
11858             const char *const key = floatit ? "float" : "integer";
11859             const STRLEN keylen = floatit ? 5 : 7;
11860             sv = S_new_constant(aTHX_ PL_tokenbuf, d - PL_tokenbuf,
11861                                 key, keylen, sv, NULL, NULL, 0, NULL);
11862         }
11863         break;
11864
11865     /* if it starts with a v, it could be a v-string */
11866     case 'v':
11867     vstring:
11868                 sv = newSV(5); /* preallocate storage space */
11869                 ENTER_with_name("scan_vstring");
11870                 SAVEFREESV(sv);
11871                 s = scan_vstring(s, PL_bufend, sv);
11872                 SvREFCNT_inc_simple_void_NN(sv);
11873                 LEAVE_with_name("scan_vstring");
11874         break;
11875     }
11876
11877     /* make the op for the constant and return */
11878
11879     if (sv)
11880         lvalp->opval = newSVOP(OP_CONST, 0, sv);
11881     else
11882         lvalp->opval = NULL;
11883
11884     return (char *)s;
11885 }
11886
11887 STATIC char *
11888 S_scan_formline(pTHX_ char *s)
11889 {
11890     SV * const stuff = newSVpvs("");
11891     bool needargs = FALSE;
11892     bool eofmt = FALSE;
11893
11894     PERL_ARGS_ASSERT_SCAN_FORMLINE;
11895
11896     while (!needargs) {
11897         char *eol;
11898         if (*s == '.') {
11899             char *t = s+1;
11900 #ifdef PERL_STRICT_CR
11901             while (SPACE_OR_TAB(*t))
11902                 t++;
11903 #else
11904             while (SPACE_OR_TAB(*t) || *t == '\r')
11905                 t++;
11906 #endif
11907             if (*t == '\n' || t == PL_bufend) {
11908                 eofmt = TRUE;
11909                 break;
11910             }
11911         }
11912         eol = (char *) memchr(s,'\n',PL_bufend-s);
11913         if (!eol++)
11914                 eol = PL_bufend;
11915         if (*s != '#') {
11916             char *t;
11917             for (t = s; t < eol; t++) {
11918                 if (*t == '~' && t[1] == '~' && SvCUR(stuff)) {
11919                     needargs = FALSE;
11920                     goto enough;        /* ~~ must be first line in formline */
11921                 }
11922                 if (*t == '@' || *t == '^')
11923                     needargs = TRUE;
11924             }
11925             if (eol > s) {
11926                 sv_catpvn(stuff, s, eol-s);
11927 #ifndef PERL_STRICT_CR
11928                 if (eol-s > 1 && eol[-2] == '\r' && eol[-1] == '\n') {
11929                     char *end = SvPVX(stuff) + SvCUR(stuff);
11930                     end[-2] = '\n';
11931                     end[-1] = '\0';
11932                     SvCUR_set(stuff, SvCUR(stuff) - 1);
11933                 }
11934 #endif
11935             }
11936             else
11937               break;
11938         }
11939         s = (char*)eol;
11940         if ((PL_rsfp || PL_parser->filtered)
11941          && PL_parser->form_lex_state == LEX_NORMAL) {
11942             bool got_some;
11943             PL_bufptr = PL_bufend;
11944             COPLINE_INC_WITH_HERELINES;
11945             got_some = lex_next_chunk(0);
11946             CopLINE_dec(PL_curcop);
11947             s = PL_bufptr;
11948             if (!got_some)
11949                 break;
11950         }
11951         incline(s, PL_bufend);
11952     }
11953   enough:
11954     if (!SvCUR(stuff) || needargs)
11955         PL_lex_state = PL_parser->form_lex_state;
11956     if (SvCUR(stuff)) {
11957         PL_expect = XSTATE;
11958         if (needargs) {
11959             const char *s2 = s;
11960             while (isSPACE(*s2) && *s2 != '\n')
11961                 s2++;
11962             if (*s2 == '{') {
11963                 PL_expect = XTERMBLOCK;
11964                 NEXTVAL_NEXTTOKE.ival = 0;
11965                 force_next(DO);
11966             }
11967             NEXTVAL_NEXTTOKE.ival = 0;
11968             force_next(FORMLBRACK);
11969         }
11970         if (!IN_BYTES) {
11971             if (UTF && is_utf8_string((U8*)SvPVX_const(stuff), SvCUR(stuff)))
11972                 SvUTF8_on(stuff);
11973         }
11974         NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0, stuff);
11975         force_next(THING);
11976     }
11977     else {
11978         SvREFCNT_dec(stuff);
11979         if (eofmt)
11980             PL_lex_formbrack = 0;
11981     }
11982     return s;
11983 }
11984
11985 I32
11986 Perl_start_subparse(pTHX_ I32 is_format, U32 flags)
11987 {
11988     const I32 oldsavestack_ix = PL_savestack_ix;
11989     CV* const outsidecv = PL_compcv;
11990
11991     SAVEI32(PL_subline);
11992     save_item(PL_subname);
11993     SAVESPTR(PL_compcv);
11994
11995     PL_compcv = MUTABLE_CV(newSV_type(is_format ? SVt_PVFM : SVt_PVCV));
11996     CvFLAGS(PL_compcv) |= flags;
11997
11998     PL_subline = CopLINE(PL_curcop);
11999     CvPADLIST(PL_compcv) = pad_new(padnew_SAVE|padnew_SAVESUB);
12000     CvOUTSIDE(PL_compcv) = MUTABLE_CV(SvREFCNT_inc_simple(outsidecv));
12001     CvOUTSIDE_SEQ(PL_compcv) = PL_cop_seqmax;
12002     if (outsidecv && CvPADLIST(outsidecv))
12003         CvPADLIST(PL_compcv)->xpadl_outid = CvPADLIST(outsidecv)->xpadl_id;
12004
12005     return oldsavestack_ix;
12006 }
12007
12008
12009 /* Do extra initialisation of a CV (typically one just created by
12010  * start_subparse()) if that CV is for a named sub
12011  */
12012
12013 void
12014 Perl_init_named_cv(pTHX_ CV *cv, OP *nameop)
12015 {
12016     PERL_ARGS_ASSERT_INIT_NAMED_CV;
12017
12018     if (nameop->op_type == OP_CONST) {
12019         const char *const name = SvPV_nolen_const(((SVOP*)nameop)->op_sv);
12020         if (   strEQ(name, "BEGIN")
12021             || strEQ(name, "END")
12022             || strEQ(name, "INIT")
12023             || strEQ(name, "CHECK")
12024             || strEQ(name, "UNITCHECK")
12025         )
12026           CvSPECIAL_on(cv);
12027     }
12028     else
12029     /* State subs inside anonymous subs need to be
12030      clonable themselves. */
12031     if (   CvANON(CvOUTSIDE(cv))
12032         || CvCLONE(CvOUTSIDE(cv))
12033         || !PadnameIsSTATE(PadlistNAMESARRAY(CvPADLIST(
12034                         CvOUTSIDE(cv)
12035                      ))[nameop->op_targ])
12036     )
12037       CvCLONE_on(cv);
12038 }
12039
12040
12041 static int
12042 S_yywarn(pTHX_ const char *const s, U32 flags)
12043 {
12044     PERL_ARGS_ASSERT_YYWARN;
12045
12046     PL_in_eval |= EVAL_WARNONLY;
12047     yyerror_pv(s, flags);
12048     return 0;
12049 }
12050
12051 void
12052 Perl_abort_execution(pTHX_ const char * const msg, const char * const name)
12053 {
12054     PERL_ARGS_ASSERT_ABORT_EXECUTION;
12055
12056     if (PL_minus_c)
12057         Perl_croak(aTHX_ "%s%s had compilation errors.\n", msg, name);
12058     else {
12059         Perl_croak(aTHX_
12060                 "%sExecution of %s aborted due to compilation errors.\n", msg, name);
12061     }
12062     NOT_REACHED; /* NOTREACHED */
12063 }
12064
12065 void
12066 Perl_yyquit(pTHX)
12067 {
12068     /* Called, after at least one error has been found, to abort the parse now,
12069      * instead of trying to forge ahead */
12070
12071     yyerror_pvn(NULL, 0, 0);
12072 }
12073
12074 int
12075 Perl_yyerror(pTHX_ const char *const s)
12076 {
12077     PERL_ARGS_ASSERT_YYERROR;
12078     return yyerror_pvn(s, strlen(s), 0);
12079 }
12080
12081 int
12082 Perl_yyerror_pv(pTHX_ const char *const s, U32 flags)
12083 {
12084     PERL_ARGS_ASSERT_YYERROR_PV;
12085     return yyerror_pvn(s, strlen(s), flags);
12086 }
12087
12088 int
12089 Perl_yyerror_pvn(pTHX_ const char *const s, STRLEN len, U32 flags)
12090 {
12091     const char *context = NULL;
12092     int contlen = -1;
12093     SV *msg;
12094     SV * const where_sv = newSVpvs_flags("", SVs_TEMP);
12095     int yychar  = PL_parser->yychar;
12096
12097     /* Output error message 's' with length 'len'.  'flags' are SV flags that
12098      * apply.  If the number of errors found is large enough, it abandons
12099      * parsing.  If 's' is NULL, there is no message, and it abandons
12100      * processing unconditionally */
12101
12102     if (s != NULL) {
12103         if (!yychar || (yychar == ';' && !PL_rsfp))
12104             sv_catpvs(where_sv, "at EOF");
12105         else if (   PL_oldoldbufptr
12106                  && PL_bufptr > PL_oldoldbufptr
12107                  && PL_bufptr - PL_oldoldbufptr < 200
12108                  && PL_oldoldbufptr != PL_oldbufptr
12109                  && PL_oldbufptr != PL_bufptr)
12110         {
12111             /*
12112                     Only for NetWare:
12113                     The code below is removed for NetWare because it
12114                     abends/crashes on NetWare when the script has error such as
12115                     not having the closing quotes like:
12116                         if ($var eq "value)
12117                     Checking of white spaces is anyway done in NetWare code.
12118             */
12119 #ifndef NETWARE
12120             while (isSPACE(*PL_oldoldbufptr))
12121                 PL_oldoldbufptr++;
12122 #endif
12123             context = PL_oldoldbufptr;
12124             contlen = PL_bufptr - PL_oldoldbufptr;
12125         }
12126         else if (  PL_oldbufptr
12127                 && PL_bufptr > PL_oldbufptr
12128                 && PL_bufptr - PL_oldbufptr < 200
12129                 && PL_oldbufptr != PL_bufptr) {
12130             /*
12131                     Only for NetWare:
12132                     The code below is removed for NetWare because it
12133                     abends/crashes on NetWare when the script has error such as
12134                     not having the closing quotes like:
12135                         if ($var eq "value)
12136                     Checking of white spaces is anyway done in NetWare code.
12137             */
12138 #ifndef NETWARE
12139             while (isSPACE(*PL_oldbufptr))
12140                 PL_oldbufptr++;
12141 #endif
12142             context = PL_oldbufptr;
12143             contlen = PL_bufptr - PL_oldbufptr;
12144         }
12145         else if (yychar > 255)
12146             sv_catpvs(where_sv, "next token ???");
12147         else if (yychar == YYEMPTY) {
12148             if (PL_lex_state == LEX_NORMAL)
12149                 sv_catpvs(where_sv, "at end of line");
12150             else if (PL_lex_inpat)
12151                 sv_catpvs(where_sv, "within pattern");
12152             else
12153                 sv_catpvs(where_sv, "within string");
12154         }
12155         else {
12156             sv_catpvs(where_sv, "next char ");
12157             if (yychar < 32)
12158                 Perl_sv_catpvf(aTHX_ where_sv, "^%c", toCTRL(yychar));
12159             else if (isPRINT_LC(yychar)) {
12160                 const char string = yychar;
12161                 sv_catpvn(where_sv, &string, 1);
12162             }
12163             else
12164                 Perl_sv_catpvf(aTHX_ where_sv, "\\%03o", yychar & 255);
12165         }
12166         msg = newSVpvn_flags(s, len, (flags & SVf_UTF8) | SVs_TEMP);
12167         Perl_sv_catpvf(aTHX_ msg, " at %s line %" IVdf ", ",
12168             OutCopFILE(PL_curcop),
12169             (IV)(PL_parser->preambling == NOLINE
12170                    ? CopLINE(PL_curcop)
12171                    : PL_parser->preambling));
12172         if (context)
12173             Perl_sv_catpvf(aTHX_ msg, "near \"%" UTF8f "\"\n",
12174                                  UTF8fARG(UTF, contlen, context));
12175         else
12176             Perl_sv_catpvf(aTHX_ msg, "%" SVf "\n", SVfARG(where_sv));
12177         if (   PL_multi_start < PL_multi_end
12178             && (U32)(CopLINE(PL_curcop) - PL_multi_end) <= 1)
12179         {
12180             Perl_sv_catpvf(aTHX_ msg,
12181             "  (Might be a runaway multi-line %c%c string starting on"
12182             " line %" IVdf ")\n",
12183                     (int)PL_multi_open,(int)PL_multi_close,(IV)PL_multi_start);
12184             PL_multi_end = 0;
12185         }
12186         if (PL_in_eval & EVAL_WARNONLY) {
12187             PL_in_eval &= ~EVAL_WARNONLY;
12188             Perl_ck_warner_d(aTHX_ packWARN(WARN_SYNTAX), "%" SVf, SVfARG(msg));
12189         }
12190         else {
12191             qerror(msg);
12192         }
12193     }
12194     if (s == NULL || PL_error_count >= 10) {
12195         const char * msg = "";
12196         const char * const name = OutCopFILE(PL_curcop);
12197
12198         if (PL_in_eval) {
12199             SV * errsv = ERRSV;
12200             if (SvCUR(errsv)) {
12201                 msg = Perl_form(aTHX_ "%" SVf, SVfARG(errsv));
12202             }
12203         }
12204
12205         if (s == NULL) {
12206             abort_execution(msg, name);
12207         }
12208         else {
12209             Perl_croak(aTHX_ "%s%s has too many errors.\n", msg, name);
12210         }
12211     }
12212     PL_in_my = 0;
12213     PL_in_my_stash = NULL;
12214     return 0;
12215 }
12216
12217 STATIC char*
12218 S_swallow_bom(pTHX_ U8 *s)
12219 {
12220     const STRLEN slen = SvCUR(PL_linestr);
12221
12222     PERL_ARGS_ASSERT_SWALLOW_BOM;
12223
12224     switch (s[0]) {
12225     case 0xFF:
12226         if (s[1] == 0xFE) {
12227             /* UTF-16 little-endian? (or UTF-32LE?) */
12228             if (s[2] == 0 && s[3] == 0)  /* UTF-32 little-endian */
12229                 /* diag_listed_as: Unsupported script encoding %s */
12230                 Perl_croak(aTHX_ "Unsupported script encoding UTF-32LE");
12231 #ifndef PERL_NO_UTF16_FILTER
12232 #ifdef DEBUGGING
12233             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (BOM)\n");
12234 #endif
12235             s += 2;
12236             if (PL_bufend > (char*)s) {
12237                 s = add_utf16_textfilter(s, TRUE);
12238             }
12239 #else
12240             /* diag_listed_as: Unsupported script encoding %s */
12241             Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12242 #endif
12243         }
12244         break;
12245     case 0xFE:
12246         if (s[1] == 0xFF) {   /* UTF-16 big-endian? */
12247 #ifndef PERL_NO_UTF16_FILTER
12248 #ifdef DEBUGGING
12249             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (BOM)\n");
12250 #endif
12251             s += 2;
12252             if (PL_bufend > (char *)s) {
12253                 s = add_utf16_textfilter(s, FALSE);
12254             }
12255 #else
12256             /* diag_listed_as: Unsupported script encoding %s */
12257             Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12258 #endif
12259         }
12260         break;
12261     case BOM_UTF8_FIRST_BYTE: {
12262         if (memBEGINs(s+1, slen - 1, BOM_UTF8_TAIL)) {
12263 #ifdef DEBUGGING
12264             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-8 script encoding (BOM)\n");
12265 #endif
12266             s += sizeof(BOM_UTF8) - 1;                     /* UTF-8 */
12267         }
12268         break;
12269     }
12270     case 0:
12271         if (slen > 3) {
12272              if (s[1] == 0) {
12273                   if (s[2] == 0xFE && s[3] == 0xFF) {
12274                        /* UTF-32 big-endian */
12275                        /* diag_listed_as: Unsupported script encoding %s */
12276                        Perl_croak(aTHX_ "Unsupported script encoding UTF-32BE");
12277                   }
12278              }
12279              else if (s[2] == 0 && s[3] != 0) {
12280                   /* Leading bytes
12281                    * 00 xx 00 xx
12282                    * are a good indicator of UTF-16BE. */
12283 #ifndef PERL_NO_UTF16_FILTER
12284 #ifdef DEBUGGING
12285                   if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (no BOM)\n");
12286 #endif
12287                   s = add_utf16_textfilter(s, FALSE);
12288 #else
12289                   /* diag_listed_as: Unsupported script encoding %s */
12290                   Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12291 #endif
12292              }
12293         }
12294         break;
12295
12296     default:
12297          if (slen > 3 && s[1] == 0 && s[2] != 0 && s[3] == 0) {
12298                   /* Leading bytes
12299                    * xx 00 xx 00
12300                    * are a good indicator of UTF-16LE. */
12301 #ifndef PERL_NO_UTF16_FILTER
12302 #ifdef DEBUGGING
12303               if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (no BOM)\n");
12304 #endif
12305               s = add_utf16_textfilter(s, TRUE);
12306 #else
12307               /* diag_listed_as: Unsupported script encoding %s */
12308               Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12309 #endif
12310          }
12311     }
12312     return (char*)s;
12313 }
12314
12315
12316 #ifndef PERL_NO_UTF16_FILTER
12317 static I32
12318 S_utf16_textfilter(pTHX_ int idx, SV *sv, int maxlen)
12319 {
12320     SV *const filter = FILTER_DATA(idx);
12321     /* We re-use this each time round, throwing the contents away before we
12322        return.  */
12323     SV *const utf16_buffer = MUTABLE_SV(IoTOP_GV(filter));
12324     SV *const utf8_buffer = filter;
12325     IV status = IoPAGE(filter);
12326     const bool reverse = cBOOL(IoLINES(filter));
12327     I32 retval;
12328
12329     PERL_ARGS_ASSERT_UTF16_TEXTFILTER;
12330
12331     /* As we're automatically added, at the lowest level, and hence only called
12332        from this file, we can be sure that we're not called in block mode. Hence
12333        don't bother writing code to deal with block mode.  */
12334     if (maxlen) {
12335         Perl_croak(aTHX_ "panic: utf16_textfilter called in block mode (for %d characters)", maxlen);
12336     }
12337     if (status < 0) {
12338         Perl_croak(aTHX_ "panic: utf16_textfilter called after error (status=%" IVdf ")", status);
12339     }
12340     DEBUG_P(PerlIO_printf(Perl_debug_log,
12341                           "utf16_textfilter(%p,%ce): idx=%d maxlen=%d status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12342                           FPTR2DPTR(void *, S_utf16_textfilter),
12343                           reverse ? 'l' : 'b', idx, maxlen, status,
12344                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12345
12346     while (1) {
12347         STRLEN chars;
12348         STRLEN have;
12349         I32 newlen;
12350         U8 *end;
12351         /* First, look in our buffer of existing UTF-8 data:  */
12352         char *nl = (char *)memchr(SvPVX(utf8_buffer), '\n', SvCUR(utf8_buffer));
12353
12354         if (nl) {
12355             ++nl;
12356         } else if (status == 0) {
12357             /* EOF */
12358             IoPAGE(filter) = 0;
12359             nl = SvEND(utf8_buffer);
12360         }
12361         if (nl) {
12362             STRLEN got = nl - SvPVX(utf8_buffer);
12363             /* Did we have anything to append?  */
12364             retval = got != 0;
12365             sv_catpvn(sv, SvPVX(utf8_buffer), got);
12366             /* Everything else in this code works just fine if SVp_POK isn't
12367                set.  This, however, needs it, and we need it to work, else
12368                we loop infinitely because the buffer is never consumed.  */
12369             sv_chop(utf8_buffer, nl);
12370             break;
12371         }
12372
12373         /* OK, not a complete line there, so need to read some more UTF-16.
12374            Read an extra octect if the buffer currently has an odd number. */
12375         while (1) {
12376             if (status <= 0)
12377                 break;
12378             if (SvCUR(utf16_buffer) >= 2) {
12379                 /* Location of the high octet of the last complete code point.
12380                    Gosh, UTF-16 is a pain. All the benefits of variable length,
12381                    *coupled* with all the benefits of partial reads and
12382                    endianness.  */
12383                 const U8 *const last_hi = (U8*)SvPVX(utf16_buffer)
12384                     + ((SvCUR(utf16_buffer) & ~1) - (reverse ? 1 : 2));
12385
12386                 if (*last_hi < 0xd8 || *last_hi > 0xdb) {
12387                     break;
12388                 }
12389
12390                 /* We have the first half of a surrogate. Read more.  */
12391                 DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter partial surrogate detected at %p\n", last_hi));
12392             }
12393
12394             status = FILTER_READ(idx + 1, utf16_buffer,
12395                                  160 + (SvCUR(utf16_buffer) & 1));
12396             DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter status=%" IVdf " SvCUR(sv)=%" UVuf "\n", status, (UV)SvCUR(utf16_buffer)));
12397             DEBUG_P({ sv_dump(utf16_buffer); sv_dump(utf8_buffer);});
12398             if (status < 0) {
12399                 /* Error */
12400                 IoPAGE(filter) = status;
12401                 return status;
12402             }
12403         }
12404
12405         /* 'chars' isn't quite the right name, as code points above 0xFFFF
12406          * require 4 bytes per char */
12407         chars = SvCUR(utf16_buffer) >> 1;
12408         have = SvCUR(utf8_buffer);
12409
12410         /* Assume the worst case size as noted by the functions: twice the
12411          * number of input bytes */
12412         SvGROW(utf8_buffer, have + chars * 4 + 1);
12413
12414         if (reverse) {
12415             end = utf16_to_utf8_reversed((U8*)SvPVX(utf16_buffer),
12416                                          (U8*)SvPVX_const(utf8_buffer) + have,
12417                                          chars * 2, &newlen);
12418         } else {
12419             end = utf16_to_utf8((U8*)SvPVX(utf16_buffer),
12420                                 (U8*)SvPVX_const(utf8_buffer) + have,
12421                                 chars * 2, &newlen);
12422         }
12423         SvCUR_set(utf8_buffer, have + newlen);
12424         *end = '\0';
12425
12426         /* No need to keep this SV "well-formed" with a '\0' after the end, as
12427            it's private to us, and utf16_to_utf8{,reversed} take a
12428            (pointer,length) pair, rather than a NUL-terminated string.  */
12429         if(SvCUR(utf16_buffer) & 1) {
12430             *SvPVX(utf16_buffer) = SvEND(utf16_buffer)[-1];
12431             SvCUR_set(utf16_buffer, 1);
12432         } else {
12433             SvCUR_set(utf16_buffer, 0);
12434         }
12435     }
12436     DEBUG_P(PerlIO_printf(Perl_debug_log,
12437                           "utf16_textfilter: returns, status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12438                           status,
12439                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12440     DEBUG_P({ sv_dump(utf8_buffer); sv_dump(sv);});
12441     return retval;
12442 }
12443
12444 static U8 *
12445 S_add_utf16_textfilter(pTHX_ U8 *const s, bool reversed)
12446 {
12447     SV *filter = filter_add(S_utf16_textfilter, NULL);
12448
12449     PERL_ARGS_ASSERT_ADD_UTF16_TEXTFILTER;
12450
12451     IoTOP_GV(filter) = MUTABLE_GV(newSVpvn((char *)s, PL_bufend - (char*)s));
12452     SvPVCLEAR(filter);
12453     IoLINES(filter) = reversed;
12454     IoPAGE(filter) = 1; /* Not EOF */
12455
12456     /* Sadly, we have to return a valid pointer, come what may, so we have to
12457        ignore any error return from this.  */
12458     SvCUR_set(PL_linestr, 0);
12459     if (FILTER_READ(0, PL_linestr, 0)) {
12460         SvUTF8_on(PL_linestr);
12461     } else {
12462         SvUTF8_on(PL_linestr);
12463     }
12464     PL_bufend = SvEND(PL_linestr);
12465     return (U8*)SvPVX(PL_linestr);
12466 }
12467 #endif
12468
12469 /*
12470 Returns a pointer to the next character after the parsed
12471 vstring, as well as updating the passed in sv.
12472
12473 Function must be called like
12474
12475         sv = sv_2mortal(newSV(5));
12476         s = scan_vstring(s,e,sv);
12477
12478 where s and e are the start and end of the string.
12479 The sv should already be large enough to store the vstring
12480 passed in, for performance reasons.
12481
12482 This function may croak if fatal warnings are enabled in the
12483 calling scope, hence the sv_2mortal in the example (to prevent
12484 a leak).  Make sure to do SvREFCNT_inc afterwards if you use
12485 sv_2mortal.
12486
12487 */
12488
12489 char *
12490 Perl_scan_vstring(pTHX_ const char *s, const char *const e, SV *sv)
12491 {
12492     const char *pos = s;
12493     const char *start = s;
12494
12495     PERL_ARGS_ASSERT_SCAN_VSTRING;
12496
12497     if (*pos == 'v') pos++;  /* get past 'v' */
12498     while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12499         pos++;
12500     if ( *pos != '.') {
12501         /* this may not be a v-string if followed by => */
12502         const char *next = pos;
12503         while (next < e && isSPACE(*next))
12504             ++next;
12505         if ((e - next) >= 2 && *next == '=' && next[1] == '>' ) {
12506             /* return string not v-string */
12507             sv_setpvn(sv,(char *)s,pos-s);
12508             return (char *)pos;
12509         }
12510     }
12511
12512     if (!isALPHA(*pos)) {
12513         U8 tmpbuf[UTF8_MAXBYTES+1];
12514
12515         if (*s == 'v')
12516             s++;  /* get past 'v' */
12517
12518         SvPVCLEAR(sv);
12519
12520         for (;;) {
12521             /* this is atoi() that tolerates underscores */
12522             U8 *tmpend;
12523             UV rev = 0;
12524             const char *end = pos;
12525             UV mult = 1;
12526             while (--end >= s) {
12527                 if (*end != '_') {
12528                     const UV orev = rev;
12529                     rev += (*end - '0') * mult;
12530                     mult *= 10;
12531                     if (orev > rev)
12532                         /* diag_listed_as: Integer overflow in %s number */
12533                         Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
12534                                          "Integer overflow in decimal number");
12535                 }
12536             }
12537
12538             /* Append native character for the rev point */
12539             tmpend = uvchr_to_utf8(tmpbuf, rev);
12540             sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
12541             if (!UVCHR_IS_INVARIANT(rev))
12542                  SvUTF8_on(sv);
12543             if (pos + 1 < e && *pos == '.' && isDIGIT(pos[1]))
12544                  s = ++pos;
12545             else {
12546                  s = pos;
12547                  break;
12548             }
12549             while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12550                  pos++;
12551         }
12552         SvPOK_on(sv);
12553         sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
12554         SvRMAGICAL_on(sv);
12555     }
12556     return (char *)s;
12557 }
12558
12559 int
12560 Perl_keyword_plugin_standard(pTHX_
12561         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
12562 {
12563     PERL_ARGS_ASSERT_KEYWORD_PLUGIN_STANDARD;
12564     PERL_UNUSED_CONTEXT;
12565     PERL_UNUSED_ARG(keyword_ptr);
12566     PERL_UNUSED_ARG(keyword_len);
12567     PERL_UNUSED_ARG(op_ptr);
12568     return KEYWORD_PLUGIN_DECLINE;
12569 }
12570
12571 /*
12572 =for apidoc wrap_keyword_plugin
12573
12574 Puts a C function into the chain of keyword plugins.  This is the
12575 preferred way to manipulate the L</PL_keyword_plugin> variable.
12576 C<new_plugin> is a pointer to the C function that is to be added to the
12577 keyword plugin chain, and C<old_plugin_p> points to the storage location
12578 where a pointer to the next function in the chain will be stored.  The
12579 value of C<new_plugin> is written into the L</PL_keyword_plugin> variable,
12580 while the value previously stored there is written to C<*old_plugin_p>.
12581
12582 L</PL_keyword_plugin> is global to an entire process, and a module wishing
12583 to hook keyword parsing may find itself invoked more than once per
12584 process, typically in different threads.  To handle that situation, this
12585 function is idempotent.  The location C<*old_plugin_p> must initially
12586 (once per process) contain a null pointer.  A C variable of static
12587 duration (declared at file scope, typically also marked C<static> to give
12588 it internal linkage) will be implicitly initialised appropriately, if it
12589 does not have an explicit initialiser.  This function will only actually
12590 modify the plugin chain if it finds C<*old_plugin_p> to be null.  This
12591 function is also thread safe on the small scale.  It uses appropriate
12592 locking to avoid race conditions in accessing L</PL_keyword_plugin>.
12593
12594 When this function is called, the function referenced by C<new_plugin>
12595 must be ready to be called, except for C<*old_plugin_p> being unfilled.
12596 In a threading situation, C<new_plugin> may be called immediately, even
12597 before this function has returned.  C<*old_plugin_p> will always be
12598 appropriately set before C<new_plugin> is called.  If C<new_plugin>
12599 decides not to do anything special with the identifier that it is given
12600 (which is the usual case for most calls to a keyword plugin), it must
12601 chain the plugin function referenced by C<*old_plugin_p>.
12602
12603 Taken all together, XS code to install a keyword plugin should typically
12604 look something like this:
12605
12606     static Perl_keyword_plugin_t next_keyword_plugin;
12607     static OP *my_keyword_plugin(pTHX_
12608         char *keyword_plugin, STRLEN keyword_len, OP **op_ptr)
12609     {
12610         if (memEQs(keyword_ptr, keyword_len,
12611                    "my_new_keyword")) {
12612             ...
12613         } else {
12614             return next_keyword_plugin(aTHX_
12615                 keyword_ptr, keyword_len, op_ptr);
12616         }
12617     }
12618     BOOT:
12619         wrap_keyword_plugin(my_keyword_plugin,
12620                             &next_keyword_plugin);
12621
12622 Direct access to L</PL_keyword_plugin> should be avoided.
12623
12624 =cut
12625 */
12626
12627 void
12628 Perl_wrap_keyword_plugin(pTHX_
12629     Perl_keyword_plugin_t new_plugin, Perl_keyword_plugin_t *old_plugin_p)
12630 {
12631     dVAR;
12632
12633     PERL_UNUSED_CONTEXT;
12634     PERL_ARGS_ASSERT_WRAP_KEYWORD_PLUGIN;
12635     if (*old_plugin_p) return;
12636     KEYWORD_PLUGIN_MUTEX_LOCK;
12637     if (!*old_plugin_p) {
12638         *old_plugin_p = PL_keyword_plugin;
12639         PL_keyword_plugin = new_plugin;
12640     }
12641     KEYWORD_PLUGIN_MUTEX_UNLOCK;
12642 }
12643
12644 #define parse_recdescent(g,p) S_parse_recdescent(aTHX_ g,p)
12645 static void
12646 S_parse_recdescent(pTHX_ int gramtype, I32 fakeeof)
12647 {
12648     SAVEI32(PL_lex_brackets);
12649     if (PL_lex_brackets > 100)
12650         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
12651     PL_lex_brackstack[PL_lex_brackets++] = XFAKEEOF;
12652     SAVEI32(PL_lex_allbrackets);
12653     PL_lex_allbrackets = 0;
12654     SAVEI8(PL_lex_fakeeof);
12655     PL_lex_fakeeof = (U8)fakeeof;
12656     if(yyparse(gramtype) && !PL_parser->error_count)
12657         qerror(Perl_mess(aTHX_ "Parse error"));
12658 }
12659
12660 #define parse_recdescent_for_op(g,p) S_parse_recdescent_for_op(aTHX_ g,p)
12661 static OP *
12662 S_parse_recdescent_for_op(pTHX_ int gramtype, I32 fakeeof)
12663 {
12664     OP *o;
12665     ENTER;
12666     SAVEVPTR(PL_eval_root);
12667     PL_eval_root = NULL;
12668     parse_recdescent(gramtype, fakeeof);
12669     o = PL_eval_root;
12670     LEAVE;
12671     return o;
12672 }
12673
12674 #define parse_expr(p,f) S_parse_expr(aTHX_ p,f)
12675 static OP *
12676 S_parse_expr(pTHX_ I32 fakeeof, U32 flags)
12677 {
12678     OP *exprop;
12679     if (flags & ~PARSE_OPTIONAL)
12680         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_expr");
12681     exprop = parse_recdescent_for_op(GRAMEXPR, fakeeof);
12682     if (!exprop && !(flags & PARSE_OPTIONAL)) {
12683         if (!PL_parser->error_count)
12684             qerror(Perl_mess(aTHX_ "Parse error"));
12685         exprop = newOP(OP_NULL, 0);
12686     }
12687     return exprop;
12688 }
12689
12690 /*
12691 =for apidoc parse_arithexpr
12692
12693 Parse a Perl arithmetic expression.  This may contain operators of precedence
12694 down to the bit shift operators.  The expression must be followed (and thus
12695 terminated) either by a comparison or lower-precedence operator or by
12696 something that would normally terminate an expression such as semicolon.
12697 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12698 otherwise it is mandatory.  It is up to the caller to ensure that the
12699 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12700 the source of the code to be parsed and the lexical context for the
12701 expression.
12702
12703 The op tree representing the expression is returned.  If an optional
12704 expression is absent, a null pointer is returned, otherwise the pointer
12705 will be non-null.
12706
12707 If an error occurs in parsing or compilation, in most cases a valid op
12708 tree is returned anyway.  The error is reflected in the parser state,
12709 normally resulting in a single exception at the top level of parsing
12710 which covers all the compilation errors that occurred.  Some compilation
12711 errors, however, will throw an exception immediately.
12712
12713 =cut
12714 */
12715
12716 OP *
12717 Perl_parse_arithexpr(pTHX_ U32 flags)
12718 {
12719     return parse_expr(LEX_FAKEEOF_COMPARE, flags);
12720 }
12721
12722 /*
12723 =for apidoc parse_termexpr
12724
12725 Parse a Perl term expression.  This may contain operators of precedence
12726 down to the assignment operators.  The expression must be followed (and thus
12727 terminated) either by a comma or lower-precedence operator or by
12728 something that would normally terminate an expression such as semicolon.
12729 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12730 otherwise it is mandatory.  It is up to the caller to ensure that the
12731 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12732 the source of the code to be parsed and the lexical context for the
12733 expression.
12734
12735 The op tree representing the expression is returned.  If an optional
12736 expression is absent, a null pointer is returned, otherwise the pointer
12737 will be non-null.
12738
12739 If an error occurs in parsing or compilation, in most cases a valid op
12740 tree is returned anyway.  The error is reflected in the parser state,
12741 normally resulting in a single exception at the top level of parsing
12742 which covers all the compilation errors that occurred.  Some compilation
12743 errors, however, will throw an exception immediately.
12744
12745 =cut
12746 */
12747
12748 OP *
12749 Perl_parse_termexpr(pTHX_ U32 flags)
12750 {
12751     return parse_expr(LEX_FAKEEOF_COMMA, flags);
12752 }
12753
12754 /*
12755 =for apidoc parse_listexpr
12756
12757 Parse a Perl list expression.  This may contain operators of precedence
12758 down to the comma operator.  The expression must be followed (and thus
12759 terminated) either by a low-precedence logic operator such as C<or> or by
12760 something that would normally terminate an expression such as semicolon.
12761 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12762 otherwise it is mandatory.  It is up to the caller to ensure that the
12763 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12764 the source of the code to be parsed and the lexical context for the
12765 expression.
12766
12767 The op tree representing the expression is returned.  If an optional
12768 expression is absent, a null pointer is returned, otherwise the pointer
12769 will be non-null.
12770
12771 If an error occurs in parsing or compilation, in most cases a valid op
12772 tree is returned anyway.  The error is reflected in the parser state,
12773 normally resulting in a single exception at the top level of parsing
12774 which covers all the compilation errors that occurred.  Some compilation
12775 errors, however, will throw an exception immediately.
12776
12777 =cut
12778 */
12779
12780 OP *
12781 Perl_parse_listexpr(pTHX_ U32 flags)
12782 {
12783     return parse_expr(LEX_FAKEEOF_LOWLOGIC, flags);
12784 }
12785
12786 /*
12787 =for apidoc parse_fullexpr
12788
12789 Parse a single complete Perl expression.  This allows the full
12790 expression grammar, including the lowest-precedence operators such
12791 as C<or>.  The expression must be followed (and thus terminated) by a
12792 token that an expression would normally be terminated by: end-of-file,
12793 closing bracketing punctuation, semicolon, or one of the keywords that
12794 signals a postfix expression-statement modifier.  If C<flags> has the
12795 C<PARSE_OPTIONAL> bit set, then the expression is optional, otherwise it is
12796 mandatory.  It is up to the caller to ensure that the dynamic parser
12797 state (L</PL_parser> et al) is correctly set to reflect the source of
12798 the code to be parsed and the lexical context for the expression.
12799
12800 The op tree representing the expression is returned.  If an optional
12801 expression is absent, a null pointer is returned, otherwise the pointer
12802 will be non-null.
12803
12804 If an error occurs in parsing or compilation, in most cases a valid op
12805 tree is returned anyway.  The error is reflected in the parser state,
12806 normally resulting in a single exception at the top level of parsing
12807 which covers all the compilation errors that occurred.  Some compilation
12808 errors, however, will throw an exception immediately.
12809
12810 =cut
12811 */
12812
12813 OP *
12814 Perl_parse_fullexpr(pTHX_ U32 flags)
12815 {
12816     return parse_expr(LEX_FAKEEOF_NONEXPR, flags);
12817 }
12818
12819 /*
12820 =for apidoc parse_block
12821
12822 Parse a single complete Perl code block.  This consists of an opening
12823 brace, a sequence of statements, and a closing brace.  The block
12824 constitutes a lexical scope, so C<my> variables and various compile-time
12825 effects can be contained within it.  It is up to the caller to ensure
12826 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12827 reflect the source of the code to be parsed and the lexical context for
12828 the statement.
12829
12830 The op tree representing the code block is returned.  This is always a
12831 real op, never a null pointer.  It will normally be a C<lineseq> list,
12832 including C<nextstate> or equivalent ops.  No ops to construct any kind
12833 of runtime scope are included by virtue of it being a block.
12834
12835 If an error occurs in parsing or compilation, in most cases a valid op
12836 tree (most likely null) is returned anyway.  The error is reflected in
12837 the parser state, normally resulting in a single exception at the top
12838 level of parsing which covers all the compilation errors that occurred.
12839 Some compilation errors, however, will throw an exception immediately.
12840
12841 The C<flags> parameter is reserved for future use, and must always
12842 be zero.
12843
12844 =cut
12845 */
12846
12847 OP *
12848 Perl_parse_block(pTHX_ U32 flags)
12849 {
12850     if (flags)
12851         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_block");
12852     return parse_recdescent_for_op(GRAMBLOCK, LEX_FAKEEOF_NEVER);
12853 }
12854
12855 /*
12856 =for apidoc parse_barestmt
12857
12858 Parse a single unadorned Perl statement.  This may be a normal imperative
12859 statement or a declaration that has compile-time effect.  It does not
12860 include any label or other affixture.  It is up to the caller to ensure
12861 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12862 reflect the source of the code to be parsed and the lexical context for
12863 the statement.
12864
12865 The op tree representing the statement is returned.  This may be a
12866 null pointer if the statement is null, for example if it was actually
12867 a subroutine definition (which has compile-time side effects).  If not
12868 null, it will be ops directly implementing the statement, suitable to
12869 pass to L</newSTATEOP>.  It will not normally include a C<nextstate> or
12870 equivalent op (except for those embedded in a scope contained entirely
12871 within the statement).
12872
12873 If an error occurs in parsing or compilation, in most cases a valid op
12874 tree (most likely null) is returned anyway.  The error is reflected in
12875 the parser state, normally resulting in a single exception at the top
12876 level of parsing which covers all the compilation errors that occurred.
12877 Some compilation errors, however, will throw an exception immediately.
12878
12879 The C<flags> parameter is reserved for future use, and must always
12880 be zero.
12881
12882 =cut
12883 */
12884
12885 OP *
12886 Perl_parse_barestmt(pTHX_ U32 flags)
12887 {
12888     if (flags)
12889         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_barestmt");
12890     return parse_recdescent_for_op(GRAMBARESTMT, LEX_FAKEEOF_NEVER);
12891 }
12892
12893 /*
12894 =for apidoc parse_label
12895
12896 Parse a single label, possibly optional, of the type that may prefix a
12897 Perl statement.  It is up to the caller to ensure that the dynamic parser
12898 state (L</PL_parser> et al) is correctly set to reflect the source of
12899 the code to be parsed.  If C<flags> has the C<PARSE_OPTIONAL> bit set, then the
12900 label is optional, otherwise it is mandatory.
12901
12902 The name of the label is returned in the form of a fresh scalar.  If an
12903 optional label is absent, a null pointer is returned.
12904
12905 If an error occurs in parsing, which can only occur if the label is
12906 mandatory, a valid label is returned anyway.  The error is reflected in
12907 the parser state, normally resulting in a single exception at the top
12908 level of parsing which covers all the compilation errors that occurred.
12909
12910 =cut
12911 */
12912
12913 SV *
12914 Perl_parse_label(pTHX_ U32 flags)
12915 {
12916     if (flags & ~PARSE_OPTIONAL)
12917         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_label");
12918     if (PL_nexttoke) {
12919         PL_parser->yychar = yylex();
12920         if (PL_parser->yychar == LABEL) {
12921             SV * const labelsv = cSVOPx(pl_yylval.opval)->op_sv;
12922             PL_parser->yychar = YYEMPTY;
12923             cSVOPx(pl_yylval.opval)->op_sv = NULL;
12924             op_free(pl_yylval.opval);
12925             return labelsv;
12926         } else {
12927             yyunlex();
12928             goto no_label;
12929         }
12930     } else {
12931         char *s, *t;
12932         STRLEN wlen, bufptr_pos;
12933         lex_read_space(0);
12934         t = s = PL_bufptr;
12935         if (!isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
12936             goto no_label;
12937         t = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &wlen);
12938         if (word_takes_any_delimiter(s, wlen))
12939             goto no_label;
12940         bufptr_pos = s - SvPVX(PL_linestr);
12941         PL_bufptr = t;
12942         lex_read_space(LEX_KEEP_PREVIOUS);
12943         t = PL_bufptr;
12944         s = SvPVX(PL_linestr) + bufptr_pos;
12945         if (t[0] == ':' && t[1] != ':') {
12946             PL_oldoldbufptr = PL_oldbufptr;
12947             PL_oldbufptr = s;
12948             PL_bufptr = t+1;
12949             return newSVpvn_flags(s, wlen, UTF ? SVf_UTF8 : 0);
12950         } else {
12951             PL_bufptr = s;
12952             no_label:
12953             if (flags & PARSE_OPTIONAL) {
12954                 return NULL;
12955             } else {
12956                 qerror(Perl_mess(aTHX_ "Parse error"));
12957                 return newSVpvs("x");
12958             }
12959         }
12960     }
12961 }
12962
12963 /*
12964 =for apidoc parse_fullstmt
12965
12966 Parse a single complete Perl statement.  This may be a normal imperative
12967 statement or a declaration that has compile-time effect, and may include
12968 optional labels.  It is up to the caller to ensure that the dynamic
12969 parser state (L</PL_parser> et al) is correctly set to reflect the source
12970 of the code to be parsed and the lexical context for the statement.
12971
12972 The op tree representing the statement is returned.  This may be a
12973 null pointer if the statement is null, for example if it was actually
12974 a subroutine definition (which has compile-time side effects).  If not
12975 null, it will be the result of a L</newSTATEOP> call, normally including
12976 a C<nextstate> or equivalent op.
12977
12978 If an error occurs in parsing or compilation, in most cases a valid op
12979 tree (most likely null) is returned anyway.  The error is reflected in
12980 the parser state, normally resulting in a single exception at the top
12981 level of parsing which covers all the compilation errors that occurred.
12982 Some compilation errors, however, will throw an exception immediately.
12983
12984 The C<flags> parameter is reserved for future use, and must always
12985 be zero.
12986
12987 =cut
12988 */
12989
12990 OP *
12991 Perl_parse_fullstmt(pTHX_ U32 flags)
12992 {
12993     if (flags)
12994         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_fullstmt");
12995     return parse_recdescent_for_op(GRAMFULLSTMT, LEX_FAKEEOF_NEVER);
12996 }
12997
12998 /*
12999 =for apidoc parse_stmtseq
13000
13001 Parse a sequence of zero or more Perl statements.  These may be normal
13002 imperative statements, including optional labels, or declarations
13003 that have compile-time effect, or any mixture thereof.  The statement
13004 sequence ends when a closing brace or end-of-file is encountered in a
13005 place where a new statement could have validly started.  It is up to
13006 the caller to ensure that the dynamic parser state (L</PL_parser> et al)
13007 is correctly set to reflect the source of the code to be parsed and the
13008 lexical context for the statements.
13009
13010 The op tree representing the statement sequence is returned.  This may
13011 be a null pointer if the statements were all null, for example if there
13012 were no statements or if there were only subroutine definitions (which
13013 have compile-time side effects).  If not null, it will be a C<lineseq>
13014 list, normally including C<nextstate> or equivalent ops.
13015
13016 If an error occurs in parsing or compilation, in most cases a valid op
13017 tree is returned anyway.  The error is reflected in the parser state,
13018 normally resulting in a single exception at the top level of parsing
13019 which covers all the compilation errors that occurred.  Some compilation
13020 errors, however, will throw an exception immediately.
13021
13022 The C<flags> parameter is reserved for future use, and must always
13023 be zero.
13024
13025 =cut
13026 */
13027
13028 OP *
13029 Perl_parse_stmtseq(pTHX_ U32 flags)
13030 {
13031     OP *stmtseqop;
13032     I32 c;
13033     if (flags)
13034         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_stmtseq");
13035     stmtseqop = parse_recdescent_for_op(GRAMSTMTSEQ, LEX_FAKEEOF_CLOSING);
13036     c = lex_peek_unichar(0);
13037     if (c != -1 && c != /*{*/'}')
13038         qerror(Perl_mess(aTHX_ "Parse error"));
13039     return stmtseqop;
13040 }
13041
13042 /*
13043 =for apidoc parse_subsignature
13044
13045 Parse a subroutine signature declaration. This is the contents of the
13046 parentheses following a named or anonymous subroutine declaration when the
13047 C<signatures> feature is enabled. Note that this function neither expects
13048 nor consumes the opening and closing parentheses around the signature; it
13049 is the caller's job to handle these.
13050
13051 This function must only be called during parsing of a subroutine; after
13052 L</start_subparse> has been called. It might allocate lexical variables on
13053 the pad for the current subroutine.
13054
13055 The op tree to unpack the arguments from the stack at runtime is returned.
13056 This op tree should appear at the beginning of the compiled function. The
13057 caller may wish to use L</op_append_list> to build their function body
13058 after it, or splice it together with the body before calling L</newATTRSUB>.
13059
13060 The C<flags> parameter is reserved for future use, and must always
13061 be zero.
13062
13063 =cut
13064 */
13065
13066 OP *
13067 Perl_parse_subsignature(pTHX_ U32 flags)
13068 {
13069     if (flags)
13070         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_subsignature");
13071     return parse_recdescent_for_op(GRAMSUBSIGNATURE, LEX_FAKEEOF_NONEXPR);
13072 }
13073
13074 /*
13075  * ex: set ts=8 sts=4 sw=4 et:
13076  */