This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
pp_(get|set)priority: remove ancient glibc C++ workaround
[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 "invlist_inline.h"
42
43 #define new_constant(a,b,c,d,e,f,g, h)  \
44         S_new_constant(aTHX_ a,b,STR_WITH_LEN(c),d,e,f, g, h)
45
46 #define pl_yylval       (PL_parser->yylval)
47
48 /* XXX temporary backwards compatibility */
49 #define PL_lex_brackets         (PL_parser->lex_brackets)
50 #define PL_lex_allbrackets      (PL_parser->lex_allbrackets)
51 #define PL_lex_fakeeof          (PL_parser->lex_fakeeof)
52 #define PL_lex_brackstack       (PL_parser->lex_brackstack)
53 #define PL_lex_casemods         (PL_parser->lex_casemods)
54 #define PL_lex_casestack        (PL_parser->lex_casestack)
55 #define PL_lex_dojoin           (PL_parser->lex_dojoin)
56 #define PL_lex_formbrack        (PL_parser->lex_formbrack)
57 #define PL_lex_inpat            (PL_parser->lex_inpat)
58 #define PL_lex_inwhat           (PL_parser->lex_inwhat)
59 #define PL_lex_op               (PL_parser->lex_op)
60 #define PL_lex_repl             (PL_parser->lex_repl)
61 #define PL_lex_starts           (PL_parser->lex_starts)
62 #define PL_lex_stuff            (PL_parser->lex_stuff)
63 #define PL_multi_start          (PL_parser->multi_start)
64 #define PL_multi_open           (PL_parser->multi_open)
65 #define PL_multi_close          (PL_parser->multi_close)
66 #define PL_preambled            (PL_parser->preambled)
67 #define PL_linestr              (PL_parser->linestr)
68 #define PL_expect               (PL_parser->expect)
69 #define PL_copline              (PL_parser->copline)
70 #define PL_bufptr               (PL_parser->bufptr)
71 #define PL_oldbufptr            (PL_parser->oldbufptr)
72 #define PL_oldoldbufptr         (PL_parser->oldoldbufptr)
73 #define PL_linestart            (PL_parser->linestart)
74 #define PL_bufend               (PL_parser->bufend)
75 #define PL_last_uni             (PL_parser->last_uni)
76 #define PL_last_lop             (PL_parser->last_lop)
77 #define PL_last_lop_op          (PL_parser->last_lop_op)
78 #define PL_lex_state            (PL_parser->lex_state)
79 #define PL_rsfp                 (PL_parser->rsfp)
80 #define PL_rsfp_filters         (PL_parser->rsfp_filters)
81 #define PL_in_my                (PL_parser->in_my)
82 #define PL_in_my_stash          (PL_parser->in_my_stash)
83 #define PL_tokenbuf             (PL_parser->tokenbuf)
84 #define PL_multi_end            (PL_parser->multi_end)
85 #define PL_error_count          (PL_parser->error_count)
86
87 #  define PL_nexttoke           (PL_parser->nexttoke)
88 #  define PL_nexttype           (PL_parser->nexttype)
89 #  define PL_nextval            (PL_parser->nextval)
90
91
92 #define SvEVALED(sv) \
93     (SvTYPE(sv) >= SVt_PVNV \
94     && ((XPVIV*)SvANY(sv))->xiv_u.xivu_eval_seen)
95
96 static const char* const ident_too_long = "Identifier too long";
97
98 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
99
100 #define XENUMMASK  0x3f
101 #define XFAKEEOF   0x40
102 #define XFAKEBRACK 0x80
103
104 #ifdef USE_UTF8_SCRIPTS
105 #   define UTF cBOOL(!IN_BYTES)
106 #else
107 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
108 #endif
109
110 /* The maximum number of characters preceding the unrecognized one to display */
111 #define UNRECOGNIZED_PRECEDE_COUNT 10
112
113 /* In variables named $^X, these are the legal values for X.
114  * 1999-02-27 mjd-perl-patch@plover.com */
115 #define isCONTROLVAR(x) (isUPPER(x) || memCHRs("[\\]^_?", (x)))
116
117 #define SPACE_OR_TAB(c) isBLANK_A(c)
118
119 #define HEXFP_PEEK(s)     \
120     (((s[0] == '.') && \
121       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
122      isALPHA_FOLD_EQ(s[0], 'p'))
123
124 /* LEX_* are values for PL_lex_state, the state of the lexer.
125  * They are arranged oddly so that the guard on the switch statement
126  * can get by with a single comparison (if the compiler is smart enough).
127  *
128  * These values refer to the various states within a sublex parse,
129  * i.e. within a double quotish string
130  */
131
132 /* #define LEX_NOTPARSING               11 is done in perl.h. */
133
134 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
135 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
136 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
137 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
138 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
139
140                                    /* at end of code, eg "$x" followed by:  */
141 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
142 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
143
144 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
145                                         string or after \E, $foo, etc       */
146 #define LEX_INTERPCONST          2 /* NOT USED */
147 #define LEX_FORMLINE             1 /* expecting a format line               */
148
149
150 #ifdef DEBUGGING
151 static const char* const lex_state_names[] = {
152     "KNOWNEXT",
153     "FORMLINE",
154     "INTERPCONST",
155     "INTERPCONCAT",
156     "INTERPENDMAYBE",
157     "INTERPEND",
158     "INTERPSTART",
159     "INTERPPUSH",
160     "INTERPCASEMOD",
161     "INTERPNORMAL",
162     "NORMAL"
163 };
164 #endif
165
166 #include "keywords.h"
167
168 /* CLINE is a macro that ensures PL_copline has a sane value */
169
170 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
171
172 /*
173  * Convenience functions to return different tokens and prime the
174  * lexer for the next token.  They all take an argument.
175  *
176  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
177  * OPERATOR     : generic operator
178  * AOPERATOR    : assignment operator
179  * PREBLOCK     : beginning the block after an if, while, foreach, ...
180  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
181  * PREREF       : *EXPR where EXPR is not a simple identifier
182  * TERM         : expression term
183  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
184  * LOOPX        : loop exiting command (goto, last, dump, etc)
185  * FTST         : file test operator
186  * FUN0         : zero-argument function
187  * FUN0OP       : zero-argument function, with its op created in this file
188  * FUN1         : not used, except for not, which isn't a UNIOP
189  * BOop         : bitwise or or xor
190  * BAop         : bitwise and
191  * BCop         : bitwise complement
192  * SHop         : shift operator
193  * PWop         : power operator
194  * PMop         : pattern-matching operator
195  * Aop          : addition-level operator
196  * AopNOASSIGN  : addition-level operator that is never part of .=
197  * Mop          : multiplication-level operator
198  * Eop          : equality-testing operator
199  * Rop          : relational operator <= != gt
200  *
201  * Also see LOP and lop() below.
202  */
203
204 #ifdef DEBUGGING /* Serve -DT. */
205 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
206 #else
207 #   define REPORT(retval) (retval)
208 #endif
209
210 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
211 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
212 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
213 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
214 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
215 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
216 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
217 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
218 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
219                          pl_yylval.ival=f, \
220                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
221                          REPORT((int)LOOPEX))
222 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
223 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
224 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
225 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
226 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
227 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
228 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
229                        REPORT('~')
230 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
231 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
232 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
233 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
234 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
235 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
236 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
237 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
238
239 /* This bit of chicanery makes a unary function followed by
240  * a parenthesis into a function with one argument, highest precedence.
241  * The UNIDOR macro is for unary functions that can be followed by the //
242  * operator (such as C<shift // 0>).
243  */
244 #define UNI3(f,x,have_x) { \
245         pl_yylval.ival = f; \
246         if (have_x) PL_expect = x; \
247         PL_bufptr = s; \
248         PL_last_uni = PL_oldbufptr; \
249         PL_last_lop_op = (f) < 0 ? -(f) : (f); \
250         if (*s == '(') \
251             return REPORT( (int)FUNC1 ); \
252         s = skipspace(s); \
253         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
254         }
255 #define UNI(f)    UNI3(f,XTERM,1)
256 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
257 #define UNIPROTO(f,optional) { \
258         if (optional) PL_last_uni = PL_oldbufptr; \
259         OPERATOR(f); \
260         }
261
262 #define UNIBRACK(f) UNI3(f,0,0)
263
264 /* grandfather return to old style */
265 #define OLDLOP(f) \
266         do { \
267             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
268                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
269             pl_yylval.ival = (f); \
270             PL_expect = XTERM; \
271             PL_bufptr = s; \
272             return (int)LSTOP; \
273         } while(0)
274
275 #define COPLINE_INC_WITH_HERELINES                  \
276     STMT_START {                                     \
277         CopLINE_inc(PL_curcop);                       \
278         if (PL_parser->herelines)                      \
279             CopLINE(PL_curcop) += PL_parser->herelines, \
280             PL_parser->herelines = 0;                    \
281     } STMT_END
282 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
283  * is no sublex_push to follow. */
284 #define COPLINE_SET_FROM_MULTI_END            \
285     STMT_START {                               \
286         CopLINE_set(PL_curcop, PL_multi_end);   \
287         if (PL_multi_end != PL_multi_start)      \
288             PL_parser->herelines = 0;             \
289     } STMT_END
290
291
292 /* A file-local structure for passing around information about subroutines and
293  * related definable words */
294 struct code {
295     SV *sv;
296     CV *cv;
297     GV *gv, **gvp;
298     OP *rv2cv_op;
299     PADOFFSET off;
300     bool lex;
301 };
302
303 static const struct code no_code = { NULL, NULL, NULL, NULL, NULL, 0, FALSE };
304
305
306 #ifdef DEBUGGING
307
308 /* how to interpret the pl_yylval associated with the token */
309 enum token_type {
310     TOKENTYPE_NONE,
311     TOKENTYPE_IVAL,
312     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
313     TOKENTYPE_PVAL,
314     TOKENTYPE_OPVAL
315 };
316
317 static struct debug_tokens {
318     const int token;
319     enum token_type type;
320     const char *name;
321 } const debug_tokens[] =
322 {
323     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
324     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
325     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
326     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
327     { ANON_SIGSUB,      TOKENTYPE_IVAL,         "ANON_SIGSUB" },
328     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
329     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
330     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
331     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
332     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
333     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
334     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
335     { DO,               TOKENTYPE_NONE,         "DO" },
336     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
337     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
338     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
339     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
340     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
341     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
342     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
343     { FOR,              TOKENTYPE_IVAL,         "FOR" },
344     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
345     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
346     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
347     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
348     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
349     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
350     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
351     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
352     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
353     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
354     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
355     { IF,               TOKENTYPE_IVAL,         "IF" },
356     { LABEL,            TOKENTYPE_OPVAL,        "LABEL" },
357     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
358     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
359     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
360     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
361     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
362     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
363     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
364     { MY,               TOKENTYPE_IVAL,         "MY" },
365     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
366     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
367     { OROP,             TOKENTYPE_IVAL,         "OROP" },
368     { OROR,             TOKENTYPE_NONE,         "OROR" },
369     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
370     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
371     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
372     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
373     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
374     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
375     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
376     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
377     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
378     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
379     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
380     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
381     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
382     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
383     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
384     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
385     { SIGSUB,           TOKENTYPE_NONE,         "SIGSUB" },
386     { SUB,              TOKENTYPE_NONE,         "SUB" },
387     { SUBLEXEND,        TOKENTYPE_NONE,         "SUBLEXEND" },
388     { SUBLEXSTART,      TOKENTYPE_NONE,         "SUBLEXSTART" },
389     { THING,            TOKENTYPE_OPVAL,        "THING" },
390     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
391     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
392     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
393     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
394     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
395     { USE,              TOKENTYPE_IVAL,         "USE" },
396     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
397     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
398     { BAREWORD,         TOKENTYPE_OPVAL,        "BAREWORD" },
399     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
400     { 0,                TOKENTYPE_NONE,         NULL }
401 };
402
403 /* dump the returned token in rv, plus any optional arg in pl_yylval */
404
405 STATIC int
406 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
407 {
408     PERL_ARGS_ASSERT_TOKEREPORT;
409
410     if (DEBUG_T_TEST) {
411         const char *name = NULL;
412         enum token_type type = TOKENTYPE_NONE;
413         const struct debug_tokens *p;
414         SV* const report = newSVpvs("<== ");
415
416         for (p = debug_tokens; p->token; p++) {
417             if (p->token == (int)rv) {
418                 name = p->name;
419                 type = p->type;
420                 break;
421             }
422         }
423         if (name)
424             Perl_sv_catpv(aTHX_ report, name);
425         else if (isGRAPH(rv))
426         {
427             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
428             if ((char)rv == 'p')
429                 sv_catpvs(report, " (pending identifier)");
430         }
431         else if (!rv)
432             sv_catpvs(report, "EOF");
433         else
434             Perl_sv_catpvf(aTHX_ report, "?? %" IVdf, (IV)rv);
435         switch (type) {
436         case TOKENTYPE_NONE:
437             break;
438         case TOKENTYPE_IVAL:
439             Perl_sv_catpvf(aTHX_ report, "(ival=%" IVdf ")", (IV)lvalp->ival);
440             break;
441         case TOKENTYPE_OPNUM:
442             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
443                                     PL_op_name[lvalp->ival]);
444             break;
445         case TOKENTYPE_PVAL:
446             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
447             break;
448         case TOKENTYPE_OPVAL:
449             if (lvalp->opval) {
450                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
451                                     PL_op_name[lvalp->opval->op_type]);
452                 if (lvalp->opval->op_type == OP_CONST) {
453                     Perl_sv_catpvf(aTHX_ report, " %s",
454                         SvPEEK(cSVOPx_sv(lvalp->opval)));
455                 }
456
457             }
458             else
459                 sv_catpvs(report, "(opval=null)");
460             break;
461         }
462         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
463     };
464     return (int)rv;
465 }
466
467
468 /* print the buffer with suitable escapes */
469
470 STATIC void
471 S_printbuf(pTHX_ const char *const fmt, const char *const s)
472 {
473     SV* const tmp = newSVpvs("");
474
475     PERL_ARGS_ASSERT_PRINTBUF;
476
477     GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
478     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
479     GCC_DIAG_RESTORE_STMT;
480     SvREFCNT_dec(tmp);
481 }
482
483 #endif
484
485 /*
486  * S_ao
487  *
488  * This subroutine looks for an '=' next to the operator that has just been
489  * parsed and turns it into an ASSIGNOP if it finds one.
490  */
491
492 STATIC int
493 S_ao(pTHX_ int toketype)
494 {
495     if (*PL_bufptr == '=') {
496         PL_bufptr++;
497         if (toketype == ANDAND)
498             pl_yylval.ival = OP_ANDASSIGN;
499         else if (toketype == OROR)
500             pl_yylval.ival = OP_ORASSIGN;
501         else if (toketype == DORDOR)
502             pl_yylval.ival = OP_DORASSIGN;
503         toketype = ASSIGNOP;
504     }
505     return REPORT(toketype);
506 }
507
508 /*
509  * S_no_op
510  * When Perl expects an operator and finds something else, no_op
511  * prints the warning.  It always prints "<something> found where
512  * operator expected.  It prints "Missing semicolon on previous line?"
513  * if the surprise occurs at the start of the line.  "do you need to
514  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
515  * where the compiler doesn't know if foo is a method call or a function.
516  * It prints "Missing operator before end of line" if there's nothing
517  * after the missing operator, or "... before <...>" if there is something
518  * after the missing operator.
519  *
520  * PL_bufptr is expected to point to the start of the thing that was found,
521  * and s after the next token or partial token.
522  */
523
524 STATIC void
525 S_no_op(pTHX_ const char *const what, char *s)
526 {
527     char * const oldbp = PL_bufptr;
528     const bool is_first = (PL_oldbufptr == PL_linestart);
529
530     PERL_ARGS_ASSERT_NO_OP;
531
532     if (!s)
533         s = oldbp;
534     else
535         PL_bufptr = s;
536     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
537     if (ckWARN_d(WARN_SYNTAX)) {
538         if (is_first)
539             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
540                     "\t(Missing semicolon on previous line?)\n");
541         else if (PL_oldoldbufptr && isIDFIRST_lazy_if_safe(PL_oldoldbufptr,
542                                                            PL_bufend,
543                                                            UTF))
544         {
545             const char *t;
546             for (t = PL_oldoldbufptr;
547                  (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF) || *t == ':');
548                  t += UTF ? UTF8SKIP(t) : 1)
549             {
550                 NOOP;
551             }
552             if (t < PL_bufptr && isSPACE(*t))
553                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
554                         "\t(Do you need to predeclare %" UTF8f "?)\n",
555                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
556         }
557         else {
558             assert(s >= oldbp);
559             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
560                     "\t(Missing operator before %" UTF8f "?)\n",
561                      UTF8fARG(UTF, s - oldbp, oldbp));
562         }
563     }
564     PL_bufptr = oldbp;
565 }
566
567 /*
568  * S_missingterm
569  * Complain about missing quote/regexp/heredoc terminator.
570  * If it's called with NULL then it cauterizes the line buffer.
571  * If we're in a delimited string and the delimiter is a control
572  * character, it's reformatted into a two-char sequence like ^C.
573  * This is fatal.
574  */
575
576 STATIC void
577 S_missingterm(pTHX_ char *s, STRLEN len)
578 {
579     char tmpbuf[UTF8_MAXBYTES + 1];
580     char q;
581     bool uni = FALSE;
582     SV *sv;
583     if (s) {
584         char * const nl = (char *) my_memrchr(s, '\n', len);
585         if (nl) {
586             *nl = '\0';
587             len = nl - s;
588         }
589         uni = UTF;
590     }
591     else if (PL_multi_close < 32) {
592         *tmpbuf = '^';
593         tmpbuf[1] = (char)toCTRL(PL_multi_close);
594         tmpbuf[2] = '\0';
595         s = tmpbuf;
596         len = 2;
597     }
598     else {
599         if (LIKELY(PL_multi_close < 256)) {
600             *tmpbuf = (char)PL_multi_close;
601             tmpbuf[1] = '\0';
602             len = 1;
603         }
604         else {
605             char *end = (char *)uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close);
606             *end = '\0';
607             len = end - tmpbuf;
608             uni = TRUE;
609         }
610         s = tmpbuf;
611     }
612     q = memchr(s, '"', len) ? '\'' : '"';
613     sv = sv_2mortal(newSVpvn(s, len));
614     if (uni)
615         SvUTF8_on(sv);
616     Perl_croak(aTHX_ "Can't find string terminator %c%" SVf "%c"
617                      " anywhere before EOF", q, SVfARG(sv), q);
618 }
619
620 #include "feature.h"
621
622 /*
623  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
624  * utf16-to-utf8-reversed.
625  */
626
627 #ifdef PERL_CR_FILTER
628 static void
629 strip_return(SV *sv)
630 {
631     const char *s = SvPVX_const(sv);
632     const char * const e = s + SvCUR(sv);
633
634     PERL_ARGS_ASSERT_STRIP_RETURN;
635
636     /* outer loop optimized to do nothing if there are no CR-LFs */
637     while (s < e) {
638         if (*s++ == '\r' && *s == '\n') {
639             /* hit a CR-LF, need to copy the rest */
640             char *d = s - 1;
641             *d++ = *s++;
642             while (s < e) {
643                 if (*s == '\r' && s[1] == '\n')
644                     s++;
645                 *d++ = *s++;
646             }
647             SvCUR(sv) -= s - d;
648             return;
649         }
650     }
651 }
652
653 STATIC I32
654 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
655 {
656     const I32 count = FILTER_READ(idx+1, sv, maxlen);
657     if (count > 0 && !maxlen)
658         strip_return(sv);
659     return count;
660 }
661 #endif
662
663 /*
664 =for apidoc lex_start
665
666 Creates and initialises a new lexer/parser state object, supplying
667 a context in which to lex and parse from a new source of Perl code.
668 A pointer to the new state object is placed in L</PL_parser>.  An entry
669 is made on the save stack so that upon unwinding, the new state object
670 will be destroyed and the former value of L</PL_parser> will be restored.
671 Nothing else need be done to clean up the parsing context.
672
673 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
674 non-null, provides a string (in SV form) containing code to be parsed.
675 A copy of the string is made, so subsequent modification of C<line>
676 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
677 from which code will be read to be parsed.  If both are non-null, the
678 code in C<line> comes first and must consist of complete lines of input,
679 and C<rsfp> supplies the remainder of the source.
680
681 The C<flags> parameter is reserved for future use.  Currently it is only
682 used by perl internally, so extensions should always pass zero.
683
684 =cut
685 */
686
687 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
688    can share filters with the current parser.
689    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
690    caller, hence isn't owned by the parser, so shouldn't be closed on parser
691    destruction. This is used to handle the case of defaulting to reading the
692    script from the standard input because no filename was given on the command
693    line (without getting confused by situation where STDIN has been closed, so
694    the script handle is opened on fd 0)  */
695
696 void
697 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
698 {
699     const char *s = NULL;
700     yy_parser *parser, *oparser;
701
702     if (flags && flags & ~LEX_START_FLAGS)
703         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
704
705     /* create and initialise a parser */
706
707     Newxz(parser, 1, yy_parser);
708     parser->old_parser = oparser = PL_parser;
709     PL_parser = parser;
710
711     parser->stack = NULL;
712     parser->stack_max1 = NULL;
713     parser->ps = NULL;
714
715     /* on scope exit, free this parser and restore any outer one */
716     SAVEPARSER(parser);
717     parser->saved_curcop = PL_curcop;
718
719     /* initialise lexer state */
720
721     parser->nexttoke = 0;
722     parser->error_count = oparser ? oparser->error_count : 0;
723     parser->copline = parser->preambling = NOLINE;
724     parser->lex_state = LEX_NORMAL;
725     parser->expect = XSTATE;
726     parser->rsfp = rsfp;
727     parser->recheck_utf8_validity = TRUE;
728     parser->rsfp_filters =
729       !(flags & LEX_START_SAME_FILTER) || !oparser
730         ? NULL
731         : MUTABLE_AV(SvREFCNT_inc(
732             oparser->rsfp_filters
733              ? oparser->rsfp_filters
734              : (oparser->rsfp_filters = newAV())
735           ));
736
737     Newx(parser->lex_brackstack, 120, char);
738     Newx(parser->lex_casestack, 12, char);
739     *parser->lex_casestack = '\0';
740     Newxz(parser->lex_shared, 1, LEXSHARED);
741
742     if (line) {
743         STRLEN len;
744         const U8* first_bad_char_loc;
745
746         s = SvPV_const(line, len);
747
748         if (   SvUTF8(line)
749             && UNLIKELY(! is_utf8_string_loc((U8 *) s,
750                                              SvCUR(line),
751                                              &first_bad_char_loc)))
752         {
753             _force_out_malformed_utf8_message(first_bad_char_loc,
754                                               (U8 *) s + SvCUR(line),
755                                               0,
756                                               1 /* 1 means die */ );
757             NOT_REACHED; /* NOTREACHED */
758         }
759
760         parser->linestr = flags & LEX_START_COPIED
761                             ? SvREFCNT_inc_simple_NN(line)
762                             : newSVpvn_flags(s, len, SvUTF8(line));
763         if (!rsfp)
764             sv_catpvs(parser->linestr, "\n;");
765     } else {
766         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
767     }
768
769     parser->oldoldbufptr =
770         parser->oldbufptr =
771         parser->bufptr =
772         parser->linestart = SvPVX(parser->linestr);
773     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
774     parser->last_lop = parser->last_uni = NULL;
775
776     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
777                                                         |LEX_DONT_CLOSE_RSFP));
778     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
779                                                         |LEX_DONT_CLOSE_RSFP));
780
781     parser->in_pod = parser->filtered = 0;
782 }
783
784
785 /* delete a parser object */
786
787 void
788 Perl_parser_free(pTHX_  const yy_parser *parser)
789 {
790     PERL_ARGS_ASSERT_PARSER_FREE;
791
792     PL_curcop = parser->saved_curcop;
793     SvREFCNT_dec(parser->linestr);
794
795     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
796         PerlIO_clearerr(parser->rsfp);
797     else if (parser->rsfp && (!parser->old_parser
798           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
799         PerlIO_close(parser->rsfp);
800     SvREFCNT_dec(parser->rsfp_filters);
801     SvREFCNT_dec(parser->lex_stuff);
802     SvREFCNT_dec(parser->lex_sub_repl);
803
804     Safefree(parser->lex_brackstack);
805     Safefree(parser->lex_casestack);
806     Safefree(parser->lex_shared);
807     PL_parser = parser->old_parser;
808     Safefree(parser);
809 }
810
811 void
812 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
813 {
814     I32 nexttoke = parser->nexttoke;
815     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
816     while (nexttoke--) {
817         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
818          && parser->nextval[nexttoke].opval
819          && parser->nextval[nexttoke].opval->op_slabbed
820          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
821             op_free(parser->nextval[nexttoke].opval);
822             parser->nextval[nexttoke].opval = NULL;
823         }
824     }
825 }
826
827
828 /*
829 =for apidoc AmnxUN|SV *|PL_parser-E<gt>linestr
830
831 Buffer scalar containing the chunk currently under consideration of the
832 text currently being lexed.  This is always a plain string scalar (for
833 which C<SvPOK> is true).  It is not intended to be used as a scalar by
834 normal scalar means; instead refer to the buffer directly by the pointer
835 variables described below.
836
837 The lexer maintains various C<char*> pointers to things in the
838 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
839 reallocated, all of these pointers must be updated.  Don't attempt to
840 do this manually, but rather use L</lex_grow_linestr> if you need to
841 reallocate the buffer.
842
843 The content of the text chunk in the buffer is commonly exactly one
844 complete line of input, up to and including a newline terminator,
845 but there are situations where it is otherwise.  The octets of the
846 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
847 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
848 flag on this scalar, which may disagree with it.
849
850 For direct examination of the buffer, the variable
851 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
852 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
853 of these pointers is usually preferable to examination of the scalar
854 through normal scalar means.
855
856 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufend
857
858 Direct pointer to the end of the chunk of text currently being lexed, the
859 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
860 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
861 always located at the end of the buffer, and does not count as part of
862 the buffer's contents.
863
864 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufptr
865
866 Points to the current position of lexing inside the lexer buffer.
867 Characters around this point may be freely examined, within
868 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
869 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
870 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
871
872 Lexing code (whether in the Perl core or not) moves this pointer past
873 the characters that it consumes.  It is also expected to perform some
874 bookkeeping whenever a newline character is consumed.  This movement
875 can be more conveniently performed by the function L</lex_read_to>,
876 which handles newlines appropriately.
877
878 Interpretation of the buffer's octets can be abstracted out by
879 using the slightly higher-level functions L</lex_peek_unichar> and
880 L</lex_read_unichar>.
881
882 =for apidoc AmnxUN|char *|PL_parser-E<gt>linestart
883
884 Points to the start of the current line inside the lexer buffer.
885 This is useful for indicating at which column an error occurred, and
886 not much else.  This must be updated by any lexing code that consumes
887 a newline; the function L</lex_read_to> handles this detail.
888
889 =cut
890 */
891
892 /*
893 =for apidoc lex_bufutf8
894
895 Indicates whether the octets in the lexer buffer
896 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
897 of Unicode characters.  If not, they should be interpreted as Latin-1
898 characters.  This is analogous to the C<SvUTF8> flag for scalars.
899
900 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
901 contains valid UTF-8.  Lexing code must be robust in the face of invalid
902 encoding.
903
904 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
905 is significant, but not the whole story regarding the input character
906 encoding.  Normally, when a file is being read, the scalar contains octets
907 and its C<SvUTF8> flag is off, but the octets should be interpreted as
908 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
909 however, the scalar may have the C<SvUTF8> flag on, and in this case its
910 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
911 is in effect.  This logic may change in the future; use this function
912 instead of implementing the logic yourself.
913
914 =cut
915 */
916
917 bool
918 Perl_lex_bufutf8(pTHX)
919 {
920     return UTF;
921 }
922
923 /*
924 =for apidoc lex_grow_linestr
925
926 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
927 at least C<len> octets (including terminating C<NUL>).  Returns a
928 pointer to the reallocated buffer.  This is necessary before making
929 any direct modification of the buffer that would increase its length.
930 L</lex_stuff_pvn> provides a more convenient way to insert text into
931 the buffer.
932
933 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
934 this function updates all of the lexer's variables that point directly
935 into the buffer.
936
937 =cut
938 */
939
940 char *
941 Perl_lex_grow_linestr(pTHX_ STRLEN len)
942 {
943     SV *linestr;
944     char *buf;
945     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
946     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
947     bool current;
948
949     linestr = PL_parser->linestr;
950     buf = SvPVX(linestr);
951     if (len <= SvLEN(linestr))
952         return buf;
953
954     /* Is the lex_shared linestr SV the same as the current linestr SV?
955      * Only in this case does re_eval_start need adjusting, since it
956      * points within lex_shared->ls_linestr's buffer */
957     current = (   !PL_parser->lex_shared->ls_linestr
958                || linestr == PL_parser->lex_shared->ls_linestr);
959
960     bufend_pos = PL_parser->bufend - buf;
961     bufptr_pos = PL_parser->bufptr - buf;
962     oldbufptr_pos = PL_parser->oldbufptr - buf;
963     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
964     linestart_pos = PL_parser->linestart - buf;
965     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
966     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
967     re_eval_start_pos = (current && PL_parser->lex_shared->re_eval_start) ?
968                             PL_parser->lex_shared->re_eval_start - buf : 0;
969
970     buf = sv_grow(linestr, len);
971
972     PL_parser->bufend = buf + bufend_pos;
973     PL_parser->bufptr = buf + bufptr_pos;
974     PL_parser->oldbufptr = buf + oldbufptr_pos;
975     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
976     PL_parser->linestart = buf + linestart_pos;
977     if (PL_parser->last_uni)
978         PL_parser->last_uni = buf + last_uni_pos;
979     if (PL_parser->last_lop)
980         PL_parser->last_lop = buf + last_lop_pos;
981     if (current && PL_parser->lex_shared->re_eval_start)
982         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
983     return buf;
984 }
985
986 /*
987 =for apidoc lex_stuff_pvn
988
989 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
990 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
991 reallocating the buffer if necessary.  This means that lexing code that
992 runs later will see the characters as if they had appeared in the input.
993 It is not recommended to do this as part of normal parsing, and most
994 uses of this facility run the risk of the inserted characters being
995 interpreted in an unintended manner.
996
997 The string to be inserted is represented by C<len> octets starting
998 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
999 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
1000 The characters are recoded for the lexer buffer, according to how the
1001 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
1002 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
1003 function is more convenient.
1004
1005 =for apidoc Amnh||LEX_STUFF_UTF8
1006
1007 =cut
1008 */
1009
1010 void
1011 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
1012 {
1013     dVAR;
1014     char *bufptr;
1015     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
1016     if (flags & ~(LEX_STUFF_UTF8))
1017         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
1018     if (UTF) {
1019         if (flags & LEX_STUFF_UTF8) {
1020             goto plain_copy;
1021         } else {
1022             STRLEN highhalf = variant_under_utf8_count((U8 *) pv,
1023                                                        (U8 *) pv + len);
1024             const char *p, *e = pv+len;;
1025             if (!highhalf)
1026                 goto plain_copy;
1027             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
1028             bufptr = PL_parser->bufptr;
1029             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
1030             SvCUR_set(PL_parser->linestr,
1031                 SvCUR(PL_parser->linestr) + len+highhalf);
1032             PL_parser->bufend += len+highhalf;
1033             for (p = pv; p != e; p++) {
1034                 append_utf8_from_native_byte(*p, (U8 **) &bufptr);
1035             }
1036         }
1037     } else {
1038         if (flags & LEX_STUFF_UTF8) {
1039             STRLEN highhalf = 0;
1040             const char *p, *e = pv+len;
1041             for (p = pv; p != e; p++) {
1042                 U8 c = (U8)*p;
1043                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1044                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1045                                 "non-Latin-1 character into Latin-1 input");
1046                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1047                     p++;
1048                     highhalf++;
1049                 } else assert(UTF8_IS_INVARIANT(c));
1050             }
1051             if (!highhalf)
1052                 goto plain_copy;
1053             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1054             bufptr = PL_parser->bufptr;
1055             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1056             SvCUR_set(PL_parser->linestr,
1057                 SvCUR(PL_parser->linestr) + len-highhalf);
1058             PL_parser->bufend += len-highhalf;
1059             p = pv;
1060             while (p < e) {
1061                 if (UTF8_IS_INVARIANT(*p)) {
1062                     *bufptr++ = *p;
1063                     p++;
1064                 }
1065                 else {
1066                     assert(p < e -1 );
1067                     *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1068                     p += 2;
1069                 }
1070             }
1071         } else {
1072           plain_copy:
1073             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1074             bufptr = PL_parser->bufptr;
1075             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1076             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1077             PL_parser->bufend += len;
1078             Copy(pv, bufptr, len, char);
1079         }
1080     }
1081 }
1082
1083 /*
1084 =for apidoc lex_stuff_pv
1085
1086 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1087 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1088 reallocating the buffer if necessary.  This means that lexing code that
1089 runs later will see the characters as if they had appeared in the input.
1090 It is not recommended to do this as part of normal parsing, and most
1091 uses of this facility run the risk of the inserted characters being
1092 interpreted in an unintended manner.
1093
1094 The string to be inserted is represented by octets starting at C<pv>
1095 and continuing to the first nul.  These octets are interpreted as either
1096 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1097 in C<flags>.  The characters are recoded for the lexer buffer, according
1098 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1099 If it is not convenient to nul-terminate a string to be inserted, the
1100 L</lex_stuff_pvn> function is more appropriate.
1101
1102 =cut
1103 */
1104
1105 void
1106 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1107 {
1108     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1109     lex_stuff_pvn(pv, strlen(pv), flags);
1110 }
1111
1112 /*
1113 =for apidoc lex_stuff_sv
1114
1115 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1116 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1117 reallocating the buffer if necessary.  This means that lexing code that
1118 runs later will see the characters as if they had appeared in the input.
1119 It is not recommended to do this as part of normal parsing, and most
1120 uses of this facility run the risk of the inserted characters being
1121 interpreted in an unintended manner.
1122
1123 The string to be inserted is the string value of C<sv>.  The characters
1124 are recoded for the lexer buffer, according to how the buffer is currently
1125 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1126 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1127 need to construct a scalar.
1128
1129 =cut
1130 */
1131
1132 void
1133 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1134 {
1135     char *pv;
1136     STRLEN len;
1137     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1138     if (flags)
1139         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1140     pv = SvPV(sv, len);
1141     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1142 }
1143
1144 /*
1145 =for apidoc lex_unstuff
1146
1147 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1148 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1149 This hides the discarded text from any lexing code that runs later,
1150 as if the text had never appeared.
1151
1152 This is not the normal way to consume lexed text.  For that, use
1153 L</lex_read_to>.
1154
1155 =cut
1156 */
1157
1158 void
1159 Perl_lex_unstuff(pTHX_ char *ptr)
1160 {
1161     char *buf, *bufend;
1162     STRLEN unstuff_len;
1163     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1164     buf = PL_parser->bufptr;
1165     if (ptr < buf)
1166         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1167     if (ptr == buf)
1168         return;
1169     bufend = PL_parser->bufend;
1170     if (ptr > bufend)
1171         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1172     unstuff_len = ptr - buf;
1173     Move(ptr, buf, bufend+1-ptr, char);
1174     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1175     PL_parser->bufend = bufend - unstuff_len;
1176 }
1177
1178 /*
1179 =for apidoc lex_read_to
1180
1181 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1182 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1183 performing the correct bookkeeping whenever a newline character is passed.
1184 This is the normal way to consume lexed text.
1185
1186 Interpretation of the buffer's octets can be abstracted out by
1187 using the slightly higher-level functions L</lex_peek_unichar> and
1188 L</lex_read_unichar>.
1189
1190 =cut
1191 */
1192
1193 void
1194 Perl_lex_read_to(pTHX_ char *ptr)
1195 {
1196     char *s;
1197     PERL_ARGS_ASSERT_LEX_READ_TO;
1198     s = PL_parser->bufptr;
1199     if (ptr < s || ptr > PL_parser->bufend)
1200         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1201     for (; s != ptr; s++)
1202         if (*s == '\n') {
1203             COPLINE_INC_WITH_HERELINES;
1204             PL_parser->linestart = s+1;
1205         }
1206     PL_parser->bufptr = ptr;
1207 }
1208
1209 /*
1210 =for apidoc lex_discard_to
1211
1212 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1213 up to C<ptr>.  The remaining content of the buffer will be moved, and
1214 all pointers into the buffer updated appropriately.  C<ptr> must not
1215 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1216 it is not permitted to discard text that has yet to be lexed.
1217
1218 Normally it is not necessarily to do this directly, because it suffices to
1219 use the implicit discarding behaviour of L</lex_next_chunk> and things
1220 based on it.  However, if a token stretches across multiple lines,
1221 and the lexing code has kept multiple lines of text in the buffer for
1222 that purpose, then after completion of the token it would be wise to
1223 explicitly discard the now-unneeded earlier lines, to avoid future
1224 multi-line tokens growing the buffer without bound.
1225
1226 =cut
1227 */
1228
1229 void
1230 Perl_lex_discard_to(pTHX_ char *ptr)
1231 {
1232     char *buf;
1233     STRLEN discard_len;
1234     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1235     buf = SvPVX(PL_parser->linestr);
1236     if (ptr < buf)
1237         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1238     if (ptr == buf)
1239         return;
1240     if (ptr > PL_parser->bufptr)
1241         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1242     discard_len = ptr - buf;
1243     if (PL_parser->oldbufptr < ptr)
1244         PL_parser->oldbufptr = ptr;
1245     if (PL_parser->oldoldbufptr < ptr)
1246         PL_parser->oldoldbufptr = ptr;
1247     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1248         PL_parser->last_uni = NULL;
1249     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1250         PL_parser->last_lop = NULL;
1251     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1252     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1253     PL_parser->bufend -= discard_len;
1254     PL_parser->bufptr -= discard_len;
1255     PL_parser->oldbufptr -= discard_len;
1256     PL_parser->oldoldbufptr -= discard_len;
1257     if (PL_parser->last_uni)
1258         PL_parser->last_uni -= discard_len;
1259     if (PL_parser->last_lop)
1260         PL_parser->last_lop -= discard_len;
1261 }
1262
1263 void
1264 Perl_notify_parser_that_changed_to_utf8(pTHX)
1265 {
1266     /* Called when $^H is changed to indicate that HINT_UTF8 has changed from
1267      * off to on.  At compile time, this has the effect of entering a 'use
1268      * utf8' section.  This means that any input was not previously checked for
1269      * UTF-8 (because it was off), but now we do need to check it, or our
1270      * assumptions about the input being sane could be wrong, and we could
1271      * segfault.  This routine just sets a flag so that the next time we look
1272      * at the input we do the well-formed UTF-8 check.  If we aren't in the
1273      * proper phase, there may not be a parser object, but if there is, setting
1274      * the flag is harmless */
1275
1276     if (PL_parser) {
1277         PL_parser->recheck_utf8_validity = TRUE;
1278     }
1279 }
1280
1281 /*
1282 =for apidoc lex_next_chunk
1283
1284 Reads in the next chunk of text to be lexed, appending it to
1285 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1286 looked to the end of the current chunk and wants to know more.  It is
1287 usual, but not necessary, for lexing to have consumed the entirety of
1288 the current chunk at this time.
1289
1290 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1291 chunk (i.e., the current chunk has been entirely consumed), normally the
1292 current chunk will be discarded at the same time that the new chunk is
1293 read in.  If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1294 will not be discarded.  If the current chunk has not been entirely
1295 consumed, then it will not be discarded regardless of the flag.
1296
1297 Returns true if some new text was added to the buffer, or false if the
1298 buffer has reached the end of the input text.
1299
1300 =for apidoc Amnh||LEX_KEEP_PREVIOUS
1301
1302 =cut
1303 */
1304
1305 #define LEX_FAKE_EOF 0x80000000
1306 #define LEX_NO_TERM  0x40000000 /* here-doc */
1307
1308 bool
1309 Perl_lex_next_chunk(pTHX_ U32 flags)
1310 {
1311     SV *linestr;
1312     char *buf;
1313     STRLEN old_bufend_pos, new_bufend_pos;
1314     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1315     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1316     bool got_some_for_debugger = 0;
1317     bool got_some;
1318
1319     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1320         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1321     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1322         return FALSE;
1323     linestr = PL_parser->linestr;
1324     buf = SvPVX(linestr);
1325     if (!(flags & LEX_KEEP_PREVIOUS)
1326           && PL_parser->bufptr == PL_parser->bufend)
1327     {
1328         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1329         linestart_pos = 0;
1330         if (PL_parser->last_uni != PL_parser->bufend)
1331             PL_parser->last_uni = NULL;
1332         if (PL_parser->last_lop != PL_parser->bufend)
1333             PL_parser->last_lop = NULL;
1334         last_uni_pos = last_lop_pos = 0;
1335         *buf = 0;
1336         SvCUR_set(linestr, 0);
1337     } else {
1338         old_bufend_pos = PL_parser->bufend - buf;
1339         bufptr_pos = PL_parser->bufptr - buf;
1340         oldbufptr_pos = PL_parser->oldbufptr - buf;
1341         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1342         linestart_pos = PL_parser->linestart - buf;
1343         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1344         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1345     }
1346     if (flags & LEX_FAKE_EOF) {
1347         goto eof;
1348     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1349         got_some = 0;
1350     } else if (filter_gets(linestr, old_bufend_pos)) {
1351         got_some = 1;
1352         got_some_for_debugger = 1;
1353     } else if (flags & LEX_NO_TERM) {
1354         got_some = 0;
1355     } else {
1356         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1357             SvPVCLEAR(linestr);
1358         eof:
1359         /* End of real input.  Close filehandle (unless it was STDIN),
1360          * then add implicit termination.
1361          */
1362         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1363             PerlIO_clearerr(PL_parser->rsfp);
1364         else if (PL_parser->rsfp)
1365             (void)PerlIO_close(PL_parser->rsfp);
1366         PL_parser->rsfp = NULL;
1367         PL_parser->in_pod = PL_parser->filtered = 0;
1368         if (!PL_in_eval && PL_minus_p) {
1369             sv_catpvs(linestr,
1370                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1371             PL_minus_n = PL_minus_p = 0;
1372         } else if (!PL_in_eval && PL_minus_n) {
1373             sv_catpvs(linestr, /*{*/";}");
1374             PL_minus_n = 0;
1375         } else
1376             sv_catpvs(linestr, ";");
1377         got_some = 1;
1378     }
1379     buf = SvPVX(linestr);
1380     new_bufend_pos = SvCUR(linestr);
1381     PL_parser->bufend = buf + new_bufend_pos;
1382     PL_parser->bufptr = buf + bufptr_pos;
1383
1384     if (UTF) {
1385         const U8* first_bad_char_loc;
1386         if (UNLIKELY(! is_utf8_string_loc(
1387                             (U8 *) PL_parser->bufptr,
1388                                    PL_parser->bufend - PL_parser->bufptr,
1389                                    &first_bad_char_loc)))
1390         {
1391             _force_out_malformed_utf8_message(first_bad_char_loc,
1392                                               (U8 *) PL_parser->bufend,
1393                                               0,
1394                                               1 /* 1 means die */ );
1395             NOT_REACHED; /* NOTREACHED */
1396         }
1397     }
1398
1399     PL_parser->oldbufptr = buf + oldbufptr_pos;
1400     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1401     PL_parser->linestart = buf + linestart_pos;
1402     if (PL_parser->last_uni)
1403         PL_parser->last_uni = buf + last_uni_pos;
1404     if (PL_parser->last_lop)
1405         PL_parser->last_lop = buf + last_lop_pos;
1406     if (PL_parser->preambling != NOLINE) {
1407         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1408         PL_parser->preambling = NOLINE;
1409     }
1410     if (   got_some_for_debugger
1411         && PERLDB_LINE_OR_SAVESRC
1412         && PL_curstash != PL_debstash)
1413     {
1414         /* debugger active and we're not compiling the debugger code,
1415          * so store the line into the debugger's array of lines
1416          */
1417         update_debugger_info(NULL, buf+old_bufend_pos,
1418             new_bufend_pos-old_bufend_pos);
1419     }
1420     return got_some;
1421 }
1422
1423 /*
1424 =for apidoc lex_peek_unichar
1425
1426 Looks ahead one (Unicode) character in the text currently being lexed.
1427 Returns the codepoint (unsigned integer value) of the next character,
1428 or -1 if lexing has reached the end of the input text.  To consume the
1429 peeked character, use L</lex_read_unichar>.
1430
1431 If the next character is in (or extends into) the next chunk of input
1432 text, the next chunk will be read in.  Normally the current chunk will be
1433 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1434 bit set, then the current chunk will not be discarded.
1435
1436 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1437 is encountered, an exception is generated.
1438
1439 =cut
1440 */
1441
1442 I32
1443 Perl_lex_peek_unichar(pTHX_ U32 flags)
1444 {
1445     dVAR;
1446     char *s, *bufend;
1447     if (flags & ~(LEX_KEEP_PREVIOUS))
1448         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1449     s = PL_parser->bufptr;
1450     bufend = PL_parser->bufend;
1451     if (UTF) {
1452         U8 head;
1453         I32 unichar;
1454         STRLEN len, retlen;
1455         if (s == bufend) {
1456             if (!lex_next_chunk(flags))
1457                 return -1;
1458             s = PL_parser->bufptr;
1459             bufend = PL_parser->bufend;
1460         }
1461         head = (U8)*s;
1462         if (UTF8_IS_INVARIANT(head))
1463             return head;
1464         if (UTF8_IS_START(head)) {
1465             len = UTF8SKIP(&head);
1466             while ((STRLEN)(bufend-s) < len) {
1467                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1468                     break;
1469                 s = PL_parser->bufptr;
1470                 bufend = PL_parser->bufend;
1471             }
1472         }
1473         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1474         if (retlen == (STRLEN)-1) {
1475             _force_out_malformed_utf8_message((U8 *) s,
1476                                               (U8 *) bufend,
1477                                               0,
1478                                               1 /* 1 means die */ );
1479             NOT_REACHED; /* NOTREACHED */
1480         }
1481         return unichar;
1482     } else {
1483         if (s == bufend) {
1484             if (!lex_next_chunk(flags))
1485                 return -1;
1486             s = PL_parser->bufptr;
1487         }
1488         return (U8)*s;
1489     }
1490 }
1491
1492 /*
1493 =for apidoc lex_read_unichar
1494
1495 Reads the next (Unicode) character in the text currently being lexed.
1496 Returns the codepoint (unsigned integer value) of the character read,
1497 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1498 if lexing has reached the end of the input text.  To non-destructively
1499 examine the next character, use L</lex_peek_unichar> instead.
1500
1501 If the next character is in (or extends into) the next chunk of input
1502 text, the next chunk will be read in.  Normally the current chunk will be
1503 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1504 bit set, then the current chunk will not be discarded.
1505
1506 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1507 is encountered, an exception is generated.
1508
1509 =cut
1510 */
1511
1512 I32
1513 Perl_lex_read_unichar(pTHX_ U32 flags)
1514 {
1515     I32 c;
1516     if (flags & ~(LEX_KEEP_PREVIOUS))
1517         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1518     c = lex_peek_unichar(flags);
1519     if (c != -1) {
1520         if (c == '\n')
1521             COPLINE_INC_WITH_HERELINES;
1522         if (UTF)
1523             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1524         else
1525             ++(PL_parser->bufptr);
1526     }
1527     return c;
1528 }
1529
1530 /*
1531 =for apidoc lex_read_space
1532
1533 Reads optional spaces, in Perl style, in the text currently being
1534 lexed.  The spaces may include ordinary whitespace characters and
1535 Perl-style comments.  C<#line> directives are processed if encountered.
1536 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1537 at a non-space character (or the end of the input text).
1538
1539 If spaces extend into the next chunk of input text, the next chunk will
1540 be read in.  Normally the current chunk will be discarded at the same
1541 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1542 chunk will not be discarded.
1543
1544 =cut
1545 */
1546
1547 #define LEX_NO_INCLINE    0x40000000
1548 #define LEX_NO_NEXT_CHUNK 0x80000000
1549
1550 void
1551 Perl_lex_read_space(pTHX_ U32 flags)
1552 {
1553     char *s, *bufend;
1554     const bool can_incline = !(flags & LEX_NO_INCLINE);
1555     bool need_incline = 0;
1556     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1557         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1558     s = PL_parser->bufptr;
1559     bufend = PL_parser->bufend;
1560     while (1) {
1561         char c = *s;
1562         if (c == '#') {
1563             do {
1564                 c = *++s;
1565             } while (!(c == '\n' || (c == 0 && s == bufend)));
1566         } else if (c == '\n') {
1567             s++;
1568             if (can_incline) {
1569                 PL_parser->linestart = s;
1570                 if (s == bufend)
1571                     need_incline = 1;
1572                 else
1573                     incline(s, bufend);
1574             }
1575         } else if (isSPACE(c)) {
1576             s++;
1577         } else if (c == 0 && s == bufend) {
1578             bool got_more;
1579             line_t l;
1580             if (flags & LEX_NO_NEXT_CHUNK)
1581                 break;
1582             PL_parser->bufptr = s;
1583             l = CopLINE(PL_curcop);
1584             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1585             got_more = lex_next_chunk(flags);
1586             CopLINE_set(PL_curcop, l);
1587             s = PL_parser->bufptr;
1588             bufend = PL_parser->bufend;
1589             if (!got_more)
1590                 break;
1591             if (can_incline && need_incline && PL_parser->rsfp) {
1592                 incline(s, bufend);
1593                 need_incline = 0;
1594             }
1595         } else if (!c) {
1596             s++;
1597         } else {
1598             break;
1599         }
1600     }
1601     PL_parser->bufptr = s;
1602 }
1603
1604 /*
1605
1606 =for apidoc validate_proto
1607
1608 This function performs syntax checking on a prototype, C<proto>.
1609 If C<warn> is true, any illegal characters or mismatched brackets
1610 will trigger illegalproto warnings, declaring that they were
1611 detected in the prototype for C<name>.
1612
1613 The return value is C<true> if this is a valid prototype, and
1614 C<false> if it is not, regardless of whether C<warn> was C<true> or
1615 C<false>.
1616
1617 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1618
1619 =cut
1620
1621  */
1622
1623 bool
1624 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn, bool curstash)
1625 {
1626     STRLEN len, origlen;
1627     char *p;
1628     bool bad_proto = FALSE;
1629     bool in_brackets = FALSE;
1630     bool after_slash = FALSE;
1631     char greedy_proto = ' ';
1632     bool proto_after_greedy_proto = FALSE;
1633     bool must_be_last = FALSE;
1634     bool underscore = FALSE;
1635     bool bad_proto_after_underscore = FALSE;
1636
1637     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1638
1639     if (!proto)
1640         return TRUE;
1641
1642     p = SvPV(proto, len);
1643     origlen = len;
1644     for (; len--; p++) {
1645         if (!isSPACE(*p)) {
1646             if (must_be_last)
1647                 proto_after_greedy_proto = TRUE;
1648             if (underscore) {
1649                 if (!memCHRs(";@%", *p))
1650                     bad_proto_after_underscore = TRUE;
1651                 underscore = FALSE;
1652             }
1653             if (!memCHRs("$@%*;[]&\\_+", *p) || *p == '\0') {
1654                 bad_proto = TRUE;
1655             }
1656             else {
1657                 if (*p == '[')
1658                     in_brackets = TRUE;
1659                 else if (*p == ']')
1660                     in_brackets = FALSE;
1661                 else if ((*p == '@' || *p == '%')
1662                          && !after_slash
1663                          && !in_brackets )
1664                 {
1665                     must_be_last = TRUE;
1666                     greedy_proto = *p;
1667                 }
1668                 else if (*p == '_')
1669                     underscore = TRUE;
1670             }
1671             if (*p == '\\')
1672                 after_slash = TRUE;
1673             else
1674                 after_slash = FALSE;
1675         }
1676     }
1677
1678     if (warn) {
1679         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1680         p -= origlen;
1681         p = SvUTF8(proto)
1682             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1683                              origlen, UNI_DISPLAY_ISPRINT)
1684             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1685
1686         if (curstash && !memchr(SvPVX(name), ':', SvCUR(name))) {
1687             SV *name2 = sv_2mortal(newSVsv(PL_curstname));
1688             sv_catpvs(name2, "::");
1689             sv_catsv(name2, (SV *)name);
1690             name = name2;
1691         }
1692
1693         if (proto_after_greedy_proto)
1694             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1695                         "Prototype after '%c' for %" SVf " : %s",
1696                         greedy_proto, SVfARG(name), p);
1697         if (in_brackets)
1698             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1699                         "Missing ']' in prototype for %" SVf " : %s",
1700                         SVfARG(name), p);
1701         if (bad_proto)
1702             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1703                         "Illegal character in prototype for %" SVf " : %s",
1704                         SVfARG(name), p);
1705         if (bad_proto_after_underscore)
1706             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1707                         "Illegal character after '_' in prototype for %" SVf " : %s",
1708                         SVfARG(name), p);
1709     }
1710
1711     return (! (proto_after_greedy_proto || bad_proto) );
1712 }
1713
1714 /*
1715  * S_incline
1716  * This subroutine has nothing to do with tilting, whether at windmills
1717  * or pinball tables.  Its name is short for "increment line".  It
1718  * increments the current line number in CopLINE(PL_curcop) and checks
1719  * to see whether the line starts with a comment of the form
1720  *    # line 500 "foo.pm"
1721  * If so, it sets the current line number and file to the values in the comment.
1722  */
1723
1724 STATIC void
1725 S_incline(pTHX_ const char *s, const char *end)
1726 {
1727     const char *t;
1728     const char *n;
1729     const char *e;
1730     line_t line_num;
1731     UV uv;
1732
1733     PERL_ARGS_ASSERT_INCLINE;
1734
1735     assert(end >= s);
1736
1737     COPLINE_INC_WITH_HERELINES;
1738     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1739      && s+1 == PL_bufend && *s == ';') {
1740         /* fake newline in string eval */
1741         CopLINE_dec(PL_curcop);
1742         return;
1743     }
1744     if (*s++ != '#')
1745         return;
1746     while (SPACE_OR_TAB(*s))
1747         s++;
1748     if (memBEGINs(s, (STRLEN) (end - s), "line"))
1749         s += sizeof("line") - 1;
1750     else
1751         return;
1752     if (SPACE_OR_TAB(*s))
1753         s++;
1754     else
1755         return;
1756     while (SPACE_OR_TAB(*s))
1757         s++;
1758     if (!isDIGIT(*s))
1759         return;
1760
1761     n = s;
1762     while (isDIGIT(*s))
1763         s++;
1764     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1765         return;
1766     while (SPACE_OR_TAB(*s))
1767         s++;
1768     if (*s == '"' && (t = (char *) memchr(s+1, '"', end - s))) {
1769         s++;
1770         e = t + 1;
1771     }
1772     else {
1773         t = s;
1774         while (*t && !isSPACE(*t))
1775             t++;
1776         e = t;
1777     }
1778     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1779         e++;
1780     if (*e != '\n' && *e != '\0')
1781         return;         /* false alarm */
1782
1783     if (!grok_atoUV(n, &uv, &e))
1784         return;
1785     line_num = ((line_t)uv) - 1;
1786
1787     if (t - s > 0) {
1788         const STRLEN len = t - s;
1789
1790         if (!PL_rsfp && !PL_parser->filtered) {
1791             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1792              * to *{"::_<newfilename"} */
1793             /* However, the long form of evals is only turned on by the
1794                debugger - usually they're "(eval %lu)" */
1795             GV * const cfgv = CopFILEGV(PL_curcop);
1796             if (cfgv) {
1797                 char smallbuf[128];
1798                 STRLEN tmplen2 = len;
1799                 char *tmpbuf2;
1800                 GV *gv2;
1801
1802                 if (tmplen2 + 2 <= sizeof smallbuf)
1803                     tmpbuf2 = smallbuf;
1804                 else
1805                     Newx(tmpbuf2, tmplen2 + 2, char);
1806
1807                 tmpbuf2[0] = '_';
1808                 tmpbuf2[1] = '<';
1809
1810                 memcpy(tmpbuf2 + 2, s, tmplen2);
1811                 tmplen2 += 2;
1812
1813                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1814                 if (!isGV(gv2)) {
1815                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1816                     /* adjust ${"::_<newfilename"} to store the new file name */
1817                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1818                     /* The line number may differ. If that is the case,
1819                        alias the saved lines that are in the array.
1820                        Otherwise alias the whole array. */
1821                     if (CopLINE(PL_curcop) == line_num) {
1822                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1823                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1824                     }
1825                     else if (GvAV(cfgv)) {
1826                         AV * const av = GvAV(cfgv);
1827                         const line_t start = CopLINE(PL_curcop)+1;
1828                         SSize_t items = AvFILLp(av) - start;
1829                         if (items > 0) {
1830                             AV * const av2 = GvAVn(gv2);
1831                             SV **svp = AvARRAY(av) + start;
1832                             Size_t l = line_num+1;
1833                             while (items-- && l < SSize_t_MAX && l == (line_t)l)
1834                                 av_store(av2, (SSize_t)l++, SvREFCNT_inc(*svp++));
1835                         }
1836                     }
1837                 }
1838
1839                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1840             }
1841         }
1842         CopFILE_free(PL_curcop);
1843         CopFILE_setn(PL_curcop, s, len);
1844     }
1845     CopLINE_set(PL_curcop, line_num);
1846 }
1847
1848 STATIC void
1849 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1850 {
1851     AV *av = CopFILEAVx(PL_curcop);
1852     if (av) {
1853         SV * sv;
1854         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1855         else {
1856             sv = *av_fetch(av, 0, 1);
1857             SvUPGRADE(sv, SVt_PVMG);
1858         }
1859         if (!SvPOK(sv)) SvPVCLEAR(sv);
1860         if (orig_sv)
1861             sv_catsv(sv, orig_sv);
1862         else
1863             sv_catpvn(sv, buf, len);
1864         if (!SvIOK(sv)) {
1865             (void)SvIOK_on(sv);
1866             SvIV_set(sv, 0);
1867         }
1868         if (PL_parser->preambling == NOLINE)
1869             av_store(av, CopLINE(PL_curcop), sv);
1870     }
1871 }
1872
1873 /*
1874  * skipspace
1875  * Called to gobble the appropriate amount and type of whitespace.
1876  * Skips comments as well.
1877  * Returns the next character after the whitespace that is skipped.
1878  *
1879  * peekspace
1880  * Same thing, but look ahead without incrementing line numbers or
1881  * adjusting PL_linestart.
1882  */
1883
1884 #define skipspace(s) skipspace_flags(s, 0)
1885 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1886
1887 char *
1888 Perl_skipspace_flags(pTHX_ char *s, U32 flags)
1889 {
1890     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1891     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1892         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1893             s++;
1894     } else {
1895         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1896         PL_bufptr = s;
1897         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1898                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1899                     LEX_NO_NEXT_CHUNK : 0));
1900         s = PL_bufptr;
1901         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1902         if (PL_linestart > PL_bufptr)
1903             PL_bufptr = PL_linestart;
1904         return s;
1905     }
1906     return s;
1907 }
1908
1909 /*
1910  * S_check_uni
1911  * Check the unary operators to ensure there's no ambiguity in how they're
1912  * used.  An ambiguous piece of code would be:
1913  *     rand + 5
1914  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1915  * the +5 is its argument.
1916  */
1917
1918 STATIC void
1919 S_check_uni(pTHX)
1920 {
1921     const char *s;
1922
1923     if (PL_oldoldbufptr != PL_last_uni)
1924         return;
1925     while (isSPACE(*PL_last_uni))
1926         PL_last_uni++;
1927     s = PL_last_uni;
1928     while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF) || *s == '-')
1929         s += UTF ? UTF8SKIP(s) : 1;
1930     if (s < PL_bufptr && memchr(s, '(', PL_bufptr - s))
1931         return;
1932
1933     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1934                      "Warning: Use of \"%" UTF8f "\" without parentheses is ambiguous",
1935                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1936 }
1937
1938 /*
1939  * LOP : macro to build a list operator.  Its behaviour has been replaced
1940  * with a subroutine, S_lop() for which LOP is just another name.
1941  */
1942
1943 #define LOP(f,x) return lop(f,x,s)
1944
1945 /*
1946  * S_lop
1947  * Build a list operator (or something that might be one).  The rules:
1948  *  - if we have a next token, then it's a list operator (no parens) for
1949  *    which the next token has already been parsed; e.g.,
1950  *       sort foo @args
1951  *       sort foo (@args)
1952  *  - if the next thing is an opening paren, then it's a function
1953  *  - else it's a list operator
1954  */
1955
1956 STATIC I32
1957 S_lop(pTHX_ I32 f, U8 x, char *s)
1958 {
1959     PERL_ARGS_ASSERT_LOP;
1960
1961     pl_yylval.ival = f;
1962     CLINE;
1963     PL_bufptr = s;
1964     PL_last_lop = PL_oldbufptr;
1965     PL_last_lop_op = (OPCODE)f;
1966     if (PL_nexttoke)
1967         goto lstop;
1968     PL_expect = x;
1969     if (*s == '(')
1970         return REPORT(FUNC);
1971     s = skipspace(s);
1972     if (*s == '(')
1973         return REPORT(FUNC);
1974     else {
1975         lstop:
1976         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1977             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1978         return REPORT(LSTOP);
1979     }
1980 }
1981
1982 /*
1983  * S_force_next
1984  * When the lexer realizes it knows the next token (for instance,
1985  * it is reordering tokens for the parser) then it can call S_force_next
1986  * to know what token to return the next time the lexer is called.  Caller
1987  * will need to set PL_nextval[] and possibly PL_expect to ensure
1988  * the lexer handles the token correctly.
1989  */
1990
1991 STATIC void
1992 S_force_next(pTHX_ I32 type)
1993 {
1994 #ifdef DEBUGGING
1995     if (DEBUG_T_TEST) {
1996         PerlIO_printf(Perl_debug_log, "### forced token:\n");
1997         tokereport(type, &NEXTVAL_NEXTTOKE);
1998     }
1999 #endif
2000     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
2001     PL_nexttype[PL_nexttoke] = type;
2002     PL_nexttoke++;
2003 }
2004
2005 /*
2006  * S_postderef
2007  *
2008  * This subroutine handles postfix deref syntax after the arrow has already
2009  * been emitted.  @* $* etc. are emitted as two separate tokens right here.
2010  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
2011  * only the first, leaving yylex to find the next.
2012  */
2013
2014 static int
2015 S_postderef(pTHX_ int const funny, char const next)
2016 {
2017     assert(funny == DOLSHARP || memCHRs("$@%&*", funny));
2018     if (next == '*') {
2019         PL_expect = XOPERATOR;
2020         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
2021             assert('@' == funny || '$' == funny || DOLSHARP == funny);
2022             PL_lex_state = LEX_INTERPEND;
2023             if ('@' == funny)
2024                 force_next(POSTJOIN);
2025         }
2026         force_next(next);
2027         PL_bufptr+=2;
2028     }
2029     else {
2030         if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
2031          && !PL_lex_brackets)
2032             PL_lex_dojoin = 2;
2033         PL_expect = XOPERATOR;
2034         PL_bufptr++;
2035     }
2036     return funny;
2037 }
2038
2039 void
2040 Perl_yyunlex(pTHX)
2041 {
2042     int yyc = PL_parser->yychar;
2043     if (yyc != YYEMPTY) {
2044         if (yyc) {
2045             NEXTVAL_NEXTTOKE = PL_parser->yylval;
2046             if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
2047                 PL_lex_allbrackets--;
2048                 PL_lex_brackets--;
2049                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
2050             } else if (yyc == '('/*)*/) {
2051                 PL_lex_allbrackets--;
2052                 yyc |= (2<<24);
2053             }
2054             force_next(yyc);
2055         }
2056         PL_parser->yychar = YYEMPTY;
2057     }
2058 }
2059
2060 STATIC SV *
2061 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
2062 {
2063     SV * const sv = newSVpvn_utf8(start, len,
2064                     ! IN_BYTES
2065                   &&  UTF
2066                   &&  len != 0
2067                   &&  is_utf8_non_invariant_string((const U8*)start, len));
2068     return sv;
2069 }
2070
2071 /*
2072  * S_force_word
2073  * When the lexer knows the next thing is a word (for instance, it has
2074  * just seen -> and it knows that the next char is a word char, then
2075  * it calls S_force_word to stick the next word into the PL_nexttoke/val
2076  * lookahead.
2077  *
2078  * Arguments:
2079  *   char *start : buffer position (must be within PL_linestr)
2080  *   int token   : PL_next* will be this type of bare word
2081  *                 (e.g., METHOD,BAREWORD)
2082  *   int check_keyword : if true, Perl checks to make sure the word isn't
2083  *       a keyword (do this if the word is a label, e.g. goto FOO)
2084  *   int allow_pack : if true, : characters will also be allowed (require,
2085  *       use, etc. do this)
2086  */
2087
2088 STATIC char *
2089 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2090 {
2091     char *s;
2092     STRLEN len;
2093
2094     PERL_ARGS_ASSERT_FORCE_WORD;
2095
2096     start = skipspace(start);
2097     s = start;
2098     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
2099         || (allow_pack && *s == ':' && s[1] == ':') )
2100     {
2101         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2102         if (check_keyword) {
2103           char *s2 = PL_tokenbuf;
2104           STRLEN len2 = len;
2105           if (allow_pack && memBEGINPs(s2, len, "CORE::")) {
2106             s2 += sizeof("CORE::") - 1;
2107             len2 -= sizeof("CORE::") - 1;
2108           }
2109           if (keyword(s2, len2, 0))
2110             return start;
2111         }
2112         if (token == METHOD) {
2113             s = skipspace(s);
2114             if (*s == '(')
2115                 PL_expect = XTERM;
2116             else {
2117                 PL_expect = XOPERATOR;
2118             }
2119         }
2120         NEXTVAL_NEXTTOKE.opval
2121             = newSVOP(OP_CONST,0,
2122                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2123         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2124         force_next(token);
2125     }
2126     return s;
2127 }
2128
2129 /*
2130  * S_force_ident
2131  * Called when the lexer wants $foo *foo &foo etc, but the program
2132  * text only contains the "foo" portion.  The first argument is a pointer
2133  * to the "foo", and the second argument is the type symbol to prefix.
2134  * Forces the next token to be a "BAREWORD".
2135  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2136  */
2137
2138 STATIC void
2139 S_force_ident(pTHX_ const char *s, int kind)
2140 {
2141     PERL_ARGS_ASSERT_FORCE_IDENT;
2142
2143     if (s[0]) {
2144         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2145         OP* const o = newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2146                                                                 UTF ? SVf_UTF8 : 0));
2147         NEXTVAL_NEXTTOKE.opval = o;
2148         force_next(BAREWORD);
2149         if (kind) {
2150             o->op_private = OPpCONST_ENTERED;
2151             /* XXX see note in pp_entereval() for why we forgo typo
2152                warnings if the symbol must be introduced in an eval.
2153                GSAR 96-10-12 */
2154             gv_fetchpvn_flags(s, len,
2155                               (PL_in_eval ? GV_ADDMULTI
2156                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2157                               kind == '$' ? SVt_PV :
2158                               kind == '@' ? SVt_PVAV :
2159                               kind == '%' ? SVt_PVHV :
2160                               SVt_PVGV
2161                               );
2162         }
2163     }
2164 }
2165
2166 static void
2167 S_force_ident_maybe_lex(pTHX_ char pit)
2168 {
2169     NEXTVAL_NEXTTOKE.ival = pit;
2170     force_next('p');
2171 }
2172
2173 NV
2174 Perl_str_to_version(pTHX_ SV *sv)
2175 {
2176     NV retval = 0.0;
2177     NV nshift = 1.0;
2178     STRLEN len;
2179     const char *start = SvPV_const(sv,len);
2180     const char * const end = start + len;
2181     const bool utf = cBOOL(SvUTF8(sv));
2182
2183     PERL_ARGS_ASSERT_STR_TO_VERSION;
2184
2185     while (start < end) {
2186         STRLEN skip;
2187         UV n;
2188         if (utf)
2189             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2190         else {
2191             n = *(U8*)start;
2192             skip = 1;
2193         }
2194         retval += ((NV)n)/nshift;
2195         start += skip;
2196         nshift *= 1000;
2197     }
2198     return retval;
2199 }
2200
2201 /*
2202  * S_force_version
2203  * Forces the next token to be a version number.
2204  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2205  * and if "guessing" is TRUE, then no new token is created (and the caller
2206  * must use an alternative parsing method).
2207  */
2208
2209 STATIC char *
2210 S_force_version(pTHX_ char *s, int guessing)
2211 {
2212     OP *version = NULL;
2213     char *d;
2214
2215     PERL_ARGS_ASSERT_FORCE_VERSION;
2216
2217     s = skipspace(s);
2218
2219     d = s;
2220     if (*d == 'v')
2221         d++;
2222     if (isDIGIT(*d)) {
2223         while (isDIGIT(*d) || *d == '_' || *d == '.')
2224             d++;
2225         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2226             SV *ver;
2227             s = scan_num(s, &pl_yylval);
2228             version = pl_yylval.opval;
2229             ver = cSVOPx(version)->op_sv;
2230             if (SvPOK(ver) && !SvNIOK(ver)) {
2231                 SvUPGRADE(ver, SVt_PVNV);
2232                 SvNV_set(ver, str_to_version(ver));
2233                 SvNOK_on(ver);          /* hint that it is a version */
2234             }
2235         }
2236         else if (guessing) {
2237             return s;
2238         }
2239     }
2240
2241     /* NOTE: The parser sees the package name and the VERSION swapped */
2242     NEXTVAL_NEXTTOKE.opval = version;
2243     force_next(BAREWORD);
2244
2245     return s;
2246 }
2247
2248 /*
2249  * S_force_strict_version
2250  * Forces the next token to be a version number using strict syntax rules.
2251  */
2252
2253 STATIC char *
2254 S_force_strict_version(pTHX_ char *s)
2255 {
2256     OP *version = NULL;
2257     const char *errstr = NULL;
2258
2259     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2260
2261     while (isSPACE(*s)) /* leading whitespace */
2262         s++;
2263
2264     if (is_STRICT_VERSION(s,&errstr)) {
2265         SV *ver = newSV(0);
2266         s = (char *)scan_version(s, ver, 0);
2267         version = newSVOP(OP_CONST, 0, ver);
2268     }
2269     else if ((*s != ';' && *s != '{' && *s != '}' )
2270              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2271     {
2272         PL_bufptr = s;
2273         if (errstr)
2274             yyerror(errstr); /* version required */
2275         return s;
2276     }
2277
2278     /* NOTE: The parser sees the package name and the VERSION swapped */
2279     NEXTVAL_NEXTTOKE.opval = version;
2280     force_next(BAREWORD);
2281
2282     return s;
2283 }
2284
2285 /*
2286  * S_tokeq
2287  * Turns any \\ into \ in a quoted string passed in in 'sv', returning 'sv',
2288  * modified as necessary.  However, if HINT_NEW_STRING is on, 'sv' is
2289  * unchanged, and a new SV containing the modified input is returned.
2290  */
2291
2292 STATIC SV *
2293 S_tokeq(pTHX_ SV *sv)
2294 {
2295     char *s;
2296     char *send;
2297     char *d;
2298     SV *pv = sv;
2299
2300     PERL_ARGS_ASSERT_TOKEQ;
2301
2302     assert (SvPOK(sv));
2303     assert (SvLEN(sv));
2304     assert (!SvIsCOW(sv));
2305     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2306         goto finish;
2307     s = SvPVX(sv);
2308     send = SvEND(sv);
2309     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2310     while (s < send && !(*s == '\\' && s[1] == '\\'))
2311         s++;
2312     if (s == send)
2313         goto finish;
2314     d = s;
2315     if ( PL_hints & HINT_NEW_STRING ) {
2316         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2317                             SVs_TEMP | SvUTF8(sv));
2318     }
2319     while (s < send) {
2320         if (*s == '\\') {
2321             if (s + 1 < send && (s[1] == '\\'))
2322                 s++;            /* all that, just for this */
2323         }
2324         *d++ = *s++;
2325     }
2326     *d = '\0';
2327     SvCUR_set(sv, d - SvPVX_const(sv));
2328   finish:
2329     if ( PL_hints & HINT_NEW_STRING )
2330        return new_constant(NULL, 0, "q", sv, pv, "q", 1, NULL);
2331     return sv;
2332 }
2333
2334 /*
2335  * Now come three functions related to double-quote context,
2336  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2337  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2338  * interact with PL_lex_state, and create fake ( ... ) argument lists
2339  * to handle functions and concatenation.
2340  * For example,
2341  *   "foo\lbar"
2342  * is tokenised as
2343  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2344  */
2345
2346 /*
2347  * S_sublex_start
2348  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2349  *
2350  * Pattern matching will set PL_lex_op to the pattern-matching op to
2351  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2352  *
2353  * OP_CONST is easy--just make the new op and return.
2354  *
2355  * Everything else becomes a FUNC.
2356  *
2357  * Sets PL_lex_state to LEX_INTERPPUSH unless ival was OP_NULL or we
2358  * had an OP_CONST.  This just sets us up for a
2359  * call to S_sublex_push().
2360  */
2361
2362 STATIC I32
2363 S_sublex_start(pTHX)
2364 {
2365     const I32 op_type = pl_yylval.ival;
2366
2367     if (op_type == OP_NULL) {
2368         pl_yylval.opval = PL_lex_op;
2369         PL_lex_op = NULL;
2370         return THING;
2371     }
2372     if (op_type == OP_CONST) {
2373         SV *sv = PL_lex_stuff;
2374         PL_lex_stuff = NULL;
2375         sv = tokeq(sv);
2376
2377         if (SvTYPE(sv) == SVt_PVIV) {
2378             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2379             STRLEN len;
2380             const char * const p = SvPV_const(sv, len);
2381             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2382             SvREFCNT_dec(sv);
2383             sv = nsv;
2384         }
2385         pl_yylval.opval = newSVOP(op_type, 0, sv);
2386         return THING;
2387     }
2388
2389     PL_parser->lex_super_state = PL_lex_state;
2390     PL_parser->lex_sub_inwhat = (U16)op_type;
2391     PL_parser->lex_sub_op = PL_lex_op;
2392     PL_parser->sub_no_recover = FALSE;
2393     PL_parser->sub_error_count = PL_error_count;
2394     PL_lex_state = LEX_INTERPPUSH;
2395
2396     PL_expect = XTERM;
2397     if (PL_lex_op) {
2398         pl_yylval.opval = PL_lex_op;
2399         PL_lex_op = NULL;
2400         return PMFUNC;
2401     }
2402     else
2403         return FUNC;
2404 }
2405
2406 /*
2407  * S_sublex_push
2408  * Create a new scope to save the lexing state.  The scope will be
2409  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2410  * to the uc, lc, etc. found before.
2411  * Sets PL_lex_state to LEX_INTERPCONCAT.
2412  */
2413
2414 STATIC I32
2415 S_sublex_push(pTHX)
2416 {
2417     LEXSHARED *shared;
2418     const bool is_heredoc = PL_multi_close == '<';
2419     ENTER;
2420
2421     PL_lex_state = PL_parser->lex_super_state;
2422     SAVEI8(PL_lex_dojoin);
2423     SAVEI32(PL_lex_brackets);
2424     SAVEI32(PL_lex_allbrackets);
2425     SAVEI32(PL_lex_formbrack);
2426     SAVEI8(PL_lex_fakeeof);
2427     SAVEI32(PL_lex_casemods);
2428     SAVEI32(PL_lex_starts);
2429     SAVEI8(PL_lex_state);
2430     SAVESPTR(PL_lex_repl);
2431     SAVEVPTR(PL_lex_inpat);
2432     SAVEI16(PL_lex_inwhat);
2433     if (is_heredoc)
2434     {
2435         SAVECOPLINE(PL_curcop);
2436         SAVEI32(PL_multi_end);
2437         SAVEI32(PL_parser->herelines);
2438         PL_parser->herelines = 0;
2439     }
2440     SAVEIV(PL_multi_close);
2441     SAVEPPTR(PL_bufptr);
2442     SAVEPPTR(PL_bufend);
2443     SAVEPPTR(PL_oldbufptr);
2444     SAVEPPTR(PL_oldoldbufptr);
2445     SAVEPPTR(PL_last_lop);
2446     SAVEPPTR(PL_last_uni);
2447     SAVEPPTR(PL_linestart);
2448     SAVESPTR(PL_linestr);
2449     SAVEGENERICPV(PL_lex_brackstack);
2450     SAVEGENERICPV(PL_lex_casestack);
2451     SAVEGENERICPV(PL_parser->lex_shared);
2452     SAVEBOOL(PL_parser->lex_re_reparsing);
2453     SAVEI32(PL_copline);
2454
2455     /* The here-doc parser needs to be able to peek into outer lexing
2456        scopes to find the body of the here-doc.  So we put PL_linestr and
2457        PL_bufptr into lex_shared, to â€˜share’ those values.
2458      */
2459     PL_parser->lex_shared->ls_linestr = PL_linestr;
2460     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2461
2462     PL_linestr = PL_lex_stuff;
2463     PL_lex_repl = PL_parser->lex_sub_repl;
2464     PL_lex_stuff = NULL;
2465     PL_parser->lex_sub_repl = NULL;
2466
2467     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2468        set for an inner quote-like operator and then an error causes scope-
2469        popping.  We must not have a PL_lex_stuff value left dangling, as
2470        that breaks assumptions elsewhere.  See bug #123617.  */
2471     SAVEGENERICSV(PL_lex_stuff);
2472     SAVEGENERICSV(PL_parser->lex_sub_repl);
2473
2474     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2475         = SvPVX(PL_linestr);
2476     PL_bufend += SvCUR(PL_linestr);
2477     PL_last_lop = PL_last_uni = NULL;
2478     SAVEFREESV(PL_linestr);
2479     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2480
2481     PL_lex_dojoin = FALSE;
2482     PL_lex_brackets = PL_lex_formbrack = 0;
2483     PL_lex_allbrackets = 0;
2484     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2485     Newx(PL_lex_brackstack, 120, char);
2486     Newx(PL_lex_casestack, 12, char);
2487     PL_lex_casemods = 0;
2488     *PL_lex_casestack = '\0';
2489     PL_lex_starts = 0;
2490     PL_lex_state = LEX_INTERPCONCAT;
2491     if (is_heredoc)
2492         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2493     PL_copline = NOLINE;
2494
2495     Newxz(shared, 1, LEXSHARED);
2496     shared->ls_prev = PL_parser->lex_shared;
2497     PL_parser->lex_shared = shared;
2498
2499     PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2500     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2501     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2502         PL_lex_inpat = PL_parser->lex_sub_op;
2503     else
2504         PL_lex_inpat = NULL;
2505
2506     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2507     PL_in_eval &= ~EVAL_RE_REPARSING;
2508
2509     return SUBLEXSTART;
2510 }
2511
2512 /*
2513  * S_sublex_done
2514  * Restores lexer state after a S_sublex_push.
2515  */
2516
2517 STATIC I32
2518 S_sublex_done(pTHX)
2519 {
2520     if (!PL_lex_starts++) {
2521         SV * const sv = newSVpvs("");
2522         if (SvUTF8(PL_linestr))
2523             SvUTF8_on(sv);
2524         PL_expect = XOPERATOR;
2525         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
2526         return THING;
2527     }
2528
2529     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2530         PL_lex_state = LEX_INTERPCASEMOD;
2531         return yylex();
2532     }
2533
2534     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2535     assert(PL_lex_inwhat != OP_TRANSR);
2536     if (PL_lex_repl) {
2537         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2538         PL_linestr = PL_lex_repl;
2539         PL_lex_inpat = 0;
2540         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2541         PL_bufend += SvCUR(PL_linestr);
2542         PL_last_lop = PL_last_uni = NULL;
2543         PL_lex_dojoin = FALSE;
2544         PL_lex_brackets = 0;
2545         PL_lex_allbrackets = 0;
2546         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2547         PL_lex_casemods = 0;
2548         *PL_lex_casestack = '\0';
2549         PL_lex_starts = 0;
2550         if (SvEVALED(PL_lex_repl)) {
2551             PL_lex_state = LEX_INTERPNORMAL;
2552             PL_lex_starts++;
2553             /*  we don't clear PL_lex_repl here, so that we can check later
2554                 whether this is an evalled subst; that means we rely on the
2555                 logic to ensure sublex_done() is called again only via the
2556                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2557         }
2558         else {
2559             PL_lex_state = LEX_INTERPCONCAT;
2560             PL_lex_repl = NULL;
2561         }
2562         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2563             CopLINE(PL_curcop) +=
2564                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2565                  + PL_parser->herelines;
2566             PL_parser->herelines = 0;
2567         }
2568         return '/';
2569     }
2570     else {
2571         const line_t l = CopLINE(PL_curcop);
2572         LEAVE;
2573         if (PL_parser->sub_error_count != PL_error_count) {
2574             if (PL_parser->sub_no_recover) {
2575                 yyquit();
2576                 NOT_REACHED;
2577             }
2578         }
2579         if (PL_multi_close == '<')
2580             PL_parser->herelines += l - PL_multi_end;
2581         PL_bufend = SvPVX(PL_linestr);
2582         PL_bufend += SvCUR(PL_linestr);
2583         PL_expect = XOPERATOR;
2584         return SUBLEXEND;
2585     }
2586 }
2587
2588 STATIC SV*
2589 S_get_and_check_backslash_N_name_wrapper(pTHX_ const char* s, const char* const e)
2590 {
2591     /* This justs wraps get_and_check_backslash_N_name() to output any error
2592      * message it returns. */
2593
2594     const char * error_msg = NULL;
2595     SV * result;
2596
2597     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME_WRAPPER;
2598
2599     /* charnames doesn't work well if there have been errors found */
2600     if (PL_error_count > 0) {
2601         return NULL;
2602     }
2603
2604     result = get_and_check_backslash_N_name(s, e, cBOOL(UTF), &error_msg);
2605
2606     if (error_msg) {
2607         yyerror_pv(error_msg, UTF ? SVf_UTF8 : 0);
2608     }
2609
2610     return result;
2611 }
2612
2613 SV*
2614 Perl_get_and_check_backslash_N_name(pTHX_ const char* s,
2615                                           const char* const e,
2616                                           const bool is_utf8,
2617                                           const char ** error_msg)
2618 {
2619     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2620      * interior, hence to the "}".  Finds what the name resolves to, returning
2621      * an SV* containing it; NULL if no valid one found.
2622      *
2623      * 'is_utf8' is TRUE if we know we want the result to be UTF-8 even if it
2624      * doesn't have to be. */
2625
2626     SV* res;
2627     HV * table;
2628     SV **cvp;
2629     SV *cv;
2630     SV *rv;
2631     HV *stash;
2632     const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2633     dVAR;
2634
2635     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2636
2637     assert(e >= s);
2638     assert(s > (char *) 3);
2639
2640     res = newSVpvn_flags(s, e - s, (is_utf8) ? SVf_UTF8 : 0);
2641
2642     if (!SvCUR(res)) {
2643         SvREFCNT_dec_NN(res);
2644         /* diag_listed_as: Unknown charname '%s' */
2645         *error_msg = Perl_form(aTHX_ "Unknown charname ''");
2646         return NULL;
2647     }
2648
2649     res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2650                         /* include the <}> */
2651                         e - backslash_ptr + 1, error_msg);
2652     if (! SvPOK(res)) {
2653         SvREFCNT_dec_NN(res);
2654         return NULL;
2655     }
2656
2657     /* See if the charnames handler is the Perl core's, and if so, we can skip
2658      * the validation needed for a user-supplied one, as Perl's does its own
2659      * validation. */
2660     table = GvHV(PL_hintgv);             /* ^H */
2661     cvp = hv_fetchs(table, "charnames", FALSE);
2662     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2663         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2664     {
2665         const char * const name = HvNAME(stash);
2666          if (memEQs(name, HvNAMELEN(stash), "_charnames")) {
2667            return res;
2668        }
2669     }
2670
2671     /* Here, it isn't Perl's charname handler.  We can't rely on a
2672      * user-supplied handler to validate the input name.  For non-ut8 input,
2673      * look to see that the first character is legal.  Then loop through the
2674      * rest checking that each is a continuation */
2675
2676     /* This code makes the reasonable assumption that the only Latin1-range
2677      * characters that begin a character name alias are alphabetic, otherwise
2678      * would have to create a isCHARNAME_BEGIN macro */
2679
2680     if (! is_utf8) {
2681         if (! isALPHAU(*s)) {
2682             goto bad_charname;
2683         }
2684         s++;
2685         while (s < e) {
2686             if (! isCHARNAME_CONT(*s)) {
2687                 goto bad_charname;
2688             }
2689             if (*s == ' ' && *(s-1) == ' ') {
2690                 goto multi_spaces;
2691             }
2692             s++;
2693         }
2694     }
2695     else {
2696         /* Similarly for utf8.  For invariants can check directly; for other
2697          * Latin1, can calculate their code point and check; otherwise  use an
2698          * inversion list */
2699         if (UTF8_IS_INVARIANT(*s)) {
2700             if (! isALPHAU(*s)) {
2701                 goto bad_charname;
2702             }
2703             s++;
2704         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2705             if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2706                 goto bad_charname;
2707             }
2708             s += 2;
2709         }
2710         else {
2711             if (! _invlist_contains_cp(PL_utf8_charname_begin,
2712                                        utf8_to_uvchr_buf((U8 *) s,
2713                                                          (U8 *) e,
2714                                                          NULL)))
2715             {
2716                 goto bad_charname;
2717             }
2718             s += UTF8SKIP(s);
2719         }
2720
2721         while (s < e) {
2722             if (UTF8_IS_INVARIANT(*s)) {
2723                 if (! isCHARNAME_CONT(*s)) {
2724                     goto bad_charname;
2725                 }
2726                 if (*s == ' ' && *(s-1) == ' ') {
2727                     goto multi_spaces;
2728                 }
2729                 s++;
2730             }
2731             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2732                 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2733                 {
2734                     goto bad_charname;
2735                 }
2736                 s += 2;
2737             }
2738             else {
2739                 if (! _invlist_contains_cp(PL_utf8_charname_continue,
2740                                            utf8_to_uvchr_buf((U8 *) s,
2741                                                              (U8 *) e,
2742                                                              NULL)))
2743                 {
2744                     goto bad_charname;
2745                 }
2746                 s += UTF8SKIP(s);
2747             }
2748         }
2749     }
2750     if (*(s-1) == ' ') {
2751         /* diag_listed_as: charnames alias definitions may not contain
2752                            trailing white-space; marked by <-- HERE in %s
2753          */
2754         *error_msg = Perl_form(aTHX_
2755             "charnames alias definitions may not contain trailing "
2756             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2757             (int)(s - backslash_ptr + 1), backslash_ptr,
2758             (int)(e - s + 1), s + 1);
2759         return NULL;
2760     }
2761
2762     if (SvUTF8(res)) { /* Don't accept malformed charname value */
2763         const U8* first_bad_char_loc;
2764         STRLEN len;
2765         const char* const str = SvPV_const(res, len);
2766         if (UNLIKELY(! is_utf8_string_loc((U8 *) str, len,
2767                                           &first_bad_char_loc)))
2768         {
2769             _force_out_malformed_utf8_message(first_bad_char_loc,
2770                                               (U8 *) PL_parser->bufend,
2771                                               0,
2772                                               0 /* 0 means don't die */ );
2773             /* diag_listed_as: Malformed UTF-8 returned by \N{%s}
2774                                immediately after '%s' */
2775             *error_msg = Perl_form(aTHX_
2776                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2777                  (int) (e - backslash_ptr + 1), backslash_ptr,
2778                  (int) ((char *) first_bad_char_loc - str), str);
2779             return NULL;
2780         }
2781     }
2782
2783     return res;
2784
2785   bad_charname: {
2786
2787         /* The final %.*s makes sure that should the trailing NUL be missing
2788          * that this print won't run off the end of the string */
2789         /* diag_listed_as: Invalid character in \N{...}; marked by <-- HERE
2790                            in \N{%s} */
2791         *error_msg = Perl_form(aTHX_
2792             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2793             (int)(s - backslash_ptr + 1), backslash_ptr,
2794             (int)(e - s + 1), s + 1);
2795         return NULL;
2796     }
2797
2798   multi_spaces:
2799         /* diag_listed_as: charnames alias definitions may not contain a
2800                            sequence of multiple spaces; marked by <-- HERE
2801                            in %s */
2802         *error_msg = Perl_form(aTHX_
2803             "charnames alias definitions may not contain a sequence of "
2804             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2805             (int)(s - backslash_ptr + 1), backslash_ptr,
2806             (int)(e - s + 1), s + 1);
2807         return NULL;
2808 }
2809
2810 /*
2811   scan_const
2812
2813   Extracts the next constant part of a pattern, double-quoted string,
2814   or transliteration.  This is terrifying code.
2815
2816   For example, in parsing the double-quoted string "ab\x63$d", it would
2817   stop at the '$' and return an OP_CONST containing 'abc'.
2818
2819   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2820   processing a pattern (PL_lex_inpat is true), a transliteration
2821   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2822
2823   Returns a pointer to the character scanned up to. If this is
2824   advanced from the start pointer supplied (i.e. if anything was
2825   successfully parsed), will leave an OP_CONST for the substring scanned
2826   in pl_yylval. Caller must intuit reason for not parsing further
2827   by looking at the next characters herself.
2828
2829   In patterns:
2830     expand:
2831       \N{FOO}  => \N{U+hex_for_character_FOO}
2832       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2833
2834     pass through:
2835         all other \-char, including \N and \N{ apart from \N{ABC}
2836
2837     stops on:
2838         @ and $ where it appears to be a var, but not for $ as tail anchor
2839         \l \L \u \U \Q \E
2840         (?{  or  (??{
2841
2842   In transliterations:
2843     characters are VERY literal, except for - not at the start or end
2844     of the string, which indicates a range.  However some backslash sequences
2845     are recognized: \r, \n, and the like
2846                     \007 \o{}, \x{}, \N{}
2847     If all elements in the transliteration are below 256,
2848     scan_const expands the range to the full set of intermediate
2849     characters. If the range is in utf8, the hyphen is replaced with
2850     a certain range mark which will be handled by pmtrans() in op.c.
2851
2852   In double-quoted strings:
2853     backslashes:
2854       all those recognized in transliterations
2855       deprecated backrefs: \1 (in substitution replacements)
2856       case and quoting: \U \Q \E
2857     stops on @ and $
2858
2859   scan_const does *not* construct ops to handle interpolated strings.
2860   It stops processing as soon as it finds an embedded $ or @ variable
2861   and leaves it to the caller to work out what's going on.
2862
2863   embedded arrays (whether in pattern or not) could be:
2864       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2865
2866   $ in double-quoted strings must be the symbol of an embedded scalar.
2867
2868   $ in pattern could be $foo or could be tail anchor.  Assumption:
2869   it's a tail anchor if $ is the last thing in the string, or if it's
2870   followed by one of "()| \r\n\t"
2871
2872   \1 (backreferences) are turned into $1 in substitutions
2873
2874   The structure of the code is
2875       while (there's a character to process) {
2876           handle transliteration ranges
2877           skip regexp comments /(?#comment)/ and codes /(?{code})/
2878           skip #-initiated comments in //x patterns
2879           check for embedded arrays
2880           check for embedded scalars
2881           if (backslash) {
2882               deprecate \1 in substitution replacements
2883               handle string-changing backslashes \l \U \Q \E, etc.
2884               switch (what was escaped) {
2885                   handle \- in a transliteration (becomes a literal -)
2886                   if a pattern and not \N{, go treat as regular character
2887                   handle \132 (octal characters)
2888                   handle \x15 and \x{1234} (hex characters)
2889                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2890                   handle \cV (control characters)
2891                   handle printf-style backslashes (\f, \r, \n, etc)
2892               } (end switch)
2893               continue
2894           } (end if backslash)
2895           handle regular character
2896     } (end while character to read)
2897
2898 */
2899
2900 STATIC char *
2901 S_scan_const(pTHX_ char *start)
2902 {
2903     char *send = PL_bufend;             /* end of the constant */
2904     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
2905                                            on sizing. */
2906     char *s = start;                    /* start of the constant */
2907     char *d = SvPVX(sv);                /* destination for copies */
2908     bool dorange = FALSE;               /* are we in a translit range? */
2909     bool didrange = FALSE;              /* did we just finish a range? */
2910     bool in_charclass = FALSE;          /* within /[...]/ */
2911     bool s_is_utf8 = cBOOL(UTF);        /* Is the source string assumed to be
2912                                            UTF8?  But, this can show as true
2913                                            when the source isn't utf8, as for
2914                                            example when it is entirely composed
2915                                            of hex constants */
2916     bool d_is_utf8 = FALSE;             /* Output constant is UTF8 */
2917     STRLEN utf8_variant_count = 0;      /* When not in UTF-8, this counts the
2918                                            number of characters found so far
2919                                            that will expand (into 2 bytes)
2920                                            should we have to convert to
2921                                            UTF-8) */
2922     SV *res;                            /* result from charnames */
2923     STRLEN offset_to_max = 0;   /* The offset in the output to where the range
2924                                    high-end character is temporarily placed */
2925
2926     /* Does something require special handling in tr/// ?  This avoids extra
2927      * work in a less likely case.  As such, khw didn't feel it was worth
2928      * adding any branches to the more mainline code to handle this, which
2929      * means that this doesn't get set in some circumstances when things like
2930      * \x{100} get expanded out.  As a result there needs to be extra testing
2931      * done in the tr code */
2932     bool has_above_latin1 = FALSE;
2933
2934     /* Note on sizing:  The scanned constant is placed into sv, which is
2935      * initialized by newSV() assuming one byte of output for every byte of
2936      * input.  This routine expects newSV() to allocate an extra byte for a
2937      * trailing NUL, which this routine will append if it gets to the end of
2938      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2939      * CAPITAL LETTER A}), or more output than input if the constant ends up
2940      * recoded to utf8, but each time a construct is found that might increase
2941      * the needed size, SvGROW() is called.  Its size parameter each time is
2942      * based on the best guess estimate at the time, namely the length used so
2943      * far, plus the length the current construct will occupy, plus room for
2944      * the trailing NUL, plus one byte for every input byte still unscanned */
2945
2946     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2947                        before set */
2948 #ifdef EBCDIC
2949     int backslash_N = 0;            /* ? was the character from \N{} */
2950     int non_portable_endpoint = 0;  /* ? In a range is an endpoint
2951                                        platform-specific like \x65 */
2952 #endif
2953
2954     PERL_ARGS_ASSERT_SCAN_CONST;
2955
2956     assert(PL_lex_inwhat != OP_TRANSR);
2957
2958     /* Protect sv from errors and fatal warnings. */
2959     ENTER_with_name("scan_const");
2960     SAVEFREESV(sv);
2961
2962     /* A bunch of code in the loop below assumes that if s[n] exists and is not
2963      * NUL, then s[n+1] exists.  This assertion makes sure that assumption is
2964      * valid */
2965     assert(*send == '\0');
2966
2967     while (s < send
2968            || dorange   /* Handle tr/// range at right edge of input */
2969     ) {
2970
2971         /* get transliterations out of the way (they're most literal) */
2972         if (PL_lex_inwhat == OP_TRANS) {
2973
2974             /* But there isn't any special handling necessary unless there is a
2975              * range, so for most cases we just drop down and handle the value
2976              * as any other.  There are two exceptions.
2977              *
2978              * 1.  A hyphen indicates that we are actually going to have a
2979              *     range.  In this case, skip the '-', set a flag, then drop
2980              *     down to handle what should be the end range value.
2981              * 2.  After we've handled that value, the next time through, that
2982              *     flag is set and we fix up the range.
2983              *
2984              * Ranges entirely within Latin1 are expanded out entirely, in
2985              * order to make the transliteration a simple table look-up.
2986              * Ranges that extend above Latin1 have to be done differently, so
2987              * there is no advantage to expanding them here, so they are
2988              * stored here as Min, RANGE_INDICATOR, Max.  'RANGE_INDICATOR' is
2989              * a byte that can't occur in legal UTF-8, and hence can signify a
2990              * hyphen without any possible ambiguity.  On EBCDIC machines, if
2991              * the range is expressed as Unicode, the Latin1 portion is
2992              * expanded out even if the range extends above Latin1.  This is
2993              * because each code point in it has to be processed here
2994              * individually to get its native translation */
2995
2996             if (! dorange) {
2997
2998                 /* Here, we don't think we're in a range.  If the new character
2999                  * is not a hyphen; or if it is a hyphen, but it's too close to
3000                  * either edge to indicate a range, or if we haven't output any
3001                  * characters yet then it's a regular character. */
3002                 if (*s != '-' || s >= send - 1 || s == start || d == SvPVX(sv))
3003                 {
3004
3005                     /* A regular character.  Process like any other, but first
3006                      * clear any flags */
3007                     didrange = FALSE;
3008                     dorange = FALSE;
3009 #ifdef EBCDIC
3010                     non_portable_endpoint = 0;
3011                     backslash_N = 0;
3012 #endif
3013                     /* The tests here for being above Latin1 and similar ones
3014                      * in the following 'else' suffice to find all such
3015                      * occurences in the constant, except those added by a
3016                      * backslash escape sequence, like \x{100}.  Mostly, those
3017                      * set 'has_above_latin1' as appropriate */
3018                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3019                         has_above_latin1 = TRUE;
3020                     }
3021
3022                     /* Drops down to generic code to process current byte */
3023                 }
3024                 else {  /* Is a '-' in the context where it means a range */
3025                     if (didrange) { /* Something like y/A-C-Z// */
3026                         Perl_croak(aTHX_ "Ambiguous range in transliteration"
3027                                          " operator");
3028                     }
3029
3030                     dorange = TRUE;
3031
3032                     s++;    /* Skip past the hyphen */
3033
3034                     /* d now points to where the end-range character will be
3035                      * placed.  Drop down to get that character.  We'll finish
3036                      * processing the range the next time through the loop */
3037
3038                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3039                         has_above_latin1 = TRUE;
3040                     }
3041
3042                     /* Drops down to generic code to process current byte */
3043                 }
3044             }  /* End of not a range */
3045             else {
3046                 /* Here we have parsed a range.  Now must handle it.  At this
3047                  * point:
3048                  * 'sv' is a SV* that contains the output string we are
3049                  *      constructing.  The final two characters in that string
3050                  *      are the range start and range end, in order.
3051                  * 'd'  points to just beyond the range end in the 'sv' string,
3052                  *      where we would next place something
3053                  */
3054                 char * max_ptr;
3055                 char * min_ptr;
3056                 IV range_min;
3057                 IV range_max;   /* last character in range */
3058                 STRLEN grow;
3059                 Size_t offset_to_min = 0;
3060                 Size_t extras = 0;
3061 #ifdef EBCDIC
3062                 bool convert_unicode;
3063                 IV real_range_max = 0;
3064 #endif
3065                 /* Get the code point values of the range ends. */
3066                 max_ptr = (d_is_utf8) ? (char *) utf8_hop( (U8*) d, -1) : d - 1;
3067                 offset_to_max = max_ptr - SvPVX_const(sv);
3068                 if (d_is_utf8) {
3069                     /* We know the utf8 is valid, because we just constructed
3070                      * it ourselves in previous loop iterations */
3071                     min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
3072                     range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
3073                     range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
3074
3075                     /* This compensates for not all code setting
3076                      * 'has_above_latin1', so that we don't skip stuff that
3077                      * should be executed */
3078                     if (range_max > 255) {
3079                         has_above_latin1 = TRUE;
3080                     }
3081                 }
3082                 else {
3083                     min_ptr = max_ptr - 1;
3084                     range_min = * (U8*) min_ptr;
3085                     range_max = * (U8*) max_ptr;
3086                 }
3087
3088                 /* If the range is just a single code point, like tr/a-a/.../,
3089                  * that code point is already in the output, twice.  We can
3090                  * just back up over the second instance and avoid all the rest
3091                  * of the work.  But if it is a variant character, it's been
3092                  * counted twice, so decrement.  (This unlikely scenario is
3093                  * special cased, like the one for a range of 2 code points
3094                  * below, only because the main-line code below needs a range
3095                  * of 3 or more to work without special casing.  Might as well
3096                  * get it out of the way now.) */
3097                 if (UNLIKELY(range_max == range_min)) {
3098                     d = max_ptr;
3099                     if (! d_is_utf8 && ! UVCHR_IS_INVARIANT(range_max)) {
3100                         utf8_variant_count--;
3101                     }
3102                     goto range_done;
3103                 }
3104
3105 #ifdef EBCDIC
3106                 /* On EBCDIC platforms, we may have to deal with portable
3107                  * ranges.  These happen if at least one range endpoint is a
3108                  * Unicode value (\N{...}), or if the range is a subset of
3109                  * [A-Z] or [a-z], and both ends are literal characters,
3110                  * like 'A', and not like \x{C1} */
3111                 convert_unicode =
3112                                cBOOL(backslash_N)   /* \N{} forces Unicode,
3113                                                        hence portable range */
3114                     || (     ! non_portable_endpoint
3115                         && ((  isLOWER_A(range_min) && isLOWER_A(range_max))
3116                            || (isUPPER_A(range_min) && isUPPER_A(range_max))));
3117                 if (convert_unicode) {
3118
3119                     /* Special handling is needed for these portable ranges.
3120                      * They are defined to be in Unicode terms, which includes
3121                      * all the Unicode code points between the end points.
3122                      * Convert to Unicode to get the Unicode range.  Later we
3123                      * will convert each code point in the range back to
3124                      * native.  */
3125                     range_min = NATIVE_TO_UNI(range_min);
3126                     range_max = NATIVE_TO_UNI(range_max);
3127                 }
3128 #endif
3129
3130                 if (range_min > range_max) {
3131 #ifdef EBCDIC
3132                     if (convert_unicode) {
3133                         /* Need to convert back to native for meaningful
3134                          * messages for this platform */
3135                         range_min = UNI_TO_NATIVE(range_min);
3136                         range_max = UNI_TO_NATIVE(range_max);
3137                     }
3138 #endif
3139                     /* Use the characters themselves for the error message if
3140                      * ASCII printables; otherwise some visible representation
3141                      * of them */
3142                     if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3143                         Perl_croak(aTHX_
3144                          "Invalid range \"%c-%c\" in transliteration operator",
3145                          (char)range_min, (char)range_max);
3146                     }
3147 #ifdef EBCDIC
3148                     else if (convert_unicode) {
3149         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3150                         Perl_croak(aTHX_
3151                            "Invalid range \"\\N{U+%04" UVXf "}-\\N{U+%04"
3152                            UVXf "}\" in transliteration operator",
3153                            range_min, range_max);
3154                     }
3155 #endif
3156                     else {
3157         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3158                         Perl_croak(aTHX_
3159                            "Invalid range \"\\x{%04" UVXf "}-\\x{%04" UVXf "}\""
3160                            " in transliteration operator",
3161                            range_min, range_max);
3162                     }
3163                 }
3164
3165                 /* If the range is exactly two code points long, they are
3166                  * already both in the output */
3167                 if (UNLIKELY(range_min + 1 == range_max)) {
3168                     goto range_done;
3169                 }
3170
3171                 /* Here the range contains at least 3 code points */
3172
3173                 if (d_is_utf8) {
3174
3175                     /* If everything in the transliteration is below 256, we
3176                      * can avoid special handling later.  A translation table
3177                      * for each of those bytes is created by op.c.  So we
3178                      * expand out all ranges to their constituent code points.
3179                      * But if we've encountered something above 255, the
3180                      * expanding won't help, so skip doing that.  But if it's
3181                      * EBCDIC, we may have to look at each character below 256
3182                      * if we have to convert to/from Unicode values */
3183                     if (   has_above_latin1
3184 #ifdef EBCDIC
3185                         && (range_min > 255 || ! convert_unicode)
3186 #endif
3187                     ) {
3188                         const STRLEN off = d - SvPVX(sv);
3189                         const STRLEN extra = 1 + (send - s) + 1;
3190                         char *e;
3191
3192                         /* Move the high character one byte to the right; then
3193                          * insert between it and the range begin, an illegal
3194                          * byte which serves to indicate this is a range (using
3195                          * a '-' would be ambiguous). */
3196
3197                         if (off + extra > SvLEN(sv)) {
3198                             d = off + SvGROW(sv, off + extra);
3199                             max_ptr = d - off + offset_to_max;
3200                         }
3201
3202                         e = d++;
3203                         while (e-- > max_ptr) {
3204                             *(e + 1) = *e;
3205                         }
3206                         *(e + 1) = (char) RANGE_INDICATOR;
3207                         goto range_done;
3208                     }
3209
3210                     /* Here, we're going to expand out the range.  For EBCDIC
3211                      * the range can extend above 255 (not so in ASCII), so
3212                      * for EBCDIC, split it into the parts above and below
3213                      * 255/256 */
3214 #ifdef EBCDIC
3215                     if (range_max > 255) {
3216                         real_range_max = range_max;
3217                         range_max = 255;
3218                     }
3219 #endif
3220                 }
3221
3222                 /* Here we need to expand out the string to contain each
3223                  * character in the range.  Grow the output to handle this.
3224                  * For non-UTF8, we need a byte for each code point in the
3225                  * range, minus the three that we've already allocated for: the
3226                  * hyphen, the min, and the max.  For UTF-8, we need this
3227                  * plus an extra byte for each code point that occupies two
3228                  * bytes (is variant) when in UTF-8 (except we've already
3229                  * allocated for the end points, including if they are
3230                  * variants).  For ASCII platforms and Unicode ranges on EBCDIC
3231                  * platforms, it's easy to calculate a precise number.  To
3232                  * start, we count the variants in the range, which we need
3233                  * elsewhere in this function anyway.  (For the case where it
3234                  * isn't easy to calculate, 'extras' has been initialized to 0,
3235                  * and the calculation is done in a loop further down.) */
3236 #ifdef EBCDIC
3237                 if (convert_unicode)
3238 #endif
3239                 {
3240                     /* This is executed unconditionally on ASCII, and for
3241                      * Unicode ranges on EBCDIC.  Under these conditions, all
3242                      * code points above a certain value are variant; and none
3243                      * under that value are.  We just need to find out how much
3244                      * of the range is above that value.  We don't count the
3245                      * end points here, as they will already have been counted
3246                      * as they were parsed. */
3247                     if (range_min >= UTF_CONTINUATION_MARK) {
3248
3249                         /* The whole range is made up of variants */
3250                         extras = (range_max - 1) - (range_min + 1) + 1;
3251                     }
3252                     else if (range_max >= UTF_CONTINUATION_MARK) {
3253
3254                         /* Only the higher portion of the range is variants */
3255                         extras = (range_max - 1) - UTF_CONTINUATION_MARK + 1;
3256                     }
3257
3258                     utf8_variant_count += extras;
3259                 }
3260
3261                 /* The base growth is the number of code points in the range,
3262                  * not including the endpoints, which have already been sized
3263                  * for (and output).  We don't subtract for the hyphen, as it
3264                  * has been parsed but not output, and the SvGROW below is
3265                  * based only on what's been output plus what's left to parse.
3266                  * */
3267                 grow = (range_max - 1) - (range_min + 1) + 1;
3268
3269                 if (d_is_utf8) {
3270 #ifdef EBCDIC
3271                     /* In some cases in EBCDIC, we haven't yet calculated a
3272                      * precise amount needed for the UTF-8 variants.  Just
3273                      * assume the worst case, that everything will expand by a
3274                      * byte */
3275                     if (! convert_unicode) {
3276                         grow *= 2;
3277                     }
3278                     else
3279 #endif
3280                     {
3281                         /* Otherwise we know exactly how many variants there
3282                          * are in the range. */
3283                         grow += extras;
3284                     }
3285                 }
3286
3287                 /* Grow, but position the output to overwrite the range min end
3288                  * point, because in some cases we overwrite that */
3289                 SvCUR_set(sv, d - SvPVX_const(sv));
3290                 offset_to_min = min_ptr - SvPVX_const(sv);
3291
3292                 /* See Note on sizing above. */
3293                 d = offset_to_min + SvGROW(sv, SvCUR(sv)
3294                                              + (send - s)
3295                                              + grow
3296                                              + 1 /* Trailing NUL */ );
3297
3298                 /* Now, we can expand out the range. */
3299 #ifdef EBCDIC
3300                 if (convert_unicode) {
3301                     SSize_t i;
3302
3303                     /* Recall that the min and max are now in Unicode terms, so
3304                      * we have to convert each character to its native
3305                      * equivalent */
3306                     if (d_is_utf8) {
3307                         for (i = range_min; i <= range_max; i++) {
3308                             append_utf8_from_native_byte(
3309                                                     LATIN1_TO_NATIVE((U8) i),
3310                                                     (U8 **) &d);
3311                         }
3312                     }
3313                     else {
3314                         for (i = range_min; i <= range_max; i++) {
3315                             *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3316                         }
3317                     }
3318                 }
3319                 else
3320 #endif
3321                 /* Always gets run for ASCII, and sometimes for EBCDIC. */
3322                 {
3323                     /* Here, no conversions are necessary, which means that the
3324                      * first character in the range is already in 'd' and
3325                      * valid, so we can skip overwriting it */
3326                     if (d_is_utf8) {
3327                         SSize_t i;
3328                         d += UTF8SKIP(d);
3329                         for (i = range_min + 1; i <= range_max; i++) {
3330                             append_utf8_from_native_byte((U8) i, (U8 **) &d);
3331                         }
3332                     }
3333                     else {
3334                         SSize_t i;
3335                         d++;
3336                         assert(range_min + 1 <= range_max);
3337                         for (i = range_min + 1; i < range_max; i++) {
3338 #ifdef EBCDIC
3339                             /* In this case on EBCDIC, we haven't calculated
3340                              * the variants.  Do it here, as we go along */
3341                             if (! UVCHR_IS_INVARIANT(i)) {
3342                                 utf8_variant_count++;
3343                             }
3344 #endif
3345                             *d++ = (char)i;
3346                         }
3347
3348                         /* The range_max is done outside the loop so as to
3349                          * avoid having to special case not incrementing
3350                          * 'utf8_variant_count' on EBCDIC (it's already been
3351                          * counted when originally parsed) */
3352                         *d++ = (char) range_max;
3353                     }
3354                 }
3355
3356 #ifdef EBCDIC
3357                 /* If the original range extended above 255, add in that
3358                  * portion. */
3359                 if (real_range_max) {
3360                     *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3361                     *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3362                     if (real_range_max > 0x100) {
3363                         if (real_range_max > 0x101) {
3364                             *d++ = (char) RANGE_INDICATOR;
3365                         }
3366                         d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3367                     }
3368                 }
3369 #endif
3370
3371               range_done:
3372                 /* mark the range as done, and continue */
3373                 didrange = TRUE;
3374                 dorange = FALSE;
3375 #ifdef EBCDIC
3376                 non_portable_endpoint = 0;
3377                 backslash_N = 0;
3378 #endif
3379                 continue;
3380             } /* End of is a range */
3381         } /* End of transliteration.  Joins main code after these else's */
3382         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3383             char *s1 = s-1;
3384             int esc = 0;
3385             while (s1 >= start && *s1-- == '\\')
3386                 esc = !esc;
3387             if (!esc)
3388                 in_charclass = TRUE;
3389         }
3390         else if (*s == ']' && PL_lex_inpat && in_charclass) {
3391             char *s1 = s-1;
3392             int esc = 0;
3393             while (s1 >= start && *s1-- == '\\')
3394                 esc = !esc;
3395             if (!esc)
3396                 in_charclass = FALSE;
3397         }
3398             /* skip for regexp comments /(?#comment)/, except for the last
3399              * char, which will be done separately.  Stop on (?{..}) and
3400              * friends */
3401         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3402             if (s[2] == '#') {
3403                 if (s_is_utf8) {
3404                     PERL_UINT_FAST8_T  len = UTF8SKIP(s);
3405
3406                     while (s + len < send && *s != ')') {
3407                         Copy(s, d, len, U8);
3408                         d += len;
3409                         s += len;
3410                         len = UTF8_SAFE_SKIP(s, send);
3411                     }
3412                 }
3413                 else while (s+1 < send && *s != ')') {
3414                     *d++ = *s++;
3415                 }
3416             }
3417             else if (!PL_lex_casemods
3418                      && (    s[2] == '{' /* This should match regcomp.c */
3419                          || (s[2] == '?' && s[3] == '{')))
3420             {
3421                 break;
3422             }
3423         }
3424             /* likewise skip #-initiated comments in //x patterns */
3425         else if (*s == '#'
3426                  && PL_lex_inpat
3427                  && !in_charclass
3428                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3429         {
3430             while (s < send && *s != '\n')
3431                 *d++ = *s++;
3432         }
3433             /* no further processing of single-quoted regex */
3434         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3435             goto default_action;
3436
3437             /* check for embedded arrays
3438              * (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3439              */
3440         else if (*s == '@' && s[1]) {
3441             if (UTF
3442                ? isIDFIRST_utf8_safe(s+1, send)
3443                : isWORDCHAR_A(s[1]))
3444             {
3445                 break;
3446             }
3447             if (memCHRs(":'{$", s[1]))
3448                 break;
3449             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3450                 break; /* in regexp, neither @+ nor @- are interpolated */
3451         }
3452             /* check for embedded scalars.  only stop if we're sure it's a
3453              * variable.  */
3454         else if (*s == '$') {
3455             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3456                 break;
3457             if (s + 1 < send && !memCHRs("()| \r\n\t", s[1])) {
3458                 if (s[1] == '\\') {
3459                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3460                                    "Possible unintended interpolation of $\\ in regex");
3461                 }
3462                 break;          /* in regexp, $ might be tail anchor */
3463             }
3464         }
3465
3466         /* End of else if chain - OP_TRANS rejoin rest */
3467
3468         if (UNLIKELY(s >= send)) {
3469             assert(s == send);
3470             break;
3471         }
3472
3473         /* backslashes */
3474         if (*s == '\\' && s+1 < send) {
3475             char* e;    /* Can be used for ending '}', etc. */
3476
3477             s++;
3478
3479             /* warn on \1 - \9 in substitution replacements, but note that \11
3480              * is an octal; and \19 is \1 followed by '9' */
3481             if (PL_lex_inwhat == OP_SUBST
3482                 && !PL_lex_inpat
3483                 && isDIGIT(*s)
3484                 && *s != '0'
3485                 && !isDIGIT(s[1]))
3486             {
3487                 /* diag_listed_as: \%d better written as $%d */
3488                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3489                 *--s = '$';
3490                 break;
3491             }
3492
3493             /* string-change backslash escapes */
3494             if (PL_lex_inwhat != OP_TRANS && *s && memCHRs("lLuUEQF", *s)) {
3495                 --s;
3496                 break;
3497             }
3498             /* In a pattern, process \N, but skip any other backslash escapes.
3499              * This is because we don't want to translate an escape sequence
3500              * into a meta symbol and have the regex compiler use the meta
3501              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3502              * in spite of this, we do have to process \N here while the proper
3503              * charnames handler is in scope.  See bugs #56444 and #62056.
3504              *
3505              * There is a complication because \N in a pattern may also stand
3506              * for 'match a non-nl', and not mean a charname, in which case its
3507              * processing should be deferred to the regex compiler.  To be a
3508              * charname it must be followed immediately by a '{', and not look
3509              * like \N followed by a curly quantifier, i.e., not something like
3510              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3511              * quantifier */
3512             else if (PL_lex_inpat
3513                     && (*s != 'N'
3514                         || s[1] != '{'
3515                         || regcurly(s + 1)))
3516             {
3517                 *d++ = '\\';
3518                 goto default_action;
3519             }
3520
3521             switch (*s) {
3522             default:
3523                 {
3524                     if ((isALPHANUMERIC(*s)))
3525                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3526                                        "Unrecognized escape \\%c passed through",
3527                                        *s);
3528                     /* default action is to copy the quoted character */
3529                     goto default_action;
3530                 }
3531
3532             /* eg. \132 indicates the octal constant 0132 */
3533             case '0': case '1': case '2': case '3':
3534             case '4': case '5': case '6': case '7':
3535                 {
3536                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
3537                               | PERL_SCAN_NOTIFY_ILLDIGIT;
3538                     STRLEN len = 3;
3539                     uv = grok_oct(s, &len, &flags, NULL);
3540                     s += len;
3541                     if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
3542                         && s < send
3543                         && isDIGIT(*s)  /* like \08, \178 */
3544                         && ckWARN(WARN_MISC))
3545                     {
3546                         Perl_warner(aTHX_ packWARN(WARN_MISC), "%s",
3547                             form_alien_digit_msg(8, len, s, send, UTF, FALSE));
3548                     }
3549                 }
3550                 goto NUM_ESCAPE_INSERT;
3551
3552             /* eg. \o{24} indicates the octal constant \024 */
3553             case 'o':
3554                 {
3555                     const char* error;
3556
3557                     if (! grok_bslash_o(&s, send,
3558                                                &uv, &error,
3559                                                NULL,
3560                                                FALSE, /* Not strict */
3561                                                FALSE, /* No illegal cp's */
3562                                                UTF))
3563                     {
3564                         yyerror(error);
3565                         uv = 0; /* drop through to ensure range ends are set */
3566                     }
3567                     goto NUM_ESCAPE_INSERT;
3568                 }
3569
3570             /* eg. \x24 indicates the hex constant 0x24 */
3571             case 'x':
3572                 {
3573                     const char* error;
3574
3575                     if (! grok_bslash_x(&s, send,
3576                                                &uv, &error,
3577                                                NULL,
3578                                                FALSE, /* Not strict */
3579                                                FALSE, /* No illegal cp's */
3580                                                UTF))
3581                     {
3582                         yyerror(error);
3583                         uv = 0; /* drop through to ensure range ends are set */
3584                     }
3585                 }
3586
3587               NUM_ESCAPE_INSERT:
3588                 /* Insert oct or hex escaped character. */
3589
3590                 /* Here uv is the ordinal of the next character being added */
3591                 if (UVCHR_IS_INVARIANT(uv)) {
3592                     *d++ = (char) uv;
3593                 }
3594                 else {
3595                     if (!d_is_utf8 && uv > 255) {
3596
3597                         /* Here, 'uv' won't fit unless we convert to UTF-8.
3598                          * If we've only seen invariants so far, all we have to
3599                          * do is turn on the flag */
3600                         if (utf8_variant_count == 0) {
3601                             SvUTF8_on(sv);
3602                         }
3603                         else {
3604                             SvCUR_set(sv, d - SvPVX_const(sv));
3605                             SvPOK_on(sv);
3606                             *d = '\0';
3607
3608                             sv_utf8_upgrade_flags_grow(
3609                                            sv,
3610                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3611
3612                                            /* Since we're having to grow here,
3613                                             * make sure we have enough room for
3614                                             * this escape and a NUL, so the
3615                                             * code immediately below won't have
3616                                             * to actually grow again */
3617                                           UVCHR_SKIP(uv)
3618                                         + (STRLEN)(send - s) + 1);
3619                             d = SvPVX(sv) + SvCUR(sv);
3620                         }
3621
3622                         has_above_latin1 = TRUE;
3623                         d_is_utf8 = TRUE;
3624                     }
3625
3626                     if (! d_is_utf8) {
3627                         *d++ = (char)uv;
3628                         utf8_variant_count++;
3629                     }
3630                     else {
3631                        /* Usually, there will already be enough room in 'sv'
3632                         * since such escapes are likely longer than any UTF-8
3633                         * sequence they can end up as.  This isn't the case on
3634                         * EBCDIC where \x{40000000} contains 12 bytes, and the
3635                         * UTF-8 for it contains 14.  And, we have to allow for
3636                         * a trailing NUL.  It probably can't happen on ASCII
3637                         * platforms, but be safe.  See Note on sizing above. */
3638                         const STRLEN needed = d - SvPVX(sv)
3639                                             + UVCHR_SKIP(uv)
3640                                             + (send - s)
3641                                             + 1;
3642                         if (UNLIKELY(needed > SvLEN(sv))) {
3643                             SvCUR_set(sv, d - SvPVX_const(sv));
3644                             d = SvCUR(sv) + SvGROW(sv, needed);
3645                         }
3646
3647                         d = (char*) uvchr_to_utf8_flags((U8*)d, uv,
3648                                                    (ckWARN(WARN_PORTABLE))
3649                                                    ? UNICODE_WARN_PERL_EXTENDED
3650                                                    : 0);
3651                     }
3652                 }
3653 #ifdef EBCDIC
3654                 non_portable_endpoint++;
3655 #endif
3656                 continue;
3657
3658             case 'N':
3659                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3660                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3661                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3662                  * GRAVE} (except y/// can't handle the latter, croaking).  For
3663                  * convenience all three forms are referred to as "named
3664                  * characters" below.
3665                  *
3666                  * For patterns, \N also can mean to match a non-newline.  Code
3667                  * before this 'switch' statement should already have handled
3668                  * this situation, and hence this code only has to deal with
3669                  * the named character cases.
3670                  *
3671                  * For non-patterns, the named characters are converted to
3672                  * their string equivalents.  In patterns, named characters are
3673                  * not converted to their ultimate forms for the same reasons
3674                  * that other escapes aren't (mainly that the ultimate
3675                  * character could be considered a meta-symbol by the regex
3676                  * compiler).  Instead, they are converted to the \N{U+...}
3677                  * form to get the value from the charnames that is in effect
3678                  * right now, while preserving the fact that it was a named
3679                  * character, so that the regex compiler knows this.
3680                  *
3681                  * The structure of this section of code (besides checking for
3682                  * errors and upgrading to utf8) is:
3683                  *    If the named character is of the form \N{U+...}, pass it
3684                  *      through if a pattern; otherwise convert the code point
3685                  *      to utf8
3686                  *    Otherwise must be some \N{NAME}: convert to
3687                  *      \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3688                  *
3689                  * Transliteration is an exception.  The conversion to utf8 is
3690                  * only done if the code point requires it to be representable.
3691                  *
3692                  * Here, 's' points to the 'N'; the test below is guaranteed to
3693                  * succeed if we are being called on a pattern, as we already
3694                  * know from a test above that the next character is a '{'.  A
3695                  * non-pattern \N must mean 'named character', which requires
3696                  * braces */
3697                 s++;
3698                 if (*s != '{') {
3699                     yyerror("Missing braces on \\N{}");
3700                     *d++ = '\0';
3701                     continue;
3702                 }
3703                 s++;
3704
3705                 /* If there is no matching '}', it is an error. */
3706                 if (! (e = (char *) memchr(s, '}', send - s))) {
3707                     if (! PL_lex_inpat) {
3708                         yyerror("Missing right brace on \\N{}");
3709                     } else {
3710                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3711                     }
3712                     yyquit(); /* Have exhausted the input. */
3713                 }
3714
3715                 /* Here it looks like a named character */
3716
3717                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3718                     s += 2;         /* Skip to next char after the 'U+' */
3719                     if (PL_lex_inpat) {
3720
3721                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3722                         /* Check the syntax.  */
3723                         const char *orig_s;
3724                         orig_s = s - 5;
3725                         if (!isXDIGIT(*s)) {
3726                           bad_NU:
3727                             yyerror(
3728                                 "Invalid hexadecimal number in \\N{U+...}"
3729                             );
3730                             s = e + 1;
3731                             *d++ = '\0';
3732                             continue;
3733                         }
3734                         while (++s < e) {
3735                             if (isXDIGIT(*s))
3736                                 continue;
3737                             else if ((*s == '.' || *s == '_')
3738                                   && isXDIGIT(s[1]))
3739                                 continue;
3740                             goto bad_NU;
3741                         }
3742
3743                         /* Pass everything through unchanged.
3744                          * +1 is for the '}' */
3745                         Copy(orig_s, d, e - orig_s + 1, char);
3746                         d += e - orig_s + 1;
3747                     }
3748                     else {  /* Not a pattern: convert the hex to string */
3749                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3750                                   | PERL_SCAN_SILENT_ILLDIGIT
3751                                   | PERL_SCAN_SILENT_OVERFLOW
3752                                   | PERL_SCAN_DISALLOW_PREFIX;
3753                         STRLEN len = e - s;
3754
3755                         uv = grok_hex(s, &len, &flags, NULL);
3756                         if (len == 0 || (len != (STRLEN)(e - s)))
3757                             goto bad_NU;
3758
3759                         if (    uv > MAX_LEGAL_CP
3760                             || (flags & PERL_SCAN_GREATER_THAN_UV_MAX))
3761                         {
3762                             yyerror(form_cp_too_large_msg(16, s, len, 0));
3763                             uv = 0; /* drop through to ensure range ends are
3764                                        set */
3765                         }
3766
3767                          /* For non-tr///, if the destination is not in utf8,
3768                           * unconditionally recode it to be so.  This is
3769                           * because \N{} implies Unicode semantics, and scalars
3770                           * have to be in utf8 to guarantee those semantics.
3771                           * tr/// doesn't care about Unicode rules, so no need
3772                           * there to upgrade to UTF-8 for small enough code
3773                           * points */
3774                         if (! d_is_utf8 && (   uv > 0xFF
3775                                            || PL_lex_inwhat != OP_TRANS))
3776                         {
3777                             /* See Note on sizing above.  */
3778                             const STRLEN extra = OFFUNISKIP(uv) + (send - e) + 1;
3779
3780                             SvCUR_set(sv, d - SvPVX_const(sv));
3781                             SvPOK_on(sv);
3782                             *d = '\0';
3783
3784                             if (utf8_variant_count == 0) {
3785                                 SvUTF8_on(sv);
3786                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3787                             }
3788                             else {
3789                                 sv_utf8_upgrade_flags_grow(
3790                                                sv,
3791                                                SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3792                                                extra);
3793                                 d = SvPVX(sv) + SvCUR(sv);
3794                             }
3795
3796                             d_is_utf8 = TRUE;
3797                             has_above_latin1 = TRUE;
3798                         }
3799
3800                         /* Add the (Unicode) code point to the output. */
3801                         if (! d_is_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3802                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3803                         }
3804                         else {
3805                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv,
3806                                                    (ckWARN(WARN_PORTABLE))
3807                                                    ? UNICODE_WARN_PERL_EXTENDED
3808                                                    : 0);
3809                         }
3810                     }
3811                 }
3812                 else /* Here is \N{NAME} but not \N{U+...}. */
3813                      if (! (res = get_and_check_backslash_N_name_wrapper(s, e)))
3814                 {   /* Failed.  We should die eventually, but for now use a NUL
3815                        to keep parsing */
3816                     *d++ = '\0';
3817                 }
3818                 else {  /* Successfully evaluated the name */
3819                     STRLEN len;
3820                     const char *str = SvPV_const(res, len);
3821                     if (PL_lex_inpat) {
3822
3823                         if (! len) { /* The name resolved to an empty string */
3824                             const char empty_N[] = "\\N{_}";
3825                             Copy(empty_N, d, sizeof(empty_N) - 1, char);
3826                             d += sizeof(empty_N) - 1;
3827                         }
3828                         else {
3829                             /* In order to not lose information for the regex
3830                             * compiler, pass the result in the specially made
3831                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3832                             * the code points in hex of each character
3833                             * returned by charnames */
3834
3835                             const char *str_end = str + len;
3836                             const STRLEN off = d - SvPVX_const(sv);
3837
3838                             if (! SvUTF8(res)) {
3839                                 /* For the non-UTF-8 case, we can determine the
3840                                  * exact length needed without having to parse
3841                                  * through the string.  Each character takes up
3842                                  * 2 hex digits plus either a trailing dot or
3843                                  * the "}" */
3844                                 const char initial_text[] = "\\N{U+";
3845                                 const STRLEN initial_len = sizeof(initial_text)
3846                                                            - 1;
3847                                 d = off + SvGROW(sv, off
3848                                                     + 3 * len
3849
3850                                                     /* +1 for trailing NUL */
3851                                                     + initial_len + 1
3852
3853                                                     + (STRLEN)(send - e));
3854                                 Copy(initial_text, d, initial_len, char);
3855                                 d += initial_len;
3856                                 while (str < str_end) {
3857                                     char hex_string[4];
3858                                     int len =
3859                                         my_snprintf(hex_string,
3860                                                   sizeof(hex_string),
3861                                                   "%02X.",
3862
3863                                                   /* The regex compiler is
3864                                                    * expecting Unicode, not
3865                                                    * native */
3866                                                   NATIVE_TO_LATIN1(*str));
3867                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3868                                                            sizeof(hex_string));
3869                                     Copy(hex_string, d, 3, char);
3870                                     d += 3;
3871                                     str++;
3872                                 }
3873                                 d--;    /* Below, we will overwrite the final
3874                                            dot with a right brace */
3875                             }
3876                             else {
3877                                 STRLEN char_length; /* cur char's byte length */
3878
3879                                 /* and the number of bytes after this is
3880                                  * translated into hex digits */
3881                                 STRLEN output_length;
3882
3883                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3884                                  * for max('U+', '.'); and 1 for NUL */
3885                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3886
3887                                 /* Get the first character of the result. */
3888                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3889                                                         len,
3890                                                         &char_length,
3891                                                         UTF8_ALLOW_ANYUV);
3892                                 /* Convert first code point to Unicode hex,
3893                                  * including the boiler plate before it. */
3894                                 output_length =
3895                                     my_snprintf(hex_string, sizeof(hex_string),
3896                                              "\\N{U+%X",
3897                                              (unsigned int) NATIVE_TO_UNI(uv));
3898
3899                                 /* Make sure there is enough space to hold it */
3900                                 d = off + SvGROW(sv, off
3901                                                     + output_length
3902                                                     + (STRLEN)(send - e)
3903                                                     + 2);       /* '}' + NUL */
3904                                 /* And output it */
3905                                 Copy(hex_string, d, output_length, char);
3906                                 d += output_length;
3907
3908                                 /* For each subsequent character, append dot and
3909                                 * its Unicode code point in hex */
3910                                 while ((str += char_length) < str_end) {
3911                                     const STRLEN off = d - SvPVX_const(sv);
3912                                     U32 uv = utf8n_to_uvchr((U8 *) str,
3913                                                             str_end - str,
3914                                                             &char_length,
3915                                                             UTF8_ALLOW_ANYUV);
3916                                     output_length =
3917                                         my_snprintf(hex_string,
3918                                              sizeof(hex_string),
3919                                              ".%X",
3920                                              (unsigned int) NATIVE_TO_UNI(uv));
3921
3922                                     d = off + SvGROW(sv, off
3923                                                         + output_length
3924                                                         + (STRLEN)(send - e)
3925                                                         + 2);   /* '}' +  NUL */
3926                                     Copy(hex_string, d, output_length, char);
3927                                     d += output_length;
3928                                 }
3929                             }
3930
3931                             *d++ = '}'; /* Done.  Add the trailing brace */
3932                         }
3933                     }
3934                     else { /* Here, not in a pattern.  Convert the name to a
3935                             * string. */
3936
3937                         if (PL_lex_inwhat == OP_TRANS) {
3938                             str = SvPV_const(res, len);
3939                             if (len > ((SvUTF8(res))
3940                                        ? UTF8SKIP(str)
3941                                        : 1U))
3942                             {
3943                                 yyerror(Perl_form(aTHX_
3944                                     "%.*s must not be a named sequence"
3945                                     " in transliteration operator",
3946                                         /*  +1 to include the "}" */
3947                                     (int) (e + 1 - start), start));
3948                                 *d++ = '\0';
3949                                 goto end_backslash_N;
3950                             }
3951
3952                             if (SvUTF8(res) && UTF8_IS_ABOVE_LATIN1(*str)) {
3953                                 has_above_latin1 = TRUE;
3954                             }
3955
3956                         }
3957                         else if (! SvUTF8(res)) {
3958                             /* Make sure \N{} return is UTF-8.  This is because
3959                              * \N{} implies Unicode semantics, and scalars have
3960                              * to be in utf8 to guarantee those semantics; but
3961                              * not needed in tr/// */
3962                             sv_utf8_upgrade_flags(res, 0);
3963                             str = SvPV_const(res, len);
3964                         }
3965
3966                          /* Upgrade destination to be utf8 if this new
3967                           * component is */
3968                         if (! d_is_utf8 && SvUTF8(res)) {
3969                             /* See Note on sizing above.  */
3970                             const STRLEN extra = len + (send - s) + 1;
3971
3972                             SvCUR_set(sv, d - SvPVX_const(sv));
3973                             SvPOK_on(sv);
3974                             *d = '\0';
3975
3976                             if (utf8_variant_count == 0) {
3977                                 SvUTF8_on(sv);
3978                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3979                             }
3980                             else {
3981                                 sv_utf8_upgrade_flags_grow(sv,
3982                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3983                                                 extra);
3984                                 d = SvPVX(sv) + SvCUR(sv);
3985                             }
3986                             d_is_utf8 = TRUE;
3987                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3988
3989                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3990                              * set correctly here). */
3991                             const STRLEN extra = len + (send - e) + 1;
3992                             const STRLEN off = d - SvPVX_const(sv);
3993                             d = off + SvGROW(sv, off + extra);
3994                         }
3995                         Copy(str, d, len, char);
3996                         d += len;
3997                     }
3998
3999                     SvREFCNT_dec(res);
4000
4001                 } /* End \N{NAME} */
4002
4003               end_backslash_N:
4004 #ifdef EBCDIC
4005                 backslash_N++; /* \N{} is defined to be Unicode */
4006 #endif
4007                 s = e + 1;  /* Point to just after the '}' */
4008                 continue;
4009
4010             /* \c is a control character */
4011             case 'c':
4012                 s++;
4013                 if (s < send) {
4014                     const char * message;
4015
4016                     if (! grok_bslash_c(*s, (U8 *) d, &message, NULL)) {
4017                         yyerror(message);
4018                         yyquit();   /* Have always immediately croaked on
4019                                        errors in this */
4020                     }
4021                     d++;
4022                 }
4023                 else {
4024                     yyerror("Missing control char name in \\c");
4025                     yyquit();   /* Are at end of input, no sense continuing */
4026                 }
4027 #ifdef EBCDIC
4028                 non_portable_endpoint++;
4029 #endif
4030                 break;
4031
4032             /* printf-style backslashes, formfeeds, newlines, etc */
4033             case 'b':
4034                 *d++ = '\b';
4035                 break;
4036             case 'n':
4037                 *d++ = '\n';
4038                 break;
4039             case 'r':
4040                 *d++ = '\r';
4041                 break;
4042             case 'f':
4043                 *d++ = '\f';
4044                 break;
4045             case 't':
4046                 *d++ = '\t';
4047                 break;
4048             case 'e':
4049                 *d++ = ESC_NATIVE;
4050                 break;
4051             case 'a':
4052                 *d++ = '\a';
4053                 break;
4054             } /* end switch */
4055
4056             s++;
4057             continue;
4058         } /* end if (backslash) */
4059
4060     default_action:
4061         /* Just copy the input to the output, though we may have to convert
4062          * to/from UTF-8.
4063          *
4064          * If the input has the same representation in UTF-8 as not, it will be
4065          * a single byte, and we don't care about UTF8ness; just copy the byte */
4066         if (NATIVE_BYTE_IS_INVARIANT((U8)(*s))) {
4067             *d++ = *s++;
4068         }
4069         else if (! s_is_utf8 && ! d_is_utf8) {
4070             /* If neither source nor output is UTF-8, is also a single byte,
4071              * just copy it; but this byte counts should we later have to
4072              * convert to UTF-8 */
4073             *d++ = *s++;
4074             utf8_variant_count++;
4075         }
4076         else if (s_is_utf8 && d_is_utf8) {   /* Both UTF-8, can just copy */
4077             const STRLEN len = UTF8SKIP(s);
4078
4079             /* We expect the source to have already been checked for
4080              * malformedness */
4081             assert(isUTF8_CHAR((U8 *) s, (U8 *) send));
4082
4083             Copy(s, d, len, U8);
4084             d += len;
4085             s += len;
4086         }
4087         else if (s_is_utf8) { /* UTF8ness matters: convert output to utf8 */
4088             STRLEN need = send - s + 1; /* See Note on sizing above. */
4089
4090             SvCUR_set(sv, d - SvPVX_const(sv));
4091             SvPOK_on(sv);
4092             *d = '\0';
4093
4094             if (utf8_variant_count == 0) {
4095                 SvUTF8_on(sv);
4096                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + need);
4097             }
4098             else {
4099                 sv_utf8_upgrade_flags_grow(sv,
4100                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4101                                            need);
4102                 d = SvPVX(sv) + SvCUR(sv);
4103             }
4104             d_is_utf8 = TRUE;
4105             goto default_action; /* Redo, having upgraded so both are UTF-8 */
4106         }
4107         else {  /* UTF8ness matters: convert this non-UTF8 source char to
4108                    UTF-8 for output.  It will occupy 2 bytes, but don't include
4109                    the input byte since we haven't incremented 's' yet. See
4110                    Note on sizing above. */
4111             const STRLEN off = d - SvPVX(sv);
4112             const STRLEN extra = 2 + (send - s - 1) + 1;
4113             if (off + extra > SvLEN(sv)) {
4114                 d = off + SvGROW(sv, off + extra);
4115             }
4116             *d++ = UTF8_EIGHT_BIT_HI(*s);
4117             *d++ = UTF8_EIGHT_BIT_LO(*s);
4118             s++;
4119         }
4120     } /* while loop to process each character */
4121
4122     {
4123         const STRLEN off = d - SvPVX(sv);
4124
4125         /* See if room for the terminating NUL */
4126         if (UNLIKELY(off >= SvLEN(sv))) {
4127
4128 #ifndef DEBUGGING
4129
4130             if (off > SvLEN(sv))
4131 #endif
4132                 Perl_croak(aTHX_ "panic: constant overflowed allocated space,"
4133                         " %" UVuf " >= %" UVuf, (UV)off, (UV)SvLEN(sv));
4134
4135             /* Whew!  Here we don't have room for the terminating NUL, but
4136              * everything else so far has fit.  It's not too late to grow
4137              * to fit the NUL and continue on.  But it is a bug, as the code
4138              * above was supposed to have made room for this, so under
4139              * DEBUGGING builds, we panic anyway.  */
4140             d = off + SvGROW(sv, off + 1);
4141         }
4142     }
4143
4144     /* terminate the string and set up the sv */
4145     *d = '\0';
4146     SvCUR_set(sv, d - SvPVX_const(sv));
4147
4148     SvPOK_on(sv);
4149     if (d_is_utf8) {
4150         SvUTF8_on(sv);
4151     }
4152
4153     /* shrink the sv if we allocated more than we used */
4154     if (SvCUR(sv) + 5 < SvLEN(sv)) {
4155         SvPV_shrink_to_cur(sv);
4156     }
4157
4158     /* return the substring (via pl_yylval) only if we parsed anything */
4159     if (s > start) {
4160         char *s2 = start;
4161         for (; s2 < s; s2++) {
4162             if (*s2 == '\n')
4163                 COPLINE_INC_WITH_HERELINES;
4164         }
4165         SvREFCNT_inc_simple_void_NN(sv);
4166         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
4167             && ! PL_parser->lex_re_reparsing)
4168         {
4169             const char *const key = PL_lex_inpat ? "qr" : "q";
4170             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
4171             const char *type;
4172             STRLEN typelen;
4173
4174             if (PL_lex_inwhat == OP_TRANS) {
4175                 type = "tr";
4176                 typelen = 2;
4177             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
4178                 type = "s";
4179                 typelen = 1;
4180             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
4181                 type = "q";
4182                 typelen = 1;
4183             } else  {
4184                 type = "qq";
4185                 typelen = 2;
4186             }
4187
4188             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
4189                                 type, typelen, NULL);
4190         }
4191         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
4192     }
4193     LEAVE_with_name("scan_const");
4194     return s;
4195 }
4196
4197 /* S_intuit_more
4198  * Returns TRUE if there's more to the expression (e.g., a subscript),
4199  * FALSE otherwise.
4200  *
4201  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
4202  *
4203  * ->[ and ->{ return TRUE
4204  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
4205  * { and [ outside a pattern are always subscripts, so return TRUE
4206  * if we're outside a pattern and it's not { or [, then return FALSE
4207  * if we're in a pattern and the first char is a {
4208  *   {4,5} (any digits around the comma) returns FALSE
4209  * if we're in a pattern and the first char is a [
4210  *   [] returns FALSE
4211  *   [SOMETHING] has a funky algorithm to decide whether it's a
4212  *      character class or not.  It has to deal with things like
4213  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
4214  * anything else returns TRUE
4215  */
4216
4217 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
4218
4219 STATIC int
4220 S_intuit_more(pTHX_ char *s, char *e)
4221 {
4222     PERL_ARGS_ASSERT_INTUIT_MORE;
4223
4224     if (PL_lex_brackets)
4225         return TRUE;
4226     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
4227         return TRUE;
4228     if (*s == '-' && s[1] == '>'
4229      && FEATURE_POSTDEREF_QQ_IS_ENABLED
4230      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
4231         ||(s[2] == '@' && memCHRs("*[{",s[3])) ))
4232         return TRUE;
4233     if (*s != '{' && *s != '[')
4234         return FALSE;
4235     PL_parser->sub_no_recover = TRUE;
4236     if (!PL_lex_inpat)
4237         return TRUE;
4238
4239     /* In a pattern, so maybe we have {n,m}. */
4240     if (*s == '{') {
4241         if (regcurly(s)) {
4242             return FALSE;
4243         }
4244         return TRUE;
4245     }
4246
4247     /* On the other hand, maybe we have a character class */
4248
4249     s++;
4250     if (*s == ']' || *s == '^')
4251         return FALSE;
4252     else {
4253         /* this is terrifying, and it works */
4254         int weight;
4255         char seen[256];
4256         const char * const send = (char *) memchr(s, ']', e - s);
4257         unsigned char un_char, last_un_char;
4258         char tmpbuf[sizeof PL_tokenbuf * 4];
4259
4260         if (!send)              /* has to be an expression */
4261             return TRUE;
4262         weight = 2;             /* let's weigh the evidence */
4263
4264         if (*s == '$')
4265             weight -= 3;
4266         else if (isDIGIT(*s)) {
4267             if (s[1] != ']') {
4268                 if (isDIGIT(s[1]) && s[2] == ']')
4269                     weight -= 10;
4270             }
4271             else
4272                 weight -= 100;
4273         }
4274         Zero(seen,256,char);
4275         un_char = 255;
4276         for (; s < send; s++) {
4277             last_un_char = un_char;
4278             un_char = (unsigned char)*s;
4279             switch (*s) {
4280             case '@':
4281             case '&':
4282             case '$':
4283                 weight -= seen[un_char] * 10;
4284                 if (isWORDCHAR_lazy_if_safe(s+1, PL_bufend, UTF)) {
4285                     int len;
4286                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
4287                     len = (int)strlen(tmpbuf);
4288                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
4289                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
4290                         weight -= 100;
4291                     else
4292                         weight -= 10;
4293                 }
4294                 else if (*s == '$'
4295                          && s[1]
4296                          && memCHRs("[#!%*<>()-=",s[1]))
4297                 {
4298                     if (/*{*/ memCHRs("])} =",s[2]))
4299                         weight -= 10;
4300                     else
4301                         weight -= 1;
4302                 }
4303                 break;
4304             case '\\':
4305                 un_char = 254;
4306                 if (s[1]) {
4307                     if (memCHRs("wds]",s[1]))
4308                         weight += 100;
4309                     else if (seen[(U8)'\''] || seen[(U8)'"'])
4310                         weight += 1;
4311                     else if (memCHRs("rnftbxcav",s[1]))
4312                         weight += 40;
4313                     else if (isDIGIT(s[1])) {
4314                         weight += 40;
4315                         while (s[1] && isDIGIT(s[1]))
4316                             s++;
4317                     }
4318                 }
4319                 else
4320                     weight += 100;
4321                 break;
4322             case '-':
4323                 if (s[1] == '\\')
4324                     weight += 50;
4325                 if (memCHRs("aA01! ",last_un_char))
4326                     weight += 30;
4327                 if (memCHRs("zZ79~",s[1]))
4328                     weight += 30;
4329                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4330                     weight -= 5;        /* cope with negative subscript */
4331                 break;
4332             default:
4333                 if (!isWORDCHAR(last_un_char)
4334                     && !(last_un_char == '$' || last_un_char == '@'
4335                          || last_un_char == '&')
4336                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4337                     char *d = s;
4338                     while (isALPHA(*s))
4339                         s++;
4340                     if (keyword(d, s - d, 0))
4341                         weight -= 150;
4342                 }
4343                 if (un_char == last_un_char + 1)
4344                     weight += 5;
4345                 weight -= seen[un_char];
4346                 break;
4347             }
4348             seen[un_char]++;
4349         }
4350         if (weight >= 0)        /* probably a character class */
4351             return FALSE;
4352     }
4353
4354     return TRUE;
4355 }
4356
4357 /*
4358  * S_intuit_method
4359  *
4360  * Does all the checking to disambiguate
4361  *   foo bar
4362  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
4363  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4364  *
4365  * First argument is the stuff after the first token, e.g. "bar".
4366  *
4367  * Not a method if foo is a filehandle.
4368  * Not a method if foo is a subroutine prototyped to take a filehandle.
4369  * Not a method if it's really "Foo $bar"
4370  * Method if it's "foo $bar"
4371  * Not a method if it's really "print foo $bar"
4372  * Method if it's really "foo package::" (interpreted as package->foo)
4373  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4374  * Not a method if bar is a filehandle or package, but is quoted with
4375  *   =>
4376  */
4377
4378 STATIC int
4379 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4380 {
4381     char *s = start + (*start == '$');
4382     char tmpbuf[sizeof PL_tokenbuf];
4383     STRLEN len;
4384     GV* indirgv;
4385         /* Mustn't actually add anything to a symbol table.
4386            But also don't want to "initialise" any placeholder
4387            constants that might already be there into full
4388            blown PVGVs with attached PVCV.  */
4389     GV * const gv =
4390         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4391
4392     PERL_ARGS_ASSERT_INTUIT_METHOD;
4393
4394     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4395             return 0;
4396     if (cv && SvPOK(cv)) {
4397         const char *proto = CvPROTO(cv);
4398         if (proto) {
4399             while (*proto && (isSPACE(*proto) || *proto == ';'))
4400                 proto++;
4401             if (*proto == '*')
4402                 return 0;
4403         }
4404     }
4405
4406     if (*start == '$') {
4407         SSize_t start_off = start - SvPVX(PL_linestr);
4408         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4409             || isUPPER(*PL_tokenbuf))
4410             return 0;
4411         /* this could be $# */
4412         if (isSPACE(*s))
4413             s = skipspace(s);
4414         PL_bufptr = SvPVX(PL_linestr) + start_off;
4415         PL_expect = XREF;
4416         return *s == '(' ? FUNCMETH : METHOD;
4417     }
4418
4419     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4420     /* start is the beginning of the possible filehandle/object,
4421      * and s is the end of it
4422      * tmpbuf is a copy of it (but with single quotes as double colons)
4423      */
4424
4425     if (!keyword(tmpbuf, len, 0)) {
4426         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4427             len -= 2;
4428             tmpbuf[len] = '\0';
4429             goto bare_package;
4430         }
4431         indirgv = gv_fetchpvn_flags(tmpbuf, len,
4432                                     GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4433                                     SVt_PVCV);
4434         if (indirgv && SvTYPE(indirgv) != SVt_NULL
4435          && (!isGV(indirgv) || GvCVu(indirgv)))
4436             return 0;
4437         /* filehandle or package name makes it a method */
4438         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4439             s = skipspace(s);
4440             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4441                 return 0;       /* no assumptions -- "=>" quotes bareword */
4442       bare_package:
4443             NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0,
4444                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4445             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4446             PL_expect = XTERM;
4447             force_next(BAREWORD);
4448             PL_bufptr = s;
4449             return *s == '(' ? FUNCMETH : METHOD;
4450         }
4451     }
4452     return 0;
4453 }
4454
4455 /* Encoded script support. filter_add() effectively inserts a
4456  * 'pre-processing' function into the current source input stream.
4457  * Note that the filter function only applies to the current source file
4458  * (e.g., it will not affect files 'require'd or 'use'd by this one).
4459  *
4460  * The datasv parameter (which may be NULL) can be used to pass
4461  * private data to this instance of the filter. The filter function
4462  * can recover the SV using the FILTER_DATA macro and use it to
4463  * store private buffers and state information.
4464  *
4465  * The supplied datasv parameter is upgraded to a PVIO type
4466  * and the IoDIRP/IoANY field is used to store the function pointer,
4467  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4468  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4469  * private use must be set using malloc'd pointers.
4470  */
4471
4472 SV *
4473 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4474 {
4475     if (!funcp)
4476         return NULL;
4477
4478     if (!PL_parser)
4479         return NULL;
4480
4481     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4482         Perl_croak(aTHX_ "Source filters apply only to byte streams");
4483
4484     if (!PL_rsfp_filters)
4485         PL_rsfp_filters = newAV();
4486     if (!datasv)
4487         datasv = newSV(0);
4488     SvUPGRADE(datasv, SVt_PVIO);
4489     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4490     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4491     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4492                           FPTR2DPTR(void *, IoANY(datasv)),
4493                           SvPV_nolen(datasv)));
4494     av_unshift(PL_rsfp_filters, 1);
4495     av_store(PL_rsfp_filters, 0, datasv) ;
4496     if (
4497         !PL_parser->filtered
4498      && PL_parser->lex_flags & LEX_EVALBYTES
4499      && PL_bufptr < PL_bufend
4500     ) {
4501         const char *s = PL_bufptr;
4502         while (s < PL_bufend) {
4503             if (*s == '\n') {
4504                 SV *linestr = PL_parser->linestr;
4505                 char *buf = SvPVX(linestr);
4506                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4507                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4508                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4509                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4510                 STRLEN const last_uni_pos =
4511                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4512                 STRLEN const last_lop_pos =
4513                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4514                 av_push(PL_rsfp_filters, linestr);
4515                 PL_parser->linestr =
4516                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4517                 buf = SvPVX(PL_parser->linestr);
4518                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4519                 PL_parser->bufptr = buf + bufptr_pos;
4520                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4521                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4522                 PL_parser->linestart = buf + linestart_pos;
4523                 if (PL_parser->last_uni)
4524                     PL_parser->last_uni = buf + last_uni_pos;
4525                 if (PL_parser->last_lop)
4526                     PL_parser->last_lop = buf + last_lop_pos;
4527                 SvLEN_set(linestr, SvCUR(linestr));
4528                 SvCUR_set(linestr, s - SvPVX(linestr));
4529                 PL_parser->filtered = 1;
4530                 break;
4531             }
4532             s++;
4533         }
4534     }
4535     return(datasv);
4536 }
4537
4538
4539 /* Delete most recently added instance of this filter function. */
4540 void
4541 Perl_filter_del(pTHX_ filter_t funcp)
4542 {
4543     SV *datasv;
4544
4545     PERL_ARGS_ASSERT_FILTER_DEL;
4546
4547 #ifdef DEBUGGING
4548     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4549                           FPTR2DPTR(void*, funcp)));
4550 #endif
4551     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4552         return;
4553     /* if filter is on top of stack (usual case) just pop it off */
4554     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4555     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4556         sv_free(av_pop(PL_rsfp_filters));
4557
4558         return;
4559     }
4560     /* we need to search for the correct entry and clear it     */
4561     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4562 }
4563
4564
4565 /* Invoke the idxth filter function for the current rsfp.        */
4566 /* maxlen 0 = read one text line */
4567 I32
4568 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4569 {
4570     filter_t funcp;
4571     I32 ret;
4572     SV *datasv = NULL;
4573     /* This API is bad. It should have been using unsigned int for maxlen.
4574        Not sure if we want to change the API, but if not we should sanity
4575        check the value here.  */
4576     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4577
4578     PERL_ARGS_ASSERT_FILTER_READ;
4579
4580     if (!PL_parser || !PL_rsfp_filters)
4581         return -1;
4582     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4583         /* Provide a default input filter to make life easy.    */
4584         /* Note that we append to the line. This is handy.      */
4585         DEBUG_P(PerlIO_printf(Perl_debug_log,
4586                               "filter_read %d: from rsfp\n", idx));
4587         if (correct_length) {
4588             /* Want a block */
4589             int len ;
4590             const int old_len = SvCUR(buf_sv);
4591
4592             /* ensure buf_sv is large enough */
4593             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4594             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4595                                    correct_length)) <= 0) {
4596                 if (PerlIO_error(PL_rsfp))
4597                     return -1;          /* error */
4598                 else
4599                     return 0 ;          /* end of file */
4600             }
4601             SvCUR_set(buf_sv, old_len + len) ;
4602             SvPVX(buf_sv)[old_len + len] = '\0';
4603         } else {
4604             /* Want a line */
4605             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4606                 if (PerlIO_error(PL_rsfp))
4607                     return -1;          /* error */
4608                 else
4609                     return 0 ;          /* end of file */
4610             }
4611         }
4612         return SvCUR(buf_sv);
4613     }
4614     /* Skip this filter slot if filter has been deleted */
4615     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4616         DEBUG_P(PerlIO_printf(Perl_debug_log,
4617                               "filter_read %d: skipped (filter deleted)\n",
4618                               idx));
4619         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4620     }
4621     if (SvTYPE(datasv) != SVt_PVIO) {
4622         if (correct_length) {
4623             /* Want a block */
4624             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4625             if (!remainder) return 0; /* eof */
4626             if (correct_length > remainder) correct_length = remainder;
4627             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4628             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4629         } else {
4630             /* Want a line */
4631             const char *s = SvEND(datasv);
4632             const char *send = SvPVX(datasv) + SvLEN(datasv);
4633             while (s < send) {
4634                 if (*s == '\n') {
4635                     s++;
4636                     break;
4637                 }
4638                 s++;
4639             }
4640             if (s == send) return 0; /* eof */
4641             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4642             SvCUR_set(datasv, s-SvPVX(datasv));
4643         }
4644         return SvCUR(buf_sv);
4645     }
4646     /* Get function pointer hidden within datasv        */
4647     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4648     DEBUG_P(PerlIO_printf(Perl_debug_log,
4649                           "filter_read %d: via function %p (%s)\n",
4650                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4651     /* Call function. The function is expected to       */
4652     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4653     /* Return: <0:error, =0:eof, >0:not eof             */
4654     ENTER;
4655     save_scalar(PL_errgv);
4656     ret = (*funcp)(aTHX_ idx, buf_sv, correct_length);
4657     LEAVE;
4658     return ret;
4659 }
4660
4661 STATIC char *
4662 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4663 {
4664     PERL_ARGS_ASSERT_FILTER_GETS;
4665
4666 #ifdef PERL_CR_FILTER
4667     if (!PL_rsfp_filters) {
4668         filter_add(S_cr_textfilter,NULL);
4669     }
4670 #endif
4671     if (PL_rsfp_filters) {
4672         if (!append)
4673             SvCUR_set(sv, 0);   /* start with empty line        */
4674         if (FILTER_READ(0, sv, 0) > 0)
4675             return ( SvPVX(sv) ) ;
4676         else
4677             return NULL ;
4678     }
4679     else
4680         return (sv_gets(sv, PL_rsfp, append));
4681 }
4682
4683 STATIC HV *
4684 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4685 {
4686     GV *gv;
4687
4688     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4689
4690     if (memEQs(pkgname, len, "__PACKAGE__"))
4691         return PL_curstash;
4692
4693     if (len > 2
4694         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4695         && (gv = gv_fetchpvn_flags(pkgname,
4696                                    len,
4697                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4698     {
4699         return GvHV(gv);                        /* Foo:: */
4700     }
4701
4702     /* use constant CLASS => 'MyClass' */
4703     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4704     if (gv && GvCV(gv)) {
4705         SV * const sv = cv_const_sv(GvCV(gv));
4706         if (sv)
4707             return gv_stashsv(sv, 0);
4708     }
4709
4710     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4711 }
4712
4713
4714 STATIC char *
4715 S_tokenize_use(pTHX_ int is_use, char *s) {
4716     PERL_ARGS_ASSERT_TOKENIZE_USE;
4717
4718     if (PL_expect != XSTATE)
4719         /* diag_listed_as: "use" not allowed in expression */
4720         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4721                     is_use ? "use" : "no"));
4722     PL_expect = XTERM;
4723     s = skipspace(s);
4724     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4725         s = force_version(s, TRUE);
4726         if (*s == ';' || *s == '}'
4727                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4728             NEXTVAL_NEXTTOKE.opval = NULL;
4729             force_next(BAREWORD);
4730         }
4731         else if (*s == 'v') {
4732             s = force_word(s,BAREWORD,FALSE,TRUE);
4733             s = force_version(s, FALSE);
4734         }
4735     }
4736     else {
4737         s = force_word(s,BAREWORD,FALSE,TRUE);
4738         s = force_version(s, FALSE);
4739     }
4740     pl_yylval.ival = is_use;
4741     return s;
4742 }
4743 #ifdef DEBUGGING
4744     static const char* const exp_name[] =
4745         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4746           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4747           "SIGVAR", "TERMORDORDOR"
4748         };
4749 #endif
4750
4751 #define word_takes_any_delimiter(p,l) S_word_takes_any_delimiter(p,l)
4752 STATIC bool
4753 S_word_takes_any_delimiter(char *p, STRLEN len)
4754 {
4755     return (len == 1 && memCHRs("msyq", p[0]))
4756             || (len == 2
4757                 && ((p[0] == 't' && p[1] == 'r')
4758                     || (p[0] == 'q' && memCHRs("qwxr", p[1]))));
4759 }
4760
4761 static void
4762 S_check_scalar_slice(pTHX_ char *s)
4763 {
4764     s++;
4765     while (SPACE_OR_TAB(*s)) s++;
4766     if (*s == 'q' && s[1] == 'w' && !isWORDCHAR_lazy_if_safe(s+2,
4767                                                              PL_bufend,
4768                                                              UTF))
4769     {
4770         return;
4771     }
4772     while (    isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF)
4773            || (*s && memCHRs(" \t$#+-'\"", *s)))
4774     {
4775         s += UTF ? UTF8SKIP(s) : 1;
4776     }
4777     if (*s == '}' || *s == ']')
4778         pl_yylval.ival = OPpSLICEWARNING;
4779 }
4780
4781 #define lex_token_boundary() S_lex_token_boundary(aTHX)
4782 static void
4783 S_lex_token_boundary(pTHX)
4784 {
4785     PL_oldoldbufptr = PL_oldbufptr;
4786     PL_oldbufptr = PL_bufptr;
4787 }
4788
4789 #define vcs_conflict_marker(s) S_vcs_conflict_marker(aTHX_ s)
4790 static char *
4791 S_vcs_conflict_marker(pTHX_ char *s)
4792 {
4793     lex_token_boundary();
4794     PL_bufptr = s;
4795     yyerror("Version control conflict marker");
4796     while (s < PL_bufend && *s != '\n')
4797         s++;
4798     return s;
4799 }
4800
4801 static int
4802 yyl_sigvar(pTHX_ char *s)
4803 {
4804     /* we expect the sigil and optional var name part of a
4805      * signature element here. Since a '$' is not necessarily
4806      * followed by a var name, handle it specially here; the general
4807      * yylex code would otherwise try to interpret whatever follows
4808      * as a var; e.g. ($, ...) would be seen as the var '$,'
4809      */
4810
4811     U8 sigil;
4812
4813     s = skipspace(s);
4814     sigil = *s++;
4815     PL_bufptr = s; /* for error reporting */
4816     switch (sigil) {
4817     case '$':
4818     case '@':
4819     case '%':
4820         /* spot stuff that looks like an prototype */
4821         if (memCHRs("$:@%&*;\\[]", *s)) {
4822             yyerror("Illegal character following sigil in a subroutine signature");
4823             break;
4824         }
4825         /* '$#' is banned, while '$ # comment' isn't */
4826         if (*s == '#') {
4827             yyerror("'#' not allowed immediately following a sigil in a subroutine signature");
4828             break;
4829         }
4830         s = skipspace(s);
4831         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
4832             char *dest = PL_tokenbuf + 1;
4833             /* read var name, including sigil, into PL_tokenbuf */
4834             PL_tokenbuf[0] = sigil;
4835             parse_ident(&s, &dest, dest + sizeof(PL_tokenbuf) - 1,
4836                 0, cBOOL(UTF), FALSE, FALSE);
4837             *dest = '\0';
4838             assert(PL_tokenbuf[1]); /* we have a variable name */
4839         }
4840         else {
4841             *PL_tokenbuf = 0;
4842             PL_in_my = 0;
4843         }
4844
4845         s = skipspace(s);
4846         /* parse the = for the default ourselves to avoid '+=' etc being accepted here
4847          * as the ASSIGNOP, and exclude other tokens that start with =
4848          */
4849         if (*s == '=' && (!s[1] || memCHRs("=~>", s[1]) == 0)) {
4850             /* save now to report with the same context as we did when
4851              * all ASSIGNOPS were accepted */
4852             PL_oldbufptr = s;
4853
4854             ++s;
4855             NEXTVAL_NEXTTOKE.ival = 0;
4856             force_next(ASSIGNOP);
4857             PL_expect = XTERM;
4858         }
4859         else if (*s == ',' || *s == ')') {
4860             PL_expect = XOPERATOR;
4861         }
4862         else {
4863             /* make sure the context shows the unexpected character and
4864              * hopefully a bit more */
4865             if (*s) ++s;
4866             while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4867                 s++;
4868             PL_bufptr = s; /* for error reporting */
4869             yyerror("Illegal operator following parameter in a subroutine signature");
4870             PL_in_my = 0;
4871         }
4872         if (*PL_tokenbuf) {
4873             NEXTVAL_NEXTTOKE.ival = sigil;
4874             force_next('p'); /* force a signature pending identifier */
4875         }
4876         break;
4877
4878     case ')':
4879         PL_expect = XBLOCK;
4880         break;
4881     case ',': /* handle ($a,,$b) */
4882         break;
4883
4884     default:
4885         PL_in_my = 0;
4886         yyerror("A signature parameter must start with '$', '@' or '%'");
4887         /* very crude error recovery: skip to likely next signature
4888          * element */
4889         while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4890             s++;
4891         break;
4892     }
4893
4894     TOKEN(sigil);
4895 }
4896
4897 static int
4898 yyl_dollar(pTHX_ char *s)
4899 {
4900     CLINE;
4901
4902     if (PL_expect == XPOSTDEREF) {
4903         if (s[1] == '#') {
4904             s++;
4905             POSTDEREF(DOLSHARP);
4906         }
4907         POSTDEREF('$');
4908     }
4909
4910     if (   s[1] == '#'
4911         && (   isIDFIRST_lazy_if_safe(s+2, PL_bufend, UTF)
4912             || memCHRs("{$:+-@", s[2])))
4913     {
4914         PL_tokenbuf[0] = '@';
4915         s = scan_ident(s + 1, PL_tokenbuf + 1,
4916                        sizeof PL_tokenbuf - 1, FALSE);
4917         if (PL_expect == XOPERATOR) {
4918             char *d = s;
4919             if (PL_bufptr > s) {
4920                 d = PL_bufptr-1;
4921                 PL_bufptr = PL_oldbufptr;
4922             }
4923             no_op("Array length", d);
4924         }
4925         if (!PL_tokenbuf[1])
4926             PREREF(DOLSHARP);
4927         PL_expect = XOPERATOR;
4928         force_ident_maybe_lex('#');
4929         TOKEN(DOLSHARP);
4930     }
4931
4932     PL_tokenbuf[0] = '$';
4933     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
4934     if (PL_expect == XOPERATOR) {
4935         char *d = s;
4936         if (PL_bufptr > s) {
4937             d = PL_bufptr-1;
4938             PL_bufptr = PL_oldbufptr;
4939         }
4940         no_op("Scalar", d);
4941     }
4942     if (!PL_tokenbuf[1]) {
4943         if (s == PL_bufend)
4944             yyerror("Final $ should be \\$ or $name");
4945         PREREF('$');
4946     }
4947
4948     {
4949         const char tmp = *s;
4950         if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
4951             s = skipspace(s);
4952
4953         if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
4954             && intuit_more(s, PL_bufend)) {
4955             if (*s == '[') {
4956                 PL_tokenbuf[0] = '@';
4957                 if (ckWARN(WARN_SYNTAX)) {
4958                     char *t = s+1;
4959
4960                     while ( t < PL_bufend ) {
4961                         if (isSPACE(*t)) {
4962                             do { t += UTF ? UTF8SKIP(t) : 1; } while (t < PL_bufend && isSPACE(*t));
4963                             /* consumed one or more space chars */
4964                         } else if (*t == '$' || *t == '@') {
4965                             /* could be more than one '$' like $$ref or @$ref */
4966                             do { t++; } while (t < PL_bufend && *t == '$');
4967
4968                             /* could be an abigail style identifier like $ foo */
4969                             while (t < PL_bufend && *t == ' ') t++;
4970
4971                             /* strip off the name of the var */
4972                             while (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
4973                                 t += UTF ? UTF8SKIP(t) : 1;
4974                             /* consumed a varname */
4975                         } else if (isDIGIT(*t)) {
4976                             /* deal with hex constants like 0x11 */
4977                             if (t[0] == '0' && t[1] == 'x') {
4978                                 t += 2;
4979                                 while (t < PL_bufend && isXDIGIT(*t)) t++;
4980                             } else {
4981                                 /* deal with decimal/octal constants like 1 and 0123 */
4982                                 do { t++; } while (isDIGIT(*t));
4983                                 if (t<PL_bufend && *t == '.') {
4984                                     do { t++; } while (isDIGIT(*t));
4985                                 }
4986                             }
4987                             /* consumed a number */
4988                         } else {
4989                             /* not a var nor a space nor a number */
4990                             break;
4991                         }
4992                     }
4993                     if (t < PL_bufend && *t++ == ',') {
4994                         PL_bufptr = skipspace(PL_bufptr); /* XXX can realloc */
4995                         while (t < PL_bufend && *t != ']')
4996                             t++;
4997                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
4998                                     "Multidimensional syntax %" UTF8f " not supported",
4999                                     UTF8fARG(UTF,(int)((t - PL_bufptr) + 1), PL_bufptr));
5000                     }
5001                 }
5002             }
5003             else if (*s == '{') {
5004                 char *t;
5005                 PL_tokenbuf[0] = '%';
5006                 if (    strEQ(PL_tokenbuf+1, "SIG")
5007                     && ckWARN(WARN_SYNTAX)
5008                     && (t = (char *) memchr(s, '}', PL_bufend - s))
5009                     && (t = (char *) memchr(t, '=', PL_bufend - t)))
5010                 {
5011                     char tmpbuf[sizeof PL_tokenbuf];
5012                     do {
5013                         t++;
5014                     } while (isSPACE(*t));
5015                     if (isIDFIRST_lazy_if_safe(t, PL_bufend, UTF)) {
5016                         STRLEN len;
5017                         t = scan_word(t, tmpbuf, sizeof tmpbuf, TRUE,
5018                                         &len);
5019                         while (isSPACE(*t))
5020                             t++;
5021                         if (  *t == ';'
5022                             && get_cvn_flags(tmpbuf, len, UTF
5023                                                             ? SVf_UTF8
5024                                                             : 0))
5025                         {
5026                             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
5027                                 "You need to quote \"%" UTF8f "\"",
5028                                     UTF8fARG(UTF, len, tmpbuf));
5029                         }
5030                     }
5031                 }
5032             }
5033         }
5034
5035         PL_expect = XOPERATOR;
5036         if ((PL_lex_state == LEX_NORMAL || PL_lex_brackets) && isSPACE((char)tmp)) {
5037             const bool islop = (PL_last_lop == PL_oldoldbufptr);
5038             if (!islop || PL_last_lop_op == OP_GREPSTART)
5039                 PL_expect = XOPERATOR;
5040             else if (memCHRs("$@\"'`q", *s))
5041                 PL_expect = XTERM;              /* e.g. print $fh "foo" */
5042             else if (   memCHRs("&*<%", *s)
5043                      && isIDFIRST_lazy_if_safe(s+1, PL_bufend, UTF))
5044             {
5045                 PL_expect = XTERM;              /* e.g. print $fh &sub */
5046             }
5047             else if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5048                 char tmpbuf[sizeof PL_tokenbuf];
5049                 int t2;
5050                 STRLEN len;
5051                 scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
5052                 if ((t2 = keyword(tmpbuf, len, 0))) {
5053                     /* binary operators exclude handle interpretations */
5054                     switch (t2) {
5055                     case -KEY_x:
5056                     case -KEY_eq:
5057                     case -KEY_ne:
5058                     case -KEY_gt:
5059                     case -KEY_lt:
5060                     case -KEY_ge:
5061                     case -KEY_le:
5062                     case -KEY_cmp:
5063                         break;
5064                     default:
5065                         PL_expect = XTERM;      /* e.g. print $fh length() */
5066                         break;
5067                     }
5068                 }
5069                 else {
5070                     PL_expect = XTERM;  /* e.g. print $fh subr() */
5071                 }
5072             }
5073             else if (isDIGIT(*s))
5074                 PL_expect = XTERM;              /* e.g. print $fh 3 */
5075             else if (*s == '.' && isDIGIT(s[1]))
5076                 PL_expect = XTERM;              /* e.g. print $fh .3 */
5077             else if ((*s == '?' || *s == '-' || *s == '+')
5078                      && !isSPACE(s[1]) && s[1] != '=')
5079                 PL_expect = XTERM;              /* e.g. print $fh -1 */
5080             else if (*s == '/' && !isSPACE(s[1]) && s[1] != '='
5081                      && s[1] != '/')
5082                 PL_expect = XTERM;              /* e.g. print $fh /.../
5083                                                XXX except DORDOR operator
5084                                             */
5085             else if (*s == '<' && s[1] == '<' && !isSPACE(s[2])
5086                      && s[2] != '=')
5087                 PL_expect = XTERM;              /* print $fh <<"EOF" */
5088         }
5089     }
5090     force_ident_maybe_lex('$');
5091     TOKEN('$');
5092 }
5093
5094 static int
5095 yyl_sub(pTHX_ char *s, const int key)
5096 {
5097     char * const tmpbuf = PL_tokenbuf + 1;
5098     bool have_name, have_proto;
5099     STRLEN len;
5100     SV *format_name = NULL;
5101     bool is_sigsub = FEATURE_SIGNATURES_IS_ENABLED;
5102
5103     SSize_t off = s-SvPVX(PL_linestr);
5104     char *d;
5105
5106     s = skipspace(s); /* can move PL_linestr */
5107
5108     d = SvPVX(PL_linestr)+off;
5109
5110     SAVEBOOL(PL_parser->sig_seen);
5111     PL_parser->sig_seen = FALSE;
5112
5113     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
5114         || *s == '\''
5115         || (*s == ':' && s[1] == ':'))
5116     {
5117
5118         PL_expect = XATTRBLOCK;
5119         d = scan_word(s, tmpbuf, sizeof PL_tokenbuf - 1, TRUE,
5120                       &len);
5121         if (key == KEY_format)
5122             format_name = S_newSV_maybe_utf8(aTHX_ s, d - s);
5123         *PL_tokenbuf = '&';
5124         if (memchr(tmpbuf, ':', len) || key != KEY_sub
5125          || pad_findmy_pvn(
5126                 PL_tokenbuf, len + 1, 0
5127             ) != NOT_IN_PAD)
5128             sv_setpvn(PL_subname, tmpbuf, len);
5129         else {
5130             sv_setsv(PL_subname,PL_curstname);
5131             sv_catpvs(PL_subname,"::");
5132             sv_catpvn(PL_subname,tmpbuf,len);
5133         }
5134         if (SvUTF8(PL_linestr))
5135             SvUTF8_on(PL_subname);
5136         have_name = TRUE;
5137
5138         s = skipspace(d);
5139     }
5140     else {
5141         if (key == KEY_my || key == KEY_our || key==KEY_state) {
5142             *d = '\0';
5143             /* diag_listed_as: Missing name in "%s sub" */
5144             Perl_croak(aTHX_
5145                       "Missing name in \"%s\"", PL_bufptr);
5146         }
5147         PL_expect = XATTRTERM;
5148         sv_setpvs(PL_subname,"?");
5149         have_name = FALSE;
5150     }
5151
5152     if (key == KEY_format) {
5153         if (format_name) {
5154             NEXTVAL_NEXTTOKE.opval
5155                 = newSVOP(OP_CONST,0, format_name);
5156             NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
5157             force_next(BAREWORD);
5158         }
5159         PREBLOCK(FORMAT);
5160     }
5161
5162     /* Look for a prototype */
5163     if (*s == '(' && !is_sigsub) {
5164         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5165         if (!s)
5166             Perl_croak(aTHX_ "Prototype not terminated");
5167         COPLINE_SET_FROM_MULTI_END;
5168         (void)validate_proto(PL_subname, PL_lex_stuff,
5169                              ckWARN(WARN_ILLEGALPROTO), 0);
5170         have_proto = TRUE;
5171
5172         s = skipspace(s);
5173     }
5174     else
5175         have_proto = FALSE;
5176
5177     if (  !(*s == ':' && s[1] != ':')
5178         && (*s != '{' && *s != '(') && key != KEY_format)
5179     {
5180         assert(key == KEY_sub || key == KEY_AUTOLOAD ||
5181                key == KEY_DESTROY || key == KEY_BEGIN ||
5182                key == KEY_UNITCHECK || key == KEY_CHECK ||
5183                key == KEY_INIT || key == KEY_END ||
5184                key == KEY_my || key == KEY_state ||
5185                key == KEY_our);
5186         if (!have_name)
5187             Perl_croak(aTHX_ "Illegal declaration of anonymous subroutine");
5188         else if (*s != ';' && *s != '}')
5189             Perl_croak(aTHX_ "Illegal declaration of subroutine %" SVf, SVfARG(PL_subname));
5190     }
5191
5192     if (have_proto) {
5193         NEXTVAL_NEXTTOKE.opval =
5194             newSVOP(OP_CONST, 0, PL_lex_stuff);
5195         PL_lex_stuff = NULL;
5196         force_next(THING);
5197     }
5198     if (!have_name) {
5199         if (PL_curstash)
5200             sv_setpvs(PL_subname, "__ANON__");
5201         else
5202             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5203         if (is_sigsub)
5204             TOKEN(ANON_SIGSUB);
5205         else
5206             TOKEN(ANONSUB);
5207     }
5208     force_ident_maybe_lex('&');
5209     if (is_sigsub)
5210         TOKEN(SIGSUB);
5211     else
5212         TOKEN(SUB);
5213 }
5214
5215 static int
5216 yyl_interpcasemod(pTHX_ char *s)
5217 {
5218 #ifdef DEBUGGING
5219     if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
5220         Perl_croak(aTHX_
5221                    "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
5222                    PL_bufptr, PL_bufend, *PL_bufptr);
5223 #endif
5224
5225     if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
5226         /* if at a \E */
5227         if (PL_lex_casemods) {
5228             const char oldmod = PL_lex_casestack[--PL_lex_casemods];
5229             PL_lex_casestack[PL_lex_casemods] = '\0';
5230
5231             if (PL_bufptr != PL_bufend
5232                 && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
5233                     || oldmod == 'F')) {
5234                 PL_bufptr += 2;
5235                 PL_lex_state = LEX_INTERPCONCAT;
5236             }
5237             PL_lex_allbrackets--;
5238             return REPORT(')');
5239         }
5240         else if ( PL_bufptr != PL_bufend && PL_bufptr[1] == 'E' ) {
5241            /* Got an unpaired \E */
5242            Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5243                     "Useless use of \\E");
5244         }
5245         if (PL_bufptr != PL_bufend)
5246             PL_bufptr += 2;
5247         PL_lex_state = LEX_INTERPCONCAT;
5248         return yylex();
5249     }
5250     else {
5251         DEBUG_T({
5252             PerlIO_printf(Perl_debug_log, "### Saw case modifier\n");
5253         });
5254         s = PL_bufptr + 1;
5255         if (s[1] == '\\' && s[2] == 'E') {
5256             PL_bufptr = s + 3;
5257             PL_lex_state = LEX_INTERPCONCAT;
5258             return yylex();
5259         }
5260         else {
5261             I32 tmp;
5262             if (   memBEGINs(s, (STRLEN) (PL_bufend - s), "L\\u")
5263                 || memBEGINs(s, (STRLEN) (PL_bufend - s), "U\\l"))
5264             {
5265                 tmp = *s, *s = s[2], s[2] = (char)tmp;  /* misordered... */
5266             }
5267             if ((*s == 'L' || *s == 'U' || *s == 'F')
5268                 && (strpbrk(PL_lex_casestack, "LUF")))
5269             {
5270                 PL_lex_casestack[--PL_lex_casemods] = '\0';
5271                 PL_lex_allbrackets--;
5272                 return REPORT(')');
5273             }
5274             if (PL_lex_casemods > 10)
5275                 Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
5276             PL_lex_casestack[PL_lex_casemods++] = *s;
5277             PL_lex_casestack[PL_lex_casemods] = '\0';
5278             PL_lex_state = LEX_INTERPCONCAT;
5279             NEXTVAL_NEXTTOKE.ival = 0;
5280             force_next((2<<24)|'(');
5281             if (*s == 'l')
5282                 NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
5283             else if (*s == 'u')
5284                 NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
5285             else if (*s == 'L')
5286                 NEXTVAL_NEXTTOKE.ival = OP_LC;
5287             else if (*s == 'U')
5288                 NEXTVAL_NEXTTOKE.ival = OP_UC;
5289             else if (*s == 'Q')
5290                 NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
5291             else if (*s == 'F')
5292                 NEXTVAL_NEXTTOKE.ival = OP_FC;
5293             else
5294                 Perl_croak(aTHX_ "panic: yylex, *s=%u", *s);
5295             PL_bufptr = s + 1;
5296         }
5297         force_next(FUNC);
5298         if (PL_lex_starts) {
5299             s = PL_bufptr;
5300             PL_lex_starts = 0;
5301             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
5302             if (PL_lex_casemods == 1 && PL_lex_inpat)
5303                 TOKEN(',');
5304             else
5305                 AopNOASSIGN(OP_CONCAT);
5306         }
5307         else
5308             return yylex();
5309     }
5310 }
5311
5312 static int
5313 yyl_secondclass_keyword(pTHX_ char *s, STRLEN len, int key, I32 *orig_keyword,
5314                         GV **pgv, GV ***pgvp)
5315 {
5316     GV *ogv = NULL;     /* override (winner) */
5317     GV *hgv = NULL;     /* hidden (loser) */
5318     GV *gv = *pgv;
5319
5320     if (PL_expect != XOPERATOR && (*s != ':' || s[1] != ':')) {
5321         CV *cv;
5322         if ((gv = gv_fetchpvn_flags(PL_tokenbuf, len,
5323                                     (UTF ? SVf_UTF8 : 0)|GV_NOTQUAL,
5324                                     SVt_PVCV))
5325             && (cv = GvCVu(gv)))
5326         {
5327             if (GvIMPORTED_CV(gv))
5328                 ogv = gv;
5329             else if (! CvMETHOD(cv))
5330                 hgv = gv;
5331         }
5332         if (!ogv
5333             && (*pgvp = (GV**)hv_fetch(PL_globalstash, PL_tokenbuf, len, FALSE))
5334             && (gv = **pgvp)
5335             && (isGV_with_GP(gv)
5336                 ? GvCVu(gv) && GvIMPORTED_CV(gv)
5337                 :   SvPCS_IMPORTED(gv)
5338                 && (gv_init(gv, PL_globalstash, PL_tokenbuf,
5339                                                          len, 0), 1)))
5340         {
5341             ogv = gv;
5342         }
5343     }
5344
5345     *pgv = gv;
5346
5347     if (ogv) {
5348         *orig_keyword = key;
5349         return 0;               /* overridden by import or by GLOBAL */
5350     }
5351     else if (gv && !*pgvp
5352              && -key==KEY_lock  /* XXX generalizable kludge */
5353              && GvCVu(gv))
5354     {
5355         return 0;               /* any sub overrides "weak" keyword */
5356     }
5357     else {                      /* no override */
5358         key = -key;
5359         if (key == KEY_dump) {
5360             Perl_croak(aTHX_ "dump() must be written as CORE::dump() as of Perl 5.30");
5361         }
5362         *pgv = NULL;
5363         *pgvp = 0;
5364         if (hgv && key != KEY_x)        /* never ambiguous */
5365             Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
5366                            "Ambiguous call resolved as CORE::%s(), "
5367                            "qualify as such or use &",
5368                            GvENAME(hgv));
5369         return key;
5370     }
5371 }
5372
5373 static int
5374 yyl_qw(pTHX_ char *s, STRLEN len)
5375 {
5376     OP *words = NULL;
5377
5378     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5379     if (!s)
5380         missingterm(NULL, 0);
5381
5382     COPLINE_SET_FROM_MULTI_END;
5383     PL_expect = XOPERATOR;
5384     if (SvCUR(PL_lex_stuff)) {
5385         int warned_comma = !ckWARN(WARN_QW);
5386         int warned_comment = warned_comma;
5387         char *d = SvPV_force(PL_lex_stuff, len);
5388         while (len) {
5389             for (; isSPACE(*d) && len; --len, ++d)
5390                 /**/;
5391             if (len) {
5392                 SV *sv;
5393                 const char *b = d;
5394                 if (!warned_comma || !warned_comment) {
5395                     for (; !isSPACE(*d) && len; --len, ++d) {
5396                         if (!warned_comma && *d == ',') {
5397                             Perl_warner(aTHX_ packWARN(WARN_QW),
5398                                 "Possible attempt to separate words with commas");
5399                             ++warned_comma;
5400                         }
5401                         else if (!warned_comment && *d == '#') {
5402                             Perl_warner(aTHX_ packWARN(WARN_QW),
5403                                 "Possible attempt to put comments in qw() list");
5404                             ++warned_comment;
5405                         }
5406                     }
5407                 }
5408                 else {
5409                     for (; !isSPACE(*d) && len; --len, ++d)
5410                         /**/;
5411                 }
5412                 sv = newSVpvn_utf8(b, d-b, DO_UTF8(PL_lex_stuff));
5413                 words = op_append_elem(OP_LIST, words,
5414                                        newSVOP(OP_CONST, 0, tokeq(sv)));
5415             }
5416         }
5417     }
5418     if (!words)
5419         words = newNULLLIST();
5420     SvREFCNT_dec_NN(PL_lex_stuff);
5421     PL_lex_stuff = NULL;
5422     PL_expect = XOPERATOR;
5423     pl_yylval.opval = sawparens(words);
5424     TOKEN(QWLIST);
5425 }
5426
5427 static int
5428 yyl_hyphen(pTHX_ char *s)
5429 {
5430     if (s[1] && isALPHA(s[1]) && !isWORDCHAR(s[2])) {
5431         I32 ftst = 0;
5432         char tmp;
5433
5434         s++;
5435         PL_bufptr = s;
5436         tmp = *s++;
5437
5438         while (s < PL_bufend && SPACE_OR_TAB(*s))
5439             s++;
5440
5441         if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=>")) {
5442             s = force_word(PL_bufptr,BAREWORD,FALSE,FALSE);
5443             DEBUG_T( { printbuf("### Saw unary minus before =>, forcing word %s\n", s); } );
5444             OPERATOR('-');              /* unary minus */
5445         }
5446         switch (tmp) {
5447         case 'r': ftst = OP_FTEREAD;    break;
5448         case 'w': ftst = OP_FTEWRITE;   break;
5449         case 'x': ftst = OP_FTEEXEC;    break;
5450         case 'o': ftst = OP_FTEOWNED;   break;
5451         case 'R': ftst = OP_FTRREAD;    break;
5452         case 'W': ftst = OP_FTRWRITE;   break;
5453         case 'X': ftst = OP_FTREXEC;    break;
5454         case 'O': ftst = OP_FTROWNED;   break;
5455         case 'e': ftst = OP_FTIS;       break;
5456         case 'z': ftst = OP_FTZERO;     break;
5457         case 's': ftst = OP_FTSIZE;     break;
5458         case 'f': ftst = OP_FTFILE;     break;
5459         case 'd': ftst = OP_FTDIR;      break;
5460         case 'l': ftst = OP_FTLINK;     break;
5461         case 'p': ftst = OP_FTPIPE;     break;
5462         case 'S': ftst = OP_FTSOCK;     break;
5463         case 'u': ftst = OP_FTSUID;     break;
5464         case 'g': ftst = OP_FTSGID;     break;
5465         case 'k': ftst = OP_FTSVTX;     break;
5466         case 'b': ftst = OP_FTBLK;      break;
5467         case 'c': ftst = OP_FTCHR;      break;
5468         case 't': ftst = OP_FTTTY;      break;
5469         case 'T': ftst = OP_FTTEXT;     break;
5470         case 'B': ftst = OP_FTBINARY;   break;
5471         case 'M': case 'A': case 'C':
5472             gv_fetchpvs("\024", GV_ADD|GV_NOTQUAL, SVt_PV);
5473             switch (tmp) {
5474             case 'M': ftst = OP_FTMTIME; break;
5475             case 'A': ftst = OP_FTATIME; break;
5476             case 'C': ftst = OP_FTCTIME; break;
5477             default:                     break;
5478             }
5479             break;
5480         default:
5481             break;
5482         }
5483         if (ftst) {
5484             PL_last_uni = PL_oldbufptr;
5485             PL_last_lop_op = (OPCODE)ftst;
5486             DEBUG_T( {
5487                 PerlIO_printf(Perl_debug_log, "### Saw file test %c\n", (int)tmp);
5488             } );
5489             FTST(ftst);
5490         }
5491         else {
5492             /* Assume it was a minus followed by a one-letter named
5493              * subroutine call (or a -bareword), then. */
5494             DEBUG_T( {
5495                 PerlIO_printf(Perl_debug_log,
5496                     "### '-%c' looked like a file test but was not\n",
5497                     (int) tmp);
5498             } );
5499             s = --PL_bufptr;
5500         }
5501     }
5502     {
5503         const char tmp = *s++;
5504         if (*s == tmp) {
5505             s++;
5506             if (PL_expect == XOPERATOR)
5507                 TERM(POSTDEC);
5508             else
5509                 OPERATOR(PREDEC);
5510         }
5511         else if (*s == '>') {
5512             s++;
5513             s = skipspace(s);
5514             if (((*s == '$' || *s == '&') && s[1] == '*')
5515               ||(*s == '$' && s[1] == '#' && s[2] == '*')
5516               ||((*s == '@' || *s == '%') && memCHRs("*[{", s[1]))
5517               ||(*s == '*' && (s[1] == '*' || s[1] == '{'))
5518              )
5519             {
5520                 PL_expect = XPOSTDEREF;
5521                 TOKEN(ARROW);
5522             }
5523             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5524                 s = force_word(s,METHOD,FALSE,TRUE);
5525                 TOKEN(ARROW);
5526             }
5527             else if (*s == '$')
5528                 OPERATOR(ARROW);
5529             else
5530                 TERM(ARROW);
5531         }
5532         if (PL_expect == XOPERATOR) {
5533             if (*s == '='
5534                 && !PL_lex_allbrackets
5535                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5536             {
5537                 s--;
5538                 TOKEN(0);
5539             }
5540             Aop(OP_SUBTRACT);
5541         }
5542         else {
5543             if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5544                 check_uni();
5545             OPERATOR('-');              /* unary minus */
5546         }
5547     }
5548 }
5549
5550 static int
5551 yyl_plus(pTHX_ char *s)
5552 {
5553     const char tmp = *s++;
5554     if (*s == tmp) {
5555         s++;
5556         if (PL_expect == XOPERATOR)
5557             TERM(POSTINC);
5558         else
5559             OPERATOR(PREINC);
5560     }
5561     if (PL_expect == XOPERATOR) {
5562         if (*s == '='
5563             && !PL_lex_allbrackets
5564             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5565         {
5566             s--;
5567             TOKEN(0);
5568         }
5569         Aop(OP_ADD);
5570     }
5571     else {
5572         if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5573             check_uni();
5574         OPERATOR('+');
5575     }
5576 }
5577
5578 static int
5579 yyl_star(pTHX_ char *s)
5580 {
5581     if (PL_expect == XPOSTDEREF)
5582         POSTDEREF('*');
5583
5584     if (PL_expect != XOPERATOR) {
5585         s = scan_ident(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE);
5586         PL_expect = XOPERATOR;
5587         force_ident(PL_tokenbuf, '*');
5588         if (!*PL_tokenbuf)
5589             PREREF('*');
5590         TERM('*');
5591     }
5592
5593     s++;
5594     if (*s == '*') {
5595         s++;
5596         if (*s == '=' && !PL_lex_allbrackets
5597             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5598         {
5599             s -= 2;
5600             TOKEN(0);
5601         }
5602         PWop(OP_POW);
5603     }
5604
5605     if (*s == '='
5606         && !PL_lex_allbrackets
5607         && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5608     {
5609         s--;
5610         TOKEN(0);
5611     }
5612
5613     Mop(OP_MULTIPLY);
5614 }
5615
5616 static int
5617 yyl_percent(pTHX_ char *s)
5618 {
5619     if (PL_expect == XOPERATOR) {
5620         if (s[1] == '='
5621             && !PL_lex_allbrackets
5622             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5623         {
5624             TOKEN(0);
5625         }
5626         ++s;
5627         Mop(OP_MODULO);
5628     }
5629     else if (PL_expect == XPOSTDEREF)
5630         POSTDEREF('%');
5631
5632     PL_tokenbuf[0] = '%';
5633     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
5634     pl_yylval.ival = 0;
5635     if (!PL_tokenbuf[1]) {
5636         PREREF('%');
5637     }
5638     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
5639         && intuit_more(s, PL_bufend)) {
5640         if (*s == '[')
5641             PL_tokenbuf[0] = '@';
5642     }
5643     PL_expect = XOPERATOR;
5644     force_ident_maybe_lex('%');
5645     TERM('%');
5646 }
5647
5648 static int
5649 yyl_caret(pTHX_ char *s)
5650 {
5651     char *d = s;
5652     const bool bof = cBOOL(FEATURE_BITWISE_IS_ENABLED);
5653     if (bof && s[1] == '.')
5654         s++;
5655     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
5656             (s[1] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE))
5657     {
5658         s = d;
5659         TOKEN(0);
5660     }
5661     s++;
5662     BOop(bof ? d == s-2 ? OP_SBIT_XOR : OP_NBIT_XOR : OP_BIT_XOR);
5663 }
5664
5665 static int
5666 yyl_colon(pTHX_ char *s)
5667 {
5668     OP *attrs;
5669
5670     switch (PL_expect) {
5671     case XOPERATOR:
5672         if (!PL_in_my || (PL_lex_state != LEX_NORMAL && !PL_lex_brackets))
5673             break;
5674         PL_bufptr = s;  /* update in case we back off */
5675         if (*s == '=') {
5676             Perl_croak(aTHX_
5677                        "Use of := for an empty attribute list is not allowed");
5678         }
5679         goto grabattrs;
5680     case XATTRBLOCK:
5681         PL_expect = XBLOCK;
5682         goto grabattrs;
5683     case XATTRTERM:
5684         PL_expect = XTERMBLOCK;
5685      grabattrs:
5686         /* NB: as well as parsing normal attributes, we also end up
5687          * here if there is something looking like attributes
5688          * following a signature (which is illegal, but used to be
5689          * legal in 5.20..5.26). If the latter, we still parse the
5690          * attributes so that error messages(s) are less confusing,
5691          * but ignore them (parser->sig_seen).
5692          */
5693         s = skipspace(s);
5694         attrs = NULL;
5695         while (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5696             bool sig = PL_parser->sig_seen;
5697             I32 tmp;
5698             SV *sv;
5699             STRLEN len;
5700             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
5701             if (isLOWER(*s) && (tmp = keyword(PL_tokenbuf, len, 0))) {
5702                 if (tmp < 0) tmp = -tmp;
5703                 switch (tmp) {
5704                 case KEY_or:
5705                 case KEY_and:
5706                 case KEY_for:
5707                 case KEY_foreach:
5708                 case KEY_unless:
5709                 case KEY_if:
5710                 case KEY_while:
5711                 case KEY_until:
5712                     goto got_attrs;
5713                 default:
5714                     break;
5715                 }
5716             }
5717             sv = newSVpvn_flags(s, len, UTF ? SVf_UTF8 : 0);
5718             if (*d == '(') {
5719                 d = scan_str(d,TRUE,TRUE,FALSE,NULL);
5720                 if (!d) {
5721                     if (attrs)
5722                         op_free(attrs);
5723                     sv_free(sv);
5724                     Perl_croak(aTHX_ "Unterminated attribute parameter in attribute list");
5725                 }
5726                 COPLINE_SET_FROM_MULTI_END;
5727             }
5728             if (PL_lex_stuff) {
5729                 sv_catsv(sv, PL_lex_stuff);
5730                 attrs = op_append_elem(OP_LIST, attrs,
5731                                     newSVOP(OP_CONST, 0, sv));
5732                 SvREFCNT_dec_NN(PL_lex_stuff);
5733                 PL_lex_stuff = NULL;
5734             }
5735             else {
5736                 /* NOTE: any CV attrs applied here need to be part of
5737                    the CVf_BUILTIN_ATTRS define in cv.h! */
5738                 if (!PL_in_my && memEQs(SvPVX(sv), len, "lvalue")) {
5739                     sv_free(sv);
5740                     if (!sig)
5741                         CvLVALUE_on(PL_compcv);
5742                 }
5743                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "method")) {
5744                     sv_free(sv);
5745                     if (!sig)
5746                         CvMETHOD_on(PL_compcv);
5747                 }
5748                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "const")) {
5749                     sv_free(sv);
5750                     if (!sig) {
5751                         Perl_ck_warner_d(aTHX_
5752                             packWARN(WARN_EXPERIMENTAL__CONST_ATTR),
5753                            ":const is experimental"
5754                         );
5755                         CvANONCONST_on(PL_compcv);
5756                         if (!CvANON(PL_compcv))
5757                             yyerror(":const is not permitted on named "
5758                                     "subroutines");
5759                     }
5760                 }
5761                 /* After we've set the flags, it could be argued that
5762                    we don't need to do the attributes.pm-based setting
5763                    process, and shouldn't bother appending recognized
5764                    flags.  To experiment with that, uncomment the
5765                    following "else".  (Note that's already been
5766                    uncommented.  That keeps the above-applied built-in
5767                    attributes from being intercepted (and possibly
5768                    rejected) by a package's attribute routines, but is
5769                    justified by the performance win for the common case
5770                    of applying only built-in attributes.) */
5771                 else
5772                     attrs = op_append_elem(OP_LIST, attrs,
5773                                         newSVOP(OP_CONST, 0,
5774                                                 sv));
5775             }
5776             s = skipspace(d);
5777             if (*s == ':' && s[1] != ':')
5778                 s = skipspace(s+1);
5779             else if (s == d)
5780                 break;  /* require real whitespace or :'s */
5781             /* XXX losing whitespace on sequential attributes here */
5782         }
5783
5784         if (*s != ';'
5785             && *s != '}'
5786             && !(PL_expect == XOPERATOR
5787                  ? (*s == '=' ||  *s == ')')
5788                  : (*s == '{' ||  *s == '(')))
5789         {
5790             const char q = ((*s == '\'') ? '"' : '\'');
5791             /* If here for an expression, and parsed no attrs, back off. */
5792             if (PL_expect == XOPERATOR && !attrs) {
5793                 s = PL_bufptr;
5794                 break;
5795             }
5796             /* MUST advance bufptr here to avoid bogus "at end of line"
5797                context messages from yyerror().
5798             */
5799             PL_bufptr = s;
5800             yyerror( (const char *)
5801                      (*s
5802                       ? Perl_form(aTHX_ "Invalid separator character "
5803                                   "%c%c%c in attribute list", q, *s, q)
5804                       : "Unterminated attribute list" ) );
5805             if (attrs)
5806                 op_free(attrs);
5807             OPERATOR(':');
5808         }
5809
5810     got_attrs:
5811         if (PL_parser->sig_seen) {
5812             /* see comment about about sig_seen and parser error
5813              * handling */
5814             if (attrs)
5815                 op_free(attrs);
5816             Perl_croak(aTHX_ "Subroutine attributes must come "
5817                              "before the signature");
5818         }
5819         if (attrs) {
5820             NEXTVAL_NEXTTOKE.opval = attrs;
5821             force_next(THING);
5822         }
5823         TOKEN(COLONATTR);
5824     }
5825
5826     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING) {
5827         s--;
5828         TOKEN(0);
5829     }
5830
5831     PL_lex_allbrackets--;
5832     OPERATOR(':');
5833 }
5834
5835 static int
5836 yyl_subproto(pTHX_ char *s, CV *cv)
5837 {
5838     STRLEN protolen = CvPROTOLEN(cv);
5839     const char *proto = CvPROTO(cv);
5840     bool optional;
5841
5842     proto = S_strip_spaces(aTHX_ proto, &protolen);
5843     if (!protolen)
5844         TERM(FUNC0SUB);
5845     if ((optional = *proto == ';')) {
5846         do {
5847             proto++;
5848         } while (*proto == ';');
5849     }
5850
5851     if (
5852         (
5853             (
5854                 *proto == '$' || *proto == '_'
5855              || *proto == '*' || *proto == '+'
5856             )
5857          && proto[1] == '\0'
5858         )
5859      || (
5860          *proto == '\\' && proto[1] && proto[2] == '\0'
5861         )
5862     ) {
5863         UNIPROTO(UNIOPSUB,optional);
5864     }
5865
5866     if (*proto == '\\' && proto[1] == '[') {
5867         const char *p = proto + 2;
5868         while(*p && *p != ']')
5869             ++p;
5870         if(*p == ']' && !p[1])
5871             UNIPROTO(UNIOPSUB,optional);
5872     }
5873
5874     if (*proto == '&' && *s == '{') {
5875         if (PL_curstash)
5876             sv_setpvs(PL_subname, "__ANON__");
5877         else
5878             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5879         if (!PL_lex_allbrackets
5880             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
5881         {
5882             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
5883         }
5884         PREBLOCK(LSTOPSUB);
5885     }
5886
5887     return KEY_NULL;
5888 }
5889
5890 static int
5891 yyl_leftcurly(pTHX_ char *s, const U8 formbrack)
5892 {
5893     char *d;
5894     if (PL_lex_brackets > 100) {
5895         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
5896     }
5897
5898     switch (PL_expect) {
5899     case XTERM:
5900     case XTERMORDORDOR:
5901         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5902         PL_lex_allbrackets++;
5903         OPERATOR(HASHBRACK);
5904     case XOPERATOR:
5905         while (s < PL_bufend && SPACE_OR_TAB(*s))
5906             s++;
5907         d = s;
5908         PL_tokenbuf[0] = '\0';
5909         if (d < PL_bufend && *d == '-') {
5910             PL_tokenbuf[0] = '-';
5911             d++;
5912             while (d < PL_bufend && SPACE_OR_TAB(*d))
5913                 d++;
5914         }
5915         if (d < PL_bufend && isIDFIRST_lazy_if_safe(d, PL_bufend, UTF)) {
5916             STRLEN len;
5917             d = scan_word(d, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
5918                           FALSE, &len);
5919             while (d < PL_bufend && SPACE_OR_TAB(*d))
5920                 d++;
5921             if (*d == '}') {
5922                 const char minus = (PL_tokenbuf[0] == '-');
5923                 s = force_word(s + minus, BAREWORD, FALSE, TRUE);
5924                 if (minus)
5925                     force_next('-');
5926             }
5927         }
5928         /* FALLTHROUGH */
5929     case XATTRTERM:
5930     case XTERMBLOCK:
5931         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5932         PL_lex_allbrackets++;
5933         PL_expect = XSTATE;
5934         break;
5935     case XATTRBLOCK:
5936     case XBLOCK:
5937         PL_lex_brackstack[PL_lex_brackets++] = XSTATE;
5938         PL_lex_allbrackets++;
5939         PL_expect = XSTATE;
5940         break;
5941     case XBLOCKTERM:
5942         PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5943         PL_lex_allbrackets++;
5944         PL_expect = XSTATE;
5945         break;
5946     default: {
5947             const char *t;
5948             if (PL_oldoldbufptr == PL_last_lop)
5949                 PL_lex_brackstack[PL_lex_brackets++] = XTERM;
5950             else
5951                 PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
5952             PL_lex_allbrackets++;
5953             s = skipspace(s);
5954             if (*s == '}') {
5955                 if (PL_expect == XREF && PL_lex_state == LEX_INTERPNORMAL) {
5956                     PL_expect = XTERM;
5957                     /* This hack is to get the ${} in the message. */
5958                     PL_bufptr = s+1;
5959                     yyerror("syntax error");
5960                     break;
5961                 }
5962                 OPERATOR(HASHBRACK);
5963             }
5964             if (PL_expect == XREF && PL_oldoldbufptr != PL_last_lop) {
5965                 /* ${...} or @{...} etc., but not print {...}
5966                  * Skip the disambiguation and treat this as a block.
5967                  */
5968                 goto block_expectation;
5969             }
5970             /* This hack serves to disambiguate a pair of curlies
5971              * as being a block or an anon hash.  Normally, expectation
5972              * determines that, but in cases where we're not in a
5973              * position to expect anything in particular (like inside
5974              * eval"") we have to resolve the ambiguity.  This code
5975              * covers the case where the first term in the curlies is a
5976              * quoted string.  Most other cases need to be explicitly
5977              * disambiguated by prepending a "+" before the opening
5978              * curly in order to force resolution as an anon hash.
5979              *
5980              * XXX should probably propagate the outer expectation
5981              * into eval"" to rely less on this hack, but that could
5982              * potentially break current behavior of eval"".
5983              * GSAR 97-07-21
5984              */
5985             t = s;
5986             if (*s == '\'' || *s == '"' || *s == '`') {
5987                 /* common case: get past first string, handling escapes */
5988                 for (t++; t < PL_bufend && *t != *s;)
5989                     if (*t++ == '\\')
5990                         t++;
5991                 t++;
5992             }
5993             else if (*s == 'q') {
5994                 if (++t < PL_bufend
5995                     && (!isWORDCHAR(*t)
5996                         || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
5997                             && !isWORDCHAR(*t))))
5998                 {
5999                     /* skip q//-like construct */
6000                     const char *tmps;
6001                     char open, close, term;
6002                     I32 brackets = 1;
6003
6004                     while (t < PL_bufend && isSPACE(*t))
6005                         t++;
6006                     /* check for q => */
6007                     if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
6008                         OPERATOR(HASHBRACK);
6009                     }
6010                     term = *t;
6011                     open = term;
6012                     if (term && (tmps = memCHRs("([{< )]}> )]}>",term)))
6013                         term = tmps[5];
6014                     close = term;
6015                     if (open == close)
6016                         for (t++; t < PL_bufend; t++) {
6017                             if (*t == '\\' && t+1 < PL_bufend && open != '\\')
6018                                 t++;
6019                             else if (*t == open)
6020                                 break;
6021                         }
6022                     else {
6023                         for (t++; t < PL_bufend; t++) {
6024                             if (*t == '\\' && t+1 < PL_bufend)
6025                                 t++;
6026                             else if (*t == close && --brackets <= 0)
6027                                 break;
6028                             else if (*t == open)
6029                                 brackets++;
6030                         }
6031                     }
6032                     t++;
6033                 }
6034                 else
6035                     /* skip plain q word */
6036                     while (   t < PL_bufend
6037                            && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6038                     {
6039                         t += UTF ? UTF8SKIP(t) : 1;
6040                     }
6041             }
6042             else if (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)) {
6043                 t += UTF ? UTF8SKIP(t) : 1;
6044                 while (   t < PL_bufend
6045                        && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6046                 {
6047                     t += UTF ? UTF8SKIP(t) : 1;
6048                 }
6049             }
6050             while (t < PL_bufend && isSPACE(*t))
6051                 t++;
6052             /* if comma follows first term, call it an anon hash */
6053             /* XXX it could be a comma expression with loop modifiers */
6054             if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
6055                                || (*t == '=' && t[1] == '>')))
6056                 OPERATOR(HASHBRACK);
6057             if (PL_expect == XREF) {
6058               block_expectation:
6059                 /* If there is an opening brace or 'sub:', treat it
6060                    as a term to make ${{...}}{k} and &{sub:attr...}
6061                    dwim.  Otherwise, treat it as a statement, so
6062                    map {no strict; ...} works.
6063                  */
6064                 s = skipspace(s);
6065                 if (*s == '{') {
6066                     PL_expect = XTERM;
6067                     break;
6068                 }
6069                 if (memBEGINs(s, (STRLEN) (PL_bufend - s), "sub")) {
6070                     PL_bufptr = s;
6071                     d = s + 3;
6072                     d = skipspace(d);
6073                     s = PL_bufptr;
6074                     if (*d == ':') {
6075                         PL_expect = XTERM;
6076                         break;
6077                     }
6078                 }
6079                 PL_expect = XSTATE;
6080             }
6081             else {
6082                 PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
6083                 PL_expect = XSTATE;
6084             }
6085         }
6086         break;
6087     }
6088
6089     pl_yylval.ival = CopLINE(PL_curcop);
6090     PL_copline = NOLINE;   /* invalidate current command line number */
6091     TOKEN(formbrack ? '=' : '{');
6092 }
6093
6094 static int
6095 yyl_rightcurly(pTHX_ char *s, const U8 formbrack)
6096 {
6097     assert(s != PL_bufend);
6098     s++;
6099
6100     if (PL_lex_brackets <= 0)
6101         /* diag_listed_as: Unmatched right %s bracket */
6102         yyerror("Unmatched right curly bracket");
6103     else
6104         PL_expect = (expectation)PL_lex_brackstack[--PL_lex_brackets];
6105
6106     PL_lex_allbrackets--;
6107
6108     if (PL_lex_state == LEX_INTERPNORMAL) {
6109         if (PL_lex_brackets == 0) {
6110             if (PL_expect & XFAKEBRACK) {
6111                 PL_expect &= XENUMMASK;
6112                 PL_lex_state = LEX_INTERPEND;
6113                 PL_bufptr = s;
6114                 return yylex(); /* ignore fake brackets */
6115             }
6116             if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6117              && SvEVALED(PL_lex_repl))
6118                 PL_lex_state = LEX_INTERPEND;
6119             else if (*s == '-' && s[1] == '>')
6120                 PL_lex_state = LEX_INTERPENDMAYBE;
6121             else if (*s != '[' && *s != '{')
6122                 PL_lex_state = LEX_INTERPEND;
6123         }
6124     }
6125
6126     if (PL_expect & XFAKEBRACK) {
6127         PL_expect &= XENUMMASK;
6128         PL_bufptr = s;
6129         return yylex();         /* ignore fake brackets */
6130     }
6131
6132     force_next(formbrack ? '.' : '}');
6133     if (formbrack) LEAVE_with_name("lex_format");
6134     if (formbrack == 2) { /* means . where arguments were expected */
6135         force_next(';');
6136         TOKEN(FORMRBRACK);
6137     }
6138
6139     TOKEN(';');
6140 }
6141
6142 static int
6143 yyl_ampersand(pTHX_ char *s)
6144 {
6145     if (PL_expect == XPOSTDEREF)
6146         POSTDEREF('&');
6147
6148     s++;
6149     if (*s++ == '&') {
6150         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6151                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6152             s -= 2;
6153             TOKEN(0);
6154         }
6155         AOPERATOR(ANDAND);
6156     }
6157     s--;
6158
6159     if (PL_expect == XOPERATOR) {
6160         char *d;
6161         bool bof;
6162         if (   PL_bufptr == PL_linestart
6163             && ckWARN(WARN_SEMICOLON)
6164             && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
6165         {
6166             CopLINE_dec(PL_curcop);
6167             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6168             CopLINE_inc(PL_curcop);
6169         }
6170         d = s;
6171         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6172             s++;
6173         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6174                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6175             s = d;
6176             s--;
6177             TOKEN(0);
6178         }
6179         if (d == s)
6180             BAop(bof ? OP_NBIT_AND : OP_BIT_AND);
6181         else
6182             BAop(OP_SBIT_AND);
6183     }
6184
6185     PL_tokenbuf[0] = '&';
6186     s = scan_ident(s - 1, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, TRUE);
6187     pl_yylval.ival = (OPpENTERSUB_AMPER<<8);
6188
6189     if (PL_tokenbuf[1])
6190         force_ident_maybe_lex('&');
6191     else
6192         PREREF('&');
6193
6194     TERM('&');
6195 }
6196
6197 static int
6198 yyl_verticalbar(pTHX_ char *s)
6199 {
6200     char *d;
6201     bool bof;
6202
6203     s++;
6204     if (*s++ == '|') {
6205         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6206                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6207             s -= 2;
6208             TOKEN(0);
6209         }
6210         AOPERATOR(OROR);
6211     }
6212
6213     s--;
6214     d = s;
6215     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6216         s++;
6217
6218     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6219             (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6220         s = d - 1;
6221         TOKEN(0);
6222     }
6223
6224     BOop(bof ? s == d ? OP_NBIT_OR : OP_SBIT_OR : OP_BIT_OR);
6225 }
6226
6227 static int
6228 yyl_bang(pTHX_ char *s)
6229 {
6230     const char tmp = *s++;
6231     if (tmp == '=') {
6232         /* was this !=~ where !~ was meant?
6233          * warn on m:!=~\s+([/?]|[msy]\W|tr\W): */
6234
6235         if (*s == '~' && ckWARN(WARN_SYNTAX)) {
6236             const char *t = s+1;
6237
6238             while (t < PL_bufend && isSPACE(*t))
6239                 ++t;
6240
6241             if (*t == '/' || *t == '?'
6242                 || ((*t == 'm' || *t == 's' || *t == 'y')
6243                     && !isWORDCHAR(t[1]))
6244                 || (*t == 't' && t[1] == 'r' && !isWORDCHAR(t[2])))
6245                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6246                             "!=~ should be !~");
6247         }
6248
6249         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6250             s -= 2;
6251             TOKEN(0);
6252         }
6253
6254         Eop(OP_NE);
6255     }
6256
6257     if (tmp == '~')
6258         PMop(OP_NOT);
6259
6260     s--;
6261     OPERATOR('!');
6262 }
6263
6264 static int
6265 yyl_snail(pTHX_ char *s)
6266 {
6267     if (PL_expect == XPOSTDEREF)
6268         POSTDEREF('@');
6269     PL_tokenbuf[0] = '@';
6270     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6271     if (PL_expect == XOPERATOR) {
6272         char *d = s;
6273         if (PL_bufptr > s) {
6274             d = PL_bufptr-1;
6275             PL_bufptr = PL_oldbufptr;
6276         }
6277         no_op("Array", d);
6278     }
6279     pl_yylval.ival = 0;
6280     if (!PL_tokenbuf[1]) {
6281         PREREF('@');
6282     }
6283     if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
6284         s = skipspace(s);
6285     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6286         && intuit_more(s, PL_bufend))
6287     {
6288         if (*s == '{')
6289             PL_tokenbuf[0] = '%';
6290
6291         /* Warn about @ where they meant $. */
6292         if (*s == '[' || *s == '{') {
6293             if (ckWARN(WARN_SYNTAX)) {
6294                 S_check_scalar_slice(aTHX_ s);
6295             }
6296         }
6297     }
6298     PL_expect = XOPERATOR;
6299     force_ident_maybe_lex('@');
6300     TERM('@');
6301 }
6302
6303 static int
6304 yyl_slash(pTHX_ char *s)
6305 {
6306     if ((PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR) && s[1] == '/') {
6307         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6308                 (s[2] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC))
6309             TOKEN(0);
6310         s += 2;
6311         AOPERATOR(DORDOR);
6312     }
6313     else if (PL_expect == XOPERATOR) {
6314         s++;
6315         if (*s == '=' && !PL_lex_allbrackets
6316             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6317         {
6318             s--;
6319             TOKEN(0);
6320         }
6321         Mop(OP_DIVIDE);
6322     }
6323     else {
6324         /* Disable warning on "study /blah/" */
6325         if (    PL_oldoldbufptr == PL_last_uni
6326             && (   *PL_last_uni != 's' || s - PL_last_uni < 5
6327                 || memNE(PL_last_uni, "study", 5)
6328                 || isWORDCHAR_lazy_if_safe(PL_last_uni+5, PL_bufend, UTF)
6329          ))
6330             check_uni();
6331         s = scan_pat(s,OP_MATCH);
6332         TERM(sublex_start());
6333     }
6334 }
6335
6336 static int
6337 yyl_leftsquare(pTHX_ char *s)
6338 {
6339     char tmp;
6340
6341     if (PL_lex_brackets > 100)
6342         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
6343     PL_lex_brackstack[PL_lex_brackets++] = 0;
6344     PL_lex_allbrackets++;
6345     tmp = *s++;
6346     OPERATOR(tmp);
6347 }
6348
6349 static int
6350 yyl_rightsquare(pTHX_ char *s)
6351 {
6352     if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
6353         TOKEN(0);
6354     s++;
6355     if (PL_lex_brackets <= 0)
6356         /* diag_listed_as: Unmatched right %s bracket */
6357         yyerror("Unmatched right square bracket");
6358     else
6359         --PL_lex_brackets;
6360     PL_lex_allbrackets--;
6361     if (PL_lex_state == LEX_INTERPNORMAL) {
6362         if (PL_lex_brackets == 0) {
6363             if (*s == '-' && s[1] == '>')
6364                 PL_lex_state = LEX_INTERPENDMAYBE;
6365             else if (*s != '[' && *s != '{')
6366                 PL_lex_state = LEX_INTERPEND;
6367         }
6368     }
6369     TERM(']');
6370 }
6371
6372 static int
6373 yyl_tilde(pTHX_ char *s)
6374 {
6375     bool bof;
6376     if (s[1] == '~' && (PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR)) {
6377         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6378             TOKEN(0);
6379         s += 2;
6380         Perl_ck_warner_d(aTHX_
6381             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
6382             "Smartmatch is experimental");
6383         Eop(OP_SMARTMATCH);
6384     }
6385     s++;
6386     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.') {
6387         s++;
6388         BCop(OP_SCOMPLEMENT);
6389     }
6390     BCop(bof ? OP_NCOMPLEMENT : OP_COMPLEMENT);
6391 }
6392
6393 static int
6394 yyl_leftparen(pTHX_ char *s)
6395 {
6396     if (PL_last_lop == PL_oldoldbufptr || PL_last_uni == PL_oldoldbufptr)
6397         PL_oldbufptr = PL_oldoldbufptr;         /* allow print(STDOUT 123) */
6398     else
6399         PL_expect = XTERM;
6400     s = skipspace(s);
6401     PL_lex_allbrackets++;
6402     TOKEN('(');
6403 }
6404
6405 static int
6406 yyl_rightparen(pTHX_ char *s)
6407 {
6408     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING)
6409         TOKEN(0);
6410     s++;
6411     PL_lex_allbrackets--;
6412     s = skipspace(s);
6413     if (*s == '{')
6414         PREBLOCK(')');
6415     TERM(')');
6416 }
6417
6418 static int
6419 yyl_leftpointy(pTHX_ char *s)
6420 {
6421     char tmp;
6422
6423     if (PL_expect != XOPERATOR) {
6424         if (s[1] != '<' && !memchr(s,'>', PL_bufend - s))
6425             check_uni();
6426         if (s[1] == '<' && s[2] != '>')
6427             s = scan_heredoc(s);
6428         else
6429             s = scan_inputsymbol(s);
6430         PL_expect = XOPERATOR;
6431         TOKEN(sublex_start());
6432     }
6433
6434     s++;
6435
6436     tmp = *s++;
6437     if (tmp == '<') {
6438         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6439             s -= 2;
6440             TOKEN(0);
6441         }
6442         SHop(OP_LEFT_SHIFT);
6443     }
6444     if (tmp == '=') {
6445         tmp = *s++;
6446         if (tmp == '>') {
6447             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6448                 s -= 3;
6449                 TOKEN(0);
6450             }
6451             Eop(OP_NCMP);
6452         }
6453         s--;
6454         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6455             s -= 2;
6456             TOKEN(0);
6457         }
6458         Rop(OP_LE);
6459     }
6460
6461     s--;
6462     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6463         s--;
6464         TOKEN(0);
6465     }
6466
6467     Rop(OP_LT);
6468 }
6469
6470 static int
6471 yyl_rightpointy(pTHX_ char *s)
6472 {
6473     const char tmp = *s++;
6474
6475     if (tmp == '>') {
6476         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6477             s -= 2;
6478             TOKEN(0);
6479         }
6480         SHop(OP_RIGHT_SHIFT);
6481     }
6482     else if (tmp == '=') {
6483         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6484             s -= 2;
6485             TOKEN(0);
6486         }
6487         Rop(OP_GE);
6488     }
6489
6490     s--;
6491     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6492         s--;
6493         TOKEN(0);
6494     }
6495
6496     Rop(OP_GT);
6497 }
6498
6499 static int
6500 yyl_sglquote(pTHX_ char *s)
6501 {
6502     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6503     if (!s)
6504         missingterm(NULL, 0);
6505     COPLINE_SET_FROM_MULTI_END;
6506     DEBUG_T( { printbuf("### Saw string before %s\n", s); } );
6507     if (PL_expect == XOPERATOR) {
6508         no_op("String",s);
6509     }
6510     pl_yylval.ival = OP_CONST;
6511     TERM(sublex_start());
6512 }
6513
6514 static int
6515 yyl_dblquote(pTHX_ char *s, STRLEN len)
6516 {
6517     char *d;
6518     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6519     DEBUG_T( {
6520         if (s)
6521             printbuf("### Saw string before %s\n", s);
6522         else
6523             PerlIO_printf(Perl_debug_log,
6524                          "### Saw unterminated string\n");
6525     } );
6526     if (PL_expect == XOPERATOR) {
6527             no_op("String",s);
6528     }
6529     if (!s)
6530         missingterm(NULL, 0);
6531     pl_yylval.ival = OP_CONST;
6532     /* FIXME. I think that this can be const if char *d is replaced by
6533        more localised variables.  */
6534     for (d = SvPV(PL_lex_stuff, len); len; len--, d++) {
6535         if (*d == '$' || *d == '@' || *d == '\\' || !UTF8_IS_INVARIANT((U8)*d)) {
6536             pl_yylval.ival = OP_STRINGIFY;
6537             break;
6538         }
6539     }
6540     if (pl_yylval.ival == OP_CONST)
6541         COPLINE_SET_FROM_MULTI_END;
6542     TERM(sublex_start());
6543 }
6544
6545 static int
6546 yyl_backtick(pTHX_ char *s)
6547 {
6548     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6549     DEBUG_T( {
6550         if (s)
6551             printbuf("### Saw backtick string before %s\n", s);
6552         else
6553             PerlIO_printf(Perl_debug_log,
6554                          "### Saw unterminated backtick string\n");
6555     } );
6556     if (PL_expect == XOPERATOR)
6557         no_op("Backticks",s);
6558     if (!s)
6559         missingterm(NULL, 0);
6560     pl_yylval.ival = OP_BACKTICK;
6561     TERM(sublex_start());
6562 }
6563
6564 static int
6565 yyl_backslash(pTHX_ char *s)
6566 {
6567     if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr && isDIGIT(*s))
6568         Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),"Can't use \\%c to mean $%c in expression",
6569                        *s, *s);
6570     if (PL_expect == XOPERATOR)
6571         no_op("Backslash",s);
6572     OPERATOR(REFGEN);
6573 }
6574
6575 static void
6576 yyl_data_handle(pTHX)
6577 {
6578     HV * const stash = PL_tokenbuf[2] == 'D' && PL_curstash
6579                             ? PL_curstash
6580                             : PL_defstash;
6581     GV *gv = (GV *)*hv_fetchs(stash, "DATA", 1);
6582
6583     if (!isGV(gv))
6584         gv_init(gv,stash,"DATA",4,0);
6585
6586     GvMULTI_on(gv);
6587     if (!GvIO(gv))
6588         GvIOp(gv) = newIO();
6589     IoIFP(GvIOp(gv)) = PL_rsfp;
6590
6591     /* Mark this internal pseudo-handle as clean */
6592     IoFLAGS(GvIOp(gv)) |= IOf_UNTAINT;
6593     if ((PerlIO*)PL_rsfp == PerlIO_stdin())
6594         IoTYPE(GvIOp(gv)) = IoTYPE_STD;
6595     else
6596         IoTYPE(GvIOp(gv)) = IoTYPE_RDONLY;
6597
6598 #if defined(WIN32) && !defined(PERL_TEXTMODE_SCRIPTS)
6599     /* if the script was opened in binmode, we need to revert
6600      * it to text mode for compatibility; but only iff it has CRs
6601      * XXX this is a questionable hack at best. */
6602     if (PL_bufend-PL_bufptr > 2
6603         && PL_bufend[-1] == '\n' && PL_bufend[-2] == '\r')
6604     {
6605         Off_t loc = 0;
6606         if (IoTYPE(GvIOp(gv)) == IoTYPE_RDONLY) {
6607             loc = PerlIO_tell(PL_rsfp);
6608             (void)PerlIO_seek(PL_rsfp, 0L, 0);
6609         }
6610         if (PerlLIO_setmode(RSFP_FILENO, O_TEXT) != -1) {
6611             if (loc > 0)
6612                 PerlIO_seek(PL_rsfp, loc, 0);
6613         }
6614     }
6615 #endif
6616
6617 #ifdef PERLIO_LAYERS
6618     if (!IN_BYTES) {
6619         if (UTF)
6620             PerlIO_apply_layers(aTHX_ PL_rsfp, NULL, ":utf8");
6621     }
6622 #endif
6623
6624     PL_rsfp = NULL;
6625 }
6626
6627 PERL_STATIC_NO_RET void yyl_croak_unrecognised(pTHX_ char*)
6628     __attribute__noreturn__;
6629
6630 PERL_STATIC_NO_RET void
6631 yyl_croak_unrecognised(pTHX_ char *s)
6632 {
6633     SV *dsv = newSVpvs_flags("", SVs_TEMP);
6634     const char *c;
6635     char *d;
6636     STRLEN len;
6637
6638     if (UTF) {
6639         STRLEN skiplen = UTF8SKIP(s);
6640         STRLEN stravail = PL_bufend - s;
6641         c = sv_uni_display(dsv, newSVpvn_flags(s,
6642                                                skiplen > stravail ? stravail : skiplen,
6643                                                SVs_TEMP | SVf_UTF8),
6644                            10, UNI_DISPLAY_ISPRINT);
6645     }
6646     else {
6647         c = Perl_form(aTHX_ "\\x%02X", (unsigned char)*s);
6648     }
6649
6650     if (s >= PL_linestart) {
6651         d = PL_linestart;
6652     }
6653     else {
6654         /* somehow (probably due to a parse failure), PL_linestart has advanced
6655          * pass PL_bufptr, get a reasonable beginning of line
6656          */
6657         d = s;
6658         while (d > SvPVX(PL_linestr) && d[-1] && d[-1] != '\n')
6659             --d;
6660     }
6661     len = UTF ? Perl_utf8_length(aTHX_ (U8 *) d, (U8 *) s) : (STRLEN) (s - d);
6662     if (len > UNRECOGNIZED_PRECEDE_COUNT) {
6663         d = UTF ? (char *) utf8_hop_back((U8 *) s, -UNRECOGNIZED_PRECEDE_COUNT, (U8 *)d) : s - UNRECOGNIZED_PRECEDE_COUNT;
6664     }
6665
6666     Perl_croak(aTHX_  "Unrecognized character %s; marked by <-- HERE after %" UTF8f "<-- HERE near column %d", c,
6667                       UTF8fARG(UTF, (s - d), d),
6668                      (int) len + 1);
6669 }
6670
6671 static int
6672 yyl_require(pTHX_ char *s, I32 orig_keyword)
6673 {
6674     s = skipspace(s);
6675     if (isDIGIT(*s)) {
6676         s = force_version(s, FALSE);
6677     }
6678     else if (*s != 'v' || !isDIGIT(s[1])
6679             || (s = force_version(s, TRUE), *s == 'v'))
6680     {
6681         *PL_tokenbuf = '\0';
6682         s = force_word(s,BAREWORD,TRUE,TRUE);
6683         if (isIDFIRST_lazy_if_safe(PL_tokenbuf,
6684                                    PL_tokenbuf + sizeof(PL_tokenbuf),
6685                                    UTF))
6686         {
6687             gv_stashpvn(PL_tokenbuf, strlen(PL_tokenbuf),
6688                         GV_ADD | (UTF ? SVf_UTF8 : 0));
6689         }
6690         else if (*s == '<')
6691             yyerror("<> at require-statement should be quotes");
6692     }
6693
6694     if (orig_keyword == KEY_require)
6695         pl_yylval.ival = 1;
6696     else
6697         pl_yylval.ival = 0;
6698
6699     PL_expect = PL_nexttoke ? XOPERATOR : XTERM;
6700     PL_bufptr = s;
6701     PL_last_uni = PL_oldbufptr;
6702     PL_last_lop_op = OP_REQUIRE;
6703     s = skipspace(s);
6704     return REPORT( (int)REQUIRE );
6705 }
6706
6707 static int
6708 yyl_foreach(pTHX_ char *s)
6709 {
6710     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
6711         return REPORT(0);
6712     pl_yylval.ival = CopLINE(PL_curcop);
6713     s = skipspace(s);
6714     if (PL_expect == XSTATE && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6715         char *p = s;
6716         SSize_t s_off = s - SvPVX(PL_linestr);
6717         STRLEN len;
6718
6719         if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "my") && isSPACE(p[2])) {
6720             p += 2;
6721         }
6722         else if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "our") && isSPACE(p[3])) {
6723             p += 3;
6724         }
6725
6726         p = skipspace(p);
6727         /* skip optional package name, as in "for my abc $x (..)" */
6728         if (isIDFIRST_lazy_if_safe(p, PL_bufend, UTF)) {
6729             p = scan_word(p, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6730             p = skipspace(p);
6731         }
6732         if (*p != '$' && *p != '\\')
6733             Perl_croak(aTHX_ "Missing $ on loop variable");
6734
6735         /* The buffer may have been reallocated, update s */
6736         s = SvPVX(PL_linestr) + s_off;
6737     }
6738     OPERATOR(FOR);
6739 }
6740
6741 static int
6742 yyl_do(pTHX_ char *s, I32 orig_keyword)
6743 {
6744     s = skipspace(s);
6745     if (*s == '{')
6746         PRETERMBLOCK(DO);
6747     if (*s != '\'') {
6748         char *d;
6749         STRLEN len;
6750         *PL_tokenbuf = '&';
6751         d = scan_word(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
6752                       1, &len);
6753         if (len && memNEs(PL_tokenbuf+1, len, "CORE")
6754          && !keyword(PL_tokenbuf + 1, len, 0)) {
6755             SSize_t off = s-SvPVX(PL_linestr);
6756             d = skipspace(d);
6757             s = SvPVX(PL_linestr)+off;
6758             if (*d == '(') {
6759                 force_ident_maybe_lex('&');
6760                 s = d;
6761             }
6762         }
6763     }
6764     if (orig_keyword == KEY_do)
6765         pl_yylval.ival = 1;
6766     else
6767         pl_yylval.ival = 0;
6768     OPERATOR(DO);
6769 }
6770
6771 static int
6772 yyl_my(pTHX_ char *s, I32 my)
6773 {
6774     if (PL_in_my) {
6775         PL_bufptr = s;
6776         yyerror(Perl_form(aTHX_
6777                           "Can't redeclare \"%s\" in \"%s\"",
6778                            my       == KEY_my    ? "my" :
6779                            my       == KEY_state ? "state" : "our",
6780                            PL_in_my == KEY_my    ? "my" :
6781                            PL_in_my == KEY_state ? "state" : "our"));
6782     }
6783     PL_in_my = (U16)my;
6784     s = skipspace(s);
6785     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6786         STRLEN len;
6787         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6788         if (memEQs(PL_tokenbuf, len, "sub"))
6789             return yyl_sub(aTHX_ s, my);
6790         PL_in_my_stash = find_in_my_stash(PL_tokenbuf, len);
6791         if (!PL_in_my_stash) {
6792             char tmpbuf[1024];
6793             int i;
6794             PL_bufptr = s;
6795             i = my_snprintf(tmpbuf, sizeof(tmpbuf), "No such class %.1000s", PL_tokenbuf);
6796             PERL_MY_SNPRINTF_POST_GUARD(i, sizeof(tmpbuf));
6797             yyerror_pv(tmpbuf, UTF ? SVf_UTF8 : 0);
6798         }
6799     }
6800     else if (*s == '\\') {
6801         if (!FEATURE_MYREF_IS_ENABLED)
6802             Perl_croak(aTHX_ "The experimental declared_refs "
6803                              "feature is not enabled");
6804         Perl_ck_warner_d(aTHX_
6805              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
6806             "Declaring references is experimental");
6807     }
6808     OPERATOR(MY);
6809 }
6810
6811 static int yyl_try(pTHX_ char*, STRLEN);
6812
6813 static bool
6814 yyl_eol_needs_semicolon(pTHX_ char **ps)
6815 {
6816     char *s = *ps;
6817     if (PL_lex_state != LEX_NORMAL
6818         || (PL_in_eval && !PL_rsfp && !PL_parser->filtered))
6819     {
6820         const bool in_comment = *s == '#';
6821         char *d;
6822         if (*s == '#' && s == PL_linestart && PL_in_eval
6823          && !PL_rsfp && !PL_parser->filtered) {
6824             /* handle eval qq[#line 1 "foo"\n ...] */
6825             CopLINE_dec(PL_curcop);
6826             incline(s, PL_bufend);
6827         }
6828         d = s;
6829         while (d < PL_bufend && *d != '\n')
6830             d++;
6831         if (d < PL_bufend)
6832             d++;
6833         s = d;
6834         if (in_comment && d == PL_bufend
6835             && PL_lex_state == LEX_INTERPNORMAL
6836             && PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6837             && SvEVALED(PL_lex_repl) && d[-1] == '}') s--;
6838         else
6839             incline(s, PL_bufend);
6840         if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
6841             PL_lex_state = LEX_FORMLINE;
6842             force_next(FORMRBRACK);
6843             *ps = s;
6844             return TRUE;
6845         }
6846     }
6847     else {
6848         while (s < PL_bufend && *s != '\n')
6849             s++;
6850         if (s < PL_bufend) {
6851             s++;
6852             if (s < PL_bufend)
6853                 incline(s, PL_bufend);
6854         }
6855     }
6856     *ps = s;
6857     return FALSE;
6858 }
6859
6860 static int
6861 yyl_fake_eof(pTHX_ U32 fake_eof, bool bof, char *s, STRLEN len)
6862 {
6863     char *d;
6864
6865     goto start;
6866
6867     do {
6868         fake_eof = 0;
6869         bof = cBOOL(PL_rsfp);
6870       start:
6871
6872         PL_bufptr = PL_bufend;
6873         COPLINE_INC_WITH_HERELINES;
6874         if (!lex_next_chunk(fake_eof)) {
6875             CopLINE_dec(PL_curcop);
6876             s = PL_bufptr;
6877             TOKEN(';'); /* not infinite loop because rsfp is NULL now */
6878         }
6879         CopLINE_dec(PL_curcop);
6880         s = PL_bufptr;
6881         /* If it looks like the start of a BOM or raw UTF-16,
6882          * check if it in fact is. */
6883         if (bof && PL_rsfp
6884             && (   *s == 0
6885                 || *(U8*)s == BOM_UTF8_FIRST_BYTE
6886                 || *(U8*)s >= 0xFE
6887                 || s[1] == 0))
6888         {
6889             Off_t offset = (IV)PerlIO_tell(PL_rsfp);
6890             bof = (offset == (Off_t)SvCUR(PL_linestr));
6891 #if defined(PERLIO_USING_CRLF) && defined(PERL_TEXTMODE_SCRIPTS)
6892             /* offset may include swallowed CR */
6893             if (!bof)
6894                 bof = (offset == (Off_t)SvCUR(PL_linestr)+1);
6895 #endif
6896             if (bof) {
6897                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6898                 s = swallow_bom((U8*)s);
6899             }
6900         }
6901         if (PL_parser->in_pod) {
6902             /* Incest with pod. */
6903             if (    memBEGINPs(s, (STRLEN) (PL_bufend - s), "=cut")
6904                 && !isALPHA(s[4]))
6905             {
6906                 SvPVCLEAR(PL_linestr);
6907                 PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
6908                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6909                 PL_last_lop = PL_last_uni = NULL;
6910                 PL_parser->in_pod = 0;
6911             }
6912         }
6913         if (PL_rsfp || PL_parser->filtered)
6914             incline(s, PL_bufend);
6915     } while (PL_parser->in_pod);
6916
6917     PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = PL_linestart = s;
6918     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
6919     PL_last_lop = PL_last_uni = NULL;
6920     if (CopLINE(PL_curcop) == 1) {
6921         while (s < PL_bufend && isSPACE(*s))
6922             s++;
6923         if (*s == ':' && s[1] != ':') /* for csh execing sh scripts */
6924             s++;
6925         d = NULL;
6926         if (!PL_in_eval) {
6927             if (*s == '#' && *(s+1) == '!')
6928                 d = s + 2;
6929 #ifdef ALTERNATE_SHEBANG
6930             else {
6931                 static char const as[] = ALTERNATE_SHEBANG;
6932                 if (*s == as[0] && strnEQ(s, as, sizeof(as) - 1))
6933                     d = s + (sizeof(as) - 1);
6934             }
6935 #endif /* ALTERNATE_SHEBANG */
6936         }
6937         if (d) {
6938             char *ipath;
6939             char *ipathend;
6940
6941             while (isSPACE(*d))
6942                 d++;
6943             ipath = d;
6944             while (*d && !isSPACE(*d))
6945                 d++;
6946             ipathend = d;
6947
6948 #ifdef ARG_ZERO_IS_SCRIPT
6949             if (ipathend > ipath) {
6950                 /*
6951                  * HP-UX (at least) sets argv[0] to the script name,
6952                  * which makes $^X incorrect.  And Digital UNIX and Linux,
6953                  * at least, set argv[0] to the basename of the Perl
6954                  * interpreter. So, having found "#!", we'll set it right.
6955                  */
6956                 SV* copfilesv = CopFILESV(PL_curcop);
6957                 if (copfilesv) {
6958                     SV * const x =
6959                         GvSV(gv_fetchpvs("\030", GV_ADD|GV_NOTQUAL,
6960                                          SVt_PV)); /* $^X */
6961                     assert(SvPOK(x) || SvGMAGICAL(x));
6962                     if (sv_eq(x, copfilesv)) {
6963                         sv_setpvn(x, ipath, ipathend - ipath);
6964                         SvSETMAGIC(x);
6965                     }
6966                     else {
6967                         STRLEN blen;
6968                         STRLEN llen;
6969                         const char *bstart = SvPV_const(copfilesv, blen);
6970                         const char * const lstart = SvPV_const(x, llen);
6971                         if (llen < blen) {
6972                             bstart += blen - llen;
6973                             if (strnEQ(bstart, lstart, llen) && bstart[-1] == '/') {
6974                                 sv_setpvn(x, ipath, ipathend - ipath);
6975                                 SvSETMAGIC(x);
6976                             }
6977                         }
6978                     }
6979                 }
6980                 else {
6981                     /* Anything to do if no copfilesv? */
6982                 }
6983                 TAINT_NOT;      /* $^X is always tainted, but that's OK */
6984             }
6985 #endif /* ARG_ZERO_IS_SCRIPT */
6986
6987             /*
6988              * Look for options.
6989              */
6990             d = instr(s,"perl -");
6991             if (!d) {
6992                 d = instr(s,"perl");
6993 #if defined(DOSISH)
6994                 /* avoid getting into infinite loops when shebang
6995                  * line contains "Perl" rather than "perl" */
6996                 if (!d) {
6997                     for (d = ipathend-4; d >= ipath; --d) {
6998                         if (isALPHA_FOLD_EQ(*d, 'p')
6999                             && !ibcmp(d, "perl", 4))
7000                         {
7001                             break;
7002                         }
7003                     }
7004                     if (d < ipath)
7005                         d = NULL;
7006                 }
7007 #endif
7008             }
7009 #ifdef ALTERNATE_SHEBANG
7010             /*
7011              * If the ALTERNATE_SHEBANG on this system starts with a
7012              * character that can be part of a Perl expression, then if
7013              * we see it but not "perl", we're probably looking at the
7014              * start of Perl code, not a request to hand off to some
7015              * other interpreter.  Similarly, if "perl" is there, but
7016              * not in the first 'word' of the line, we assume the line
7017              * contains the start of the Perl program.
7018              */
7019             if (d && *s != '#') {
7020                 const char *c = ipath;
7021                 while (*c && !memCHRs("; \t\r\n\f\v#", *c))
7022                     c++;
7023                 if (c < d)
7024                     d = NULL;   /* "perl" not in first word; ignore */
7025                 else
7026                     *s = '#';   /* Don't try to parse shebang line */
7027             }
7028 #endif /* ALTERNATE_SHEBANG */
7029             if (!d
7030                 && *s == '#'
7031                 && ipathend > ipath
7032                 && !PL_minus_c
7033                 && !instr(s,"indir")
7034                 && instr(PL_origargv[0],"perl"))
7035             {
7036                 dVAR;
7037                 char **newargv;
7038
7039                 *ipathend = '\0';
7040                 s = ipathend + 1;
7041                 while (s < PL_bufend && isSPACE(*s))
7042                     s++;
7043                 if (s < PL_bufend) {
7044                     Newx(newargv,PL_origargc+3,char*);
7045                     newargv[1] = s;
7046                     while (s < PL_bufend && !isSPACE(*s))
7047                         s++;
7048                     *s = '\0';
7049                     Copy(PL_origargv+1, newargv+2, PL_origargc+1, char*);
7050                 }
7051                 else
7052                     newargv = PL_origargv;
7053                 newargv[0] = ipath;
7054                 PERL_FPU_PRE_EXEC
7055                 PerlProc_execv(ipath, EXEC_ARGV_CAST(newargv));
7056                 PERL_FPU_POST_EXEC
7057                 Perl_croak(aTHX_ "Can't exec %s", ipath);
7058             }
7059             if (d) {
7060                 while (*d && !isSPACE(*d))
7061                     d++;
7062                 while (SPACE_OR_TAB(*d))
7063                     d++;
7064
7065                 if (*d++ == '-') {
7066                     const bool switches_done = PL_doswitches;
7067                     const U32 oldpdb = PL_perldb;
7068                     const bool oldn = PL_minus_n;
7069                     const bool oldp = PL_minus_p;
7070                     const char *d1 = d;
7071
7072                     do {
7073                         bool baduni = FALSE;
7074                         if (*d1 == 'C') {
7075                             const char *d2 = d1 + 1;
7076                             if (parse_unicode_opts((const char **)&d2)
7077                                 != PL_unicode)
7078                                 baduni = TRUE;
7079                         }
7080                         if (baduni || isALPHA_FOLD_EQ(*d1, 'M')) {
7081                             const char * const m = d1;
7082                             while (*d1 && !isSPACE(*d1))
7083                                 d1++;
7084                             Perl_croak(aTHX_ "Too late for \"-%.*s\" option",
7085                                   (int)(d1 - m), m);
7086                         }
7087                         d1 = moreswitches(d1);
7088                     } while (d1);
7089                     if (PL_doswitches && !switches_done) {
7090                         int argc = PL_origargc;
7091                         char **argv = PL_origargv;
7092                         do {
7093                             argc--,argv++;
7094                         } while (argc && argv[0][0] == '-' && argv[0][1]);
7095                         init_argv_symbols(argc,argv);
7096                     }
7097                     if (   (PERLDB_LINE_OR_SAVESRC && !oldpdb)
7098                         || ((PL_minus_n || PL_minus_p) && !(oldn || oldp)))
7099                           /* if we have already added "LINE: while (<>) {",
7100                              we must not do it again */
7101                     {
7102                         SvPVCLEAR(PL_linestr);
7103                         PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
7104                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7105                         PL_last_lop = PL_last_uni = NULL;
7106                         PL_preambled = FALSE;
7107                         if (PERLDB_LINE_OR_SAVESRC)
7108                             (void)gv_fetchfile(PL_origfilename);
7109                         return yyl_try(aTHX_ s, len);
7110                     }
7111                 }
7112             }
7113         }
7114     }
7115
7116     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
7117         PL_lex_state = LEX_FORMLINE;
7118         force_next(FORMRBRACK);
7119         TOKEN(';');
7120     }
7121
7122     return yyl_try(aTHX_ s, len);
7123 }
7124
7125 static int
7126 yyl_fatcomma(pTHX_ char *s, STRLEN len)
7127 {
7128     CLINE;
7129     pl_yylval.opval
7130         = newSVOP(OP_CONST, 0,
7131                        S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
7132     pl_yylval.opval->op_private = OPpCONST_BARE;
7133     TERM(BAREWORD);
7134 }
7135
7136 static int
7137 yyl_safe_bareword(pTHX_ char *s, const char lastchar)
7138 {
7139     if ((lastchar == '*' || lastchar == '%' || lastchar == '&')
7140         && PL_parser->saw_infix_sigil)
7141     {
7142         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7143                          "Operator or semicolon missing before %c%" UTF8f,
7144                          lastchar,
7145                          UTF8fARG(UTF, strlen(PL_tokenbuf),
7146                                   PL_tokenbuf));
7147         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7148                          "Ambiguous use of %c resolved as operator %c",
7149                          lastchar, lastchar);
7150     }
7151     TOKEN(BAREWORD);
7152 }
7153
7154 static int
7155 yyl_constant_op(pTHX_ char *s, SV *sv, CV *cv, OP *rv2cv_op, PADOFFSET off)
7156 {
7157     if (sv) {
7158         op_free(rv2cv_op);
7159         SvREFCNT_dec(((SVOP*)pl_yylval.opval)->op_sv);
7160         ((SVOP*)pl_yylval.opval)->op_sv = SvREFCNT_inc_simple(sv);
7161         if (SvTYPE(sv) == SVt_PVAV)
7162             pl_yylval.opval = newUNOP(OP_RV2AV, OPf_PARENS,
7163                                       pl_yylval.opval);
7164         else {
7165             pl_yylval.opval->op_private = 0;
7166             pl_yylval.opval->op_folded = 1;
7167             pl_yylval.opval->op_flags |= OPf_SPECIAL;
7168         }
7169         TOKEN(BAREWORD);
7170     }
7171
7172     op_free(pl_yylval.opval);
7173     pl_yylval.opval =
7174         off ? newCVREF(0, rv2cv_op) : rv2cv_op;
7175     pl_yylval.opval->op_private |= OPpENTERSUB_NOPAREN;
7176     PL_last_lop = PL_oldbufptr;
7177     PL_last_lop_op = OP_ENTERSUB;
7178
7179     /* Is there a prototype? */
7180     if (SvPOK(cv)) {
7181         int k = yyl_subproto(aTHX_ s, cv);
7182         if (k != KEY_NULL)
7183             return k;
7184     }
7185
7186     NEXTVAL_NEXTTOKE.opval = pl_yylval.opval;
7187     PL_expect = XTERM;
7188     force_next(off ? PRIVATEREF : BAREWORD);
7189     if (!PL_lex_allbrackets
7190         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7191     {
7192         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7193     }
7194
7195     TOKEN(NOAMP);
7196 }
7197
7198 /* Honour "reserved word" warnings, and enforce strict subs */
7199 static void
7200 yyl_strictwarn_bareword(pTHX_ const char lastchar)
7201 {
7202     /* after "print" and similar functions (corresponding to
7203      * "F? L" in opcode.pl), whatever wasn't already parsed as
7204      * a filehandle should be subject to "strict subs".
7205      * Likewise for the optional indirect-object argument to system
7206      * or exec, which can't be a bareword */
7207     if ((PL_last_lop_op == OP_PRINT
7208             || PL_last_lop_op == OP_PRTF
7209             || PL_last_lop_op == OP_SAY
7210             || PL_last_lop_op == OP_SYSTEM
7211             || PL_last_lop_op == OP_EXEC)
7212         && (PL_hints & HINT_STRICT_SUBS))
7213     {
7214         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7215     }
7216
7217     if (lastchar != '-' && ckWARN(WARN_RESERVED)) {
7218         char *d = PL_tokenbuf;
7219         while (isLOWER(*d))
7220             d++;
7221         if (!*d && !gv_stashpv(PL_tokenbuf, UTF ? SVf_UTF8 : 0)) {
7222             /* PL_warn_reserved is constant */
7223             GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
7224             Perl_warner(aTHX_ packWARN(WARN_RESERVED), PL_warn_reserved,
7225                         PL_tokenbuf);
7226             GCC_DIAG_RESTORE_STMT;
7227         }
7228     }
7229 }
7230
7231 static int
7232 yyl_just_a_word(pTHX_ char *s, STRLEN len, I32 orig_keyword, struct code c)
7233 {
7234     int pkgname = 0;
7235     const char lastchar = (PL_bufptr == PL_oldoldbufptr ? 0 : PL_bufptr[-1]);
7236     bool safebw;
7237     bool no_op_error = FALSE;
7238     /* Use this var to track whether intuit_method has been
7239        called.  intuit_method returns 0 or > 255.  */
7240     int key = 1;
7241
7242     if (PL_expect == XOPERATOR) {
7243         if (PL_bufptr == PL_linestart) {
7244             CopLINE_dec(PL_curcop);
7245             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
7246             CopLINE_inc(PL_curcop);
7247         }
7248         else
7249             /* We want to call no_op with s pointing after the
7250                bareword, so defer it.  But we want it to come
7251                before the Bad name croak.  */
7252             no_op_error = TRUE;
7253     }
7254
7255     /* Get the rest if it looks like a package qualifier */
7256
7257     if (*s == '\'' || (*s == ':' && s[1] == ':')) {
7258         STRLEN morelen;
7259         s = scan_word(s, PL_tokenbuf + len, sizeof PL_tokenbuf - len,
7260                       TRUE, &morelen);
7261         if (no_op_error) {
7262             no_op("Bareword",s);
7263             no_op_error = FALSE;
7264         }
7265         if (!morelen)
7266             Perl_croak(aTHX_ "Bad name after %" UTF8f "%s",
7267                     UTF8fARG(UTF, len, PL_tokenbuf),
7268                     *s == '\'' ? "'" : "::");
7269         len += morelen;
7270         pkgname = 1;
7271     }
7272
7273     if (no_op_error)
7274         no_op("Bareword",s);
7275
7276     /* See if the name is "Foo::",
7277        in which case Foo is a bareword
7278        (and a package name). */
7279
7280     if (len > 2 && PL_tokenbuf[len - 2] == ':' && PL_tokenbuf[len - 1] == ':') {
7281         if (ckWARN(WARN_BAREWORD)
7282             && ! gv_fetchpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0, SVt_PVHV))
7283             Perl_warner(aTHX_ packWARN(WARN_BAREWORD),
7284                         "Bareword \"%" UTF8f
7285                         "\" refers to nonexistent package",
7286                         UTF8fARG(UTF, len, PL_tokenbuf));
7287         len -= 2;
7288         PL_tokenbuf[len] = '\0';
7289         c.gv = NULL;
7290         c.gvp = 0;
7291         safebw = TRUE;
7292     }
7293     else {
7294         safebw = FALSE;
7295     }
7296
7297     /* if we saw a global override before, get the right name */
7298
7299     if (!c.sv)
7300         c.sv = S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len);
7301     if (c.gvp) {
7302         SV *sv = newSVpvs("CORE::GLOBAL::");
7303         sv_catsv(sv, c.sv);
7304         SvREFCNT_dec(c.sv);
7305         c.sv = sv;
7306     }
7307
7308     /* Presume this is going to be a bareword of some sort. */
7309     CLINE;
7310     pl_yylval.opval = newSVOP(OP_CONST, 0, c.sv);
7311     pl_yylval.opval->op_private = OPpCONST_BARE;
7312
7313     /* And if "Foo::", then that's what it certainly is. */
7314     if (safebw)
7315         return yyl_safe_bareword(aTHX_ s, lastchar);
7316
7317     if (!c.off) {
7318         OP *const_op = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(c.sv));
7319         const_op->op_private = OPpCONST_BARE;
7320         c.rv2cv_op = newCVREF(OPpMAY_RETURN_CONSTANT<<8, const_op);
7321         c.cv = c.lex
7322             ? isGV(c.gv)
7323                 ? GvCV(c.gv)
7324                 : SvROK(c.gv) && SvTYPE(SvRV(c.gv)) == SVt_PVCV
7325                     ? (CV *)SvRV(c.gv)
7326                     : ((CV *)c.gv)
7327             : rv2cv_op_cv(c.rv2cv_op, RV2CVOPCV_RETURN_STUB);
7328     }
7329
7330     /* See if it's the indirect object for a list operator. */
7331
7332     if (PL_oldoldbufptr
7333         && PL_oldoldbufptr < PL_bufptr
7334         && (PL_oldoldbufptr == PL_last_lop
7335             || PL_oldoldbufptr == PL_last_uni)
7336         && /* NO SKIPSPACE BEFORE HERE! */
7337            (PL_expect == XREF
7338             || ((PL_opargs[PL_last_lop_op] >> OASHIFT)& 7)
7339                                                    == OA_FILEREF))
7340     {
7341         bool immediate_paren = *s == '(';
7342         SSize_t s_off;
7343
7344         /* (Now we can afford to cross potential line boundary.) */
7345         s = skipspace(s);
7346
7347         /* intuit_method() can indirectly call lex_next_chunk(),
7348          * invalidating s
7349          */
7350         s_off = s - SvPVX(PL_linestr);
7351         /* Two barewords in a row may indicate method call. */
7352         if (   (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
7353                 || *s == '$')
7354             && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7355         {
7356             /* the code at method: doesn't use s */
7357             goto method;
7358         }
7359         s = SvPVX(PL_linestr) + s_off;
7360
7361         /* If not a declared subroutine, it's an indirect object. */
7362         /* (But it's an indir obj regardless for sort.) */
7363         /* Also, if "_" follows a filetest operator, it's a bareword */
7364
7365         if (
7366             ( !immediate_paren && (PL_last_lop_op == OP_SORT
7367              || (!c.cv
7368                  && (PL_last_lop_op != OP_MAPSTART
7369                      && PL_last_lop_op != OP_GREPSTART))))
7370            || (PL_tokenbuf[0] == '_' && PL_tokenbuf[1] == '\0'
7371                 && ((PL_opargs[PL_last_lop_op] & OA_CLASS_MASK)
7372                                                 == OA_FILESTATOP))
7373            )
7374         {
7375             PL_expect = (PL_last_lop == PL_oldoldbufptr) ? XTERM : XOPERATOR;
7376             yyl_strictwarn_bareword(aTHX_ lastchar);
7377             op_free(c.rv2cv_op);
7378             return yyl_safe_bareword(aTHX_ s, lastchar);
7379         }
7380     }
7381
7382     PL_expect = XOPERATOR;
7383     s = skipspace(s);
7384
7385     /* Is this a word before a => operator? */
7386     if (*s == '=' && s[1] == '>' && !pkgname) {
7387         op_free(c.rv2cv_op);
7388         CLINE;
7389         if (c.gvp || (c.lex && !c.off)) {
7390             assert (cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7391             /* This is our own scalar, created a few lines
7392                above, so this is safe. */
7393             SvREADONLY_off(c.sv);
7394             sv_setpv(c.sv, PL_tokenbuf);
7395             if (UTF && !IN_BYTES
7396              && is_utf8_string((U8*)PL_tokenbuf, len))
7397                   SvUTF8_on(c.sv);
7398             SvREADONLY_on(c.sv);
7399         }
7400         TERM(BAREWORD);
7401     }
7402
7403     /* If followed by a paren, it's certainly a subroutine. */
7404     if (*s == '(') {
7405         CLINE;
7406         if (c.cv) {
7407             char *d = s + 1;
7408             while (SPACE_OR_TAB(*d))
7409                 d++;
7410             if (*d == ')' && (c.sv = cv_const_sv_or_av(c.cv)))
7411                 return yyl_constant_op(aTHX_ d + 1, c.sv, c.cv, c.rv2cv_op, c.off);
7412         }
7413         NEXTVAL_NEXTTOKE.opval =
7414             c.off ? c.rv2cv_op : pl_yylval.opval;
7415         if (c.off)
7416              op_free(pl_yylval.opval), force_next(PRIVATEREF);
7417         else op_free(c.rv2cv_op),      force_next(BAREWORD);
7418         pl_yylval.ival = 0;
7419         TOKEN('&');
7420     }
7421
7422     /* If followed by var or block, call it a method (unless sub) */
7423
7424     if ((*s == '$' || *s == '{') && !c.cv) {
7425         op_free(c.rv2cv_op);
7426         PL_last_lop = PL_oldbufptr;
7427         PL_last_lop_op = OP_METHOD;
7428         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7429             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7430         PL_expect = XBLOCKTERM;
7431         PL_bufptr = s;
7432         return REPORT(METHOD);
7433     }
7434
7435     /* If followed by a bareword, see if it looks like indir obj. */
7436
7437     if (   key == 1
7438         && !orig_keyword
7439         && (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF) || *s == '$')
7440         && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7441     {
7442       method:
7443         if (c.lex && !c.off) {
7444             assert(cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7445             SvREADONLY_off(c.sv);
7446             sv_setpvn(c.sv, PL_tokenbuf, len);
7447             if (UTF && !IN_BYTES
7448              && is_utf8_string((U8*)PL_tokenbuf, len))
7449                 SvUTF8_on(c.sv);
7450             else SvUTF8_off(c.sv);
7451         }
7452         op_free(c.rv2cv_op);
7453         if (key == METHOD && !PL_lex_allbrackets
7454             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7455         {
7456             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7457         }
7458         return REPORT(key);
7459     }
7460
7461     /* Not a method, so call it a subroutine (if defined) */
7462
7463     if (c.cv) {
7464         /* Check for a constant sub */
7465         c.sv = cv_const_sv_or_av(c.cv);
7466         return yyl_constant_op(aTHX_ s, c.sv, c.cv, c.rv2cv_op, c.off);
7467     }
7468
7469     /* Call it a bare word */
7470
7471     if (PL_hints & HINT_STRICT_SUBS)
7472         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7473     else
7474         yyl_strictwarn_bareword(aTHX_ lastchar);
7475
7476     op_free(c.rv2cv_op);
7477
7478     return yyl_safe_bareword(aTHX_ s, lastchar);
7479 }
7480
7481 static int
7482 yyl_word_or_keyword(pTHX_ char *s, STRLEN len, I32 key, I32 orig_keyword, struct code c)
7483 {
7484     switch (key) {
7485     default:                    /* not a keyword */
7486         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7487
7488     case KEY___FILE__:
7489         FUN0OP( newSVOP(OP_CONST, 0, newSVpv(CopFILE(PL_curcop),0)) );
7490
7491     case KEY___LINE__:
7492         FUN0OP(
7493             newSVOP(OP_CONST, 0,
7494                 Perl_newSVpvf(aTHX_ "%" IVdf, (IV)CopLINE(PL_curcop)))
7495         );
7496
7497     case KEY___PACKAGE__:
7498         FUN0OP(
7499             newSVOP(OP_CONST, 0, (PL_curstash
7500                                      ? newSVhek(HvNAME_HEK(PL_curstash))
7501                                      : &PL_sv_undef))
7502         );
7503
7504     case KEY___DATA__:
7505     case KEY___END__:
7506         if (PL_rsfp && (!PL_in_eval || PL_tokenbuf[2] == 'D'))
7507             yyl_data_handle(aTHX);
7508         return yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s, len);
7509
7510     case KEY___SUB__:
7511         FUN0OP(CvCLONE(PL_compcv)
7512                     ? newOP(OP_RUNCV, 0)
7513                     : newPVOP(OP_RUNCV,0,NULL));
7514
7515     case KEY_AUTOLOAD:
7516     case KEY_DESTROY:
7517     case KEY_BEGIN:
7518     case KEY_UNITCHECK:
7519     case KEY_CHECK:
7520     case KEY_INIT:
7521     case KEY_END:
7522         if (PL_expect == XSTATE)
7523             return yyl_sub(aTHX_ PL_bufptr, key);
7524         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7525
7526     case KEY_abs:
7527         UNI(OP_ABS);
7528
7529     case KEY_alarm:
7530         UNI(OP_ALARM);
7531
7532     case KEY_accept:
7533         LOP(OP_ACCEPT,XTERM);
7534
7535     case KEY_and:
7536         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7537             return REPORT(0);
7538         OPERATOR(ANDOP);
7539
7540     case KEY_atan2:
7541         LOP(OP_ATAN2,XTERM);
7542
7543     case KEY_bind:
7544         LOP(OP_BIND,XTERM);
7545
7546     case KEY_binmode:
7547         LOP(OP_BINMODE,XTERM);
7548
7549     case KEY_bless:
7550         LOP(OP_BLESS,XTERM);
7551
7552     case KEY_break:
7553         FUN0(OP_BREAK);
7554
7555     case KEY_chop:
7556         UNI(OP_CHOP);
7557
7558     case KEY_continue:
7559         /* We have to disambiguate the two senses of
7560           "continue". If the next token is a '{' then
7561           treat it as the start of a continue block;
7562           otherwise treat it as a control operator.
7563          */
7564         s = skipspace(s);
7565         if (*s == '{')
7566             PREBLOCK(CONTINUE);
7567         else
7568             FUN0(OP_CONTINUE);
7569
7570     case KEY_chdir:
7571         /* may use HOME */
7572         (void)gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV);
7573         UNI(OP_CHDIR);
7574
7575     case KEY_close:
7576         UNI(OP_CLOSE);
7577
7578     case KEY_closedir:
7579         UNI(OP_CLOSEDIR);
7580
7581     case KEY_cmp:
7582         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7583             return REPORT(0);
7584         Eop(OP_SCMP);
7585
7586     case KEY_caller:
7587         UNI(OP_CALLER);
7588
7589     case KEY_crypt:
7590 #ifdef FCRYPT
7591         if (!PL_cryptseen) {
7592             PL_cryptseen = TRUE;
7593             init_des();
7594         }
7595 #endif
7596         LOP(OP_CRYPT,XTERM);
7597
7598     case KEY_chmod:
7599         LOP(OP_CHMOD,XTERM);
7600
7601     case KEY_chown:
7602         LOP(OP_CHOWN,XTERM);
7603
7604     case KEY_connect:
7605         LOP(OP_CONNECT,XTERM);
7606
7607     case KEY_chr:
7608         UNI(OP_CHR);
7609
7610     case KEY_cos:
7611         UNI(OP_COS);
7612
7613     case KEY_chroot:
7614         UNI(OP_CHROOT);
7615
7616     case KEY_default:
7617         PREBLOCK(DEFAULT);
7618
7619     case KEY_do:
7620         return yyl_do(aTHX_ s, orig_keyword);
7621
7622     case KEY_die:
7623         PL_hints |= HINT_BLOCK_SCOPE;
7624         LOP(OP_DIE,XTERM);
7625
7626     case KEY_defined:
7627         UNI(OP_DEFINED);
7628
7629     case KEY_delete:
7630         UNI(OP_DELETE);
7631
7632     case KEY_dbmopen:
7633         Perl_populate_isa(aTHX_ STR_WITH_LEN("AnyDBM_File::ISA"),
7634                           STR_WITH_LEN("NDBM_File::"),
7635                           STR_WITH_LEN("DB_File::"),
7636                           STR_WITH_LEN("GDBM_File::"),
7637                           STR_WITH_LEN("SDBM_File::"),
7638                           STR_WITH_LEN("ODBM_File::"),
7639                           NULL);
7640         LOP(OP_DBMOPEN,XTERM);
7641
7642     case KEY_dbmclose:
7643         UNI(OP_DBMCLOSE);
7644
7645     case KEY_dump:
7646         LOOPX(OP_DUMP);
7647
7648     case KEY_else:
7649         PREBLOCK(ELSE);
7650
7651     case KEY_elsif:
7652         pl_yylval.ival = CopLINE(PL_curcop);
7653         OPERATOR(ELSIF);
7654
7655     case KEY_eq:
7656         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7657             return REPORT(0);
7658         Eop(OP_SEQ);
7659
7660     case KEY_exists:
7661         UNI(OP_EXISTS);
7662
7663     case KEY_exit:
7664         UNI(OP_EXIT);
7665
7666     case KEY_eval:
7667         s = skipspace(s);
7668         if (*s == '{') { /* block eval */
7669             PL_expect = XTERMBLOCK;
7670             UNIBRACK(OP_ENTERTRY);
7671         }
7672         else { /* string eval */
7673             PL_expect = XTERM;
7674             UNIBRACK(OP_ENTEREVAL);
7675         }
7676
7677     case KEY_evalbytes:
7678         PL_expect = XTERM;
7679         UNIBRACK(-OP_ENTEREVAL);
7680
7681     case KEY_eof:
7682         UNI(OP_EOF);
7683
7684     case KEY_exp:
7685         UNI(OP_EXP);
7686
7687     case KEY_each:
7688         UNI(OP_EACH);
7689
7690     case KEY_exec:
7691         LOP(OP_EXEC,XREF);
7692
7693     case KEY_endhostent:
7694         FUN0(OP_EHOSTENT);
7695
7696     case KEY_endnetent:
7697         FUN0(OP_ENETENT);
7698
7699     case KEY_endservent:
7700         FUN0(OP_ESERVENT);
7701
7702     case KEY_endprotoent:
7703         FUN0(OP_EPROTOENT);
7704
7705     case KEY_endpwent:
7706         FUN0(OP_EPWENT);
7707
7708     case KEY_endgrent:
7709         FUN0(OP_EGRENT);
7710
7711     case KEY_for:
7712     case KEY_foreach:
7713         return yyl_foreach(aTHX_ s);
7714
7715     case KEY_formline:
7716         LOP(OP_FORMLINE,XTERM);
7717
7718     case KEY_fork:
7719         FUN0(OP_FORK);
7720
7721     case KEY_fc:
7722         UNI(OP_FC);
7723
7724     case KEY_fcntl:
7725         LOP(OP_FCNTL,XTERM);
7726
7727     case KEY_fileno:
7728         UNI(OP_FILENO);
7729
7730     case KEY_flock:
7731         LOP(OP_FLOCK,XTERM);
7732
7733     case KEY_gt:
7734         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7735             return REPORT(0);
7736         Rop(OP_SGT);
7737
7738     case KEY_ge:
7739         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7740             return REPORT(0);
7741         Rop(OP_SGE);
7742
7743     case KEY_grep:
7744         LOP(OP_GREPSTART, XREF);
7745
7746     case KEY_goto:
7747         LOOPX(OP_GOTO);
7748
7749     case KEY_gmtime:
7750         UNI(OP_GMTIME);
7751
7752     case KEY_getc:
7753         UNIDOR(OP_GETC);
7754
7755     case KEY_getppid:
7756         FUN0(OP_GETPPID);
7757
7758     case KEY_getpgrp:
7759         UNI(OP_GETPGRP);
7760
7761     case KEY_getpriority:
7762         LOP(OP_GETPRIORITY,XTERM);
7763
7764     case KEY_getprotobyname:
7765         UNI(OP_GPBYNAME);
7766
7767     case KEY_getprotobynumber:
7768         LOP(OP_GPBYNUMBER,XTERM);
7769
7770     case KEY_getprotoent:
7771         FUN0(OP_GPROTOENT);
7772
7773     case KEY_getpwent:
7774         FUN0(OP_GPWENT);
7775
7776     case KEY_getpwnam:
7777         UNI(OP_GPWNAM);
7778
7779     case KEY_getpwuid:
7780         UNI(OP_GPWUID);
7781
7782     case KEY_getpeername:
7783         UNI(OP_GETPEERNAME);
7784
7785     case KEY_gethostbyname:
7786         UNI(OP_GHBYNAME);
7787
7788     case KEY_gethostbyaddr:
7789         LOP(OP_GHBYADDR,XTERM);
7790
7791     case KEY_gethostent:
7792         FUN0(OP_GHOSTENT);
7793
7794     case KEY_getnetbyname:
7795         UNI(OP_GNBYNAME);
7796
7797     case KEY_getnetbyaddr:
7798         LOP(OP_GNBYADDR,XTERM);
7799
7800     case KEY_getnetent:
7801         FUN0(OP_GNETENT);
7802
7803     case KEY_getservbyname:
7804         LOP(OP_GSBYNAME,XTERM);
7805
7806     case KEY_getservbyport:
7807         LOP(OP_GSBYPORT,XTERM);
7808
7809     case KEY_getservent:
7810         FUN0(OP_GSERVENT);
7811
7812     case KEY_getsockname:
7813         UNI(OP_GETSOCKNAME);
7814
7815     case KEY_getsockopt:
7816         LOP(OP_GSOCKOPT,XTERM);
7817
7818     case KEY_getgrent:
7819         FUN0(OP_GGRENT);
7820
7821     case KEY_getgrnam:
7822         UNI(OP_GGRNAM);
7823
7824     case KEY_getgrgid:
7825         UNI(OP_GGRGID);
7826
7827     case KEY_getlogin:
7828         FUN0(OP_GETLOGIN);
7829
7830     case KEY_given:
7831         pl_yylval.ival = CopLINE(PL_curcop);
7832         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
7833                          "given is experimental");
7834         OPERATOR(GIVEN);
7835
7836     case KEY_glob:
7837         LOP( orig_keyword==KEY_glob ? -OP_GLOB : OP_GLOB, XTERM );
7838
7839     case KEY_hex:
7840         UNI(OP_HEX);
7841
7842     case KEY_if:
7843         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7844             return REPORT(0);
7845         pl_yylval.ival = CopLINE(PL_curcop);
7846         OPERATOR(IF);
7847
7848     case KEY_index:
7849         LOP(OP_INDEX,XTERM);
7850
7851     case KEY_int:
7852         UNI(OP_INT);
7853
7854     case KEY_ioctl:
7855         LOP(OP_IOCTL,XTERM);
7856
7857     case KEY_isa:
7858         Perl_ck_warner_d(aTHX_
7859             packWARN(WARN_EXPERIMENTAL__ISA), "isa is experimental");
7860         Rop(OP_ISA);
7861
7862     case KEY_join:
7863         LOP(OP_JOIN,XTERM);
7864
7865     case KEY_keys:
7866         UNI(OP_KEYS);
7867
7868     case KEY_kill:
7869         LOP(OP_KILL,XTERM);
7870
7871     case KEY_last:
7872         LOOPX(OP_LAST);
7873
7874     case KEY_lc:
7875         UNI(OP_LC);
7876
7877     case KEY_lcfirst:
7878         UNI(OP_LCFIRST);
7879
7880     case KEY_local:
7881         OPERATOR(LOCAL);
7882
7883     case KEY_length:
7884         UNI(OP_LENGTH);
7885
7886     case KEY_lt:
7887         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7888             return REPORT(0);
7889         Rop(OP_SLT);
7890
7891     case KEY_le:
7892         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7893             return REPORT(0);
7894         Rop(OP_SLE);
7895
7896     case KEY_localtime:
7897         UNI(OP_LOCALTIME);
7898
7899     case KEY_log:
7900         UNI(OP_LOG);
7901
7902     case KEY_link:
7903         LOP(OP_LINK,XTERM);
7904
7905     case KEY_listen:
7906         LOP(OP_LISTEN,XTERM);
7907
7908     case KEY_lock:
7909         UNI(OP_LOCK);
7910
7911     case KEY_lstat:
7912         UNI(OP_LSTAT);
7913
7914     case KEY_m:
7915         s = scan_pat(s,OP_MATCH);
7916         TERM(sublex_start());
7917
7918     case KEY_map:
7919         LOP(OP_MAPSTART, XREF);
7920
7921     case KEY_mkdir:
7922         LOP(OP_MKDIR,XTERM);
7923
7924     case KEY_msgctl:
7925         LOP(OP_MSGCTL,XTERM);
7926
7927     case KEY_msgget:
7928         LOP(OP_MSGGET,XTERM);
7929
7930     case KEY_msgrcv:
7931         LOP(OP_MSGRCV,XTERM);
7932
7933     case KEY_msgsnd:
7934         LOP(OP_MSGSND,XTERM);
7935
7936     case KEY_our:
7937     case KEY_my:
7938     case KEY_state:
7939         return yyl_my(aTHX_ s, key);
7940
7941     case KEY_next:
7942         LOOPX(OP_NEXT);
7943
7944     case KEY_ne:
7945         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7946             return REPORT(0);
7947         Eop(OP_SNE);
7948
7949     case KEY_no:
7950         s = tokenize_use(0, s);
7951         TOKEN(USE);
7952
7953     case KEY_not:
7954         if (*s == '(' || (s = skipspace(s), *s == '('))
7955             FUN1(OP_NOT);
7956         else {
7957             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7958                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7959             OPERATOR(NOTOP);
7960         }
7961
7962     case KEY_open:
7963         s = skipspace(s);
7964         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
7965             const char *t;
7966             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
7967             for (t=d; isSPACE(*t);)
7968                 t++;
7969             if ( *t && memCHRs("|&*+-=!?:.", *t) && ckWARN_d(WARN_PRECEDENCE)
7970                 /* [perl #16184] */
7971                 && !(t[0] == '=' && t[1] == '>')
7972                 && !(t[0] == ':' && t[1] == ':')
7973                 && !keyword(s, d-s, 0)
7974             ) {
7975                 Perl_warner(aTHX_ packWARN(WARN_PRECEDENCE),
7976                    "Precedence problem: open %" UTF8f " should be open(%" UTF8f ")",
7977                     UTF8fARG(UTF, d-s, s), UTF8fARG(UTF, d-s, s));
7978             }
7979         }
7980         LOP(OP_OPEN,XTERM);
7981
7982     case KEY_or:
7983         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7984             return REPORT(0);
7985         pl_yylval.ival = OP_OR;
7986         OPERATOR(OROP);
7987
7988     case KEY_ord:
7989         UNI(OP_ORD);
7990
7991     case KEY_oct:
7992         UNI(OP_OCT);
7993
7994     case KEY_opendir:
7995         LOP(OP_OPEN_DIR,XTERM);
7996
7997     case KEY_print:
7998         checkcomma(s,PL_tokenbuf,"filehandle");
7999         LOP(OP_PRINT,XREF);
8000
8001     case KEY_printf:
8002         checkcomma(s,PL_tokenbuf,"filehandle");
8003         LOP(OP_PRTF,XREF);
8004
8005     case KEY_prototype:
8006         UNI(OP_PROTOTYPE);
8007
8008     case KEY_push:
8009         LOP(OP_PUSH,XTERM);
8010
8011     case KEY_pop:
8012         UNIDOR(OP_POP);
8013
8014     case KEY_pos:
8015         UNIDOR(OP_POS);
8016
8017     case KEY_pack:
8018         LOP(OP_PACK,XTERM);
8019
8020     case KEY_package:
8021         s = force_word(s,BAREWORD,FALSE,TRUE);
8022         s = skipspace(s);
8023         s = force_strict_version(s);
8024         PREBLOCK(PACKAGE);
8025
8026     case KEY_pipe:
8027         LOP(OP_PIPE_OP,XTERM);
8028
8029     case KEY_q:
8030         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8031         if (!s)
8032             missingterm(NULL, 0);
8033         COPLINE_SET_FROM_MULTI_END;
8034         pl_yylval.ival = OP_CONST;
8035         TERM(sublex_start());
8036
8037     case KEY_quotemeta:
8038         UNI(OP_QUOTEMETA);
8039
8040     case KEY_qw:
8041         return yyl_qw(aTHX_ s, len);
8042
8043     case KEY_qq:
8044         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8045         if (!s)
8046             missingterm(NULL, 0);
8047         pl_yylval.ival = OP_STRINGIFY;
8048         if (SvIVX(PL_lex_stuff) == '\'')
8049             SvIV_set(PL_lex_stuff, 0);  /* qq'$foo' should interpolate */
8050         TERM(sublex_start());
8051
8052     case KEY_qr:
8053         s = scan_pat(s,OP_QR);
8054         TERM(sublex_start());
8055
8056     case KEY_qx:
8057         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8058         if (!s)
8059             missingterm(NULL, 0);
8060         pl_yylval.ival = OP_BACKTICK;
8061         TERM(sublex_start());
8062
8063     case KEY_return:
8064         OLDLOP(OP_RETURN);
8065
8066     case KEY_require:
8067         return yyl_require(aTHX_ s, orig_keyword);
8068
8069     case KEY_reset:
8070         UNI(OP_RESET);
8071
8072     case KEY_redo:
8073         LOOPX(OP_REDO);
8074
8075     case KEY_rename:
8076         LOP(OP_RENAME,XTERM);
8077
8078     case KEY_rand:
8079         UNI(OP_RAND);
8080
8081     case KEY_rmdir:
8082         UNI(OP_RMDIR);
8083
8084     case KEY_rindex:
8085         LOP(OP_RINDEX,XTERM);
8086
8087     case KEY_read:
8088         LOP(OP_READ,XTERM);
8089
8090     case KEY_readdir:
8091         UNI(OP_READDIR);
8092
8093     case KEY_readline:
8094         UNIDOR(OP_READLINE);
8095
8096     case KEY_readpipe:
8097         UNIDOR(OP_BACKTICK);
8098
8099     case KEY_rewinddir:
8100         UNI(OP_REWINDDIR);
8101
8102     case KEY_recv:
8103         LOP(OP_RECV,XTERM);
8104
8105     case KEY_reverse:
8106         LOP(OP_REVERSE,XTERM);
8107
8108     case KEY_readlink:
8109         UNIDOR(OP_READLINK);
8110
8111     case KEY_ref:
8112         UNI(OP_REF);
8113
8114     case KEY_s:
8115         s = scan_subst(s);
8116         if (pl_yylval.opval)
8117             TERM(sublex_start());
8118         else
8119             TOKEN(1);   /* force error */
8120
8121     case KEY_say:
8122         checkcomma(s,PL_tokenbuf,"filehandle");
8123         LOP(OP_SAY,XREF);
8124
8125     case KEY_chomp:
8126         UNI(OP_CHOMP);
8127
8128     case KEY_scalar:
8129         UNI(OP_SCALAR);
8130
8131     case KEY_select:
8132         LOP(OP_SELECT,XTERM);
8133
8134     case KEY_seek:
8135         LOP(OP_SEEK,XTERM);
8136
8137     case KEY_semctl:
8138         LOP(OP_SEMCTL,XTERM);
8139
8140     case KEY_semget:
8141         LOP(OP_SEMGET,XTERM);
8142
8143     case KEY_semop:
8144         LOP(OP_SEMOP,XTERM);
8145
8146     case KEY_send:
8147         LOP(OP_SEND,XTERM);
8148
8149     case KEY_setpgrp:
8150         LOP(OP_SETPGRP,XTERM);
8151
8152     case KEY_setpriority:
8153         LOP(OP_SETPRIORITY,XTERM);
8154
8155     case KEY_sethostent:
8156         UNI(OP_SHOSTENT);
8157
8158     case KEY_setnetent:
8159         UNI(OP_SNETENT);
8160
8161     case KEY_setservent:
8162         UNI(OP_SSERVENT);
8163
8164     case KEY_setprotoent:
8165         UNI(OP_SPROTOENT);
8166
8167     case KEY_setpwent:
8168         FUN0(OP_SPWENT);
8169
8170     case KEY_setgrent:
8171         FUN0(OP_SGRENT);
8172
8173     case KEY_seekdir:
8174         LOP(OP_SEEKDIR,XTERM);
8175
8176     case KEY_setsockopt:
8177         LOP(OP_SSOCKOPT,XTERM);
8178
8179     case KEY_shift:
8180         UNIDOR(OP_SHIFT);
8181
8182     case KEY_shmctl:
8183         LOP(OP_SHMCTL,XTERM);
8184
8185     case KEY_shmget:
8186         LOP(OP_SHMGET,XTERM);
8187
8188     case KEY_shmread:
8189         LOP(OP_SHMREAD,XTERM);
8190
8191     case KEY_shmwrite:
8192         LOP(OP_SHMWRITE,XTERM);
8193
8194     case KEY_shutdown:
8195         LOP(OP_SHUTDOWN,XTERM);
8196
8197     case KEY_sin:
8198         UNI(OP_SIN);
8199
8200     case KEY_sleep:
8201         UNI(OP_SLEEP);
8202
8203     case KEY_socket:
8204         LOP(OP_SOCKET,XTERM);
8205
8206     case KEY_socketpair:
8207         LOP(OP_SOCKPAIR,XTERM);
8208
8209     case KEY_sort:
8210         checkcomma(s,PL_tokenbuf,"subroutine name");
8211         s = skipspace(s);
8212         PL_expect = XTERM;
8213         s = force_word(s,BAREWORD,TRUE,TRUE);
8214         LOP(OP_SORT,XREF);
8215
8216     case KEY_split:
8217         LOP(OP_SPLIT,XTERM);
8218
8219     case KEY_sprintf:
8220         LOP(OP_SPRINTF,XTERM);
8221
8222     case KEY_splice:
8223         LOP(OP_SPLICE,XTERM);
8224
8225     case KEY_sqrt:
8226         UNI(OP_SQRT);
8227
8228     case KEY_srand:
8229         UNI(OP_SRAND);
8230
8231     case KEY_stat:
8232         UNI(OP_STAT);
8233
8234     case KEY_study:
8235         UNI(OP_STUDY);
8236
8237     case KEY_substr:
8238         LOP(OP_SUBSTR,XTERM);
8239
8240     case KEY_format:
8241     case KEY_sub:
8242         return yyl_sub(aTHX_ s, key);
8243
8244     case KEY_system:
8245         LOP(OP_SYSTEM,XREF);
8246
8247     case KEY_symlink:
8248         LOP(OP_SYMLINK,XTERM);
8249
8250     case KEY_syscall:
8251         LOP(OP_SYSCALL,XTERM);
8252
8253     case KEY_sysopen:
8254         LOP(OP_SYSOPEN,XTERM);
8255
8256     case KEY_sysseek:
8257         LOP(OP_SYSSEEK,XTERM);
8258
8259     case KEY_sysread:
8260         LOP(OP_SYSREAD,XTERM);
8261
8262     case KEY_syswrite:
8263         LOP(OP_SYSWRITE,XTERM);
8264
8265     case KEY_tr:
8266     case KEY_y:
8267         s = scan_trans(s);
8268         TERM(sublex_start());
8269
8270     case KEY_tell:
8271         UNI(OP_TELL);
8272
8273     case KEY_telldir:
8274         UNI(OP_TELLDIR);
8275
8276     case KEY_tie:
8277         LOP(OP_TIE,XTERM);
8278
8279     case KEY_tied:
8280         UNI(OP_TIED);
8281
8282     case KEY_time:
8283         FUN0(OP_TIME);
8284
8285     case KEY_times:
8286         FUN0(OP_TMS);
8287
8288     case KEY_truncate:
8289         LOP(OP_TRUNCATE,XTERM);
8290
8291     case KEY_uc:
8292         UNI(OP_UC);
8293
8294     case KEY_ucfirst:
8295         UNI(OP_UCFIRST);
8296
8297     case KEY_untie:
8298         UNI(OP_UNTIE);
8299
8300     case KEY_until:
8301         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8302             return REPORT(0);
8303         pl_yylval.ival = CopLINE(PL_curcop);
8304         OPERATOR(UNTIL);
8305
8306     case KEY_unless:
8307         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8308             return REPORT(0);
8309         pl_yylval.ival = CopLINE(PL_curcop);
8310         OPERATOR(UNLESS);
8311
8312     case KEY_unlink:
8313         LOP(OP_UNLINK,XTERM);
8314
8315     case KEY_undef:
8316         UNIDOR(OP_UNDEF);
8317
8318     case KEY_unpack:
8319         LOP(OP_UNPACK,XTERM);
8320
8321     case KEY_utime:
8322         LOP(OP_UTIME,XTERM);
8323
8324     case KEY_umask:
8325         UNIDOR(OP_UMASK);
8326
8327     case KEY_unshift:
8328         LOP(OP_UNSHIFT,XTERM);
8329
8330     case KEY_use:
8331         s = tokenize_use(1, s);
8332         TOKEN(USE);
8333
8334     case KEY_values:
8335         UNI(OP_VALUES);
8336
8337     case KEY_vec:
8338         LOP(OP_VEC,XTERM);
8339
8340     case KEY_when:
8341         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8342             return REPORT(0);
8343         pl_yylval.ival = CopLINE(PL_curcop);
8344         Perl_ck_warner_d(aTHX_
8345             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8346             "when is experimental");
8347         OPERATOR(WHEN);
8348
8349     case KEY_while:
8350         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8351             return REPORT(0);
8352         pl_yylval.ival = CopLINE(PL_curcop);
8353         OPERATOR(WHILE);
8354
8355     case KEY_warn:
8356         PL_hints |= HINT_BLOCK_SCOPE;
8357         LOP(OP_WARN,XTERM);
8358
8359     case KEY_wait:
8360         FUN0(OP_WAIT);
8361
8362     case KEY_waitpid:
8363         LOP(OP_WAITPID,XTERM);
8364
8365     case KEY_wantarray:
8366         FUN0(OP_WANTARRAY);
8367
8368     case KEY_write:
8369         /* Make sure $^L is defined. 0x0C is CTRL-L on ASCII platforms, and
8370          * we use the same number on EBCDIC */
8371         gv_fetchpvs("\x0C", GV_ADD|GV_NOTQUAL, SVt_PV);
8372         UNI(OP_ENTERWRITE);
8373
8374     case KEY_x:
8375         if (PL_expect == XOPERATOR) {
8376             if (*s == '=' && !PL_lex_allbrackets
8377                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8378             {
8379                 return REPORT(0);
8380             }
8381             Mop(OP_REPEAT);
8382         }
8383         check_uni();
8384         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
8385
8386     case KEY_xor:
8387         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8388             return REPORT(0);
8389         pl_yylval.ival = OP_XOR;
8390         OPERATOR(OROP);
8391     }
8392 }
8393
8394 static int
8395 yyl_key_core(pTHX_ char *s, STRLEN len, struct code c)
8396 {
8397     I32 key = 0;
8398     I32 orig_keyword = 0;
8399     STRLEN olen = len;
8400     char *d = s;
8401     s += 2;
8402     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8403     if ((*s == ':' && s[1] == ':')
8404         || (!(key = keyword(PL_tokenbuf, len, 1)) && *s == '\''))
8405     {
8406         Copy(PL_bufptr, PL_tokenbuf, olen, char);
8407         return yyl_just_a_word(aTHX_ d, olen, 0, c);
8408     }
8409     if (!key)
8410         Perl_croak(aTHX_ "CORE::%" UTF8f " is not a keyword",
8411                           UTF8fARG(UTF, len, PL_tokenbuf));
8412     if (key < 0)
8413         key = -key;
8414     else if (key == KEY_require || key == KEY_do
8415           || key == KEY_glob)
8416         /* that's a way to remember we saw "CORE::" */
8417         orig_keyword = key;
8418
8419     /* Known to be a reserved word at this point */
8420     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8421 }
8422
8423 static int
8424 yyl_keylookup(pTHX_ char *s, GV *gv)
8425 {
8426     dVAR;
8427     STRLEN len;
8428     bool anydelim;
8429     I32 key;
8430     struct code c = no_code;
8431     I32 orig_keyword = 0;
8432     char *d;
8433
8434     c.gv = gv;
8435
8436     PL_bufptr = s;
8437     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8438
8439     /* Some keywords can be followed by any delimiter, including ':' */
8440     anydelim = word_takes_any_delimiter(PL_tokenbuf, len);
8441
8442     /* x::* is just a word, unless x is "CORE" */
8443     if (!anydelim && *s == ':' && s[1] == ':') {
8444         if (memEQs(PL_tokenbuf, len, "CORE"))
8445             return yyl_key_core(aTHX_ s, len, c);
8446         return yyl_just_a_word(aTHX_ s, len, 0, c);
8447     }
8448
8449     d = s;
8450     while (d < PL_bufend && isSPACE(*d))
8451             d++;        /* no comments skipped here, or s### is misparsed */
8452
8453     /* Is this a word before a => operator? */
8454     if (*d == '=' && d[1] == '>') {
8455         return yyl_fatcomma(aTHX_ s, len);
8456     }
8457
8458     /* Check for plugged-in keyword */
8459     {
8460         OP *o;
8461         int result;
8462         char *saved_bufptr = PL_bufptr;
8463         PL_bufptr = s;
8464         result = PL_keyword_plugin(aTHX_ PL_tokenbuf, len, &o);
8465         s = PL_bufptr;
8466         if (result == KEYWORD_PLUGIN_DECLINE) {
8467             /* not a plugged-in keyword */
8468             PL_bufptr = saved_bufptr;
8469         } else if (result == KEYWORD_PLUGIN_STMT) {
8470             pl_yylval.opval = o;
8471             CLINE;
8472             if (!PL_nexttoke) PL_expect = XSTATE;
8473             return REPORT(PLUGSTMT);
8474         } else if (result == KEYWORD_PLUGIN_EXPR) {
8475             pl_yylval.opval = o;
8476             CLINE;
8477             if (!PL_nexttoke) PL_expect = XOPERATOR;
8478             return REPORT(PLUGEXPR);
8479         } else {
8480             Perl_croak(aTHX_ "Bad plugin affecting keyword '%s'", PL_tokenbuf);
8481         }
8482     }
8483
8484     /* Is this a label? */
8485     if (!anydelim && PL_expect == XSTATE
8486           && d < PL_bufend && *d == ':' && *(d + 1) != ':') {
8487         s = d + 1;
8488         pl_yylval.opval =
8489             newSVOP(OP_CONST, 0,
8490                 newSVpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0));
8491         CLINE;
8492         TOKEN(LABEL);
8493     }
8494
8495     /* Check for lexical sub */
8496     if (PL_expect != XOPERATOR) {
8497         char tmpbuf[sizeof PL_tokenbuf + 1];
8498         *tmpbuf = '&';
8499         Copy(PL_tokenbuf, tmpbuf+1, len, char);
8500         c.off = pad_findmy_pvn(tmpbuf, len+1, 0);
8501         if (c.off != NOT_IN_PAD) {
8502             assert(c.off); /* we assume this is boolean-true below */
8503             if (PAD_COMPNAME_FLAGS_isOUR(c.off)) {
8504                 HV *  const stash = PAD_COMPNAME_OURSTASH(c.off);
8505                 HEK * const stashname = HvNAME_HEK(stash);
8506                 c.sv = newSVhek(stashname);
8507                 sv_catpvs(c.sv, "::");
8508                 sv_catpvn_flags(c.sv, PL_tokenbuf, len,
8509                                 (UTF ? SV_CATUTF8 : SV_CATBYTES));
8510                 c.gv = gv_fetchsv(c.sv, GV_NOADD_NOINIT | SvUTF8(c.sv),
8511                                   SVt_PVCV);
8512                 c.off = 0;
8513                 if (!c.gv) {
8514                     sv_free(c.sv);
8515                     c.sv = NULL;
8516                     return yyl_just_a_word(aTHX_ s, len, 0, c);
8517                 }
8518             }
8519             else {
8520                 c.rv2cv_op = newOP(OP_PADANY, 0);
8521                 c.rv2cv_op->op_targ = c.off;
8522                 c.cv = find_lexical_cv(c.off);
8523             }
8524             c.lex = TRUE;
8525             return yyl_just_a_word(aTHX_ s, len, 0, c);
8526         }
8527         c.off = 0;
8528     }
8529
8530     /* Check for built-in keyword */
8531     key = keyword(PL_tokenbuf, len, 0);
8532
8533     if (key < 0)
8534         key = yyl_secondclass_keyword(aTHX_ s, len, key, &orig_keyword, &c.gv, &c.gvp);
8535
8536     if (key && key != KEY___DATA__ && key != KEY___END__
8537      && (!anydelim || *s != '#')) {
8538         /* no override, and not s### either; skipspace is safe here
8539          * check for => on following line */
8540         bool arrow;
8541         STRLEN bufoff = PL_bufptr - SvPVX(PL_linestr);
8542         STRLEN   soff = s         - SvPVX(PL_linestr);
8543         s = peekspace(s);
8544         arrow = *s == '=' && s[1] == '>';
8545         PL_bufptr = SvPVX(PL_linestr) + bufoff;
8546         s         = SvPVX(PL_linestr) +   soff;
8547         if (arrow)
8548             return yyl_fatcomma(aTHX_ s, len);
8549     }
8550
8551     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8552 }
8553
8554 static int
8555 yyl_try(pTHX_ char *s, STRLEN len)
8556 {
8557     char *d;
8558     GV *gv = NULL;
8559
8560   retry:
8561     switch (*s) {
8562     default:
8563         if (UTF ? isIDFIRST_utf8_safe(s, PL_bufend) : isALNUMC(*s))
8564             return yyl_keylookup(aTHX_ s, gv);
8565         yyl_croak_unrecognised(aTHX_ s);
8566
8567     case 4:
8568     case 26:
8569         /* emulate EOF on ^D or ^Z */
8570         return yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s, len);
8571
8572     case 0:
8573         if ((!PL_rsfp || PL_lex_inwhat)
8574          && (!PL_parser->filtered || s+1 < PL_bufend)) {
8575             PL_last_uni = 0;
8576             PL_last_lop = 0;
8577             if (PL_lex_brackets
8578                 && PL_lex_brackstack[PL_lex_brackets-1] != XFAKEEOF)
8579             {
8580                 yyerror((const char *)
8581                         (PL_lex_formbrack
8582                          ? "Format not terminated"
8583                          : "Missing right curly or square bracket"));
8584             }
8585             DEBUG_T({
8586                 PerlIO_printf(Perl_debug_log, "### Tokener got EOF\n");
8587             });
8588             TOKEN(0);
8589         }
8590         if (s++ < PL_bufend)
8591             goto retry;  /* ignore stray nulls */
8592         PL_last_uni = 0;
8593         PL_last_lop = 0;
8594         if (!PL_in_eval && !PL_preambled) {
8595             PL_preambled = TRUE;
8596             if (PL_perldb) {
8597                 /* Generate a string of Perl code to load the debugger.
8598                  * If PERL5DB is set, it will return the contents of that,
8599                  * otherwise a compile-time require of perl5db.pl.  */
8600
8601                 const char * const pdb = PerlEnv_getenv("PERL5DB");
8602
8603                 if (pdb) {
8604                     sv_setpv(PL_linestr, pdb);
8605                     sv_catpvs(PL_linestr,";");
8606                 } else {
8607                     SETERRNO(0,SS_NORMAL);
8608                     sv_setpvs(PL_linestr, "BEGIN { require 'perl5db.pl' };");
8609                 }
8610                 PL_parser->preambling = CopLINE(PL_curcop);
8611             } else
8612                 SvPVCLEAR(PL_linestr);
8613             if (PL_preambleav) {
8614                 SV **svp = AvARRAY(PL_preambleav);
8615                 SV **const end = svp + AvFILLp(PL_preambleav);
8616                 while(svp <= end) {
8617                     sv_catsv(PL_linestr, *svp);
8618                     ++svp;
8619                     sv_catpvs(PL_linestr, ";");
8620                 }
8621                 sv_free(MUTABLE_SV(PL_preambleav));
8622                 PL_preambleav = NULL;
8623             }
8624             if (PL_minus_E)
8625                 sv_catpvs(PL_linestr,
8626                           "use feature ':5." STRINGIFY(PERL_VERSION) "';");
8627             if (PL_minus_n || PL_minus_p) {
8628                 sv_catpvs(PL_linestr, "LINE: while (<>) {"/*}*/);
8629                 if (PL_minus_l)
8630                     sv_catpvs(PL_linestr,"chomp;");
8631                 if (PL_minus_a) {
8632                     if (PL_minus_F) {
8633                         if (   (   *PL_splitstr == '/'
8634                                 || *PL_splitstr == '\''
8635                                 || *PL_splitstr == '"')
8636                             && strchr(PL_splitstr + 1, *PL_splitstr))
8637                         {
8638                             /* strchr is ok, because -F pattern can't contain
8639                              * embeddded NULs */
8640                             Perl_sv_catpvf(aTHX_ PL_linestr, "our @F=split(%s);", PL_splitstr);
8641                         }
8642                         else {
8643                             /* "q\0${splitstr}\0" is legal perl. Yes, even NUL
8644                                bytes can be used as quoting characters.  :-) */
8645                             const char *splits = PL_splitstr;
8646                             sv_catpvs(PL_linestr, "our @F=split(q\0");
8647                             do {
8648                                 /* Need to \ \s  */
8649                                 if (*splits == '\\')
8650                                     sv_catpvn(PL_linestr, splits, 1);
8651                                 sv_catpvn(PL_linestr, splits, 1);
8652                             } while (*splits++);
8653                             /* This loop will embed the trailing NUL of
8654                                PL_linestr as the last thing it does before
8655                                terminating.  */
8656                             sv_catpvs(PL_linestr, ");");
8657                         }
8658                     }
8659                     else
8660                         sv_catpvs(PL_linestr,"our @F=split(' ');");
8661                 }
8662             }
8663             sv_catpvs(PL_linestr, "\n");
8664             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
8665             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
8666             PL_last_lop = PL_last_uni = NULL;
8667             if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
8668                 update_debugger_info(PL_linestr, NULL, 0);
8669             goto retry;
8670         }
8671         return yyl_fake_eof(aTHX_ 0, cBOOL(PL_rsfp), s, len);
8672
8673     case '\r':
8674 #ifdef PERL_STRICT_CR
8675         Perl_warn(aTHX_ "Illegal character \\%03o (carriage return)", '\r');
8676         Perl_croak(aTHX_
8677       "\t(Maybe you didn't strip carriage returns after a network transfer?)\n");
8678 #endif
8679     case ' ': case '\t': case '\f': case '\v':
8680         s++;
8681         goto retry;
8682
8683     case '#':
8684     case '\n': {
8685         const bool needs_semicolon = yyl_eol_needs_semicolon(aTHX_ &s);
8686         if (needs_semicolon)
8687             TOKEN(';');
8688         else
8689             goto retry;
8690     }
8691
8692     case '-':
8693         return yyl_hyphen(aTHX_ s);
8694
8695     case '+':
8696         return yyl_plus(aTHX_ s);
8697
8698     case '*':
8699         return yyl_star(aTHX_ s);
8700
8701     case '%':
8702         return yyl_percent(aTHX_ s);
8703
8704     case '^':
8705         return yyl_caret(aTHX_ s);
8706
8707     case '[':
8708         return yyl_leftsquare(aTHX_ s);
8709
8710     case '~':
8711         return yyl_tilde(aTHX_ s);
8712
8713     case ',':
8714         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8715             TOKEN(0);
8716         s++;
8717         OPERATOR(',');
8718     case ':':
8719         if (s[1] == ':')
8720             return yyl_just_a_word(aTHX_ s, 0, 0, no_code);
8721         return yyl_colon(aTHX_ s + 1);
8722
8723     case '(':
8724         return yyl_leftparen(aTHX_ s + 1);
8725
8726     case ';':
8727         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8728             TOKEN(0);
8729         CLINE;
8730         s++;
8731         PL_expect = XSTATE;
8732         TOKEN(';');
8733
8734     case ')':
8735         return yyl_rightparen(aTHX_ s);
8736
8737     case ']':
8738         return yyl_rightsquare(aTHX_ s);
8739
8740     case '{':
8741         return yyl_leftcurly(aTHX_ s + 1, 0);
8742
8743     case '}':
8744         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
8745             TOKEN(0);
8746         return yyl_rightcurly(aTHX_ s, 0);
8747
8748     case '&':
8749         return yyl_ampersand(aTHX_ s);
8750
8751     case '|':
8752         return yyl_verticalbar(aTHX_ s);
8753
8754     case '=':
8755         if (s[1] == '=' && (s == PL_linestart || s[-1] == '\n')
8756             && memBEGINs(s + 2, (STRLEN) (PL_bufend - s + 2), "====="))
8757         {
8758             s = vcs_conflict_marker(s + 7);
8759             goto retry;
8760         }
8761
8762         s++;
8763         {
8764             const char tmp = *s++;
8765             if (tmp == '=') {
8766                 if (!PL_lex_allbrackets
8767                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8768                 {
8769                     s -= 2;
8770                     TOKEN(0);
8771                 }
8772                 Eop(OP_EQ);
8773             }
8774             if (tmp == '>') {
8775                 if (!PL_lex_allbrackets
8776                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8777                 {
8778                     s -= 2;
8779                     TOKEN(0);
8780                 }
8781                 OPERATOR(',');
8782             }
8783             if (tmp == '~')
8784                 PMop(OP_MATCH);
8785             if (tmp && isSPACE(*s) && ckWARN(WARN_SYNTAX)
8786                 && memCHRs("+-*/%.^&|<",tmp))
8787                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
8788                             "Reversed %c= operator",(int)tmp);
8789             s--;
8790             if (PL_expect == XSTATE
8791                 && isALPHA(tmp)
8792                 && (s == PL_linestart+1 || s[-2] == '\n') )
8793             {
8794                 if (   (PL_in_eval && !PL_rsfp && !PL_parser->filtered)
8795                     || PL_lex_state != LEX_NORMAL)
8796                 {
8797                     d = PL_bufend;
8798                     while (s < d) {
8799                         if (*s++ == '\n') {
8800                             incline(s, PL_bufend);
8801                             if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=cut"))
8802                             {
8803                                 s = (char *) memchr(s,'\n', d - s);
8804                                 if (s)
8805                                     s++;
8806                                 else
8807                                     s = d;
8808                                 incline(s, PL_bufend);
8809                                 goto retry;
8810                             }
8811                         }
8812                     }
8813                     goto retry;
8814                 }
8815                 s = PL_bufend;
8816                 PL_parser->in_pod = 1;
8817                 goto retry;
8818             }
8819         }
8820         if (PL_expect == XBLOCK) {
8821             const char *t = s;
8822 #ifdef PERL_STRICT_CR
8823             while (SPACE_OR_TAB(*t))
8824 #else
8825             while (SPACE_OR_TAB(*t) || *t == '\r')
8826 #endif
8827                 t++;
8828             if (*t == '\n' || *t == '#') {
8829                 ENTER_with_name("lex_format");
8830                 SAVEI8(PL_parser->form_lex_state);
8831                 SAVEI32(PL_lex_formbrack);
8832                 PL_parser->form_lex_state = PL_lex_state;
8833                 PL_lex_formbrack = PL_lex_brackets + 1;
8834                 PL_parser->sub_error_count = PL_error_count;
8835                 return yyl_leftcurly(aTHX_ s, 1);
8836             }
8837         }
8838         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
8839             s--;
8840             TOKEN(0);
8841         }
8842         pl_yylval.ival = 0;
8843         OPERATOR(ASSIGNOP);
8844
8845     case '!':
8846         return yyl_bang(aTHX_ s + 1);
8847
8848     case '<':
8849         if (s[1] == '<' && (s == PL_linestart || s[-1] == '\n')
8850             && memBEGINs(s+2, (STRLEN) (PL_bufend - (s+2)), "<<<<<"))
8851         {
8852             s = vcs_conflict_marker(s + 7);
8853             goto retry;
8854         }
8855         return yyl_leftpointy(aTHX_ s);
8856
8857     case '>':
8858         if (s[1] == '>' && (s == PL_linestart || s[-1] == '\n')
8859             && memBEGINs(s + 2, (STRLEN) (PL_bufend - s + 2), ">>>>>"))
8860         {
8861             s = vcs_conflict_marker(s + 7);
8862             goto retry;
8863         }
8864         return yyl_rightpointy(aTHX_ s + 1);
8865
8866     case '$':
8867         return yyl_dollar(aTHX_ s);
8868
8869     case '@':
8870         return yyl_snail(aTHX_ s);
8871
8872     case '/':                   /* may be division, defined-or, or pattern */
8873         return yyl_slash(aTHX_ s);
8874
8875      case '?':                  /* conditional */
8876         s++;
8877         if (!PL_lex_allbrackets
8878             && PL_lex_fakeeof >= LEX_FAKEEOF_IFELSE)
8879         {
8880             s--;
8881             TOKEN(0);
8882         }
8883         PL_lex_allbrackets++;
8884         OPERATOR('?');
8885
8886     case '.':
8887         if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack
8888 #ifdef PERL_STRICT_CR
8889             && s[1] == '\n'
8890 #else
8891             && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n'))
8892 #endif
8893             && (s == PL_linestart || s[-1] == '\n') )
8894         {
8895             PL_expect = XSTATE;
8896             /* formbrack==2 means dot seen where arguments expected */
8897             return yyl_rightcurly(aTHX_ s, 2);
8898         }
8899         if (PL_expect == XSTATE && s[1] == '.' && s[2] == '.') {
8900             s += 3;
8901             OPERATOR(YADAYADA);
8902         }
8903         if (PL_expect == XOPERATOR || !isDIGIT(s[1])) {
8904             char tmp = *s++;
8905             if (*s == tmp) {
8906                 if (!PL_lex_allbrackets
8907                     && PL_lex_fakeeof >= LEX_FAKEEOF_RANGE)
8908                 {
8909                     s--;
8910                     TOKEN(0);
8911                 }
8912                 s++;
8913                 if (*s == tmp) {
8914                     s++;
8915                     pl_yylval.ival = OPf_SPECIAL;
8916                 }
8917                 else
8918                     pl_yylval.ival = 0;
8919                 OPERATOR(DOTDOT);
8920             }
8921             if (*s == '=' && !PL_lex_allbrackets
8922                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8923             {
8924                 s--;
8925                 TOKEN(0);
8926             }
8927             Aop(OP_CONCAT);
8928         }
8929         /* FALLTHROUGH */
8930     case '0': case '1': case '2': case '3': case '4':
8931     case '5': case '6': case '7': case '8': case '9':
8932         s = scan_num(s, &pl_yylval);
8933         DEBUG_T( { printbuf("### Saw number in %s\n", s); } );
8934         if (PL_expect == XOPERATOR)
8935             no_op("Number",s);
8936         TERM(THING);
8937
8938     case '\'':
8939         return yyl_sglquote(aTHX_ s);
8940
8941     case '"':
8942         return yyl_dblquote(aTHX_ s, len);
8943
8944     case '`':
8945         return yyl_backtick(aTHX_ s);
8946
8947     case '\\':
8948         return yyl_backslash(aTHX_ s + 1);
8949
8950     case 'v':
8951         if (isDIGIT(s[1]) && PL_expect != XOPERATOR) {
8952             char *start = s + 2;
8953             while (isDIGIT(*start) || *start == '_')
8954                 start++;
8955             if (*start == '.' && isDIGIT(start[1])) {
8956                 s = scan_num(s, &pl_yylval);
8957                 TERM(THING);
8958             }
8959             else if ((*start == ':' && start[1] == ':')
8960                   || (PL_expect == XSTATE && *start == ':'))
8961                 return yyl_keylookup(aTHX_ s, gv);
8962             else if (PL_expect == XSTATE) {
8963                 d = start;
8964                 while (d < PL_bufend && isSPACE(*d)) d++;
8965                 if (*d == ':')
8966                     return yyl_keylookup(aTHX_ s, gv);
8967             }
8968             /* avoid v123abc() or $h{v1}, allow C<print v10;> */
8969             if (!isALPHA(*start) && (PL_expect == XTERM
8970                         || PL_expect == XREF || PL_expect == XSTATE
8971                         || PL_expect == XTERMORDORDOR)) {
8972                 GV *const gv = gv_fetchpvn_flags(s, start - s,
8973                                                     UTF ? SVf_UTF8 : 0, SVt_PVCV);
8974                 if (!gv) {
8975                     s = scan_num(s, &pl_yylval);
8976                     TERM(THING);
8977                 }
8978             }
8979         }
8980         return yyl_keylookup(aTHX_ s, gv);
8981
8982     case 'x':
8983         if (isDIGIT(s[1]) && PL_expect == XOPERATOR) {
8984             s++;
8985             Mop(OP_REPEAT);
8986         }
8987         return yyl_keylookup(aTHX_ s, gv);
8988
8989     case '_':
8990     case 'a': case 'A':
8991     case 'b': case 'B':
8992     case 'c': case 'C':
8993     case 'd': case 'D':
8994     case 'e': case 'E':
8995     case 'f': case 'F':
8996     case 'g': case 'G':
8997     case 'h': case 'H':
8998     case 'i': case 'I':
8999     case 'j': case 'J':
9000     case 'k': case 'K':
9001     case 'l': case 'L':
9002     case 'm': case 'M':
9003     case 'n': case 'N':
9004     case 'o': case 'O':
9005     case 'p': case 'P':
9006     case 'q': case 'Q':
9007     case 'r': case 'R':
9008     case 's': case 'S':
9009     case 't': case 'T':
9010     case 'u': case 'U':
9011               case 'V':
9012     case 'w': case 'W':
9013               case 'X':
9014     case 'y': case 'Y':
9015     case 'z': case 'Z':
9016         return yyl_keylookup(aTHX_ s, gv);
9017     }
9018 }
9019
9020
9021 /*
9022   yylex
9023
9024   Works out what to call the token just pulled out of the input
9025   stream.  The yacc parser takes care of taking the ops we return and
9026   stitching them into a tree.
9027
9028   Returns:
9029     The type of the next token
9030
9031   Structure:
9032       Check if we have already built the token; if so, use it.
9033       Switch based on the current state:
9034           - if we have a case modifier in a string, deal with that
9035           - handle other cases of interpolation inside a string
9036           - scan the next line if we are inside a format
9037       In the normal state, switch on the next character:
9038           - default:
9039             if alphabetic, go to key lookup
9040             unrecognized character - croak
9041           - 0/4/26: handle end-of-line or EOF
9042           - cases for whitespace
9043           - \n and #: handle comments and line numbers
9044           - various operators, brackets and sigils
9045           - numbers
9046           - quotes
9047           - 'v': vstrings (or go to key lookup)
9048           - 'x' repetition operator (or go to key lookup)
9049           - other ASCII alphanumerics (key lookup begins here):
9050               word before => ?
9051               keyword plugin
9052               scan built-in keyword (but do nothing with it yet)
9053               check for statement label
9054               check for lexical subs
9055                   return yyl_just_a_word if there is one
9056               see whether built-in keyword is overridden
9057               switch on keyword number:
9058                   - default: return yyl_just_a_word:
9059                       not a built-in keyword; handle bareword lookup
9060                       disambiguate between method and sub call
9061                       fall back to bareword
9062                   - cases for built-in keywords
9063 */
9064
9065 #ifdef NETWARE
9066 #define RSFP_FILENO (PL_rsfp)
9067 #else
9068 #define RSFP_FILENO (PerlIO_fileno(PL_rsfp))
9069 #endif
9070
9071
9072 int
9073 Perl_yylex(pTHX)
9074 {
9075     dVAR;
9076     char *s = PL_bufptr;
9077
9078     if (UNLIKELY(PL_parser->recheck_utf8_validity)) {
9079         const U8* first_bad_char_loc;
9080         if (UTF && UNLIKELY(! is_utf8_string_loc((U8 *) PL_bufptr,
9081                                                         PL_bufend - PL_bufptr,
9082                                                         &first_bad_char_loc)))
9083         {
9084             _force_out_malformed_utf8_message(first_bad_char_loc,
9085                                               (U8 *) PL_bufend,
9086                                               0,
9087                                               1 /* 1 means die */ );
9088             NOT_REACHED; /* NOTREACHED */
9089         }
9090         PL_parser->recheck_utf8_validity = FALSE;
9091     }
9092     DEBUG_T( {
9093         SV* tmp = newSVpvs("");
9094         PerlIO_printf(Perl_debug_log, "### %" IVdf ":LEX_%s/X%s %s\n",
9095             (IV)CopLINE(PL_curcop),
9096             lex_state_names[PL_lex_state],
9097             exp_name[PL_expect],
9098             pv_display(tmp, s, strlen(s), 0, 60));
9099         SvREFCNT_dec(tmp);
9100     } );
9101
9102     /* when we've already built the next token, just pull it out of the queue */
9103     if (PL_nexttoke) {
9104         PL_nexttoke--;
9105         pl_yylval = PL_nextval[PL_nexttoke];
9106         {
9107             I32 next_type;
9108             next_type = PL_nexttype[PL_nexttoke];
9109             if (next_type & (7<<24)) {
9110                 if (next_type & (1<<24)) {
9111                     if (PL_lex_brackets > 100)
9112                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
9113                     PL_lex_brackstack[PL_lex_brackets++] =
9114                         (char) ((next_type >> 16) & 0xff);
9115                 }
9116                 if (next_type & (2<<24))
9117                     PL_lex_allbrackets++;
9118                 if (next_type & (4<<24))
9119                     PL_lex_allbrackets--;
9120                 next_type &= 0xffff;
9121             }
9122             return REPORT(next_type == 'p' ? pending_ident() : next_type);
9123         }
9124     }
9125
9126     switch (PL_lex_state) {
9127     case LEX_NORMAL:
9128     case LEX_INTERPNORMAL:
9129         break;
9130
9131     /* interpolated case modifiers like \L \U, including \Q and \E.
9132        when we get here, PL_bufptr is at the \
9133     */
9134     case LEX_INTERPCASEMOD:
9135         /* handle \E or end of string */
9136         return yyl_interpcasemod(aTHX_ s);
9137
9138     case LEX_INTERPPUSH:
9139         return REPORT(sublex_push());
9140
9141     case LEX_INTERPSTART:
9142         if (PL_bufptr == PL_bufend)
9143             return REPORT(sublex_done());
9144         DEBUG_T({
9145             if(*PL_bufptr != '(')
9146                 PerlIO_printf(Perl_debug_log, "### Interpolated variable\n");
9147         });
9148         PL_expect = XTERM;
9149         /* for /@a/, we leave the joining for the regex engine to do
9150          * (unless we're within \Q etc) */
9151         PL_lex_dojoin = (*PL_bufptr == '@'
9152                             && (!PL_lex_inpat || PL_lex_casemods));
9153         PL_lex_state = LEX_INTERPNORMAL;
9154         if (PL_lex_dojoin) {
9155             NEXTVAL_NEXTTOKE.ival = 0;
9156             force_next(',');
9157             force_ident("\"", '$');
9158             NEXTVAL_NEXTTOKE.ival = 0;
9159             force_next('$');
9160             NEXTVAL_NEXTTOKE.ival = 0;
9161             force_next((2<<24)|'(');
9162             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
9163             force_next(FUNC);
9164         }
9165         /* Convert (?{...}) and friends to 'do {...}' */
9166         if (PL_lex_inpat && *PL_bufptr == '(') {
9167             PL_parser->lex_shared->re_eval_start = PL_bufptr;
9168             PL_bufptr += 2;
9169             if (*PL_bufptr != '{')
9170                 PL_bufptr++;
9171             PL_expect = XTERMBLOCK;
9172             force_next(DO);
9173         }
9174
9175         if (PL_lex_starts++) {
9176             s = PL_bufptr;
9177             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9178             if (!PL_lex_casemods && PL_lex_inpat)
9179                 TOKEN(',');
9180             else
9181                 AopNOASSIGN(OP_CONCAT);
9182         }
9183         return yylex();
9184
9185     case LEX_INTERPENDMAYBE:
9186         if (intuit_more(PL_bufptr, PL_bufend)) {
9187             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
9188             break;
9189         }
9190         /* FALLTHROUGH */
9191
9192     case LEX_INTERPEND:
9193         if (PL_lex_dojoin) {
9194             const U8 dojoin_was = PL_lex_dojoin;
9195             PL_lex_dojoin = FALSE;
9196             PL_lex_state = LEX_INTERPCONCAT;
9197             PL_lex_allbrackets--;
9198             return REPORT(dojoin_was == 1 ? (int)')' : (int)POSTJOIN);
9199         }
9200         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
9201             && SvEVALED(PL_lex_repl))
9202         {
9203             if (PL_bufptr != PL_bufend)
9204                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
9205             PL_lex_repl = NULL;
9206         }
9207         /* Paranoia.  re_eval_start is adjusted when S_scan_heredoc sets
9208            re_eval_str.  If the here-doc body’s length equals the previous
9209            value of re_eval_start, re_eval_start will now be null.  So
9210            check re_eval_str as well. */
9211         if (PL_parser->lex_shared->re_eval_start
9212          || PL_parser->lex_shared->re_eval_str) {
9213             SV *sv;
9214             if (*PL_bufptr != ')')
9215                 Perl_croak(aTHX_ "Sequence (?{...}) not terminated with ')'");
9216             PL_bufptr++;
9217             /* having compiled a (?{..}) expression, return the original
9218              * text too, as a const */
9219             if (PL_parser->lex_shared->re_eval_str) {
9220                 sv = PL_parser->lex_shared->re_eval_str;
9221                 PL_parser->lex_shared->re_eval_str = NULL;
9222                 SvCUR_set(sv,
9223                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9224                 SvPV_shrink_to_cur(sv);
9225             }
9226             else sv = newSVpvn(PL_parser->lex_shared->re_eval_start,
9227                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9228             NEXTVAL_NEXTTOKE.opval =
9229                     newSVOP(OP_CONST, 0,
9230                                  sv);
9231             force_next(THING);
9232             PL_parser->lex_shared->re_eval_start = NULL;
9233             PL_expect = XTERM;
9234             return REPORT(',');
9235         }
9236
9237         /* FALLTHROUGH */
9238     case LEX_INTERPCONCAT:
9239 #ifdef DEBUGGING
9240         if (PL_lex_brackets)
9241             Perl_croak(aTHX_ "panic: INTERPCONCAT, lex_brackets=%ld",
9242                        (long) PL_lex_brackets);
9243 #endif
9244         if (PL_bufptr == PL_bufend)
9245             return REPORT(sublex_done());
9246
9247         /* m'foo' still needs to be parsed for possible (?{...}) */
9248         if (SvIVX(PL_linestr) == '\'' && !PL_lex_inpat) {
9249             SV *sv = newSVsv(PL_linestr);
9250             sv = tokeq(sv);
9251             pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
9252             s = PL_bufend;
9253         }
9254         else {
9255             int save_error_count = PL_error_count;
9256
9257             s = scan_const(PL_bufptr);
9258
9259             /* Set flag if this was a pattern and there were errors.  op.c will
9260              * refuse to compile a pattern with this flag set.  Otherwise, we
9261              * could get segfaults, etc. */
9262             if (PL_lex_inpat && PL_error_count > save_error_count) {
9263                 ((PMOP*)PL_lex_inpat)->op_pmflags |= PMf_HAS_ERROR;
9264             }
9265             if (*s == '\\')
9266                 PL_lex_state = LEX_INTERPCASEMOD;
9267             else
9268                 PL_lex_state = LEX_INTERPSTART;
9269         }
9270
9271         if (s != PL_bufptr) {
9272             NEXTVAL_NEXTTOKE = pl_yylval;
9273             PL_expect = XTERM;
9274             force_next(THING);
9275             if (PL_lex_starts++) {
9276                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9277                 if (!PL_lex_casemods && PL_lex_inpat)
9278                     TOKEN(',');
9279                 else
9280                     AopNOASSIGN(OP_CONCAT);
9281             }
9282             else {
9283                 PL_bufptr = s;
9284                 return yylex();
9285             }
9286         }
9287
9288         return yylex();
9289     case LEX_FORMLINE:
9290         if (PL_parser->sub_error_count != PL_error_count) {
9291             /* There was an error parsing a formline, which tends to
9292                mess up the parser.
9293                Unlike interpolated sub-parsing, we can't treat any of
9294                these as recoverable, so no need to check sub_no_recover.
9295             */
9296             yyquit();
9297         }
9298         assert(PL_lex_formbrack);
9299         s = scan_formline(PL_bufptr);
9300         if (!PL_lex_formbrack)
9301             return yyl_rightcurly(aTHX_ s, 1);
9302         PL_bufptr = s;
9303         return yylex();
9304     }
9305
9306     /* We really do *not* want PL_linestr ever becoming a COW. */
9307     assert (!SvIsCOW(PL_linestr));
9308     s = PL_bufptr;
9309     PL_oldoldbufptr = PL_oldbufptr;
9310     PL_oldbufptr = s;
9311
9312     if (PL_in_my == KEY_sigvar) {
9313         PL_parser->saw_infix_sigil = 0;
9314         return yyl_sigvar(aTHX_ s);
9315     }
9316
9317     {
9318         /* yyl_try() and its callees might consult PL_parser->saw_infix_sigil.
9319            On its return, we then need to set it to indicate whether the token
9320            we just encountered was an infix operator that (if we hadn't been
9321            expecting an operator) have been a sigil.
9322         */
9323         bool expected_operator = (PL_expect == XOPERATOR);
9324         int ret = yyl_try(aTHX_ s, 0);
9325         switch (pl_yylval.ival) {
9326         case OP_BIT_AND:
9327         case OP_MODULO:
9328         case OP_MULTIPLY:
9329         case OP_NBIT_AND:
9330             if (expected_operator) {
9331                 PL_parser->saw_infix_sigil = 1;
9332                 break;
9333             }
9334             /* FALLTHROUGH */
9335         default:
9336             PL_parser->saw_infix_sigil = 0;
9337         }
9338         return ret;
9339     }
9340 }
9341
9342
9343 /*
9344   S_pending_ident
9345
9346   Looks up an identifier in the pad or in a package
9347
9348   PL_in_my == KEY_sigvar indicates that this is a subroutine signature variable
9349   rather than a plain pad var.
9350
9351   Returns:
9352     PRIVATEREF if this is a lexical name.
9353     BAREWORD   if this belongs to a package.
9354
9355   Structure:
9356       if we're in a my declaration
9357           croak if they tried to say my($foo::bar)
9358           build the ops for a my() declaration
9359       if it's an access to a my() variable
9360           build ops for access to a my() variable
9361       if in a dq string, and they've said @foo and we can't find @foo
9362           warn
9363       build ops for a bareword
9364 */
9365
9366 static int
9367 S_pending_ident(pTHX)
9368 {
9369     PADOFFSET tmp = 0;
9370     const char pit = (char)pl_yylval.ival;
9371     const STRLEN tokenbuf_len = strlen(PL_tokenbuf);
9372     /* All routes through this function want to know if there is a colon.  */
9373     const char *const has_colon = (const char*) memchr (PL_tokenbuf, ':', tokenbuf_len);
9374
9375     DEBUG_T({ PerlIO_printf(Perl_debug_log,
9376           "### Pending identifier '%s'\n", PL_tokenbuf); });
9377     assert(tokenbuf_len >= 2);
9378
9379     /* if we're in a my(), we can't allow dynamics here.
9380        $foo'bar has already been turned into $foo::bar, so
9381        just check for colons.
9382
9383        if it's a legal name, the OP is a PADANY.
9384     */
9385     if (PL_in_my) {
9386         if (PL_in_my == KEY_our) {      /* "our" is merely analogous to "my" */
9387             if (has_colon)
9388                 /* diag_listed_as: No package name allowed for variable %s
9389                                    in "our" */
9390                 yyerror_pv(Perl_form(aTHX_ "No package name allowed for "
9391                                   "%s %s in \"our\"",
9392                                   *PL_tokenbuf=='&' ? "subroutine" : "variable",
9393                                   PL_tokenbuf), UTF ? SVf_UTF8 : 0);
9394             tmp = allocmy(PL_tokenbuf, tokenbuf_len, UTF ? SVf_UTF8 : 0);
9395         }
9396         else {
9397             OP *o;
9398             if (has_colon) {
9399                 /* "my" variable %s can't be in a package */
9400                 /* PL_no_myglob is constant */
9401                 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
9402                 yyerror_pv(Perl_form(aTHX_ PL_no_myglob,
9403                             PL_in_my == KEY_my ? "my" : "state",
9404                             *PL_tokenbuf == '&' ? "subroutine" : "variable",
9405                             PL_tokenbuf),
9406                             UTF ? SVf_UTF8 : 0);
9407                 GCC_DIAG_RESTORE_STMT;
9408             }
9409
9410             if (PL_in_my == KEY_sigvar) {
9411                 /* A signature 'padop' needs in addition, an op_first to
9412                  * point to a child sigdefelem, and an extra field to hold
9413                  * the signature index. We can achieve both by using an
9414                  * UNOP_AUX and (ab)using the op_aux field to hold the
9415                  * index. If we ever need more fields, use a real malloced
9416                  * aux strut instead.
9417                  */
9418                 o = newUNOP_AUX(OP_ARGELEM, 0, NULL,
9419                                     INT2PTR(UNOP_AUX_item *,
9420                                         (PL_parser->sig_elems)));
9421                 o->op_private |= (  PL_tokenbuf[0] == '$' ? OPpARGELEM_SV
9422                                   : PL_tokenbuf[0] == '@' ? OPpARGELEM_AV
9423                                   :                         OPpARGELEM_HV);
9424             }
9425             else
9426                 o = newOP(OP_PADANY, 0);
9427             o->op_targ = allocmy(PL_tokenbuf, tokenbuf_len,
9428                                                         UTF ? SVf_UTF8 : 0);
9429             if (PL_in_my == KEY_sigvar)
9430                 PL_in_my = 0;
9431
9432             pl_yylval.opval = o;
9433             return PRIVATEREF;
9434         }
9435     }
9436
9437     /*
9438        build the ops for accesses to a my() variable.
9439     */
9440
9441     if (!has_colon) {
9442         if (!PL_in_my)
9443             tmp = pad_findmy_pvn(PL_tokenbuf, tokenbuf_len,
9444                                  0);
9445         if (tmp != NOT_IN_PAD) {
9446             /* might be an "our" variable" */
9447             if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
9448                 /* build ops for a bareword */
9449                 HV *  const stash = PAD_COMPNAME_OURSTASH(tmp);
9450                 HEK * const stashname = HvNAME_HEK(stash);
9451                 SV *  const sym = newSVhek(stashname);
9452                 sv_catpvs(sym, "::");
9453                 sv_catpvn_flags(sym, PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0, (UTF ? SV_CATUTF8 : SV_CATBYTES ));
9454                 pl_yylval.opval = newSVOP(OP_CONST, 0, sym);
9455                 pl_yylval.opval->op_private = OPpCONST_ENTERED;
9456                 if (pit != '&')
9457                   gv_fetchsv(sym,
9458                     GV_ADDMULTI,
9459                     ((PL_tokenbuf[0] == '$') ? SVt_PV
9460                      : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9461                      : SVt_PVHV));
9462                 return BAREWORD;
9463             }
9464
9465             pl_yylval.opval = newOP(OP_PADANY, 0);
9466             pl_yylval.opval->op_targ = tmp;
9467             return PRIVATEREF;
9468         }
9469     }
9470
9471     /*
9472        Whine if they've said @foo or @foo{key} in a doublequoted string,
9473        and @foo (or %foo) isn't a variable we can find in the symbol
9474        table.
9475     */
9476     if (ckWARN(WARN_AMBIGUOUS)
9477         && pit == '@'
9478         && PL_lex_state != LEX_NORMAL
9479         && !PL_lex_brackets)
9480     {
9481         GV *const gv = gv_fetchpvn_flags(PL_tokenbuf + 1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9482                                          ( UTF ? SVf_UTF8 : 0 ) | GV_ADDMG,
9483                                          SVt_PVAV);
9484         if ((!gv || ((PL_tokenbuf[0] == '@') ? !GvAV(gv) : !GvHV(gv)))
9485            )
9486         {
9487             /* Downgraded from fatal to warning 20000522 mjd */
9488             Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9489                         "Possible unintended interpolation of %" UTF8f
9490                         " in string",
9491                         UTF8fARG(UTF, tokenbuf_len, PL_tokenbuf));
9492         }
9493     }
9494
9495     /* build ops for a bareword */
9496     pl_yylval.opval = newSVOP(OP_CONST, 0,
9497                                    newSVpvn_flags(PL_tokenbuf + 1,
9498                                                       tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9499                                                       UTF ? SVf_UTF8 : 0 ));
9500     pl_yylval.opval->op_private = OPpCONST_ENTERED;
9501     if (pit != '&')
9502         gv_fetchpvn_flags(PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9503                      (PL_in_eval ? GV_ADDMULTI : GV_ADD)
9504                      | ( UTF ? SVf_UTF8 : 0 ),
9505                      ((PL_tokenbuf[0] == '$') ? SVt_PV
9506                       : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9507                       : SVt_PVHV));
9508     return BAREWORD;
9509 }
9510
9511 STATIC void
9512 S_checkcomma(pTHX_ const char *s, const char *name, const char *what)
9513 {
9514     PERL_ARGS_ASSERT_CHECKCOMMA;
9515
9516     if (*s == ' ' && s[1] == '(') {     /* XXX gotta be a better way */
9517         if (ckWARN(WARN_SYNTAX)) {
9518             int level = 1;
9519             const char *w;
9520             for (w = s+2; *w && level; w++) {
9521                 if (*w == '(')
9522                     ++level;
9523                 else if (*w == ')')
9524                     --level;
9525             }
9526             while (isSPACE(*w))
9527                 ++w;
9528             /* the list of chars below is for end of statements or
9529              * block / parens, boolean operators (&&, ||, //) and branch
9530              * constructs (or, and, if, until, unless, while, err, for).
9531              * Not a very solid hack... */
9532             if (!*w || !memCHRs(";&/|})]oaiuwef!=", *w))
9533                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9534                             "%s (...) interpreted as function",name);
9535         }
9536     }
9537     while (s < PL_bufend && isSPACE(*s))
9538         s++;
9539     if (*s == '(')
9540         s++;
9541     while (s < PL_bufend && isSPACE(*s))
9542         s++;
9543     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
9544         const char * const w = s;
9545         s += UTF ? UTF8SKIP(s) : 1;
9546         while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
9547             s += UTF ? UTF8SKIP(s) : 1;
9548         while (s < PL_bufend && isSPACE(*s))
9549             s++;
9550         if (*s == ',') {
9551             GV* gv;
9552             if (keyword(w, s - w, 0))
9553                 return;
9554
9555             gv = gv_fetchpvn_flags(w, s - w, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
9556             if (gv && GvCVu(gv))
9557                 return;
9558             if (s - w <= 254) {
9559                 PADOFFSET off;
9560                 char tmpbuf[256];
9561                 Copy(w, tmpbuf+1, s - w, char);
9562                 *tmpbuf = '&';
9563                 off = pad_findmy_pvn(tmpbuf, s-w+1, 0);
9564                 if (off != NOT_IN_PAD) return;
9565             }
9566             Perl_croak(aTHX_ "No comma allowed after %s", what);
9567         }
9568     }
9569 }
9570
9571 /* S_new_constant(): do any overload::constant lookup.
9572
9573    Either returns sv, or mortalizes/frees sv and returns a new SV*.
9574    Best used as sv=new_constant(..., sv, ...).
9575    If s, pv are NULL, calls subroutine with one argument,
9576    and <type> is used with error messages only.
9577    <type> is assumed to be well formed UTF-8.
9578
9579    If error_msg is not NULL, *error_msg will be set to any error encountered.
9580    Otherwise yyerror() will be used to output it */
9581
9582 STATIC SV *
9583 S_new_constant(pTHX_ const char *s, STRLEN len, const char *key, STRLEN keylen,
9584                SV *sv, SV *pv, const char *type, STRLEN typelen,
9585                const char ** error_msg)
9586 {
9587     dSP;
9588     HV * table = GvHV(PL_hintgv);                /* ^H */
9589     SV *res;
9590     SV *errsv = NULL;
9591     SV **cvp;
9592     SV *cv, *typesv;
9593     const char *why1 = "", *why2 = "", *why3 = "";
9594
9595     PERL_ARGS_ASSERT_NEW_CONSTANT;
9596     /* We assume that this is true: */
9597     if (*key == 'c') { assert (strEQ(key, "charnames")); }
9598     assert(type || s);
9599
9600     sv_2mortal(sv);                     /* Parent created it permanently */
9601     if (!table
9602         || ! (PL_hints & HINT_LOCALIZE_HH)
9603         || ! (cvp = hv_fetch(table, key, keylen, FALSE))
9604         || ! SvOK(*cvp))
9605     {
9606         char *msg;
9607
9608         /* Here haven't found what we're looking for.  If it is charnames,
9609          * perhaps it needs to be loaded.  Try doing that before giving up */
9610         if (*key == 'c') {
9611             Perl_load_module(aTHX_
9612                             0,
9613                             newSVpvs("_charnames"),
9614                              /* version parameter; no need to specify it, as if
9615                               * we get too early a version, will fail anyway,
9616                               * not being able to find '_charnames' */
9617                             NULL,
9618                             newSVpvs(":full"),
9619                             newSVpvs(":short"),
9620                             NULL);
9621             assert(sp == PL_stack_sp);
9622             table = GvHV(PL_hintgv);
9623             if (table
9624                 && (PL_hints & HINT_LOCALIZE_HH)
9625                 && (cvp = hv_fetch(table, key, keylen, FALSE))
9626                 && SvOK(*cvp))
9627             {
9628                 goto now_ok;
9629             }
9630         }
9631         if (!table || !(PL_hints & HINT_LOCALIZE_HH)) {
9632             msg = Perl_form(aTHX_
9633                                "Constant(%.*s) unknown",
9634                                 (int)(type ? typelen : len),
9635                                 (type ? type: s));
9636         }
9637         else {
9638             why1 = "$^H{";
9639             why2 = key;
9640             why3 = "} is not defined";
9641         report:
9642             if (*key == 'c') {
9643                 msg = Perl_form(aTHX_
9644                             /* The +3 is for '\N{'; -4 for that, plus '}' */
9645                             "Unknown charname '%.*s'", (int)typelen - 4, type + 3
9646                       );
9647             }
9648             else {
9649                 msg = Perl_form(aTHX_ "Constant(%.*s): %s%s%s",
9650                                     (int)(type ? typelen : len),
9651                                     (type ? type: s), why1, why2, why3);
9652             }
9653         }
9654         if (error_msg) {
9655             *error_msg = msg;
9656         }
9657         else {
9658             yyerror_pv(msg, UTF ? SVf_UTF8 : 0);
9659         }
9660         return SvREFCNT_inc_simple_NN(sv);
9661     }
9662   now_ok:
9663     cv = *cvp;
9664     if (!pv && s)
9665         pv = newSVpvn_flags(s, len, SVs_TEMP);
9666     if (type && pv)
9667         typesv = newSVpvn_flags(type, typelen, SVs_TEMP);
9668     else
9669         typesv = &PL_sv_undef;
9670
9671     PUSHSTACKi(PERLSI_OVERLOAD);
9672     ENTER ;
9673     SAVETMPS;
9674
9675     PUSHMARK(SP) ;
9676     EXTEND(sp, 3);
9677     if (pv)
9678         PUSHs(pv);
9679     PUSHs(sv);
9680     if (pv)
9681         PUSHs(typesv);
9682     PUTBACK;
9683     call_sv(cv, G_SCALAR | ( PL_in_eval ? 0 : G_EVAL));
9684
9685     SPAGAIN ;
9686
9687     /* Check the eval first */
9688     if (!PL_in_eval && ((errsv = ERRSV), SvTRUE_NN(errsv))) {
9689         STRLEN errlen;
9690         const char * errstr;
9691         sv_catpvs(errsv, "Propagated");
9692         errstr = SvPV_const(errsv, errlen);
9693         yyerror_pvn(errstr, errlen, 0); /* Duplicates the message inside eval */
9694         (void)POPs;
9695         res = SvREFCNT_inc_simple_NN(sv);
9696     }
9697     else {
9698         res = POPs;
9699         SvREFCNT_inc_simple_void_NN(res);
9700     }
9701
9702     PUTBACK ;
9703     FREETMPS ;
9704     LEAVE ;
9705     POPSTACK;
9706
9707     if (!SvOK(res)) {
9708         why1 = "Call to &{$^H{";
9709         why2 = key;
9710         why3 = "}} did not return a defined value";
9711         sv = res;
9712         (void)sv_2mortal(sv);
9713         goto report;
9714     }
9715
9716     return res;
9717 }
9718
9719 PERL_STATIC_INLINE void
9720 S_parse_ident(pTHX_ char **s, char **d, char * const e, int allow_package,
9721                     bool is_utf8, bool check_dollar, bool tick_warn)
9722 {
9723     int saw_tick = 0;
9724     const char *olds = *s;
9725     PERL_ARGS_ASSERT_PARSE_IDENT;
9726
9727     while (*s < PL_bufend) {
9728         if (*d >= e)
9729             Perl_croak(aTHX_ "%s", ident_too_long);
9730         if (is_utf8 && isIDFIRST_utf8_safe(*s, PL_bufend)) {
9731              /* The UTF-8 case must come first, otherwise things
9732              * like c\N{COMBINING TILDE} would start failing, as the
9733              * isWORDCHAR_A case below would gobble the 'c' up.
9734              */
9735
9736             char *t = *s + UTF8SKIP(*s);
9737             while (isIDCONT_utf8_safe((const U8*) t, (const U8*) PL_bufend)) {
9738                 t += UTF8SKIP(t);
9739             }
9740             if (*d + (t - *s) > e)
9741                 Perl_croak(aTHX_ "%s", ident_too_long);
9742             Copy(*s, *d, t - *s, char);
9743             *d += t - *s;
9744             *s = t;
9745         }
9746         else if ( isWORDCHAR_A(**s) ) {
9747             do {
9748                 *(*d)++ = *(*s)++;
9749             } while (isWORDCHAR_A(**s) && *d < e);
9750         }
9751         else if (   allow_package
9752                  && **s == '\''
9753                  && isIDFIRST_lazy_if_safe((*s)+1, PL_bufend, is_utf8))
9754         {
9755             *(*d)++ = ':';
9756             *(*d)++ = ':';
9757             (*s)++;
9758             saw_tick++;
9759         }
9760         else if (allow_package && **s == ':' && (*s)[1] == ':'
9761            /* Disallow things like Foo::$bar. For the curious, this is
9762             * the code path that triggers the "Bad name after" warning
9763             * when looking for barewords.
9764             */
9765            && !(check_dollar && (*s)[2] == '$')) {
9766             *(*d)++ = *(*s)++;
9767             *(*d)++ = *(*s)++;
9768         }
9769         else
9770             break;
9771     }
9772     if (UNLIKELY(tick_warn && saw_tick && PL_lex_state == LEX_INTERPNORMAL
9773               && !PL_lex_brackets && ckWARN(WARN_SYNTAX))) {
9774         char *this_d;
9775         char *d2;
9776         Newx(this_d, *s - olds + saw_tick + 2, char); /* +2 for $# */
9777         d2 = this_d;
9778         SAVEFREEPV(this_d);
9779         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9780                          "Old package separator used in string");
9781         if (olds[-1] == '#')
9782             *d2++ = olds[-2];
9783         *d2++ = olds[-1];
9784         while (olds < *s) {
9785             if (*olds == '\'') {
9786                 *d2++ = '\\';
9787                 *d2++ = *olds++;
9788             }
9789             else
9790                 *d2++ = *olds++;
9791         }
9792         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9793                          "\t(Did you mean \"%" UTF8f "\" instead?)\n",
9794                           UTF8fARG(is_utf8, d2-this_d, this_d));
9795     }
9796     return;
9797 }
9798
9799 /* Returns a NUL terminated string, with the length of the string written to
9800    *slp
9801    */
9802 char *
9803 Perl_scan_word(pTHX_ char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
9804 {
9805     char *d = dest;
9806     char * const e = d + destlen - 3;  /* two-character token, ending NUL */
9807     bool is_utf8 = cBOOL(UTF);
9808
9809     PERL_ARGS_ASSERT_SCAN_WORD;
9810
9811     parse_ident(&s, &d, e, allow_package, is_utf8, TRUE, FALSE);
9812     *d = '\0';
9813     *slp = d - dest;
9814     return s;
9815 }
9816
9817 /* Is the byte 'd' a legal single character identifier name?  'u' is true
9818  * iff Unicode semantics are to be used.  The legal ones are any of:
9819  *  a) all ASCII characters except:
9820  *          1) control and space-type ones, like NUL, SOH, \t, and SPACE;
9821  *          2) '{'
9822  *     The final case currently doesn't get this far in the program, so we
9823  *     don't test for it.  If that were to change, it would be ok to allow it.
9824  *  b) When not under Unicode rules, any upper Latin1 character
9825  *  c) Otherwise, when unicode rules are used, all XIDS characters.
9826  *
9827  *      Because all ASCII characters have the same representation whether
9828  *      encoded in UTF-8 or not, we can use the foo_A macros below and '\0' and
9829  *      '{' without knowing if is UTF-8 or not. */
9830 #define VALID_LEN_ONE_IDENT(s, e, is_utf8)                                  \
9831     (isGRAPH_A(*(s)) || ((is_utf8)                                          \
9832                          ? isIDFIRST_utf8_safe(s, e)                        \
9833                          : (isGRAPH_L1(*s)                                  \
9834                             && LIKELY((U8) *(s) != LATIN1_TO_NATIVE(0xAD)))))
9835
9836 STATIC char *
9837 S_scan_ident(pTHX_ char *s, char *dest, STRLEN destlen, I32 ck_uni)
9838 {
9839     I32 herelines = PL_parser->herelines;
9840     SSize_t bracket = -1;
9841     char funny = *s++;
9842     char *d = dest;
9843     char * const e = d + destlen - 3;    /* two-character token, ending NUL */
9844     bool is_utf8 = cBOOL(UTF);
9845     I32 orig_copline = 0, tmp_copline = 0;
9846
9847     PERL_ARGS_ASSERT_SCAN_IDENT;
9848
9849     if (isSPACE(*s) || !*s)
9850         s = skipspace(s);
9851     if (isDIGIT(*s)) {
9852         while (isDIGIT(*s)) {
9853             if (d >= e)
9854                 Perl_croak(aTHX_ "%s", ident_too_long);
9855             *d++ = *s++;
9856         }
9857     }
9858     else {  /* See if it is a "normal" identifier */
9859         parse_ident(&s, &d, e, 1, is_utf8, FALSE, TRUE);
9860     }
9861     *d = '\0';
9862     d = dest;
9863     if (*d) {
9864         /* Either a digit variable, or parse_ident() found an identifier
9865            (anything valid as a bareword), so job done and return.  */
9866         if (PL_lex_state != LEX_NORMAL)
9867             PL_lex_state = LEX_INTERPENDMAYBE;
9868         return s;
9869     }
9870
9871     /* Here, it is not a run-of-the-mill identifier name */
9872
9873     if (*s == '$' && s[1]
9874         && (   isIDFIRST_lazy_if_safe(s+1, PL_bufend, is_utf8)
9875             || isDIGIT_A((U8)s[1])
9876             || s[1] == '$'
9877             || s[1] == '{'
9878             || memBEGINs(s+1, (STRLEN) (PL_bufend - (s+1)), "::")) )
9879     {
9880         /* Dereferencing a value in a scalar variable.
9881            The alternatives are different syntaxes for a scalar variable.
9882            Using ' as a leading package separator isn't allowed. :: is.   */
9883         return s;
9884     }
9885     /* Handle the opening { of @{...}, &{...}, *{...}, %{...}, ${...}  */
9886     if (*s == '{') {
9887         bracket = s - SvPVX(PL_linestr);
9888         s++;
9889         orig_copline = CopLINE(PL_curcop);
9890         if (s < PL_bufend && isSPACE(*s)) {
9891             s = skipspace(s);
9892         }
9893     }
9894     if ((s <= PL_bufend - ((is_utf8)
9895                           ? UTF8SKIP(s)
9896                           : 1))
9897         && VALID_LEN_ONE_IDENT(s, PL_bufend, is_utf8))
9898     {
9899         if (is_utf8) {
9900             const STRLEN skip = UTF8SKIP(s);
9901             STRLEN i;
9902             d[skip] = '\0';
9903             for ( i = 0; i < skip; i++ )
9904                 d[i] = *s++;
9905         }
9906         else {
9907             *d = *s++;
9908             d[1] = '\0';
9909         }
9910     }
9911     /* Convert $^F, ${^F} and the ^F of ${^FOO} to control characters */
9912     if (*d == '^' && *s && isCONTROLVAR(*s)) {
9913         *d = toCTRL(*s);
9914         s++;
9915     }
9916     /* Warn about ambiguous code after unary operators if {...} notation isn't
9917        used.  There's no difference in ambiguity; it's merely a heuristic
9918        about when not to warn.  */
9919     else if (ck_uni && bracket == -1)
9920         check_uni();
9921     if (bracket != -1) {
9922         bool skip;
9923         char *s2;
9924         /* If we were processing {...} notation then...  */
9925         if (isIDFIRST_lazy_if_safe(d, e, is_utf8)
9926             || (!isPRINT(*d) /* isCNTRL(d), plus all non-ASCII */
9927                  && isWORDCHAR(*s))
9928         ) {
9929             /* note we have to check for a normal identifier first,
9930              * as it handles utf8 symbols, and only after that has
9931              * been ruled out can we look at the caret words */
9932             if (isIDFIRST_lazy_if_safe(d, e, is_utf8) ) {
9933                 /* if it starts as a valid identifier, assume that it is one.
9934                    (the later check for } being at the expected point will trap
9935                    cases where this doesn't pan out.)  */
9936                 d += is_utf8 ? UTF8SKIP(d) : 1;
9937                 parse_ident(&s, &d, e, 1, is_utf8, TRUE, TRUE);
9938                 *d = '\0';
9939             }
9940             else { /* caret word: ${^Foo} ${^CAPTURE[0]} */
9941                 d++;
9942                 while (isWORDCHAR(*s) && d < e) {
9943                     *d++ = *s++;
9944                 }
9945                 if (d >= e)
9946                     Perl_croak(aTHX_ "%s", ident_too_long);
9947                 *d = '\0';
9948             }
9949             tmp_copline = CopLINE(PL_curcop);
9950             if (s < PL_bufend && isSPACE(*s)) {
9951                 s = skipspace(s);
9952             }
9953             if ((*s == '[' || (*s == '{' && strNE(dest, "sub")))) {
9954                 /* ${foo[0]} and ${foo{bar}} and ${^CAPTURE[0]} notation.  */
9955                 if (ckWARN(WARN_AMBIGUOUS) && keyword(dest, d - dest, 0)) {
9956                     const char * const brack =
9957                         (const char *)
9958                         ((*s == '[') ? "[...]" : "{...}");
9959                     orig_copline = CopLINE(PL_curcop);
9960                     CopLINE_set(PL_curcop, tmp_copline);
9961    /* diag_listed_as: Ambiguous use of %c{%s[...]} resolved to %c%s[...] */
9962                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9963                         "Ambiguous use of %c{%s%s} resolved to %c%s%s",
9964                         funny, dest, brack, funny, dest, brack);
9965                     CopLINE_set(PL_curcop, orig_copline);
9966                 }
9967                 bracket++;
9968                 PL_lex_brackstack[PL_lex_brackets++] = (char)(XOPERATOR | XFAKEBRACK);
9969                 PL_lex_allbrackets++;
9970                 return s;
9971             }
9972         }
9973
9974         if ( !tmp_copline )
9975             tmp_copline = CopLINE(PL_curcop);
9976         if ((skip = s < PL_bufend && isSPACE(*s))) {
9977             /* Avoid incrementing line numbers or resetting PL_linestart,
9978                in case we have to back up.  */
9979             STRLEN s_off = s - SvPVX(PL_linestr);
9980             s2 = peekspace(s);
9981             s = SvPVX(PL_linestr) + s_off;
9982         }
9983         else
9984             s2 = s;
9985
9986         /* Expect to find a closing } after consuming any trailing whitespace.
9987          */
9988         if (*s2 == '}') {
9989             /* Now increment line numbers if applicable.  */
9990             if (skip)
9991                 s = skipspace(s);
9992             s++;
9993             if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
9994                 PL_lex_state = LEX_INTERPEND;
9995                 PL_expect = XREF;
9996             }
9997             if (PL_lex_state == LEX_NORMAL || PL_lex_brackets) {
9998                 if (ckWARN(WARN_AMBIGUOUS)
9999                     && (keyword(dest, d - dest, 0)
10000                         || get_cvn_flags(dest, d - dest, is_utf8
10001                            ? SVf_UTF8
10002                            : 0)))
10003                 {
10004                     SV *tmp = newSVpvn_flags( dest, d - dest,
10005                                         SVs_TEMP | (is_utf8 ? SVf_UTF8 : 0) );
10006                     if (funny == '#')
10007                         funny = '@';
10008                     orig_copline = CopLINE(PL_curcop);
10009                     CopLINE_set(PL_curcop, tmp_copline);
10010                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
10011                         "Ambiguous use of %c{%" SVf "} resolved to %c%" SVf,
10012                         funny, SVfARG(tmp), funny, SVfARG(tmp));
10013                     CopLINE_set(PL_curcop, orig_copline);
10014                 }
10015             }
10016         }
10017         else {
10018             /* Didn't find the closing } at the point we expected, so restore
10019                state such that the next thing to process is the opening { and */
10020             s = SvPVX(PL_linestr) + bracket; /* let the parser handle it */
10021             CopLINE_set(PL_curcop, orig_copline);
10022             PL_parser->herelines = herelines;
10023             *dest = '\0';
10024             PL_parser->sub_no_recover = TRUE;
10025         }
10026     }
10027     else if (   PL_lex_state == LEX_INTERPNORMAL
10028              && !PL_lex_brackets
10029              && !intuit_more(s, PL_bufend))
10030         PL_lex_state = LEX_INTERPEND;
10031     return s;
10032 }
10033
10034 static bool
10035 S_pmflag(pTHX_ const char* const valid_flags, U32 * pmfl, char** s, char* charset, unsigned int * x_mod_count) {
10036
10037     /* Adds, subtracts to/from 'pmfl' based on the next regex modifier flag
10038      * found in the parse starting at 's', based on the subset that are valid
10039      * in this context input to this routine in 'valid_flags'. Advances s.
10040      * Returns TRUE if the input should be treated as a valid flag, so the next
10041      * char may be as well; otherwise FALSE. 'charset' should point to a NUL
10042      * upon first call on the current regex.  This routine will set it to any
10043      * charset modifier found.  The caller shouldn't change it.  This way,
10044      * another charset modifier encountered in the parse can be detected as an
10045      * error, as we have decided to allow only one */
10046
10047     const char c = **s;
10048     STRLEN charlen = UTF ? UTF8SKIP(*s) : 1;
10049
10050     if ( charlen != 1 || ! strchr(valid_flags, c) ) {
10051         if (isWORDCHAR_lazy_if_safe( *s, PL_bufend, UTF)) {
10052             yyerror_pv(Perl_form(aTHX_ "Unknown regexp modifier \"/%.*s\"", (int)charlen, *s),
10053                        UTF ? SVf_UTF8 : 0);
10054             (*s) += charlen;
10055             /* Pretend that it worked, so will continue processing before
10056              * dieing */
10057             return TRUE;
10058         }
10059         return FALSE;
10060     }
10061
10062     switch (c) {
10063
10064         CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, *x_mod_count);
10065         case GLOBAL_PAT_MOD:      *pmfl |= PMf_GLOBAL; break;
10066         case CONTINUE_PAT_MOD:    *pmfl |= PMf_CONTINUE; break;
10067         case ONCE_PAT_MOD:        *pmfl |= PMf_KEEP; break;
10068         case KEEPCOPY_PAT_MOD:    *pmfl |= RXf_PMf_KEEPCOPY; break;
10069         case NONDESTRUCT_PAT_MOD: *pmfl |= PMf_NONDESTRUCT; break;
10070         case LOCALE_PAT_MOD:
10071             if (*charset) {
10072                 goto multiple_charsets;
10073             }
10074             set_regex_charset(pmfl, REGEX_LOCALE_CHARSET);
10075             *charset = c;
10076             break;
10077         case UNICODE_PAT_MOD:
10078             if (*charset) {
10079                 goto multiple_charsets;
10080             }
10081             set_regex_charset(pmfl, REGEX_UNICODE_CHARSET);
10082             *charset = c;
10083             break;
10084         case ASCII_RESTRICT_PAT_MOD:
10085             if (! *charset) {
10086                 set_regex_charset(pmfl, REGEX_ASCII_RESTRICTED_CHARSET);
10087             }
10088             else {
10089
10090                 /* Error if previous modifier wasn't an 'a', but if it was, see
10091                  * if, and accept, a second occurrence (only) */
10092                 if (*charset != 'a'
10093                     || get_regex_charset(*pmfl)
10094                         != REGEX_ASCII_RESTRICTED_CHARSET)
10095                 {
10096                         goto multiple_charsets;
10097                 }
10098                 set_regex_charset(pmfl, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
10099             }
10100             *charset = c;
10101             break;
10102         case DEPENDS_PAT_MOD:
10103             if (*charset) {
10104                 goto multiple_charsets;
10105             }
10106             set_regex_charset(pmfl, REGEX_DEPENDS_CHARSET);
10107             *charset = c;
10108             break;
10109     }
10110
10111     (*s)++;
10112     return TRUE;
10113
10114     multiple_charsets:
10115         if (*charset != c) {
10116             yyerror(Perl_form(aTHX_ "Regexp modifiers \"/%c\" and \"/%c\" are mutually exclusive", *charset, c));
10117         }
10118         else if (c == 'a') {
10119   /* diag_listed_as: Regexp modifier "/%c" may appear a maximum of twice */
10120             yyerror("Regexp modifier \"/a\" may appear a maximum of twice");
10121         }
10122         else {
10123             yyerror(Perl_form(aTHX_ "Regexp modifier \"/%c\" may not appear twice", c));
10124         }
10125
10126         /* Pretend that it worked, so will continue processing before dieing */
10127         (*s)++;
10128         return TRUE;
10129 }
10130
10131 STATIC char *
10132 S_scan_pat(pTHX_ char *start, I32 type)
10133 {
10134     PMOP *pm;
10135     char *s;
10136     const char * const valid_flags =
10137         (const char *)((type == OP_QR) ? QR_PAT_MODS : M_PAT_MODS);
10138     char charset = '\0';    /* character set modifier */
10139     unsigned int x_mod_count = 0;
10140
10141     PERL_ARGS_ASSERT_SCAN_PAT;
10142
10143     s = scan_str(start,TRUE,FALSE, (PL_in_eval & EVAL_RE_REPARSING), NULL);
10144     if (!s)
10145         Perl_croak(aTHX_ "Search pattern not terminated");
10146
10147     pm = (PMOP*)newPMOP(type, 0);
10148     if (PL_multi_open == '?') {
10149         /* This is the only point in the code that sets PMf_ONCE:  */
10150         pm->op_pmflags |= PMf_ONCE;
10151
10152         /* Hence it's safe to do this bit of PMOP book-keeping here, which
10153            allows us to restrict the list needed by reset to just the ??
10154            matches.  */
10155         assert(type != OP_TRANS);
10156         if (PL_curstash) {
10157             MAGIC *mg = mg_find((const SV *)PL_curstash, PERL_MAGIC_symtab);
10158             U32 elements;
10159             if (!mg) {
10160                 mg = sv_magicext(MUTABLE_SV(PL_curstash), 0, PERL_MAGIC_symtab, 0, 0,
10161                                  0);
10162             }
10163             elements = mg->mg_len / sizeof(PMOP**);
10164             Renewc(mg->mg_ptr, elements + 1, PMOP*, char);
10165             ((PMOP**)mg->mg_ptr) [elements++] = pm;
10166             mg->mg_len = elements * sizeof(PMOP**);
10167             PmopSTASH_set(pm,PL_curstash);
10168         }
10169     }
10170
10171     /* if qr/...(?{..}).../, then need to parse the pattern within a new
10172      * anon CV. False positives like qr/[(?{]/ are harmless */
10173
10174     if (type == OP_QR) {
10175         STRLEN len;
10176         char *e, *p = SvPV(PL_lex_stuff, len);
10177         e = p + len;
10178         for (; p < e; p++) {
10179             if (p[0] == '(' && p[1] == '?'
10180                 && (p[2] == '{' || (p[2] == '?' && p[3] == '{')))
10181             {
10182                 pm->op_pmflags |= PMf_HAS_CV;
10183                 break;
10184             }
10185         }
10186         pm->op_pmflags |= PMf_IS_QR;
10187     }
10188
10189     while (*s && S_pmflag(aTHX_ valid_flags, &(pm->op_pmflags),
10190                                 &s, &charset, &x_mod_count))
10191     {};
10192     /* issue a warning if /c is specified,but /g is not */
10193     if ((pm->op_pmflags & PMf_CONTINUE) && !(pm->op_pmflags & PMf_GLOBAL))
10194     {
10195         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10196                        "Use of /c modifier is meaningless without /g" );
10197     }
10198
10199     PL_lex_op = (OP*)pm;
10200     pl_yylval.ival = OP_MATCH;
10201     return s;
10202 }
10203
10204 STATIC char *
10205 S_scan_subst(pTHX_ char *start)
10206 {
10207     char *s;
10208     PMOP *pm;
10209     I32 first_start;
10210     line_t first_line;
10211     line_t linediff = 0;
10212     I32 es = 0;
10213     char charset = '\0';    /* character set modifier */
10214     unsigned int x_mod_count = 0;
10215     char *t;
10216
10217     PERL_ARGS_ASSERT_SCAN_SUBST;
10218
10219     pl_yylval.ival = OP_NULL;
10220
10221     s = scan_str(start, TRUE, FALSE, FALSE, &t);
10222
10223     if (!s)
10224         Perl_croak(aTHX_ "Substitution pattern not terminated");
10225
10226     s = t;
10227
10228     first_start = PL_multi_start;
10229     first_line = CopLINE(PL_curcop);
10230     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10231     if (!s) {
10232         SvREFCNT_dec_NN(PL_lex_stuff);
10233         PL_lex_stuff = NULL;
10234         Perl_croak(aTHX_ "Substitution replacement not terminated");
10235     }
10236     PL_multi_start = first_start;       /* so whole substitution is taken together */
10237
10238     pm = (PMOP*)newPMOP(OP_SUBST, 0);
10239
10240
10241     while (*s) {
10242         if (*s == EXEC_PAT_MOD) {
10243             s++;
10244             es++;
10245         }
10246         else if (! S_pmflag(aTHX_ S_PAT_MODS, &(pm->op_pmflags),
10247                                   &s, &charset, &x_mod_count))
10248         {
10249             break;
10250         }
10251     }
10252
10253     if ((pm->op_pmflags & PMf_CONTINUE)) {
10254         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Use of /c modifier is meaningless in s///" );
10255     }
10256
10257     if (es) {
10258         SV * const repl = newSVpvs("");
10259
10260         PL_multi_end = 0;
10261         pm->op_pmflags |= PMf_EVAL;
10262         for (; es > 1; es--) {
10263             sv_catpvs(repl, "eval ");
10264         }
10265         sv_catpvs(repl, "do {");
10266         sv_catsv(repl, PL_parser->lex_sub_repl);
10267         sv_catpvs(repl, "}");
10268         SvREFCNT_dec(PL_parser->lex_sub_repl);
10269         PL_parser->lex_sub_repl = repl;
10270     }
10271
10272
10273     linediff = CopLINE(PL_curcop) - first_line;
10274     if (linediff)
10275         CopLINE_set(PL_curcop, first_line);
10276
10277     if (linediff || es) {
10278         /* the IVX field indicates that the replacement string is a s///e;
10279          * the NVX field indicates how many src code lines the replacement
10280          * spreads over */
10281         sv_upgrade(PL_parser->lex_sub_repl, SVt_PVNV);
10282         ((XPVNV*)SvANY(PL_parser->lex_sub_repl))->xnv_u.xnv_lines = linediff;
10283         ((XPVIV*)SvANY(PL_parser->lex_sub_repl))->xiv_u.xivu_eval_seen =
10284                                                                     cBOOL(es);
10285     }
10286
10287     PL_lex_op = (OP*)pm;
10288     pl_yylval.ival = OP_SUBST;
10289     return s;
10290 }
10291
10292 STATIC char *
10293 S_scan_trans(pTHX_ char *start)
10294 {
10295     char* s;
10296     OP *o;
10297     U8 squash;
10298     U8 del;
10299     U8 complement;
10300     bool nondestruct = 0;
10301     char *t;
10302
10303     PERL_ARGS_ASSERT_SCAN_TRANS;
10304
10305     pl_yylval.ival = OP_NULL;
10306
10307     s = scan_str(start,FALSE,FALSE,FALSE,&t);
10308     if (!s)
10309         Perl_croak(aTHX_ "Transliteration pattern not terminated");
10310
10311     s = t;
10312
10313     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10314     if (!s) {
10315         SvREFCNT_dec_NN(PL_lex_stuff);
10316         PL_lex_stuff = NULL;
10317         Perl_croak(aTHX_ "Transliteration replacement not terminated");
10318     }
10319
10320     complement = del = squash = 0;
10321     while (1) {
10322         switch (*s) {
10323         case 'c':
10324             complement = OPpTRANS_COMPLEMENT;
10325             break;
10326         case 'd':
10327             del = OPpTRANS_DELETE;
10328             break;
10329         case 's':
10330             squash = OPpTRANS_SQUASH;
10331             break;
10332         case 'r':
10333             nondestruct = 1;
10334             break;
10335         default:
10336             goto no_more;
10337         }
10338         s++;
10339     }
10340   no_more:
10341
10342     o = newPVOP(nondestruct ? OP_TRANSR : OP_TRANS, 0, (char*)NULL);
10343     o->op_private &= ~OPpTRANS_ALL;
10344     o->op_private |= del|squash|complement;
10345
10346     PL_lex_op = o;
10347     pl_yylval.ival = nondestruct ? OP_TRANSR : OP_TRANS;
10348
10349
10350     return s;
10351 }
10352
10353 /* scan_heredoc
10354    Takes a pointer to the first < in <<FOO.
10355    Returns a pointer to the byte following <<FOO.
10356
10357    This function scans a heredoc, which involves different methods
10358    depending on whether we are in a string eval, quoted construct, etc.
10359    This is because PL_linestr could containing a single line of input, or
10360    a whole string being evalled, or the contents of the current quote-
10361    like operator.
10362
10363    The two basic methods are:
10364     - Steal lines from the input stream
10365     - Scan the heredoc in PL_linestr and remove it therefrom
10366
10367    In a file scope or filtered eval, the first method is used; in a
10368    string eval, the second.
10369
10370    In a quote-like operator, we have to choose between the two,
10371    depending on where we can find a newline.  We peek into outer lex-
10372    ing scopes until we find one with a newline in it.  If we reach the
10373    outermost lexing scope and it is a file, we use the stream method.
10374    Otherwise it is treated as an eval.
10375 */
10376
10377 STATIC char *
10378 S_scan_heredoc(pTHX_ char *s)
10379 {
10380     I32 op_type = OP_SCALAR;
10381     I32 len;
10382     SV *tmpstr;
10383     char term;
10384     char *d;
10385     char *e;
10386     char *peek;
10387     char *indent = 0;
10388     I32 indent_len = 0;
10389     bool indented = FALSE;
10390     const bool infile = PL_rsfp || PL_parser->filtered;
10391     const line_t origline = CopLINE(PL_curcop);
10392     LEXSHARED *shared = PL_parser->lex_shared;
10393
10394     PERL_ARGS_ASSERT_SCAN_HEREDOC;
10395
10396     s += 2;
10397     d = PL_tokenbuf + 1;
10398     e = PL_tokenbuf + sizeof PL_tokenbuf - 1;
10399     *PL_tokenbuf = '\n';
10400     peek = s;
10401
10402     if (*peek == '~') {
10403         indented = TRUE;
10404         peek++; s++;
10405     }
10406
10407     while (SPACE_OR_TAB(*peek))
10408         peek++;
10409
10410     if (*peek == '`' || *peek == '\'' || *peek =='"') {
10411         s = peek;
10412         term = *s++;
10413         s = delimcpy(d, e, s, PL_bufend, term, &len);
10414         if (s == PL_bufend)
10415             Perl_croak(aTHX_ "Unterminated delimiter for here document");
10416         d += len;
10417         s++;
10418     }
10419     else {
10420         if (*s == '\\')
10421             /* <<\FOO is equivalent to <<'FOO' */
10422             s++, term = '\'';
10423         else
10424             term = '"';
10425
10426         if (! isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
10427             Perl_croak(aTHX_ "Use of bare << to mean <<\"\" is forbidden");
10428
10429         peek = s;
10430
10431         while (isWORDCHAR_lazy_if_safe(peek, PL_bufend, UTF)) {
10432             peek += UTF ? UTF8SKIP(peek) : 1;
10433         }
10434
10435         len = (peek - s >= e - d) ? (e - d) : (peek - s);
10436         Copy(s, d, len, char);
10437         s += len;
10438         d += len;
10439     }
10440
10441     if (d >= PL_tokenbuf + sizeof PL_tokenbuf - 1)
10442         Perl_croak(aTHX_ "Delimiter for here document is too long");
10443
10444     *d++ = '\n';
10445     *d = '\0';
10446     len = d - PL_tokenbuf;
10447
10448 #ifndef PERL_STRICT_CR
10449     d = (char *) memchr(s, '\r', PL_bufend - s);
10450     if (d) {
10451         char * const olds = s;
10452         s = d;
10453         while (s < PL_bufend) {
10454             if (*s == '\r') {
10455                 *d++ = '\n';
10456                 if (*++s == '\n')
10457                     s++;
10458             }
10459             else if (*s == '\n' && s[1] == '\r') {      /* \015\013 on a mac? */
10460                 *d++ = *s++;
10461                 s++;
10462             }
10463             else
10464                 *d++ = *s++;
10465         }
10466         *d = '\0';
10467         PL_bufend = d;
10468         SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10469         s = olds;
10470     }
10471 #endif
10472
10473     tmpstr = newSV_type(SVt_PVIV);
10474     SvGROW(tmpstr, 80);
10475     if (term == '\'') {
10476         op_type = OP_CONST;
10477         SvIV_set(tmpstr, -1);
10478     }
10479     else if (term == '`') {
10480         op_type = OP_BACKTICK;
10481         SvIV_set(tmpstr, '\\');
10482     }
10483
10484     PL_multi_start = origline + 1 + PL_parser->herelines;
10485     PL_multi_open = PL_multi_close = '<';
10486
10487     /* inside a string eval or quote-like operator */
10488     if (!infile || PL_lex_inwhat) {
10489         SV *linestr;
10490         char *bufend;
10491         char * const olds = s;
10492         PERL_CONTEXT * const cx = CX_CUR();
10493         /* These two fields are not set until an inner lexing scope is
10494            entered.  But we need them set here. */
10495         shared->ls_bufptr  = s;
10496         shared->ls_linestr = PL_linestr;
10497
10498         if (PL_lex_inwhat) {
10499             /* Look for a newline.  If the current buffer does not have one,
10500              peek into the line buffer of the parent lexing scope, going
10501              up as many levels as necessary to find one with a newline
10502              after bufptr.
10503             */
10504             while (!(s = (char *)memchr(
10505                                 (void *)shared->ls_bufptr, '\n',
10506                                 SvEND(shared->ls_linestr)-shared->ls_bufptr
10507                 )))
10508             {
10509                 shared = shared->ls_prev;
10510                 /* shared is only null if we have gone beyond the outermost
10511                    lexing scope.  In a file, we will have broken out of the
10512                    loop in the previous iteration.  In an eval, the string buf-
10513                    fer ends with "\n;", so the while condition above will have
10514                    evaluated to false.  So shared can never be null.  Or so you
10515                    might think.  Odd syntax errors like s;@{<<; can gobble up
10516                    the implicit semicolon at the end of a flie, causing the
10517                    file handle to be closed even when we are not in a string
10518                    eval.  So shared may be null in that case.
10519                    (Closing '>>}' here to balance the earlier open brace for
10520                    editors that look for matched pairs.) */
10521                 if (UNLIKELY(!shared))
10522                     goto interminable;
10523                 /* A LEXSHARED struct with a null ls_prev pointer is the outer-
10524                    most lexing scope.  In a file, shared->ls_linestr at that
10525                    level is just one line, so there is no body to steal. */
10526                 if (infile && !shared->ls_prev) {
10527                     s = olds;
10528                     goto streaming;
10529                 }
10530             }
10531         }
10532         else {  /* eval or we've already hit EOF */
10533             s = (char*)memchr((void*)s, '\n', PL_bufend - s);
10534             if (!s)
10535                 goto interminable;
10536         }
10537
10538         linestr = shared->ls_linestr;
10539         bufend = SvEND(linestr);
10540         d = s;
10541         if (indented) {
10542             char *myolds = s;
10543
10544             while (s < bufend - len + 1) {
10545                 if (*s++ == '\n')
10546                     ++PL_parser->herelines;
10547
10548                 if (memEQ(s, PL_tokenbuf + 1, len - 1)) {
10549                     char *backup = s;
10550                     indent_len = 0;
10551
10552                     /* Only valid if it's preceded by whitespace only */
10553                     while (backup != myolds && --backup >= myolds) {
10554                         if (! SPACE_OR_TAB(*backup)) {
10555                             break;
10556                         }
10557                         indent_len++;
10558                     }
10559
10560                     /* No whitespace or all! */
10561                     if (backup == s || *backup == '\n') {
10562                         Newx(indent, indent_len + 1, char);
10563                         memcpy(indent, backup + 1, indent_len);
10564                         indent[indent_len] = 0;
10565                         s--; /* before our delimiter */
10566                         PL_parser->herelines--; /* this line doesn't count */
10567                         break;
10568                     }
10569                 }
10570             }
10571         }
10572         else {
10573             while (s < bufend - len + 1
10574                    && memNE(s,PL_tokenbuf,len) )
10575             {
10576                 if (*s++ == '\n')
10577                     ++PL_parser->herelines;
10578             }
10579         }
10580
10581         if (s >= bufend - len + 1) {
10582             goto interminable;
10583         }
10584
10585         sv_setpvn(tmpstr,d+1,s-d);
10586         s += len - 1;
10587         /* the preceding stmt passes a newline */
10588         PL_parser->herelines++;
10589
10590         /* s now points to the newline after the heredoc terminator.
10591            d points to the newline before the body of the heredoc.
10592          */
10593
10594         /* We are going to modify linestr in place here, so set
10595            aside copies of the string if necessary for re-evals or
10596            (caller $n)[6]. */
10597         /* See the Paranoia note in case LEX_INTERPEND in yylex, for why we
10598            check shared->re_eval_str. */
10599         if (shared->re_eval_start || shared->re_eval_str) {
10600             /* Set aside the rest of the regexp */
10601             if (!shared->re_eval_str)
10602                 shared->re_eval_str =
10603                        newSVpvn(shared->re_eval_start,
10604                                 bufend - shared->re_eval_start);
10605             shared->re_eval_start -= s-d;
10606         }
10607
10608         if (cxstack_ix >= 0
10609             && CxTYPE(cx) == CXt_EVAL
10610             && CxOLD_OP_TYPE(cx) == OP_ENTEREVAL
10611             && cx->blk_eval.cur_text == linestr)
10612         {
10613             cx->blk_eval.cur_text = newSVsv(linestr);
10614             cx->blk_u16 |= 0x40; /* indicate cur_text is ref counted */
10615         }
10616
10617         /* Copy everything from s onwards back to d. */
10618         Move(s,d,bufend-s + 1,char);
10619         SvCUR_set(linestr, SvCUR(linestr) - (s-d));
10620         /* Setting PL_bufend only applies when we have not dug deeper
10621            into other scopes, because sublex_done sets PL_bufend to
10622            SvEND(PL_linestr). */
10623         if (shared == PL_parser->lex_shared)
10624             PL_bufend = SvEND(linestr);
10625         s = olds;
10626     }
10627     else {
10628         SV *linestr_save;
10629         char *oldbufptr_save;
10630         char *oldoldbufptr_save;
10631       streaming:
10632         SvPVCLEAR(tmpstr);   /* avoid "uninitialized" warning */
10633         term = PL_tokenbuf[1];
10634         len--;
10635         linestr_save = PL_linestr; /* must restore this afterwards */
10636         d = s;                   /* and this */
10637         oldbufptr_save = PL_oldbufptr;
10638         oldoldbufptr_save = PL_oldoldbufptr;
10639         PL_linestr = newSVpvs("");
10640         PL_bufend = SvPVX(PL_linestr);
10641
10642         while (1) {
10643             PL_bufptr = PL_bufend;
10644             CopLINE_set(PL_curcop,
10645                         origline + 1 + PL_parser->herelines);
10646
10647             if (   !lex_next_chunk(LEX_NO_TERM)
10648                 && (!SvCUR(tmpstr) || SvEND(tmpstr)[-1] != '\n'))
10649             {
10650                 /* Simply freeing linestr_save might seem simpler here, as it
10651                    does not matter what PL_linestr points to, since we are
10652                    about to croak; but in a quote-like op, linestr_save
10653                    will have been prospectively freed already, via
10654                    SAVEFREESV(PL_linestr) in sublex_push, so it’s easier to
10655                    restore PL_linestr. */
10656                 SvREFCNT_dec_NN(PL_linestr);
10657                 PL_linestr = linestr_save;
10658                 PL_oldbufptr = oldbufptr_save;
10659                 PL_oldoldbufptr = oldoldbufptr_save;
10660                 goto interminable;
10661             }
10662
10663             CopLINE_set(PL_curcop, origline);
10664
10665             if (!SvCUR(PL_linestr) || PL_bufend[-1] != '\n') {
10666                 s = lex_grow_linestr(SvLEN(PL_linestr) + 3);
10667                 /* ^That should be enough to avoid this needing to grow:  */
10668                 sv_catpvs(PL_linestr, "\n\0");
10669                 assert(s == SvPVX(PL_linestr));
10670                 PL_bufend = SvEND(PL_linestr);
10671             }
10672
10673             s = PL_bufptr;
10674             PL_parser->herelines++;
10675             PL_last_lop = PL_last_uni = NULL;
10676
10677 #ifndef PERL_STRICT_CR
10678             if (PL_bufend - PL_linestart >= 2) {
10679                 if (   (PL_bufend[-2] == '\r' && PL_bufend[-1] == '\n')
10680                     || (PL_bufend[-2] == '\n' && PL_bufend[-1] == '\r'))
10681                 {
10682                     PL_bufend[-2] = '\n';
10683                     PL_bufend--;
10684                     SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10685                 }
10686                 else if (PL_bufend[-1] == '\r')
10687                     PL_bufend[-1] = '\n';
10688             }
10689             else if (PL_bufend - PL_linestart == 1 && PL_bufend[-1] == '\r')
10690                 PL_bufend[-1] = '\n';
10691 #endif
10692
10693             if (indented && (PL_bufend-s) >= len) {
10694                 char * found = ninstr(s, PL_bufend, (PL_tokenbuf + 1), (PL_tokenbuf +1 + len));
10695
10696                 if (found) {
10697                     char *backup = found;
10698                     indent_len = 0;
10699
10700                     /* Only valid if it's preceded by whitespace only */
10701                     while (backup != s && --backup >= s) {
10702                         if (! SPACE_OR_TAB(*backup)) {
10703                             break;
10704                         }
10705                         indent_len++;
10706                     }
10707
10708                     /* All whitespace or none! */
10709                     if (backup == found || SPACE_OR_TAB(*backup)) {
10710                         Newx(indent, indent_len + 1, char);
10711                         memcpy(indent, backup, indent_len);
10712                         indent[indent_len] = 0;
10713                         SvREFCNT_dec(PL_linestr);
10714                         PL_linestr = linestr_save;
10715                         PL_linestart = SvPVX(linestr_save);
10716                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10717                         PL_oldbufptr = oldbufptr_save;
10718                         PL_oldoldbufptr = oldoldbufptr_save;
10719                         s = d;
10720                         break;
10721                     }
10722                 }
10723
10724                 /* Didn't find it */
10725                 sv_catsv(tmpstr,PL_linestr);
10726             }
10727             else {
10728                 if (*s == term && PL_bufend-s >= len
10729                     && memEQ(s,PL_tokenbuf + 1,len))
10730                 {
10731                     SvREFCNT_dec(PL_linestr);
10732                     PL_linestr = linestr_save;
10733                     PL_linestart = SvPVX(linestr_save);
10734                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10735                     PL_oldbufptr = oldbufptr_save;
10736                     PL_oldoldbufptr = oldoldbufptr_save;
10737                     s = d;
10738                     break;
10739                 }
10740                 else {
10741                     sv_catsv(tmpstr,PL_linestr);
10742                 }
10743             }
10744         } /* while (1) */
10745     }
10746
10747     PL_multi_end = origline + PL_parser->herelines;
10748
10749     if (indented && indent) {
10750         STRLEN linecount = 1;
10751         STRLEN herelen = SvCUR(tmpstr);
10752         char *ss = SvPVX(tmpstr);
10753         char *se = ss + herelen;
10754         SV *newstr = newSV(herelen+1);
10755         SvPOK_on(newstr);
10756
10757         /* Trim leading whitespace */
10758         while (ss < se) {
10759             /* newline only? Copy and move on */
10760             if (*ss == '\n') {
10761                 sv_catpvs(newstr,"\n");
10762                 ss++;
10763                 linecount++;
10764
10765             /* Found our indentation? Strip it */
10766             }
10767             else if (se - ss >= indent_len
10768                        && memEQ(ss, indent, indent_len))
10769             {
10770                 STRLEN le = 0;
10771                 ss += indent_len;
10772
10773                 while ((ss + le) < se && *(ss + le) != '\n')
10774                     le++;
10775
10776                 sv_catpvn(newstr, ss, le);
10777                 ss += le;
10778
10779             /* Line doesn't begin with our indentation? Croak */
10780             }
10781             else {
10782                 Safefree(indent);
10783                 Perl_croak(aTHX_
10784                     "Indentation on line %d of here-doc doesn't match delimiter",
10785                     (int)linecount
10786                 );
10787             }
10788         } /* while */
10789
10790         /* avoid sv_setsv() as we dont wan't to COW here */
10791         sv_setpvn(tmpstr,SvPVX(newstr),SvCUR(newstr));
10792         Safefree(indent);
10793         SvREFCNT_dec_NN(newstr);
10794     }
10795
10796     if (SvCUR(tmpstr) + 5 < SvLEN(tmpstr)) {
10797         SvPV_shrink_to_cur(tmpstr);
10798     }
10799
10800     if (!IN_BYTES) {
10801         if (UTF && is_utf8_string((U8*)SvPVX_const(tmpstr), SvCUR(tmpstr)))
10802             SvUTF8_on(tmpstr);
10803     }
10804
10805     PL_lex_stuff = tmpstr;
10806     pl_yylval.ival = op_type;
10807     return s;
10808
10809   interminable:
10810     if (indent)
10811         Safefree(indent);
10812     SvREFCNT_dec(tmpstr);
10813     CopLINE_set(PL_curcop, origline);
10814     missingterm(PL_tokenbuf + 1, sizeof(PL_tokenbuf) - 1);
10815 }
10816
10817
10818 /* scan_inputsymbol
10819    takes: position of first '<' in input buffer
10820    returns: position of first char following the matching '>' in
10821             input buffer
10822    side-effects: pl_yylval and lex_op are set.
10823
10824    This code handles:
10825
10826    <>           read from ARGV
10827    <<>>         read from ARGV without magic open
10828    <FH>         read from filehandle
10829    <pkg::FH>    read from package qualified filehandle
10830    <pkg'FH>     read from package qualified filehandle
10831    <$fh>        read from filehandle in $fh
10832    <*.h>        filename glob
10833
10834 */
10835
10836 STATIC char *
10837 S_scan_inputsymbol(pTHX_ char *start)
10838 {
10839     char *s = start;            /* current position in buffer */
10840     char *end;
10841     I32 len;
10842     bool nomagicopen = FALSE;
10843     char *d = PL_tokenbuf;                                      /* start of temp holding space */
10844     const char * const e = PL_tokenbuf + sizeof PL_tokenbuf;    /* end of temp holding space */
10845
10846     PERL_ARGS_ASSERT_SCAN_INPUTSYMBOL;
10847
10848     end = (char *) memchr(s, '\n', PL_bufend - s);
10849     if (!end)
10850         end = PL_bufend;
10851     if (s[1] == '<' && s[2] == '>' && s[3] == '>') {
10852         nomagicopen = TRUE;
10853         *d = '\0';
10854         len = 0;
10855         s += 3;
10856     }
10857     else
10858         s = delimcpy(d, e, s + 1, end, '>', &len);      /* extract until > */
10859
10860     /* die if we didn't have space for the contents of the <>,
10861        or if it didn't end, or if we see a newline
10862     */
10863
10864     if (len >= (I32)sizeof PL_tokenbuf)
10865         Perl_croak(aTHX_ "Excessively long <> operator");
10866     if (s >= end)
10867         Perl_croak(aTHX_ "Unterminated <> operator");
10868
10869     s++;
10870
10871     /* check for <$fh>
10872        Remember, only scalar variables are interpreted as filehandles by
10873        this code.  Anything more complex (e.g., <$fh{$num}>) will be
10874        treated as a glob() call.
10875        This code makes use of the fact that except for the $ at the front,
10876        a scalar variable and a filehandle look the same.
10877     */
10878     if (*d == '$' && d[1]) d++;
10879
10880     /* allow <Pkg'VALUE> or <Pkg::VALUE> */
10881     while (isWORDCHAR_lazy_if_safe(d, e, UTF) || *d == '\'' || *d == ':') {
10882         d += UTF ? UTF8SKIP(d) : 1;
10883     }
10884
10885     /* If we've tried to read what we allow filehandles to look like, and
10886        there's still text left, then it must be a glob() and not a getline.
10887        Use scan_str to pull out the stuff between the <> and treat it
10888        as nothing more than a string.
10889     */
10890
10891     if (d - PL_tokenbuf != len) {
10892         pl_yylval.ival = OP_GLOB;
10893         s = scan_str(start,FALSE,FALSE,FALSE,NULL);
10894         if (!s)
10895            Perl_croak(aTHX_ "Glob not terminated");
10896         return s;
10897     }
10898     else {
10899         bool readline_overriden = FALSE;
10900         GV *gv_readline;
10901         /* we're in a filehandle read situation */
10902         d = PL_tokenbuf;
10903
10904         /* turn <> into <ARGV> */
10905         if (!len)
10906             Copy("ARGV",d,5,char);
10907
10908         /* Check whether readline() is overriden */
10909         if ((gv_readline = gv_override("readline",8)))
10910             readline_overriden = TRUE;
10911
10912         /* if <$fh>, create the ops to turn the variable into a
10913            filehandle
10914         */
10915         if (*d == '$') {
10916             /* try to find it in the pad for this block, otherwise find
10917                add symbol table ops
10918             */
10919             const PADOFFSET tmp = pad_findmy_pvn(d, len, 0);
10920             if (tmp != NOT_IN_PAD) {
10921                 if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
10922                     HV * const stash = PAD_COMPNAME_OURSTASH(tmp);
10923                     HEK * const stashname = HvNAME_HEK(stash);
10924                     SV * const sym = sv_2mortal(newSVhek(stashname));
10925                     sv_catpvs(sym, "::");
10926                     sv_catpv(sym, d+1);
10927                     d = SvPVX(sym);
10928                     goto intro_sym;
10929                 }
10930                 else {
10931                     OP * const o = newOP(OP_PADSV, 0);
10932                     o->op_targ = tmp;
10933                     PL_lex_op = readline_overriden
10934                         ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10935                                 op_append_elem(OP_LIST, o,
10936                                     newCVREF(0, newGVOP(OP_GV,0,gv_readline))))
10937                         : newUNOP(OP_READLINE, 0, o);
10938                 }
10939             }
10940             else {
10941                 GV *gv;
10942                 ++d;
10943               intro_sym:
10944                 gv = gv_fetchpv(d,
10945                                 GV_ADDMULTI | ( UTF ? SVf_UTF8 : 0 ),
10946                                 SVt_PV);
10947                 PL_lex_op = readline_overriden
10948                     ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10949                             op_append_elem(OP_LIST,
10950                                 newUNOP(OP_RV2SV, 0, newGVOP(OP_GV, 0, gv)),
10951                                 newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10952                     : newUNOP(OP_READLINE, 0,
10953                             newUNOP(OP_RV2SV, 0,
10954                                 newGVOP(OP_GV, 0, gv)));
10955             }
10956             /* we created the ops in PL_lex_op, so make pl_yylval.ival a null op */
10957             pl_yylval.ival = OP_NULL;
10958         }
10959
10960         /* If it's none of the above, it must be a literal filehandle
10961            (<Foo::BAR> or <FOO>) so build a simple readline OP */
10962         else {
10963             GV * const gv = gv_fetchpv(d, GV_ADD | ( UTF ? SVf_UTF8 : 0 ), SVt_PVIO);
10964             PL_lex_op = readline_overriden
10965                 ? newUNOP(OP_ENTERSUB, OPf_STACKED,
10966                         op_append_elem(OP_LIST,
10967                             newGVOP(OP_GV, 0, gv),
10968                             newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
10969                 : newUNOP(OP_READLINE, nomagicopen ? OPf_SPECIAL : 0, newGVOP(OP_GV, 0, gv));
10970             pl_yylval.ival = OP_NULL;
10971         }
10972     }
10973
10974     return s;
10975 }
10976
10977
10978 /* scan_str
10979    takes:
10980         start                   position in buffer
10981         keep_bracketed_quoted   preserve \ quoting of embedded delimiters, but
10982                                 only if they are of the open/close form
10983         keep_delims             preserve the delimiters around the string
10984         re_reparse              compiling a run-time /(?{})/:
10985                                    collapse // to /,  and skip encoding src
10986         delimp                  if non-null, this is set to the position of
10987                                 the closing delimiter, or just after it if
10988                                 the closing and opening delimiters differ
10989                                 (i.e., the opening delimiter of a substitu-
10990                                 tion replacement)
10991    returns: position to continue reading from buffer
10992    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
10993         updates the read buffer.
10994
10995    This subroutine pulls a string out of the input.  It is called for:
10996         q               single quotes           q(literal text)
10997         '               single quotes           'literal text'
10998         qq              double quotes           qq(interpolate $here please)
10999         "               double quotes           "interpolate $here please"
11000         qx              backticks               qx(/bin/ls -l)
11001         `               backticks               `/bin/ls -l`
11002         qw              quote words             @EXPORT_OK = qw( func() $spam )
11003         m//             regexp match            m/this/
11004         s///            regexp substitute       s/this/that/
11005         tr///           string transliterate    tr/this/that/
11006         y///            string transliterate    y/this/that/
11007         ($*@)           sub prototypes          sub foo ($)
11008         (stuff)         sub attr parameters     sub foo : attr(stuff)
11009         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
11010
11011    In most of these cases (all but <>, patterns and transliterate)
11012    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
11013    calls scan_str().  s/// makes yylex() call scan_subst() which calls
11014    scan_str().  tr/// and y/// make yylex() call scan_trans() which
11015    calls scan_str().
11016
11017    It skips whitespace before the string starts, and treats the first
11018    character as the delimiter.  If the delimiter is one of ([{< then
11019    the corresponding "close" character )]}> is used as the closing
11020    delimiter.  It allows quoting of delimiters, and if the string has
11021    balanced delimiters ([{<>}]) it allows nesting.
11022
11023    On success, the SV with the resulting string is put into lex_stuff or,
11024    if that is already non-NULL, into lex_repl. The second case occurs only
11025    when parsing the RHS of the special constructs s/// and tr/// (y///).
11026    For convenience, the terminating delimiter character is stuffed into
11027    SvIVX of the SV.
11028 */
11029
11030 char *
11031 Perl_scan_str(pTHX_ char *start, int keep_bracketed_quoted, int keep_delims, int re_reparse,
11032                  char **delimp
11033     )
11034 {
11035     SV *sv;                     /* scalar value: string */
11036     const char *tmps;           /* temp string, used for delimiter matching */
11037     char *s = start;            /* current position in the buffer */
11038     char term;                  /* terminating character */
11039     char *to;                   /* current position in the sv's data */
11040     I32 brackets = 1;           /* bracket nesting level */
11041     bool d_is_utf8 = FALSE;     /* is there any utf8 content? */
11042     IV termcode;                /* terminating char. code */
11043     U8 termstr[UTF8_MAXBYTES+1]; /* terminating string */
11044     STRLEN termlen;             /* length of terminating string */
11045     line_t herelines;
11046
11047     /* The delimiters that have a mirror-image closing one */
11048     const char * opening_delims = "([{<";
11049     const char * closing_delims = ")]}>";
11050
11051     /* The only non-UTF character that isn't a stand alone grapheme is
11052      * white-space, hence can't be a delimiter. */
11053     const char * non_grapheme_msg = "Use of unassigned code point or"
11054                                     " non-standalone grapheme for a delimiter"
11055                                     " is not allowed";
11056     PERL_ARGS_ASSERT_SCAN_STR;
11057
11058     /* skip space before the delimiter */
11059     if (isSPACE(*s)) {
11060         s = skipspace(s);
11061     }
11062
11063     /* mark where we are, in case we need to report errors */
11064     CLINE;
11065
11066     /* after skipping whitespace, the next character is the terminator */
11067     term = *s;
11068     if (!UTF || UTF8_IS_INVARIANT(term)) {
11069         termcode = termstr[0] = term;
11070         termlen = 1;
11071     }
11072     else {
11073         termcode = utf8_to_uvchr_buf((U8*)s, (U8*)PL_bufend, &termlen);
11074         if (UTF && UNLIKELY(! is_grapheme((U8 *) start,
11075                                            (U8 *) s,
11076                                            (U8 *) PL_bufend,
11077                                                   termcode)))
11078         {
11079             yyerror(non_grapheme_msg);
11080         }
11081
11082         Copy(s, termstr, termlen, U8);
11083     }
11084
11085     /* mark where we are */
11086     PL_multi_start = CopLINE(PL_curcop);
11087     PL_multi_open = termcode;
11088     herelines = PL_parser->herelines;
11089
11090     /* If the delimiter has a mirror-image closing one, get it */
11091     if (term && (tmps = strchr(opening_delims, term))) {
11092         termcode = termstr[0] = term = closing_delims[tmps - opening_delims];
11093     }
11094
11095     PL_multi_close = termcode;
11096
11097     if (PL_multi_open == PL_multi_close) {
11098         keep_bracketed_quoted = FALSE;
11099     }
11100
11101     /* create a new SV to hold the contents.  79 is the SV's initial length.
11102        What a random number. */
11103     sv = newSV_type(SVt_PVIV);
11104     SvGROW(sv, 80);
11105     SvIV_set(sv, termcode);
11106     (void)SvPOK_only(sv);               /* validate pointer */
11107
11108     /* move past delimiter and try to read a complete string */
11109     if (keep_delims)
11110         sv_catpvn(sv, s, termlen);
11111     s += termlen;
11112     for (;;) {
11113         /* extend sv if need be */
11114         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
11115         /* set 'to' to the next character in the sv's string */
11116         to = SvPVX(sv)+SvCUR(sv);
11117
11118         /* if open delimiter is the close delimiter read unbridle */
11119         if (PL_multi_open == PL_multi_close) {
11120             for (; s < PL_bufend; s++,to++) {
11121                 /* embedded newlines increment the current line number */
11122                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11123                     COPLINE_INC_WITH_HERELINES;
11124                 /* handle quoted delimiters */
11125                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
11126                     if (!keep_bracketed_quoted
11127                         && (s[1] == term
11128                             || (re_reparse && s[1] == '\\'))
11129                     )
11130                         s++;
11131                     else /* any other quotes are simply copied straight through */
11132                         *to++ = *s++;
11133                 }
11134                 /* terminate when run out of buffer (the for() condition), or
11135                    have found the terminator */
11136                 else if (*s == term) {  /* First byte of terminator matches */
11137                     if (termlen == 1)   /* If is the only byte, are done */
11138                         break;
11139
11140                     /* If the remainder of the terminator matches, also are
11141                      * done, after checking that is a separate grapheme */
11142                     if (   s + termlen <= PL_bufend
11143                         && memEQ(s + 1, (char*)termstr + 1, termlen - 1))
11144                     {
11145                         if (   UTF
11146                             && UNLIKELY(! is_grapheme((U8 *) start,
11147                                                        (U8 *) s,
11148                                                        (U8 *) PL_bufend,
11149                                                               termcode)))
11150                         {
11151                             yyerror(non_grapheme_msg);
11152                         }
11153                         break;
11154                     }
11155                 }
11156                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF) {
11157                     d_is_utf8 = TRUE;
11158                 }
11159
11160                 *to = *s;
11161             }
11162         }
11163
11164         /* if the terminator isn't the same as the start character (e.g.,
11165            matched brackets), we have to allow more in the quoting, and
11166            be prepared for nested brackets.
11167         */
11168         else {
11169             /* read until we run out of string, or we find the terminator */
11170             for (; s < PL_bufend; s++,to++) {
11171                 /* embedded newlines increment the line count */
11172                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11173                     COPLINE_INC_WITH_HERELINES;
11174                 /* backslashes can escape the open or closing characters */
11175                 if (*s == '\\' && s+1 < PL_bufend) {
11176                     if (!keep_bracketed_quoted
11177                        && ( ((UV)s[1] == PL_multi_open)
11178                          || ((UV)s[1] == PL_multi_close) ))
11179                     {
11180                         s++;
11181                     }
11182                     else
11183                         *to++ = *s++;
11184                 }
11185                 /* allow nested opens and closes */
11186                 else if ((UV)*s == PL_multi_close && --brackets <= 0)
11187                     break;
11188                 else if ((UV)*s == PL_multi_open)
11189                     brackets++;
11190                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
11191                     d_is_utf8 = TRUE;
11192                 *to = *s;
11193             }
11194         }
11195         /* terminate the copied string and update the sv's end-of-string */
11196         *to = '\0';
11197         SvCUR_set(sv, to - SvPVX_const(sv));
11198
11199         /*
11200          * this next chunk reads more into the buffer if we're not done yet
11201          */
11202
11203         if (s < PL_bufend)
11204             break;              /* handle case where we are done yet :-) */
11205
11206 #ifndef PERL_STRICT_CR
11207         if (to - SvPVX_const(sv) >= 2) {
11208             if (   (to[-2] == '\r' && to[-1] == '\n')
11209                 || (to[-2] == '\n' && to[-1] == '\r'))
11210             {
11211                 to[-2] = '\n';
11212                 to--;
11213                 SvCUR_set(sv, to - SvPVX_const(sv));
11214             }
11215             else if (to[-1] == '\r')
11216                 to[-1] = '\n';
11217         }
11218         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
11219             to[-1] = '\n';
11220 #endif
11221
11222         /* if we're out of file, or a read fails, bail and reset the current
11223            line marker so we can report where the unterminated string began
11224         */
11225         COPLINE_INC_WITH_HERELINES;
11226         PL_bufptr = PL_bufend;
11227         if (!lex_next_chunk(0)) {
11228             sv_free(sv);
11229             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
11230             return NULL;
11231         }
11232         s = start = PL_bufptr;
11233     }
11234
11235     /* at this point, we have successfully read the delimited string */
11236
11237     if (keep_delims)
11238             sv_catpvn(sv, s, termlen);
11239     s += termlen;
11240
11241     if (d_is_utf8)
11242         SvUTF8_on(sv);
11243
11244     PL_multi_end = CopLINE(PL_curcop);
11245     CopLINE_set(PL_curcop, PL_multi_start);
11246     PL_parser->herelines = herelines;
11247
11248     /* if we allocated too much space, give some back */
11249     if (SvCUR(sv) + 5 < SvLEN(sv)) {
11250         SvLEN_set(sv, SvCUR(sv) + 1);
11251         SvPV_renew(sv, SvLEN(sv));
11252     }
11253
11254     /* decide whether this is the first or second quoted string we've read
11255        for this op
11256     */
11257
11258     if (PL_lex_stuff)
11259         PL_parser->lex_sub_repl = sv;
11260     else
11261         PL_lex_stuff = sv;
11262     if (delimp) *delimp = PL_multi_open == PL_multi_close ? s-termlen : s;
11263     return s;
11264 }
11265
11266 /*
11267   scan_num
11268   takes: pointer to position in buffer
11269   returns: pointer to new position in buffer
11270   side-effects: builds ops for the constant in pl_yylval.op
11271
11272   Read a number in any of the formats that Perl accepts:
11273
11274   \d(_?\d)*(\.(\d(_?\d)*)?)?[Ee][\+\-]?(\d(_?\d)*)      12 12.34 12.
11275   \.\d(_?\d)*[Ee][\+\-]?(\d(_?\d)*)                     .34
11276   0b[01](_?[01])*                                       binary integers
11277   0[0-7](_?[0-7])*                                      octal integers
11278   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*                         hexadecimal integers
11279   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*(?:\.\d*)?p[+-]?[0-9]+   hexadecimal floats
11280
11281   Like most scan_ routines, it uses the PL_tokenbuf buffer to hold the
11282   thing it reads.
11283
11284   If it reads a number without a decimal point or an exponent, it will
11285   try converting the number to an integer and see if it can do so
11286   without loss of precision.
11287 */
11288
11289 char *
11290 Perl_scan_num(pTHX_ const char *start, YYSTYPE* lvalp)
11291 {
11292     const char *s = start;      /* current position in buffer */
11293     char *d;                    /* destination in temp buffer */
11294     char *e;                    /* end of temp buffer */
11295     NV nv;                              /* number read, as a double */
11296     SV *sv = NULL;                      /* place to put the converted number */
11297     bool floatit;                       /* boolean: int or float? */
11298     const char *lastub = NULL;          /* position of last underbar */
11299     static const char* const number_too_long = "Number too long";
11300     bool warned_about_underscore = 0;
11301     I32 shift; /* shift per digit for hex/oct/bin, hoisted here for fp */
11302 #define WARN_ABOUT_UNDERSCORE() \
11303         do { \
11304             if (!warned_about_underscore) { \
11305                 warned_about_underscore = 1; \
11306                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), \
11307                                "Misplaced _ in number"); \
11308             } \
11309         } while(0)
11310     /* Hexadecimal floating point.
11311      *
11312      * In many places (where we have quads and NV is IEEE 754 double)
11313      * we can fit the mantissa bits of a NV into an unsigned quad.
11314      * (Note that UVs might not be quads even when we have quads.)
11315      * This will not work everywhere, though (either no quads, or
11316      * using long doubles), in which case we have to resort to NV,
11317      * which will probably mean horrible loss of precision due to
11318      * multiple fp operations. */
11319     bool hexfp = FALSE;
11320     int total_bits = 0;
11321     int significant_bits = 0;
11322 #if NVSIZE == 8 && defined(HAS_QUAD) && defined(Uquad_t)
11323 #  define HEXFP_UQUAD
11324     Uquad_t hexfp_uquad = 0;
11325     int hexfp_frac_bits = 0;
11326 #else
11327 #  define HEXFP_NV
11328     NV hexfp_nv = 0.0;
11329 #endif
11330     NV hexfp_mult = 1.0;
11331     UV high_non_zero = 0; /* highest digit */
11332     int non_zero_integer_digits = 0;
11333
11334     PERL_ARGS_ASSERT_SCAN_NUM;
11335
11336     /* We use the first character to decide what type of number this is */
11337
11338     switch (*s) {
11339     default:
11340         Perl_croak(aTHX_ "panic: scan_num, *s=%d", *s);
11341
11342     /* if it starts with a 0, it could be an octal number, a decimal in
11343        0.13 disguise, or a hexadecimal number, or a binary number. */
11344     case '0':
11345         {
11346           /* variables:
11347              u          holds the "number so far"
11348              overflowed was the number more than we can hold?
11349
11350              Shift is used when we add a digit.  It also serves as an "are
11351              we in octal/hex/binary?" indicator to disallow hex characters
11352              when in octal mode.
11353            */
11354             NV n = 0.0;
11355             UV u = 0;
11356             bool overflowed = FALSE;
11357             bool just_zero  = TRUE;     /* just plain 0 or binary number? */
11358             bool has_digs = FALSE;
11359             static const NV nvshift[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
11360             static const char* const bases[5] =
11361               { "", "binary", "", "octal", "hexadecimal" };
11362             static const char* const Bases[5] =
11363               { "", "Binary", "", "Octal", "Hexadecimal" };
11364             static const char* const maxima[5] =
11365               { "",
11366                 "0b11111111111111111111111111111111",
11367                 "",
11368                 "037777777777",
11369                 "0xffffffff" };
11370             const char *base, *Base, *max;
11371
11372             /* check for hex */
11373             if (isALPHA_FOLD_EQ(s[1], 'x')) {
11374                 shift = 4;
11375                 s += 2;
11376                 just_zero = FALSE;
11377             } else if (isALPHA_FOLD_EQ(s[1], 'b')) {
11378                 shift = 1;
11379                 s += 2;
11380                 just_zero = FALSE;
11381             }
11382             /* check for a decimal in disguise */
11383             else if (s[1] == '.' || isALPHA_FOLD_EQ(s[1], 'e'))
11384                 goto decimal;
11385             /* so it must be octal */
11386             else {
11387                 shift = 3;
11388                 s++;
11389             }
11390
11391             if (*s == '_') {
11392                 WARN_ABOUT_UNDERSCORE();
11393                lastub = s++;
11394             }
11395
11396             base = bases[shift];
11397             Base = Bases[shift];
11398             max  = maxima[shift];
11399
11400             /* read the rest of the number */
11401             for (;;) {
11402                 /* x is used in the overflow test,
11403                    b is the digit we're adding on. */
11404                 UV x, b;
11405
11406                 switch (*s) {
11407
11408                 /* if we don't mention it, we're done */
11409                 default:
11410                     goto out;
11411
11412                 /* _ are ignored -- but warned about if consecutive */
11413                 case '_':
11414                     if (lastub && s == lastub + 1)
11415                         WARN_ABOUT_UNDERSCORE();
11416                     lastub = s++;
11417                     break;
11418
11419                 /* 8 and 9 are not octal */
11420                 case '8': case '9':
11421                     if (shift == 3)
11422                         yyerror(Perl_form(aTHX_ "Illegal octal digit '%c'", *s));
11423                     /* FALLTHROUGH */
11424
11425                 /* octal digits */
11426                 case '2': case '3': case '4':
11427                 case '5': case '6': case '7':
11428                     if (shift == 1)
11429                         yyerror(Perl_form(aTHX_ "Illegal binary digit '%c'", *s));
11430                     /* FALLTHROUGH */
11431
11432                 case '0': case '1':
11433                     b = *s++ & 15;              /* ASCII digit -> value of digit */
11434                     goto digit;
11435
11436                 /* hex digits */
11437                 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
11438                 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
11439                     /* make sure they said 0x */
11440                     if (shift != 4)
11441                         goto out;
11442                     b = (*s++ & 7) + 9;
11443
11444                     /* Prepare to put the digit we have onto the end
11445                        of the number so far.  We check for overflows.
11446                     */
11447
11448                   digit:
11449                     just_zero = FALSE;
11450                     has_digs = TRUE;
11451                     if (!overflowed) {
11452                         assert(shift >= 0);
11453                         x = u << shift; /* make room for the digit */
11454
11455                         total_bits += shift;
11456
11457                         if ((x >> shift) != u
11458                             && !(PL_hints & HINT_NEW_BINARY)) {
11459                             overflowed = TRUE;
11460                             n = (NV) u;
11461                             Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
11462                                              "Integer overflow in %s number",
11463                                              base);
11464                         } else
11465                             u = x | b;          /* add the digit to the end */
11466                     }
11467                     if (overflowed) {
11468                         n *= nvshift[shift];
11469                         /* If an NV has not enough bits in its
11470                          * mantissa to represent an UV this summing of
11471                          * small low-order numbers is a waste of time
11472                          * (because the NV cannot preserve the
11473                          * low-order bits anyway): we could just
11474                          * remember when did we overflow and in the
11475                          * end just multiply n by the right
11476                          * amount. */
11477                         n += (NV) b;
11478                     }
11479
11480                     if (high_non_zero == 0 && b > 0)
11481                         high_non_zero = b;
11482
11483                     if (high_non_zero)
11484                         non_zero_integer_digits++;
11485
11486                     /* this could be hexfp, but peek ahead
11487                      * to avoid matching ".." */
11488                     if (UNLIKELY(HEXFP_PEEK(s))) {
11489                         goto out;
11490                     }
11491
11492                     break;
11493                 }
11494             }
11495
11496           /* if we get here, we had success: make a scalar value from
11497              the number.
11498           */
11499           out:
11500
11501             /* final misplaced underbar check */
11502             if (s[-1] == '_')
11503                 WARN_ABOUT_UNDERSCORE();
11504
11505             if (UNLIKELY(HEXFP_PEEK(s))) {
11506                 /* Do sloppy (on the underbars) but quick detection
11507                  * (and value construction) for hexfp, the decimal
11508                  * detection will shortly be more thorough with the
11509                  * underbar checks. */
11510                 const char* h = s;
11511                 significant_bits = non_zero_integer_digits * shift;
11512 #ifdef HEXFP_UQUAD
11513                 hexfp_uquad = u;
11514 #else /* HEXFP_NV */
11515                 hexfp_nv = u;
11516 #endif
11517                 /* Ignore the leading zero bits of
11518                  * the high (first) non-zero digit. */
11519                 if (high_non_zero) {
11520                     if (high_non_zero < 0x8)
11521                         significant_bits--;
11522                     if (high_non_zero < 0x4)
11523                         significant_bits--;
11524                     if (high_non_zero < 0x2)
11525                         significant_bits--;
11526                 }
11527
11528                 if (*h == '.') {
11529 #ifdef HEXFP_NV
11530                     NV nv_mult = 1.0;
11531 #endif
11532                     bool accumulate = TRUE;
11533                     U8 b;
11534                     int lim = 1 << shift;
11535                     for (h++; ((isXDIGIT(*h) && (b = XDIGIT_VALUE(*h)) < lim) ||
11536                                *h == '_'); h++) {
11537                         if (isXDIGIT(*h)) {
11538                             significant_bits += shift;
11539 #ifdef HEXFP_UQUAD
11540                             if (accumulate) {
11541                                 if (significant_bits < NV_MANT_DIG) {
11542                                     /* We are in the long "run" of xdigits,
11543                                      * accumulate the full four bits. */
11544                                     assert(shift >= 0);
11545                                     hexfp_uquad <<= shift;
11546                                     hexfp_uquad |= b;
11547                                     hexfp_frac_bits += shift;
11548                                 } else if (significant_bits - shift < NV_MANT_DIG) {
11549                                     /* We are at a hexdigit either at,
11550                                      * or straddling, the edge of mantissa.
11551                                      * We will try grabbing as many as
11552                                      * possible bits. */
11553                                     int tail =
11554                                       significant_bits - NV_MANT_DIG;
11555                                     if (tail <= 0)
11556                                        tail += shift;
11557                                     assert(tail >= 0);
11558                                     hexfp_uquad <<= tail;
11559                                     assert((shift - tail) >= 0);
11560                                     hexfp_uquad |= b >> (shift - tail);
11561                                     hexfp_frac_bits += tail;
11562
11563                                     /* Ignore the trailing zero bits
11564                                      * of the last non-zero xdigit.
11565                                      *
11566                                      * The assumption here is that if
11567                                      * one has input of e.g. the xdigit
11568                                      * eight (0x8), there is only one
11569                                      * bit being input, not the full
11570                                      * four bits.  Conversely, if one
11571                                      * specifies a zero xdigit, the
11572                                      * assumption is that one really
11573                                      * wants all those bits to be zero. */
11574                                     if (b) {
11575                                         if ((b & 0x1) == 0x0) {
11576                                             significant_bits--;
11577                                             if ((b & 0x2) == 0x0) {
11578                                                 significant_bits--;
11579                                                 if ((b & 0x4) == 0x0) {
11580                                                     significant_bits--;
11581                                                 }
11582                                             }
11583                                         }
11584                                     }
11585
11586                                     accumulate = FALSE;
11587                                 }
11588                             } else {
11589                                 /* Keep skipping the xdigits, and
11590                                  * accumulating the significant bits,
11591                                  * but do not shift the uquad
11592                                  * (which would catastrophically drop
11593                                  * high-order bits) or accumulate the
11594                                  * xdigits anymore. */
11595                             }
11596 #else /* HEXFP_NV */
11597                             if (accumulate) {
11598                                 nv_mult /= nvshift[shift];
11599                                 if (nv_mult > 0.0)
11600                                     hexfp_nv += b * nv_mult;
11601                                 else
11602                                     accumulate = FALSE;
11603                             }
11604 #endif
11605                         }
11606                         if (significant_bits >= NV_MANT_DIG)
11607                             accumulate = FALSE;
11608                     }
11609                 }
11610
11611                 if ((total_bits > 0 || significant_bits > 0) &&
11612                     isALPHA_FOLD_EQ(*h, 'p')) {
11613                     bool negexp = FALSE;
11614                     h++;
11615                     if (*h == '+')
11616                         h++;
11617                     else if (*h == '-') {
11618                         negexp = TRUE;
11619                         h++;
11620                     }
11621                     if (isDIGIT(*h)) {
11622                         I32 hexfp_exp = 0;
11623                         while (isDIGIT(*h) || *h == '_') {
11624                             if (isDIGIT(*h)) {
11625                                 hexfp_exp *= 10;
11626                                 hexfp_exp += *h - '0';
11627 #ifdef NV_MIN_EXP
11628                                 if (negexp
11629                                     && -hexfp_exp < NV_MIN_EXP - 1) {
11630                                     /* NOTE: this means that the exponent
11631                                      * underflow warning happens for
11632                                      * the IEEE 754 subnormals (denormals),
11633                                      * because DBL_MIN_EXP etc are the lowest
11634                                      * possible binary (or, rather, DBL_RADIX-base)
11635                                      * exponent for normals, not subnormals.
11636                                      *
11637                                      * This may or may not be a good thing. */
11638                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11639                                                    "Hexadecimal float: exponent underflow");
11640                                     break;
11641                                 }
11642 #endif
11643 #ifdef NV_MAX_EXP
11644                                 if (!negexp
11645                                     && hexfp_exp > NV_MAX_EXP - 1) {
11646                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11647                                                    "Hexadecimal float: exponent overflow");
11648                                     break;
11649                                 }
11650 #endif
11651                             }
11652                             h++;
11653                         }
11654                         if (negexp)
11655                             hexfp_exp = -hexfp_exp;
11656 #ifdef HEXFP_UQUAD
11657                         hexfp_exp -= hexfp_frac_bits;
11658 #endif
11659                         hexfp_mult = Perl_pow(2.0, hexfp_exp);
11660                         hexfp = TRUE;
11661                         goto decimal;
11662                     }
11663                 }
11664             }
11665
11666             if (shift != 3 && !has_digs) {
11667                 /* 0x or 0b with no digits, treat it as an error.
11668                    Originally this backed up the parse before the b or
11669                    x, but that has the potential for silent changes in
11670                    behaviour, like for: "0x.3" and "0x+$foo".
11671                 */
11672                 const char *d = s;
11673                 char *oldbp = PL_bufptr;
11674                 if (*d) ++d; /* so the user sees the bad non-digit */
11675                 PL_bufptr = (char *)d; /* so yyerror reports the context */
11676                 yyerror(Perl_form(aTHX_ "No digits found for %s literal",
11677                                   shift == 4 ? "hexadecimal" : "binary"));
11678                 PL_bufptr = oldbp;
11679             }
11680
11681             if (overflowed) {
11682                 if (n > 4294967295.0)
11683                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11684                                    "%s number > %s non-portable",
11685                                    Base, max);
11686                 sv = newSVnv(n);
11687             }
11688             else {
11689 #if UVSIZE > 4
11690                 if (u > 0xffffffff)
11691                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11692                                    "%s number > %s non-portable",
11693                                    Base, max);
11694 #endif
11695                 sv = newSVuv(u);
11696             }
11697             if (just_zero && (PL_hints & HINT_NEW_INTEGER))
11698                 sv = new_constant(start, s - start, "integer",
11699                                   sv, NULL, NULL, 0, NULL);
11700             else if (PL_hints & HINT_NEW_BINARY)
11701                 sv = new_constant(start, s - start, "binary",
11702                                   sv, NULL, NULL, 0, NULL);
11703         }
11704         break;
11705
11706     /*
11707       handle decimal numbers.
11708       we're also sent here when we read a 0 as the first digit
11709     */
11710     case '1': case '2': case '3': case '4': case '5':
11711     case '6': case '7': case '8': case '9': case '.':
11712       decimal:
11713         d = PL_tokenbuf;
11714         e = PL_tokenbuf + sizeof PL_tokenbuf - 6; /* room for various punctuation */
11715         floatit = FALSE;
11716         if (hexfp) {
11717             floatit = TRUE;
11718             *d++ = '0';
11719             switch (shift) {
11720             case 4:
11721                 *d++ = 'x';
11722                 s = start + 2;
11723                 break;
11724             case 3:
11725                 s = start + 1;
11726                 break;
11727             case 1:
11728                 *d++ = 'b';
11729                 s = start + 2;
11730                 break;
11731             default:
11732                 NOT_REACHED; /* NOTREACHED */
11733             }
11734         }
11735
11736         /* read next group of digits and _ and copy into d */
11737         while (isDIGIT(*s)
11738                || *s == '_'
11739                || UNLIKELY(hexfp && isXDIGIT(*s)))
11740         {
11741             /* skip underscores, checking for misplaced ones
11742                if -w is on
11743             */
11744             if (*s == '_') {
11745                 if (lastub && s == lastub + 1)
11746                     WARN_ABOUT_UNDERSCORE();
11747                 lastub = s++;
11748             }
11749             else {
11750                 /* check for end of fixed-length buffer */
11751                 if (d >= e)
11752                     Perl_croak(aTHX_ "%s", number_too_long);
11753                 /* if we're ok, copy the character */
11754                 *d++ = *s++;
11755             }
11756         }
11757
11758         /* final misplaced underbar check */
11759         if (lastub && s == lastub + 1)
11760             WARN_ABOUT_UNDERSCORE();
11761
11762         /* read a decimal portion if there is one.  avoid
11763            3..5 being interpreted as the number 3. followed
11764            by .5
11765         */
11766         if (*s == '.' && s[1] != '.') {
11767             floatit = TRUE;
11768             *d++ = *s++;
11769
11770             if (*s == '_') {
11771                 WARN_ABOUT_UNDERSCORE();
11772                 lastub = s;
11773             }
11774
11775             /* copy, ignoring underbars, until we run out of digits.
11776             */
11777             for (; isDIGIT(*s)
11778                    || *s == '_'
11779                    || UNLIKELY(hexfp && isXDIGIT(*s));
11780                  s++)
11781             {
11782                 /* fixed length buffer check */
11783                 if (d >= e)
11784                     Perl_croak(aTHX_ "%s", number_too_long);
11785                 if (*s == '_') {
11786                    if (lastub && s == lastub + 1)
11787                         WARN_ABOUT_UNDERSCORE();
11788                    lastub = s;
11789                 }
11790                 else
11791                     *d++ = *s;
11792             }
11793             /* fractional part ending in underbar? */
11794             if (s[-1] == '_')
11795                 WARN_ABOUT_UNDERSCORE();
11796             if (*s == '.' && isDIGIT(s[1])) {
11797                 /* oops, it's really a v-string, but without the "v" */
11798                 s = start;
11799                 goto vstring;
11800             }
11801         }
11802
11803         /* read exponent part, if present */
11804         if ((isALPHA_FOLD_EQ(*s, 'e')
11805               || UNLIKELY(hexfp && isALPHA_FOLD_EQ(*s, 'p')))
11806             && memCHRs("+-0123456789_", s[1]))
11807         {
11808             int exp_digits = 0;
11809             const char *save_s = s;
11810             char * save_d = d;
11811
11812             /* regardless of whether user said 3E5 or 3e5, use lower 'e',
11813                ditto for p (hexfloats) */
11814             if ((isALPHA_FOLD_EQ(*s, 'e'))) {
11815                 /* At least some Mach atof()s don't grok 'E' */
11816                 *d++ = 'e';
11817             }
11818             else if (UNLIKELY(hexfp && (isALPHA_FOLD_EQ(*s, 'p')))) {
11819                 *d++ = 'p';
11820             }
11821
11822             s++;
11823
11824
11825             /* stray preinitial _ */
11826             if (*s == '_') {
11827                 WARN_ABOUT_UNDERSCORE();
11828                 lastub = s++;
11829             }
11830
11831             /* allow positive or negative exponent */
11832             if (*s == '+' || *s == '-')
11833                 *d++ = *s++;
11834
11835             /* stray initial _ */
11836             if (*s == '_') {
11837                 WARN_ABOUT_UNDERSCORE();
11838                 lastub = s++;
11839             }
11840
11841             /* read digits of exponent */
11842             while (isDIGIT(*s) || *s == '_') {
11843                 if (isDIGIT(*s)) {
11844                     ++exp_digits;
11845                     if (d >= e)
11846                         Perl_croak(aTHX_ "%s", number_too_long);
11847                     *d++ = *s++;
11848                 }
11849                 else {
11850                    if (((lastub && s == lastub + 1)
11851                         || (!isDIGIT(s[1]) && s[1] != '_')))
11852                         WARN_ABOUT_UNDERSCORE();
11853                    lastub = s++;
11854                 }
11855             }
11856
11857             if (!exp_digits) {
11858                 /* no exponent digits, the [eEpP] could be for something else,
11859                  * though in practice we don't get here for p since that's preparsed
11860                  * earlier, and results in only the 0xX being consumed, so behave similarly
11861                  * for decimal floats and consume only the D.DD, leaving the [eE] to the
11862                  * next token.
11863                  */
11864                 s = save_s;
11865                 d = save_d;
11866             }
11867             else {
11868                 floatit = TRUE;
11869             }
11870         }
11871
11872
11873         /*
11874            We try to do an integer conversion first if no characters
11875            indicating "float" have been found.
11876          */
11877
11878         if (!floatit) {
11879             UV uv;
11880             const int flags = grok_number (PL_tokenbuf, d - PL_tokenbuf, &uv);
11881
11882             if (flags == IS_NUMBER_IN_UV) {
11883               if (uv <= IV_MAX)
11884                 sv = newSViv(uv); /* Prefer IVs over UVs. */
11885               else
11886                 sv = newSVuv(uv);
11887             } else if (flags == (IS_NUMBER_IN_UV | IS_NUMBER_NEG)) {
11888               if (uv <= (UV) IV_MIN)
11889                 sv = newSViv(-(IV)uv);
11890               else
11891                 floatit = TRUE;
11892             } else
11893               floatit = TRUE;
11894         }
11895         if (floatit) {
11896             /* terminate the string */
11897             *d = '\0';
11898             if (UNLIKELY(hexfp)) {
11899 #  ifdef NV_MANT_DIG
11900                 if (significant_bits > NV_MANT_DIG)
11901                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11902                                    "Hexadecimal float: mantissa overflow");
11903 #  endif
11904 #ifdef HEXFP_UQUAD
11905                 nv = hexfp_uquad * hexfp_mult;
11906 #else /* HEXFP_NV */
11907                 nv = hexfp_nv * hexfp_mult;
11908 #endif
11909             } else {
11910                 nv = Atof(PL_tokenbuf);
11911             }
11912             sv = newSVnv(nv);
11913         }
11914
11915         if ( floatit
11916              ? (PL_hints & HINT_NEW_FLOAT) : (PL_hints & HINT_NEW_INTEGER) ) {
11917             const char *const key = floatit ? "float" : "integer";
11918             const STRLEN keylen = floatit ? 5 : 7;
11919             sv = S_new_constant(aTHX_ PL_tokenbuf, d - PL_tokenbuf,
11920                                 key, keylen, sv, NULL, NULL, 0, NULL);
11921         }
11922         break;
11923
11924     /* if it starts with a v, it could be a v-string */
11925     case 'v':
11926     vstring:
11927                 sv = newSV(5); /* preallocate storage space */
11928                 ENTER_with_name("scan_vstring");
11929                 SAVEFREESV(sv);
11930                 s = scan_vstring(s, PL_bufend, sv);
11931                 SvREFCNT_inc_simple_void_NN(sv);
11932                 LEAVE_with_name("scan_vstring");
11933         break;
11934     }
11935
11936     /* make the op for the constant and return */
11937
11938     if (sv)
11939         lvalp->opval = newSVOP(OP_CONST, 0, sv);
11940     else
11941         lvalp->opval = NULL;
11942
11943     return (char *)s;
11944 }
11945
11946 STATIC char *
11947 S_scan_formline(pTHX_ char *s)
11948 {
11949     SV * const stuff = newSVpvs("");
11950     bool needargs = FALSE;
11951     bool eofmt = FALSE;
11952
11953     PERL_ARGS_ASSERT_SCAN_FORMLINE;
11954
11955     while (!needargs) {
11956         char *eol;
11957         if (*s == '.') {
11958             char *t = s+1;
11959 #ifdef PERL_STRICT_CR
11960             while (SPACE_OR_TAB(*t))
11961                 t++;
11962 #else
11963             while (SPACE_OR_TAB(*t) || *t == '\r')
11964                 t++;
11965 #endif
11966             if (*t == '\n' || t == PL_bufend) {
11967                 eofmt = TRUE;
11968                 break;
11969             }
11970         }
11971         eol = (char *) memchr(s,'\n',PL_bufend-s);
11972         if (!eol++)
11973                 eol = PL_bufend;
11974         if (*s != '#') {
11975             char *t;
11976             for (t = s; t < eol; t++) {
11977                 if (*t == '~' && t[1] == '~' && SvCUR(stuff)) {
11978                     needargs = FALSE;
11979                     goto enough;        /* ~~ must be first line in formline */
11980                 }
11981                 if (*t == '@' || *t == '^')
11982                     needargs = TRUE;
11983             }
11984             if (eol > s) {
11985                 sv_catpvn(stuff, s, eol-s);
11986 #ifndef PERL_STRICT_CR
11987                 if (eol-s > 1 && eol[-2] == '\r' && eol[-1] == '\n') {
11988                     char *end = SvPVX(stuff) + SvCUR(stuff);
11989                     end[-2] = '\n';
11990                     end[-1] = '\0';
11991                     SvCUR_set(stuff, SvCUR(stuff) - 1);
11992                 }
11993 #endif
11994             }
11995             else
11996               break;
11997         }
11998         s = (char*)eol;
11999         if ((PL_rsfp || PL_parser->filtered)
12000          && PL_parser->form_lex_state == LEX_NORMAL) {
12001             bool got_some;
12002             PL_bufptr = PL_bufend;
12003             COPLINE_INC_WITH_HERELINES;
12004             got_some = lex_next_chunk(0);
12005             CopLINE_dec(PL_curcop);
12006             s = PL_bufptr;
12007             if (!got_some)
12008                 break;
12009         }
12010         incline(s, PL_bufend);
12011     }
12012   enough:
12013     if (!SvCUR(stuff) || needargs)
12014         PL_lex_state = PL_parser->form_lex_state;
12015     if (SvCUR(stuff)) {
12016         PL_expect = XSTATE;
12017         if (needargs) {
12018             const char *s2 = s;
12019             while (isSPACE(*s2) && *s2 != '\n')
12020                 s2++;
12021             if (*s2 == '{') {
12022                 PL_expect = XTERMBLOCK;
12023                 NEXTVAL_NEXTTOKE.ival = 0;
12024                 force_next(DO);
12025             }
12026             NEXTVAL_NEXTTOKE.ival = 0;
12027             force_next(FORMLBRACK);
12028         }
12029         if (!IN_BYTES) {
12030             if (UTF && is_utf8_string((U8*)SvPVX_const(stuff), SvCUR(stuff)))
12031                 SvUTF8_on(stuff);
12032         }
12033         NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0, stuff);
12034         force_next(THING);
12035     }
12036     else {
12037         SvREFCNT_dec(stuff);
12038         if (eofmt)
12039             PL_lex_formbrack = 0;
12040     }
12041     return s;
12042 }
12043
12044 I32
12045 Perl_start_subparse(pTHX_ I32 is_format, U32 flags)
12046 {
12047     const I32 oldsavestack_ix = PL_savestack_ix;
12048     CV* const outsidecv = PL_compcv;
12049
12050     SAVEI32(PL_subline);
12051     save_item(PL_subname);
12052     SAVESPTR(PL_compcv);
12053
12054     PL_compcv = MUTABLE_CV(newSV_type(is_format ? SVt_PVFM : SVt_PVCV));
12055     CvFLAGS(PL_compcv) |= flags;
12056
12057     PL_subline = CopLINE(PL_curcop);
12058     CvPADLIST(PL_compcv) = pad_new(padnew_SAVE|padnew_SAVESUB);
12059     CvOUTSIDE(PL_compcv) = MUTABLE_CV(SvREFCNT_inc_simple(outsidecv));
12060     CvOUTSIDE_SEQ(PL_compcv) = PL_cop_seqmax;
12061     if (outsidecv && CvPADLIST(outsidecv))
12062         CvPADLIST(PL_compcv)->xpadl_outid = CvPADLIST(outsidecv)->xpadl_id;
12063
12064     return oldsavestack_ix;
12065 }
12066
12067
12068 /* Do extra initialisation of a CV (typically one just created by
12069  * start_subparse()) if that CV is for a named sub
12070  */
12071
12072 void
12073 Perl_init_named_cv(pTHX_ CV *cv, OP *nameop)
12074 {
12075     PERL_ARGS_ASSERT_INIT_NAMED_CV;
12076
12077     if (nameop->op_type == OP_CONST) {
12078         const char *const name = SvPV_nolen_const(((SVOP*)nameop)->op_sv);
12079         if (   strEQ(name, "BEGIN")
12080             || strEQ(name, "END")
12081             || strEQ(name, "INIT")
12082             || strEQ(name, "CHECK")
12083             || strEQ(name, "UNITCHECK")
12084         )
12085           CvSPECIAL_on(cv);
12086     }
12087     else
12088     /* State subs inside anonymous subs need to be
12089      clonable themselves. */
12090     if (   CvANON(CvOUTSIDE(cv))
12091         || CvCLONE(CvOUTSIDE(cv))
12092         || !PadnameIsSTATE(PadlistNAMESARRAY(CvPADLIST(
12093                         CvOUTSIDE(cv)
12094                      ))[nameop->op_targ])
12095     )
12096       CvCLONE_on(cv);
12097 }
12098
12099
12100 static int
12101 S_yywarn(pTHX_ const char *const s, U32 flags)
12102 {
12103     PERL_ARGS_ASSERT_YYWARN;
12104
12105     PL_in_eval |= EVAL_WARNONLY;
12106     yyerror_pv(s, flags);
12107     return 0;
12108 }
12109
12110 void
12111 Perl_abort_execution(pTHX_ const char * const msg, const char * const name)
12112 {
12113     PERL_ARGS_ASSERT_ABORT_EXECUTION;
12114
12115     if (PL_minus_c)
12116         Perl_croak(aTHX_ "%s%s had compilation errors.\n", msg, name);
12117     else {
12118         Perl_croak(aTHX_
12119                 "%sExecution of %s aborted due to compilation errors.\n", msg, name);
12120     }
12121     NOT_REACHED; /* NOTREACHED */
12122 }
12123
12124 void
12125 Perl_yyquit(pTHX)
12126 {
12127     /* Called, after at least one error has been found, to abort the parse now,
12128      * instead of trying to forge ahead */
12129
12130     yyerror_pvn(NULL, 0, 0);
12131 }
12132
12133 int
12134 Perl_yyerror(pTHX_ const char *const s)
12135 {
12136     PERL_ARGS_ASSERT_YYERROR;
12137     return yyerror_pvn(s, strlen(s), 0);
12138 }
12139
12140 int
12141 Perl_yyerror_pv(pTHX_ const char *const s, U32 flags)
12142 {
12143     PERL_ARGS_ASSERT_YYERROR_PV;
12144     return yyerror_pvn(s, strlen(s), flags);
12145 }
12146
12147 int
12148 Perl_yyerror_pvn(pTHX_ const char *const s, STRLEN len, U32 flags)
12149 {
12150     const char *context = NULL;
12151     int contlen = -1;
12152     SV *msg;
12153     SV * const where_sv = newSVpvs_flags("", SVs_TEMP);
12154     int yychar  = PL_parser->yychar;
12155
12156     /* Output error message 's' with length 'len'.  'flags' are SV flags that
12157      * apply.  If the number of errors found is large enough, it abandons
12158      * parsing.  If 's' is NULL, there is no message, and it abandons
12159      * processing unconditionally */
12160
12161     if (s != NULL) {
12162         if (!yychar || (yychar == ';' && !PL_rsfp))
12163             sv_catpvs(where_sv, "at EOF");
12164         else if (   PL_oldoldbufptr
12165                  && PL_bufptr > PL_oldoldbufptr
12166                  && PL_bufptr - PL_oldoldbufptr < 200
12167                  && PL_oldoldbufptr != PL_oldbufptr
12168                  && PL_oldbufptr != PL_bufptr)
12169         {
12170             /*
12171                     Only for NetWare:
12172                     The code below is removed for NetWare because it
12173                     abends/crashes on NetWare when the script has error such as
12174                     not having the closing quotes like:
12175                         if ($var eq "value)
12176                     Checking of white spaces is anyway done in NetWare code.
12177             */
12178 #ifndef NETWARE
12179             while (isSPACE(*PL_oldoldbufptr))
12180                 PL_oldoldbufptr++;
12181 #endif
12182             context = PL_oldoldbufptr;
12183             contlen = PL_bufptr - PL_oldoldbufptr;
12184         }
12185         else if (  PL_oldbufptr
12186                 && PL_bufptr > PL_oldbufptr
12187                 && PL_bufptr - PL_oldbufptr < 200
12188                 && PL_oldbufptr != PL_bufptr) {
12189             /*
12190                     Only for NetWare:
12191                     The code below is removed for NetWare because it
12192                     abends/crashes on NetWare when the script has error such as
12193                     not having the closing quotes like:
12194                         if ($var eq "value)
12195                     Checking of white spaces is anyway done in NetWare code.
12196             */
12197 #ifndef NETWARE
12198             while (isSPACE(*PL_oldbufptr))
12199                 PL_oldbufptr++;
12200 #endif
12201             context = PL_oldbufptr;
12202             contlen = PL_bufptr - PL_oldbufptr;
12203         }
12204         else if (yychar > 255)
12205             sv_catpvs(where_sv, "next token ???");
12206         else if (yychar == YYEMPTY) {
12207             if (PL_lex_state == LEX_NORMAL)
12208                 sv_catpvs(where_sv, "at end of line");
12209             else if (PL_lex_inpat)
12210                 sv_catpvs(where_sv, "within pattern");
12211             else
12212                 sv_catpvs(where_sv, "within string");
12213         }
12214         else {
12215             sv_catpvs(where_sv, "next char ");
12216             if (yychar < 32)
12217                 Perl_sv_catpvf(aTHX_ where_sv, "^%c", toCTRL(yychar));
12218             else if (isPRINT_LC(yychar)) {
12219                 const char string = yychar;
12220                 sv_catpvn(where_sv, &string, 1);
12221             }
12222             else
12223                 Perl_sv_catpvf(aTHX_ where_sv, "\\%03o", yychar & 255);
12224         }
12225         msg = newSVpvn_flags(s, len, (flags & SVf_UTF8) | SVs_TEMP);
12226         Perl_sv_catpvf(aTHX_ msg, " at %s line %" IVdf ", ",
12227             OutCopFILE(PL_curcop),
12228             (IV)(PL_parser->preambling == NOLINE
12229                    ? CopLINE(PL_curcop)
12230                    : PL_parser->preambling));
12231         if (context)
12232             Perl_sv_catpvf(aTHX_ msg, "near \"%" UTF8f "\"\n",
12233                                  UTF8fARG(UTF, contlen, context));
12234         else
12235             Perl_sv_catpvf(aTHX_ msg, "%" SVf "\n", SVfARG(where_sv));
12236         if (   PL_multi_start < PL_multi_end
12237             && (U32)(CopLINE(PL_curcop) - PL_multi_end) <= 1)
12238         {
12239             Perl_sv_catpvf(aTHX_ msg,
12240             "  (Might be a runaway multi-line %c%c string starting on"
12241             " line %" IVdf ")\n",
12242                     (int)PL_multi_open,(int)PL_multi_close,(IV)PL_multi_start);
12243             PL_multi_end = 0;
12244         }
12245         if (PL_in_eval & EVAL_WARNONLY) {
12246             PL_in_eval &= ~EVAL_WARNONLY;
12247             Perl_ck_warner_d(aTHX_ packWARN(WARN_SYNTAX), "%" SVf, SVfARG(msg));
12248         }
12249         else {
12250             qerror(msg);
12251         }
12252     }
12253     if (s == NULL || PL_error_count >= 10) {
12254         const char * msg = "";
12255         const char * const name = OutCopFILE(PL_curcop);
12256
12257         if (PL_in_eval) {
12258             SV * errsv = ERRSV;
12259             if (SvCUR(errsv)) {
12260                 msg = Perl_form(aTHX_ "%" SVf, SVfARG(errsv));
12261             }
12262         }
12263
12264         if (s == NULL) {
12265             abort_execution(msg, name);
12266         }
12267         else {
12268             Perl_croak(aTHX_ "%s%s has too many errors.\n", msg, name);
12269         }
12270     }
12271     PL_in_my = 0;
12272     PL_in_my_stash = NULL;
12273     return 0;
12274 }
12275
12276 STATIC char*
12277 S_swallow_bom(pTHX_ U8 *s)
12278 {
12279     const STRLEN slen = SvCUR(PL_linestr);
12280
12281     PERL_ARGS_ASSERT_SWALLOW_BOM;
12282
12283     switch (s[0]) {
12284     case 0xFF:
12285         if (s[1] == 0xFE) {
12286             /* UTF-16 little-endian? (or UTF-32LE?) */
12287             if (s[2] == 0 && s[3] == 0)  /* UTF-32 little-endian */
12288                 /* diag_listed_as: Unsupported script encoding %s */
12289                 Perl_croak(aTHX_ "Unsupported script encoding UTF-32LE");
12290 #ifndef PERL_NO_UTF16_FILTER
12291 #ifdef DEBUGGING
12292             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (BOM)\n");
12293 #endif
12294             s += 2;
12295             if (PL_bufend > (char*)s) {
12296                 s = add_utf16_textfilter(s, TRUE);
12297             }
12298 #else
12299             /* diag_listed_as: Unsupported script encoding %s */
12300             Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12301 #endif
12302         }
12303         break;
12304     case 0xFE:
12305         if (s[1] == 0xFF) {   /* UTF-16 big-endian? */
12306 #ifndef PERL_NO_UTF16_FILTER
12307 #ifdef DEBUGGING
12308             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (BOM)\n");
12309 #endif
12310             s += 2;
12311             if (PL_bufend > (char *)s) {
12312                 s = add_utf16_textfilter(s, FALSE);
12313             }
12314 #else
12315             /* diag_listed_as: Unsupported script encoding %s */
12316             Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12317 #endif
12318         }
12319         break;
12320     case BOM_UTF8_FIRST_BYTE: {
12321         if (memBEGINs(s+1, slen - 1, BOM_UTF8_TAIL)) {
12322 #ifdef DEBUGGING
12323             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-8 script encoding (BOM)\n");
12324 #endif
12325             s += sizeof(BOM_UTF8) - 1;                     /* UTF-8 */
12326         }
12327         break;
12328     }
12329     case 0:
12330         if (slen > 3) {
12331              if (s[1] == 0) {
12332                   if (s[2] == 0xFE && s[3] == 0xFF) {
12333                        /* UTF-32 big-endian */
12334                        /* diag_listed_as: Unsupported script encoding %s */
12335                        Perl_croak(aTHX_ "Unsupported script encoding UTF-32BE");
12336                   }
12337              }
12338              else if (s[2] == 0 && s[3] != 0) {
12339                   /* Leading bytes
12340                    * 00 xx 00 xx
12341                    * are a good indicator of UTF-16BE. */
12342 #ifndef PERL_NO_UTF16_FILTER
12343 #ifdef DEBUGGING
12344                   if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (no BOM)\n");
12345 #endif
12346                   s = add_utf16_textfilter(s, FALSE);
12347 #else
12348                   /* diag_listed_as: Unsupported script encoding %s */
12349                   Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12350 #endif
12351              }
12352         }
12353         break;
12354
12355     default:
12356          if (slen > 3 && s[1] == 0 && s[2] != 0 && s[3] == 0) {
12357                   /* Leading bytes
12358                    * xx 00 xx 00
12359                    * are a good indicator of UTF-16LE. */
12360 #ifndef PERL_NO_UTF16_FILTER
12361 #ifdef DEBUGGING
12362               if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (no BOM)\n");
12363 #endif
12364               s = add_utf16_textfilter(s, TRUE);
12365 #else
12366               /* diag_listed_as: Unsupported script encoding %s */
12367               Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12368 #endif
12369          }
12370     }
12371     return (char*)s;
12372 }
12373
12374
12375 #ifndef PERL_NO_UTF16_FILTER
12376 static I32
12377 S_utf16_textfilter(pTHX_ int idx, SV *sv, int maxlen)
12378 {
12379     SV *const filter = FILTER_DATA(idx);
12380     /* We re-use this each time round, throwing the contents away before we
12381        return.  */
12382     SV *const utf16_buffer = MUTABLE_SV(IoTOP_GV(filter));
12383     SV *const utf8_buffer = filter;
12384     IV status = IoPAGE(filter);
12385     const bool reverse = cBOOL(IoLINES(filter));
12386     I32 retval;
12387
12388     PERL_ARGS_ASSERT_UTF16_TEXTFILTER;
12389
12390     /* As we're automatically added, at the lowest level, and hence only called
12391        from this file, we can be sure that we're not called in block mode. Hence
12392        don't bother writing code to deal with block mode.  */
12393     if (maxlen) {
12394         Perl_croak(aTHX_ "panic: utf16_textfilter called in block mode (for %d characters)", maxlen);
12395     }
12396     if (status < 0) {
12397         Perl_croak(aTHX_ "panic: utf16_textfilter called after error (status=%" IVdf ")", status);
12398     }
12399     DEBUG_P(PerlIO_printf(Perl_debug_log,
12400                           "utf16_textfilter(%p,%ce): idx=%d maxlen=%d status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12401                           FPTR2DPTR(void *, S_utf16_textfilter),
12402                           reverse ? 'l' : 'b', idx, maxlen, status,
12403                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12404
12405     while (1) {
12406         STRLEN chars;
12407         STRLEN have;
12408         Size_t newlen;
12409         U8 *end;
12410         /* First, look in our buffer of existing UTF-8 data:  */
12411         char *nl = (char *)memchr(SvPVX(utf8_buffer), '\n', SvCUR(utf8_buffer));
12412
12413         if (nl) {
12414             ++nl;
12415         } else if (status == 0) {
12416             /* EOF */
12417             IoPAGE(filter) = 0;
12418             nl = SvEND(utf8_buffer);
12419         }
12420         if (nl) {
12421             STRLEN got = nl - SvPVX(utf8_buffer);
12422             /* Did we have anything to append?  */
12423             retval = got != 0;
12424             sv_catpvn(sv, SvPVX(utf8_buffer), got);
12425             /* Everything else in this code works just fine if SVp_POK isn't
12426                set.  This, however, needs it, and we need it to work, else
12427                we loop infinitely because the buffer is never consumed.  */
12428             sv_chop(utf8_buffer, nl);
12429             break;
12430         }
12431
12432         /* OK, not a complete line there, so need to read some more UTF-16.
12433            Read an extra octect if the buffer currently has an odd number. */
12434         while (1) {
12435             if (status <= 0)
12436                 break;
12437             if (SvCUR(utf16_buffer) >= 2) {
12438                 /* Location of the high octet of the last complete code point.
12439                    Gosh, UTF-16 is a pain. All the benefits of variable length,
12440                    *coupled* with all the benefits of partial reads and
12441                    endianness.  */
12442                 const U8 *const last_hi = (U8*)SvPVX(utf16_buffer)
12443                     + ((SvCUR(utf16_buffer) & ~1) - (reverse ? 1 : 2));
12444
12445                 if (*last_hi < 0xd8 || *last_hi > 0xdb) {
12446                     break;
12447                 }
12448
12449                 /* We have the first half of a surrogate. Read more.  */
12450                 DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter partial surrogate detected at %p\n", last_hi));
12451             }
12452
12453             status = FILTER_READ(idx + 1, utf16_buffer,
12454                                  160 + (SvCUR(utf16_buffer) & 1));
12455             DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter status=%" IVdf " SvCUR(sv)=%" UVuf "\n", status, (UV)SvCUR(utf16_buffer)));
12456             DEBUG_P({ sv_dump(utf16_buffer); sv_dump(utf8_buffer);});
12457             if (status < 0) {
12458                 /* Error */
12459                 IoPAGE(filter) = status;
12460                 return status;
12461             }
12462         }
12463
12464         /* 'chars' isn't quite the right name, as code points above 0xFFFF
12465          * require 4 bytes per char */
12466         chars = SvCUR(utf16_buffer) >> 1;
12467         have = SvCUR(utf8_buffer);
12468
12469         /* Assume the worst case size as noted by the functions: twice the
12470          * number of input bytes */
12471         SvGROW(utf8_buffer, have + chars * 4 + 1);
12472
12473         if (reverse) {
12474             end = utf16_to_utf8_reversed((U8*)SvPVX(utf16_buffer),
12475                                          (U8*)SvPVX_const(utf8_buffer) + have,
12476                                          chars * 2, &newlen);
12477         } else {
12478             end = utf16_to_utf8((U8*)SvPVX(utf16_buffer),
12479                                 (U8*)SvPVX_const(utf8_buffer) + have,
12480                                 chars * 2, &newlen);
12481         }
12482         SvCUR_set(utf8_buffer, have + newlen);
12483         *end = '\0';
12484
12485         /* No need to keep this SV "well-formed" with a '\0' after the end, as
12486            it's private to us, and utf16_to_utf8{,reversed} take a
12487            (pointer,length) pair, rather than a NUL-terminated string.  */
12488         if(SvCUR(utf16_buffer) & 1) {
12489             *SvPVX(utf16_buffer) = SvEND(utf16_buffer)[-1];
12490             SvCUR_set(utf16_buffer, 1);
12491         } else {
12492             SvCUR_set(utf16_buffer, 0);
12493         }
12494     }
12495     DEBUG_P(PerlIO_printf(Perl_debug_log,
12496                           "utf16_textfilter: returns, status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12497                           status,
12498                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12499     DEBUG_P({ sv_dump(utf8_buffer); sv_dump(sv);});
12500     return retval;
12501 }
12502
12503 static U8 *
12504 S_add_utf16_textfilter(pTHX_ U8 *const s, bool reversed)
12505 {
12506     SV *filter = filter_add(S_utf16_textfilter, NULL);
12507
12508     PERL_ARGS_ASSERT_ADD_UTF16_TEXTFILTER;
12509
12510     IoTOP_GV(filter) = MUTABLE_GV(newSVpvn((char *)s, PL_bufend - (char*)s));
12511     SvPVCLEAR(filter);
12512     IoLINES(filter) = reversed;
12513     IoPAGE(filter) = 1; /* Not EOF */
12514
12515     /* Sadly, we have to return a valid pointer, come what may, so we have to
12516        ignore any error return from this.  */
12517     SvCUR_set(PL_linestr, 0);
12518     if (FILTER_READ(0, PL_linestr, 0)) {
12519         SvUTF8_on(PL_linestr);
12520     } else {
12521         SvUTF8_on(PL_linestr);
12522     }
12523     PL_bufend = SvEND(PL_linestr);
12524     return (U8*)SvPVX(PL_linestr);
12525 }
12526 #endif
12527
12528 /*
12529 Returns a pointer to the next character after the parsed
12530 vstring, as well as updating the passed in sv.
12531
12532 Function must be called like
12533
12534         sv = sv_2mortal(newSV(5));
12535         s = scan_vstring(s,e,sv);
12536
12537 where s and e are the start and end of the string.
12538 The sv should already be large enough to store the vstring
12539 passed in, for performance reasons.
12540
12541 This function may croak if fatal warnings are enabled in the
12542 calling scope, hence the sv_2mortal in the example (to prevent
12543 a leak).  Make sure to do SvREFCNT_inc afterwards if you use
12544 sv_2mortal.
12545
12546 */
12547
12548 char *
12549 Perl_scan_vstring(pTHX_ const char *s, const char *const e, SV *sv)
12550 {
12551     const char *pos = s;
12552     const char *start = s;
12553
12554     PERL_ARGS_ASSERT_SCAN_VSTRING;
12555
12556     if (*pos == 'v') pos++;  /* get past 'v' */
12557     while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12558         pos++;
12559     if ( *pos != '.') {
12560         /* this may not be a v-string if followed by => */
12561         const char *next = pos;
12562         while (next < e && isSPACE(*next))
12563             ++next;
12564         if ((e - next) >= 2 && *next == '=' && next[1] == '>' ) {
12565             /* return string not v-string */
12566             sv_setpvn(sv,(char *)s,pos-s);
12567             return (char *)pos;
12568         }
12569     }
12570
12571     if (!isALPHA(*pos)) {
12572         U8 tmpbuf[UTF8_MAXBYTES+1];
12573
12574         if (*s == 'v')
12575             s++;  /* get past 'v' */
12576
12577         SvPVCLEAR(sv);
12578
12579         for (;;) {
12580             /* this is atoi() that tolerates underscores */
12581             U8 *tmpend;
12582             UV rev = 0;
12583             const char *end = pos;
12584             UV mult = 1;
12585             while (--end >= s) {
12586                 if (*end != '_') {
12587                     const UV orev = rev;
12588                     rev += (*end - '0') * mult;
12589                     mult *= 10;
12590                     if (orev > rev)
12591                         /* diag_listed_as: Integer overflow in %s number */
12592                         Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
12593                                          "Integer overflow in decimal number");
12594                 }
12595             }
12596
12597             /* Append native character for the rev point */
12598             tmpend = uvchr_to_utf8(tmpbuf, rev);
12599             sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
12600             if (!UVCHR_IS_INVARIANT(rev))
12601                  SvUTF8_on(sv);
12602             if (pos + 1 < e && *pos == '.' && isDIGIT(pos[1]))
12603                  s = ++pos;
12604             else {
12605                  s = pos;
12606                  break;
12607             }
12608             while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12609                  pos++;
12610         }
12611         SvPOK_on(sv);
12612         sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
12613         SvRMAGICAL_on(sv);
12614     }
12615     return (char *)s;
12616 }
12617
12618 int
12619 Perl_keyword_plugin_standard(pTHX_
12620         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
12621 {
12622     PERL_ARGS_ASSERT_KEYWORD_PLUGIN_STANDARD;
12623     PERL_UNUSED_CONTEXT;
12624     PERL_UNUSED_ARG(keyword_ptr);
12625     PERL_UNUSED_ARG(keyword_len);
12626     PERL_UNUSED_ARG(op_ptr);
12627     return KEYWORD_PLUGIN_DECLINE;
12628 }
12629
12630 /*
12631 =for apidoc wrap_keyword_plugin
12632
12633 Puts a C function into the chain of keyword plugins.  This is the
12634 preferred way to manipulate the L</PL_keyword_plugin> variable.
12635 C<new_plugin> is a pointer to the C function that is to be added to the
12636 keyword plugin chain, and C<old_plugin_p> points to the storage location
12637 where a pointer to the next function in the chain will be stored.  The
12638 value of C<new_plugin> is written into the L</PL_keyword_plugin> variable,
12639 while the value previously stored there is written to C<*old_plugin_p>.
12640
12641 L</PL_keyword_plugin> is global to an entire process, and a module wishing
12642 to hook keyword parsing may find itself invoked more than once per
12643 process, typically in different threads.  To handle that situation, this
12644 function is idempotent.  The location C<*old_plugin_p> must initially
12645 (once per process) contain a null pointer.  A C variable of static
12646 duration (declared at file scope, typically also marked C<static> to give
12647 it internal linkage) will be implicitly initialised appropriately, if it
12648 does not have an explicit initialiser.  This function will only actually
12649 modify the plugin chain if it finds C<*old_plugin_p> to be null.  This
12650 function is also thread safe on the small scale.  It uses appropriate
12651 locking to avoid race conditions in accessing L</PL_keyword_plugin>.
12652
12653 When this function is called, the function referenced by C<new_plugin>
12654 must be ready to be called, except for C<*old_plugin_p> being unfilled.
12655 In a threading situation, C<new_plugin> may be called immediately, even
12656 before this function has returned.  C<*old_plugin_p> will always be
12657 appropriately set before C<new_plugin> is called.  If C<new_plugin>
12658 decides not to do anything special with the identifier that it is given
12659 (which is the usual case for most calls to a keyword plugin), it must
12660 chain the plugin function referenced by C<*old_plugin_p>.
12661
12662 Taken all together, XS code to install a keyword plugin should typically
12663 look something like this:
12664
12665     static Perl_keyword_plugin_t next_keyword_plugin;
12666     static OP *my_keyword_plugin(pTHX_
12667         char *keyword_plugin, STRLEN keyword_len, OP **op_ptr)
12668     {
12669         if (memEQs(keyword_ptr, keyword_len,
12670                    "my_new_keyword")) {
12671             ...
12672         } else {
12673             return next_keyword_plugin(aTHX_
12674                 keyword_ptr, keyword_len, op_ptr);
12675         }
12676     }
12677     BOOT:
12678         wrap_keyword_plugin(my_keyword_plugin,
12679                             &next_keyword_plugin);
12680
12681 Direct access to L</PL_keyword_plugin> should be avoided.
12682
12683 =cut
12684 */
12685
12686 void
12687 Perl_wrap_keyword_plugin(pTHX_
12688     Perl_keyword_plugin_t new_plugin, Perl_keyword_plugin_t *old_plugin_p)
12689 {
12690     dVAR;
12691
12692     PERL_UNUSED_CONTEXT;
12693     PERL_ARGS_ASSERT_WRAP_KEYWORD_PLUGIN;
12694     if (*old_plugin_p) return;
12695     KEYWORD_PLUGIN_MUTEX_LOCK;
12696     if (!*old_plugin_p) {
12697         *old_plugin_p = PL_keyword_plugin;
12698         PL_keyword_plugin = new_plugin;
12699     }
12700     KEYWORD_PLUGIN_MUTEX_UNLOCK;
12701 }
12702
12703 #define parse_recdescent(g,p) S_parse_recdescent(aTHX_ g,p)
12704 static void
12705 S_parse_recdescent(pTHX_ int gramtype, I32 fakeeof)
12706 {
12707     SAVEI32(PL_lex_brackets);
12708     if (PL_lex_brackets > 100)
12709         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
12710     PL_lex_brackstack[PL_lex_brackets++] = XFAKEEOF;
12711     SAVEI32(PL_lex_allbrackets);
12712     PL_lex_allbrackets = 0;
12713     SAVEI8(PL_lex_fakeeof);
12714     PL_lex_fakeeof = (U8)fakeeof;
12715     if(yyparse(gramtype) && !PL_parser->error_count)
12716         qerror(Perl_mess(aTHX_ "Parse error"));
12717 }
12718
12719 #define parse_recdescent_for_op(g,p) S_parse_recdescent_for_op(aTHX_ g,p)
12720 static OP *
12721 S_parse_recdescent_for_op(pTHX_ int gramtype, I32 fakeeof)
12722 {
12723     OP *o;
12724     ENTER;
12725     SAVEVPTR(PL_eval_root);
12726     PL_eval_root = NULL;
12727     parse_recdescent(gramtype, fakeeof);
12728     o = PL_eval_root;
12729     LEAVE;
12730     return o;
12731 }
12732
12733 #define parse_expr(p,f) S_parse_expr(aTHX_ p,f)
12734 static OP *
12735 S_parse_expr(pTHX_ I32 fakeeof, U32 flags)
12736 {
12737     OP *exprop;
12738     if (flags & ~PARSE_OPTIONAL)
12739         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_expr");
12740     exprop = parse_recdescent_for_op(GRAMEXPR, fakeeof);
12741     if (!exprop && !(flags & PARSE_OPTIONAL)) {
12742         if (!PL_parser->error_count)
12743             qerror(Perl_mess(aTHX_ "Parse error"));
12744         exprop = newOP(OP_NULL, 0);
12745     }
12746     return exprop;
12747 }
12748
12749 /*
12750 =for apidoc parse_arithexpr
12751
12752 Parse a Perl arithmetic expression.  This may contain operators of precedence
12753 down to the bit shift operators.  The expression must be followed (and thus
12754 terminated) either by a comparison or lower-precedence operator or by
12755 something that would normally terminate an expression such as semicolon.
12756 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12757 otherwise it is mandatory.  It is up to the caller to ensure that the
12758 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12759 the source of the code to be parsed and the lexical context for the
12760 expression.
12761
12762 The op tree representing the expression is returned.  If an optional
12763 expression is absent, a null pointer is returned, otherwise the pointer
12764 will be non-null.
12765
12766 If an error occurs in parsing or compilation, in most cases a valid op
12767 tree is returned anyway.  The error is reflected in the parser state,
12768 normally resulting in a single exception at the top level of parsing
12769 which covers all the compilation errors that occurred.  Some compilation
12770 errors, however, will throw an exception immediately.
12771
12772 =for apidoc Amnh||PARSE_OPTIONAL
12773
12774 =cut
12775
12776 */
12777
12778 OP *
12779 Perl_parse_arithexpr(pTHX_ U32 flags)
12780 {
12781     return parse_expr(LEX_FAKEEOF_COMPARE, flags);
12782 }
12783
12784 /*
12785 =for apidoc parse_termexpr
12786
12787 Parse a Perl term expression.  This may contain operators of precedence
12788 down to the assignment operators.  The expression must be followed (and thus
12789 terminated) either by a comma or lower-precedence operator or by
12790 something that would normally terminate an expression such as semicolon.
12791 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12792 otherwise it is mandatory.  It is up to the caller to ensure that the
12793 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12794 the source of the code to be parsed and the lexical context for the
12795 expression.
12796
12797 The op tree representing the expression is returned.  If an optional
12798 expression is absent, a null pointer is returned, otherwise the pointer
12799 will be non-null.
12800
12801 If an error occurs in parsing or compilation, in most cases a valid op
12802 tree is returned anyway.  The error is reflected in the parser state,
12803 normally resulting in a single exception at the top level of parsing
12804 which covers all the compilation errors that occurred.  Some compilation
12805 errors, however, will throw an exception immediately.
12806
12807 =cut
12808 */
12809
12810 OP *
12811 Perl_parse_termexpr(pTHX_ U32 flags)
12812 {
12813     return parse_expr(LEX_FAKEEOF_COMMA, flags);
12814 }
12815
12816 /*
12817 =for apidoc parse_listexpr
12818
12819 Parse a Perl list expression.  This may contain operators of precedence
12820 down to the comma operator.  The expression must be followed (and thus
12821 terminated) either by a low-precedence logic operator such as C<or> or by
12822 something that would normally terminate an expression such as semicolon.
12823 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12824 otherwise it is mandatory.  It is up to the caller to ensure that the
12825 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12826 the source of the code to be parsed and the lexical context for the
12827 expression.
12828
12829 The op tree representing the expression is returned.  If an optional
12830 expression is absent, a null pointer is returned, otherwise the pointer
12831 will be non-null.
12832
12833 If an error occurs in parsing or compilation, in most cases a valid op
12834 tree is returned anyway.  The error is reflected in the parser state,
12835 normally resulting in a single exception at the top level of parsing
12836 which covers all the compilation errors that occurred.  Some compilation
12837 errors, however, will throw an exception immediately.
12838
12839 =cut
12840 */
12841
12842 OP *
12843 Perl_parse_listexpr(pTHX_ U32 flags)
12844 {
12845     return parse_expr(LEX_FAKEEOF_LOWLOGIC, flags);
12846 }
12847
12848 /*
12849 =for apidoc parse_fullexpr
12850
12851 Parse a single complete Perl expression.  This allows the full
12852 expression grammar, including the lowest-precedence operators such
12853 as C<or>.  The expression must be followed (and thus terminated) by a
12854 token that an expression would normally be terminated by: end-of-file,
12855 closing bracketing punctuation, semicolon, or one of the keywords that
12856 signals a postfix expression-statement modifier.  If C<flags> has the
12857 C<PARSE_OPTIONAL> bit set, then the expression is optional, otherwise it is
12858 mandatory.  It is up to the caller to ensure that the dynamic parser
12859 state (L</PL_parser> et al) is correctly set to reflect the source of
12860 the code to be parsed and the lexical context for the expression.
12861
12862 The op tree representing the expression is returned.  If an optional
12863 expression is absent, a null pointer is returned, otherwise the pointer
12864 will be non-null.
12865
12866 If an error occurs in parsing or compilation, in most cases a valid op
12867 tree is returned anyway.  The error is reflected in the parser state,
12868 normally resulting in a single exception at the top level of parsing
12869 which covers all the compilation errors that occurred.  Some compilation
12870 errors, however, will throw an exception immediately.
12871
12872 =cut
12873 */
12874
12875 OP *
12876 Perl_parse_fullexpr(pTHX_ U32 flags)
12877 {
12878     return parse_expr(LEX_FAKEEOF_NONEXPR, flags);
12879 }
12880
12881 /*
12882 =for apidoc parse_block
12883
12884 Parse a single complete Perl code block.  This consists of an opening
12885 brace, a sequence of statements, and a closing brace.  The block
12886 constitutes a lexical scope, so C<my> variables and various compile-time
12887 effects can be contained within it.  It is up to the caller to ensure
12888 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12889 reflect the source of the code to be parsed and the lexical context for
12890 the statement.
12891
12892 The op tree representing the code block is returned.  This is always a
12893 real op, never a null pointer.  It will normally be a C<lineseq> list,
12894 including C<nextstate> or equivalent ops.  No ops to construct any kind
12895 of runtime scope are included by virtue of it being a block.
12896
12897 If an error occurs in parsing or compilation, in most cases a valid op
12898 tree (most likely null) is returned anyway.  The error is reflected in
12899 the parser state, normally resulting in a single exception at the top
12900 level of parsing which covers all the compilation errors that occurred.
12901 Some compilation errors, however, will throw an exception immediately.
12902
12903 The C<flags> parameter is reserved for future use, and must always
12904 be zero.
12905
12906 =cut
12907 */
12908
12909 OP *
12910 Perl_parse_block(pTHX_ U32 flags)
12911 {
12912     if (flags)
12913         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_block");
12914     return parse_recdescent_for_op(GRAMBLOCK, LEX_FAKEEOF_NEVER);
12915 }
12916
12917 /*
12918 =for apidoc parse_barestmt
12919
12920 Parse a single unadorned Perl statement.  This may be a normal imperative
12921 statement or a declaration that has compile-time effect.  It does not
12922 include any label or other affixture.  It is up to the caller to ensure
12923 that the dynamic parser state (L</PL_parser> et al) is correctly set to
12924 reflect the source of the code to be parsed and the lexical context for
12925 the statement.
12926
12927 The op tree representing the statement is returned.  This may be a
12928 null pointer if the statement is null, for example if it was actually
12929 a subroutine definition (which has compile-time side effects).  If not
12930 null, it will be ops directly implementing the statement, suitable to
12931 pass to L</newSTATEOP>.  It will not normally include a C<nextstate> or
12932 equivalent op (except for those embedded in a scope contained entirely
12933 within the statement).
12934
12935 If an error occurs in parsing or compilation, in most cases a valid op
12936 tree (most likely null) is returned anyway.  The error is reflected in
12937 the parser state, normally resulting in a single exception at the top
12938 level of parsing which covers all the compilation errors that occurred.
12939 Some compilation errors, however, will throw an exception immediately.
12940
12941 The C<flags> parameter is reserved for future use, and must always
12942 be zero.
12943
12944 =cut
12945 */
12946
12947 OP *
12948 Perl_parse_barestmt(pTHX_ U32 flags)
12949 {
12950     if (flags)
12951         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_barestmt");
12952     return parse_recdescent_for_op(GRAMBARESTMT, LEX_FAKEEOF_NEVER);
12953 }
12954
12955 /*
12956 =for apidoc parse_label
12957
12958 Parse a single label, possibly optional, of the type that may prefix a
12959 Perl statement.  It is up to the caller to ensure that the dynamic parser
12960 state (L</PL_parser> et al) is correctly set to reflect the source of
12961 the code to be parsed.  If C<flags> has the C<PARSE_OPTIONAL> bit set, then the
12962 label is optional, otherwise it is mandatory.
12963
12964 The name of the label is returned in the form of a fresh scalar.  If an
12965 optional label is absent, a null pointer is returned.
12966
12967 If an error occurs in parsing, which can only occur if the label is
12968 mandatory, a valid label is returned anyway.  The error is reflected in
12969 the parser state, normally resulting in a single exception at the top
12970 level of parsing which covers all the compilation errors that occurred.
12971
12972 =cut
12973 */
12974
12975 SV *
12976 Perl_parse_label(pTHX_ U32 flags)
12977 {
12978     if (flags & ~PARSE_OPTIONAL)
12979         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_label");
12980     if (PL_nexttoke) {
12981         PL_parser->yychar = yylex();
12982         if (PL_parser->yychar == LABEL) {
12983             SV * const labelsv = cSVOPx(pl_yylval.opval)->op_sv;
12984             PL_parser->yychar = YYEMPTY;
12985             cSVOPx(pl_yylval.opval)->op_sv = NULL;
12986             op_free(pl_yylval.opval);
12987             return labelsv;
12988         } else {
12989             yyunlex();
12990             goto no_label;
12991         }
12992     } else {
12993         char *s, *t;
12994         STRLEN wlen, bufptr_pos;
12995         lex_read_space(0);
12996         t = s = PL_bufptr;
12997         if (!isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
12998             goto no_label;
12999         t = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &wlen);
13000         if (word_takes_any_delimiter(s, wlen))
13001             goto no_label;
13002         bufptr_pos = s - SvPVX(PL_linestr);
13003         PL_bufptr = t;
13004         lex_read_space(LEX_KEEP_PREVIOUS);
13005         t = PL_bufptr;
13006         s = SvPVX(PL_linestr) + bufptr_pos;
13007         if (t[0] == ':' && t[1] != ':') {
13008             PL_oldoldbufptr = PL_oldbufptr;
13009             PL_oldbufptr = s;
13010             PL_bufptr = t+1;
13011             return newSVpvn_flags(s, wlen, UTF ? SVf_UTF8 : 0);
13012         } else {
13013             PL_bufptr = s;
13014             no_label:
13015             if (flags & PARSE_OPTIONAL) {
13016                 return NULL;
13017             } else {
13018                 qerror(Perl_mess(aTHX_ "Parse error"));
13019                 return newSVpvs("x");
13020             }
13021         }
13022     }
13023 }
13024
13025 /*
13026 =for apidoc parse_fullstmt
13027
13028 Parse a single complete Perl statement.  This may be a normal imperative
13029 statement or a declaration that has compile-time effect, and may include
13030 optional labels.  It is up to the caller to ensure that the dynamic
13031 parser state (L</PL_parser> et al) is correctly set to reflect the source
13032 of the code to be parsed and the lexical context for the statement.
13033
13034 The op tree representing the statement is returned.  This may be a
13035 null pointer if the statement is null, for example if it was actually
13036 a subroutine definition (which has compile-time side effects).  If not
13037 null, it will be the result of a L</newSTATEOP> call, normally including
13038 a C<nextstate> or equivalent op.
13039
13040 If an error occurs in parsing or compilation, in most cases a valid op
13041 tree (most likely null) is returned anyway.  The error is reflected in
13042 the parser state, normally resulting in a single exception at the top
13043 level of parsing which covers all the compilation errors that occurred.
13044 Some compilation errors, however, will throw an exception immediately.
13045
13046 The C<flags> parameter is reserved for future use, and must always
13047 be zero.
13048
13049 =cut
13050 */
13051
13052 OP *
13053 Perl_parse_fullstmt(pTHX_ U32 flags)
13054 {
13055     if (flags)
13056         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_fullstmt");
13057     return parse_recdescent_for_op(GRAMFULLSTMT, LEX_FAKEEOF_NEVER);
13058 }
13059
13060 /*
13061 =for apidoc parse_stmtseq
13062
13063 Parse a sequence of zero or more Perl statements.  These may be normal
13064 imperative statements, including optional labels, or declarations
13065 that have compile-time effect, or any mixture thereof.  The statement
13066 sequence ends when a closing brace or end-of-file is encountered in a
13067 place where a new statement could have validly started.  It is up to
13068 the caller to ensure that the dynamic parser state (L</PL_parser> et al)
13069 is correctly set to reflect the source of the code to be parsed and the
13070 lexical context for the statements.
13071
13072 The op tree representing the statement sequence is returned.  This may
13073 be a null pointer if the statements were all null, for example if there
13074 were no statements or if there were only subroutine definitions (which
13075 have compile-time side effects).  If not null, it will be a C<lineseq>
13076 list, normally including C<nextstate> or equivalent ops.
13077
13078 If an error occurs in parsing or compilation, in most cases a valid op
13079 tree is returned anyway.  The error is reflected in the parser state,
13080 normally resulting in a single exception at the top level of parsing
13081 which covers all the compilation errors that occurred.  Some compilation
13082 errors, however, will throw an exception immediately.
13083
13084 The C<flags> parameter is reserved for future use, and must always
13085 be zero.
13086
13087 =cut
13088 */
13089
13090 OP *
13091 Perl_parse_stmtseq(pTHX_ U32 flags)
13092 {
13093     OP *stmtseqop;
13094     I32 c;
13095     if (flags)
13096         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_stmtseq");
13097     stmtseqop = parse_recdescent_for_op(GRAMSTMTSEQ, LEX_FAKEEOF_CLOSING);
13098     c = lex_peek_unichar(0);
13099     if (c != -1 && c != /*{*/'}')
13100         qerror(Perl_mess(aTHX_ "Parse error"));
13101     return stmtseqop;
13102 }
13103
13104 /*
13105 =for apidoc parse_subsignature
13106
13107 Parse a subroutine signature declaration. This is the contents of the
13108 parentheses following a named or anonymous subroutine declaration when the
13109 C<signatures> feature is enabled. Note that this function neither expects
13110 nor consumes the opening and closing parentheses around the signature; it
13111 is the caller's job to handle these.
13112
13113 This function must only be called during parsing of a subroutine; after
13114 L</start_subparse> has been called. It might allocate lexical variables on
13115 the pad for the current subroutine.
13116
13117 The op tree to unpack the arguments from the stack at runtime is returned.
13118 This op tree should appear at the beginning of the compiled function. The
13119 caller may wish to use L</op_append_list> to build their function body
13120 after it, or splice it together with the body before calling L</newATTRSUB>.
13121
13122 The C<flags> parameter is reserved for future use, and must always
13123 be zero.
13124
13125 =cut
13126 */
13127
13128 OP *
13129 Perl_parse_subsignature(pTHX_ U32 flags)
13130 {
13131     if (flags)
13132         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_subsignature");
13133     return parse_recdescent_for_op(GRAMSUBSIGNATURE, LEX_FAKEEOF_NONEXPR);
13134 }
13135
13136 /*
13137  * ex: set ts=8 sts=4 sw=4 et:
13138  */