This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
f95c47bc5e4f2a14a9613de816a98db7eaefa0c0
[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 static const char* const ident_var_zero_multi_digit = "Numeric variables with more than one digit may not start with '0'";
98
99 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
100
101 #define XENUMMASK  0x3f
102 #define XFAKEEOF   0x40
103 #define XFAKEBRACK 0x80
104
105 #ifdef USE_UTF8_SCRIPTS
106 #   define UTF cBOOL(!IN_BYTES)
107 #else
108 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
109 #endif
110
111 /* The maximum number of characters preceding the unrecognized one to display */
112 #define UNRECOGNIZED_PRECEDE_COUNT 10
113
114 /* In variables named $^X, these are the legal values for X.
115  * 1999-02-27 mjd-perl-patch@plover.com */
116 #define isCONTROLVAR(x) (isUPPER(x) || memCHRs("[\\]^_?", (x)))
117
118 #define SPACE_OR_TAB(c) isBLANK_A(c)
119
120 #define HEXFP_PEEK(s)     \
121     (((s[0] == '.') && \
122       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
123      isALPHA_FOLD_EQ(s[0], 'p'))
124
125 /* LEX_* are values for PL_lex_state, the state of the lexer.
126  * They are arranged oddly so that the guard on the switch statement
127  * can get by with a single comparison (if the compiler is smart enough).
128  *
129  * These values refer to the various states within a sublex parse,
130  * i.e. within a double quotish string
131  */
132
133 /* #define LEX_NOTPARSING               11 is done in perl.h. */
134
135 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
136 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
137 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
138 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
139 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
140
141                                    /* at end of code, eg "$x" followed by:  */
142 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
143 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
144
145 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
146                                         string or after \E, $foo, etc       */
147 #define LEX_INTERPCONST          2 /* NOT USED */
148 #define LEX_FORMLINE             1 /* expecting a format line               */
149
150 /* returned to yyl_try() to request it to retry the parse loop, expected to only
151    be returned directly by yyl_fake_eof(), but functions that call yyl_fake_eof()
152    can also return it.
153
154    yylex (aka Perl_yylex) returns 0 on EOF rather than returning -1,
155    other token values are 258 or higher (see perly.h), so -1 should be
156    a safe value here.
157 */
158 #define YYL_RETRY (-1)
159
160 #ifdef DEBUGGING
161 static const char* const lex_state_names[] = {
162     "KNOWNEXT",
163     "FORMLINE",
164     "INTERPCONST",
165     "INTERPCONCAT",
166     "INTERPENDMAYBE",
167     "INTERPEND",
168     "INTERPSTART",
169     "INTERPPUSH",
170     "INTERPCASEMOD",
171     "INTERPNORMAL",
172     "NORMAL"
173 };
174 #endif
175
176 #include "keywords.h"
177
178 /* CLINE is a macro that ensures PL_copline has a sane value */
179
180 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
181
182 /*
183  * Convenience functions to return different tokens and prime the
184  * lexer for the next token.  They all take an argument.
185  *
186  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
187  * OPERATOR     : generic operator
188  * AOPERATOR    : assignment operator
189  * PREBLOCK     : beginning the block after an if, while, foreach, ...
190  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
191  * PREREF       : *EXPR where EXPR is not a simple identifier
192  * TERM         : expression term
193  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
194  * LOOPX        : loop exiting command (goto, last, dump, etc)
195  * FTST         : file test operator
196  * FUN0         : zero-argument function
197  * FUN0OP       : zero-argument function, with its op created in this file
198  * FUN1         : not used, except for not, which isn't a UNIOP
199  * BOop         : bitwise or or xor
200  * BAop         : bitwise and
201  * BCop         : bitwise complement
202  * SHop         : shift operator
203  * PWop         : power operator
204  * PMop         : pattern-matching operator
205  * Aop          : addition-level operator
206  * AopNOASSIGN  : addition-level operator that is never part of .=
207  * Mop          : multiplication-level operator
208  * ChEop        : chaining equality-testing operator
209  * NCEop        : non-chaining comparison operator at equality precedence
210  * ChRop        : chaining relational operator <= != gt
211  * NCRop        : non-chaining relational operator isa
212  *
213  * Also see LOP and lop() below.
214  */
215
216 #ifdef DEBUGGING /* Serve -DT. */
217 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
218 #else
219 #   define REPORT(retval) (retval)
220 #endif
221
222 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
223 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
224 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
225 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
226 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
227 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
228 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
229 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
230 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
231                          pl_yylval.ival=f, \
232                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
233                          REPORT((int)LOOPEX))
234 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
235 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
236 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
237 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
238 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
239 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
240 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
241                        REPORT(PERLY_TILDE)
242 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
243 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
244 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
245 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
246 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
247 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
248 #define ChEop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)CHEQOP))
249 #define NCEop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)NCEQOP))
250 #define ChRop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)CHRELOP))
251 #define NCRop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)NCRELOP))
252
253 /* This bit of chicanery makes a unary function followed by
254  * a parenthesis into a function with one argument, highest precedence.
255  * The UNIDOR macro is for unary functions that can be followed by the //
256  * operator (such as C<shift // 0>).
257  */
258 #define UNI3(f,x,have_x) { \
259         pl_yylval.ival = f; \
260         if (have_x) PL_expect = x; \
261         PL_bufptr = s; \
262         PL_last_uni = PL_oldbufptr; \
263         PL_last_lop_op = (f) < 0 ? -(f) : (f); \
264         if (*s == '(') \
265             return REPORT( (int)FUNC1 ); \
266         s = skipspace(s); \
267         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
268         }
269 #define UNI(f)    UNI3(f,XTERM,1)
270 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
271 #define UNIPROTO(f,optional) { \
272         if (optional) PL_last_uni = PL_oldbufptr; \
273         OPERATOR(f); \
274         }
275
276 #define UNIBRACK(f) UNI3(f,0,0)
277
278 /* grandfather return to old style */
279 #define OLDLOP(f) \
280         do { \
281             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
282                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
283             pl_yylval.ival = (f); \
284             PL_expect = XTERM; \
285             PL_bufptr = s; \
286             return (int)LSTOP; \
287         } while(0)
288
289 #define COPLINE_INC_WITH_HERELINES                  \
290     STMT_START {                                     \
291         CopLINE_inc(PL_curcop);                       \
292         if (PL_parser->herelines)                      \
293             CopLINE(PL_curcop) += PL_parser->herelines, \
294             PL_parser->herelines = 0;                    \
295     } STMT_END
296 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
297  * is no sublex_push to follow. */
298 #define COPLINE_SET_FROM_MULTI_END            \
299     STMT_START {                               \
300         CopLINE_set(PL_curcop, PL_multi_end);   \
301         if (PL_multi_end != PL_multi_start)      \
302             PL_parser->herelines = 0;             \
303     } STMT_END
304
305
306 /* A file-local structure for passing around information about subroutines and
307  * related definable words */
308 struct code {
309     SV *sv;
310     CV *cv;
311     GV *gv, **gvp;
312     OP *rv2cv_op;
313     PADOFFSET off;
314     bool lex;
315 };
316
317 static const struct code no_code = { NULL, NULL, NULL, NULL, NULL, 0, FALSE };
318
319 #ifdef DEBUGGING
320
321 /* how to interpret the pl_yylval associated with the token */
322 enum token_type {
323     TOKENTYPE_NONE,
324     TOKENTYPE_IVAL,
325     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
326     TOKENTYPE_PVAL,
327     TOKENTYPE_OPVAL
328 };
329
330 #define DEBUG_TOKEN(Type, Name)                                         \
331     { Name, TOKENTYPE_##Type, #Name }
332
333 static struct debug_tokens {
334     const int token;
335     enum token_type type;
336     const char *name;
337 } const debug_tokens[] =
338 {
339     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
340     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
341     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
342     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
343     { ANON_SIGSUB,      TOKENTYPE_IVAL,         "ANON_SIGSUB" },
344     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
345     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
346     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
347     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
348     { CHEQOP,           TOKENTYPE_OPNUM,        "CHEQOP" },
349     { CHRELOP,          TOKENTYPE_OPNUM,        "CHRELOP" },
350     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
351     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
352     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
353     { DO,               TOKENTYPE_NONE,         "DO" },
354     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
355     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
356     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
357     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
358     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
359     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
360     { FOR,              TOKENTYPE_IVAL,         "FOR" },
361     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
362     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
363     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
364     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
365     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
366     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
367     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
368     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
369     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
370     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
371     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
372     { IF,               TOKENTYPE_IVAL,         "IF" },
373     { LABEL,            TOKENTYPE_OPVAL,        "LABEL" },
374     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
375     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
376     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
377     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
378     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
379     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
380     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
381     { MY,               TOKENTYPE_IVAL,         "MY" },
382     { NCEQOP,           TOKENTYPE_OPNUM,        "NCEQOP" },
383     { NCRELOP,          TOKENTYPE_OPNUM,        "NCRELOP" },
384     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
385     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
386     { OROP,             TOKENTYPE_IVAL,         "OROP" },
387     { OROR,             TOKENTYPE_NONE,         "OROR" },
388     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
389     DEBUG_TOKEN (IVAL, PERLY_AMPERSAND),
390     DEBUG_TOKEN (IVAL, PERLY_BRACE_CLOSE),
391     DEBUG_TOKEN (IVAL, PERLY_BRACE_OPEN),
392     DEBUG_TOKEN (IVAL, PERLY_BRACKET_CLOSE),
393     DEBUG_TOKEN (IVAL, PERLY_BRACKET_OPEN),
394     DEBUG_TOKEN (IVAL, PERLY_COLON),
395     DEBUG_TOKEN (IVAL, PERLY_COMMA),
396     DEBUG_TOKEN (IVAL, PERLY_DOT),
397     DEBUG_TOKEN (IVAL, PERLY_EQUAL_SIGN),
398     DEBUG_TOKEN (IVAL, PERLY_EXCLAMATION_MARK),
399     DEBUG_TOKEN (IVAL, PERLY_MINUS),
400     DEBUG_TOKEN (IVAL, PERLY_PLUS),
401     DEBUG_TOKEN (IVAL, PERLY_QUESTION_MARK),
402     DEBUG_TOKEN (IVAL, PERLY_SEMICOLON),
403     DEBUG_TOKEN (IVAL, PERLY_SNAIL),
404     DEBUG_TOKEN (IVAL, PERLY_TILDE),
405     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
406     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
407     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
408     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
409     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
410     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
411     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
412     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
413     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
414     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
415     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
416     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
417     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
418     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
419     { SIGSUB,           TOKENTYPE_NONE,         "SIGSUB" },
420     { SUB,              TOKENTYPE_NONE,         "SUB" },
421     { SUBLEXEND,        TOKENTYPE_NONE,         "SUBLEXEND" },
422     { SUBLEXSTART,      TOKENTYPE_NONE,         "SUBLEXSTART" },
423     { THING,            TOKENTYPE_OPVAL,        "THING" },
424     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
425     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
426     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
427     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
428     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
429     { USE,              TOKENTYPE_IVAL,         "USE" },
430     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
431     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
432     { BAREWORD,         TOKENTYPE_OPVAL,        "BAREWORD" },
433     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
434     { 0,                TOKENTYPE_NONE,         NULL }
435 };
436
437 #undef DEBUG_TOKEN
438
439 /* dump the returned token in rv, plus any optional arg in pl_yylval */
440
441 STATIC int
442 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
443 {
444     PERL_ARGS_ASSERT_TOKEREPORT;
445
446     if (DEBUG_T_TEST) {
447         const char *name = NULL;
448         enum token_type type = TOKENTYPE_NONE;
449         const struct debug_tokens *p;
450         SV* const report = newSVpvs("<== ");
451
452         for (p = debug_tokens; p->token; p++) {
453             if (p->token == (int)rv) {
454                 name = p->name;
455                 type = p->type;
456                 break;
457             }
458         }
459         if (name)
460             Perl_sv_catpv(aTHX_ report, name);
461         else if (isGRAPH(rv))
462         {
463             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
464             if ((char)rv == 'p')
465                 sv_catpvs(report, " (pending identifier)");
466         }
467         else if (!rv)
468             sv_catpvs(report, "EOF");
469         else
470             Perl_sv_catpvf(aTHX_ report, "?? %" IVdf, (IV)rv);
471         switch (type) {
472         case TOKENTYPE_NONE:
473             break;
474         case TOKENTYPE_IVAL:
475             Perl_sv_catpvf(aTHX_ report, "(ival=%" IVdf ")", (IV)lvalp->ival);
476             break;
477         case TOKENTYPE_OPNUM:
478             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
479                                     PL_op_name[lvalp->ival]);
480             break;
481         case TOKENTYPE_PVAL:
482             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
483             break;
484         case TOKENTYPE_OPVAL:
485             if (lvalp->opval) {
486                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
487                                     PL_op_name[lvalp->opval->op_type]);
488                 if (lvalp->opval->op_type == OP_CONST) {
489                     Perl_sv_catpvf(aTHX_ report, " %s",
490                         SvPEEK(cSVOPx_sv(lvalp->opval)));
491                 }
492
493             }
494             else
495                 sv_catpvs(report, "(opval=null)");
496             break;
497         }
498         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
499     };
500     return (int)rv;
501 }
502
503
504 /* print the buffer with suitable escapes */
505
506 STATIC void
507 S_printbuf(pTHX_ const char *const fmt, const char *const s)
508 {
509     SV* const tmp = newSVpvs("");
510
511     PERL_ARGS_ASSERT_PRINTBUF;
512
513     GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral); /* fmt checked by caller */
514     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
515     GCC_DIAG_RESTORE_STMT;
516     SvREFCNT_dec(tmp);
517 }
518
519 #endif
520
521 /*
522  * S_ao
523  *
524  * This subroutine looks for an '=' next to the operator that has just been
525  * parsed and turns it into an ASSIGNOP if it finds one.
526  */
527
528 STATIC int
529 S_ao(pTHX_ int toketype)
530 {
531     if (*PL_bufptr == '=') {
532         PL_bufptr++;
533         if (toketype == ANDAND)
534             pl_yylval.ival = OP_ANDASSIGN;
535         else if (toketype == OROR)
536             pl_yylval.ival = OP_ORASSIGN;
537         else if (toketype == DORDOR)
538             pl_yylval.ival = OP_DORASSIGN;
539         toketype = ASSIGNOP;
540     }
541     return REPORT(toketype);
542 }
543
544 /*
545  * S_no_op
546  * When Perl expects an operator and finds something else, no_op
547  * prints the warning.  It always prints "<something> found where
548  * operator expected.  It prints "Missing semicolon on previous line?"
549  * if the surprise occurs at the start of the line.  "do you need to
550  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
551  * where the compiler doesn't know if foo is a method call or a function.
552  * It prints "Missing operator before end of line" if there's nothing
553  * after the missing operator, or "... before <...>" if there is something
554  * after the missing operator.
555  *
556  * PL_bufptr is expected to point to the start of the thing that was found,
557  * and s after the next token or partial token.
558  */
559
560 STATIC void
561 S_no_op(pTHX_ const char *const what, char *s)
562 {
563     char * const oldbp = PL_bufptr;
564     const bool is_first = (PL_oldbufptr == PL_linestart);
565
566     PERL_ARGS_ASSERT_NO_OP;
567
568     if (!s)
569         s = oldbp;
570     else
571         PL_bufptr = s;
572     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
573     if (ckWARN_d(WARN_SYNTAX)) {
574         if (is_first)
575             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
576                     "\t(Missing semicolon on previous line?)\n");
577         else if (PL_oldoldbufptr && isIDFIRST_lazy_if_safe(PL_oldoldbufptr,
578                                                            PL_bufend,
579                                                            UTF))
580         {
581             const char *t;
582             for (t = PL_oldoldbufptr;
583                  (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF) || *t == ':');
584                  t += UTF ? UTF8SKIP(t) : 1)
585             {
586                 NOOP;
587             }
588             if (t < PL_bufptr && isSPACE(*t))
589                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
590                         "\t(Do you need to predeclare %" UTF8f "?)\n",
591                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
592         }
593         else {
594             assert(s >= oldbp);
595             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
596                     "\t(Missing operator before %" UTF8f "?)\n",
597                      UTF8fARG(UTF, s - oldbp, oldbp));
598         }
599     }
600     PL_bufptr = oldbp;
601 }
602
603 /*
604  * S_missingterm
605  * Complain about missing quote/regexp/heredoc terminator.
606  * If it's called with NULL then it cauterizes the line buffer.
607  * If we're in a delimited string and the delimiter is a control
608  * character, it's reformatted into a two-char sequence like ^C.
609  * This is fatal.
610  */
611
612 STATIC void
613 S_missingterm(pTHX_ char *s, STRLEN len)
614 {
615     char tmpbuf[UTF8_MAXBYTES + 1];
616     char q;
617     bool uni = FALSE;
618     SV *sv;
619     if (s) {
620         char * const nl = (char *) my_memrchr(s, '\n', len);
621         if (nl) {
622             *nl = '\0';
623             len = nl - s;
624         }
625         uni = UTF;
626     }
627     else if (PL_multi_close < 32) {
628         *tmpbuf = '^';
629         tmpbuf[1] = (char)toCTRL(PL_multi_close);
630         tmpbuf[2] = '\0';
631         s = tmpbuf;
632         len = 2;
633     }
634     else {
635         if (LIKELY(PL_multi_close < 256)) {
636             *tmpbuf = (char)PL_multi_close;
637             tmpbuf[1] = '\0';
638             len = 1;
639         }
640         else {
641             char *end = (char *)uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close);
642             *end = '\0';
643             len = end - tmpbuf;
644             uni = TRUE;
645         }
646         s = tmpbuf;
647     }
648     q = memchr(s, '"', len) ? '\'' : '"';
649     sv = sv_2mortal(newSVpvn(s, len));
650     if (uni)
651         SvUTF8_on(sv);
652     Perl_croak(aTHX_ "Can't find string terminator %c%" SVf "%c"
653                      " anywhere before EOF", q, SVfARG(sv), q);
654 }
655
656 #include "feature.h"
657
658 /*
659  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
660  * utf16-to-utf8-reversed.
661  */
662
663 #ifdef PERL_CR_FILTER
664 static void
665 strip_return(SV *sv)
666 {
667     const char *s = SvPVX_const(sv);
668     const char * const e = s + SvCUR(sv);
669
670     PERL_ARGS_ASSERT_STRIP_RETURN;
671
672     /* outer loop optimized to do nothing if there are no CR-LFs */
673     while (s < e) {
674         if (*s++ == '\r' && *s == '\n') {
675             /* hit a CR-LF, need to copy the rest */
676             char *d = s - 1;
677             *d++ = *s++;
678             while (s < e) {
679                 if (*s == '\r' && s[1] == '\n')
680                     s++;
681                 *d++ = *s++;
682             }
683             SvCUR(sv) -= s - d;
684             return;
685         }
686     }
687 }
688
689 STATIC I32
690 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
691 {
692     const I32 count = FILTER_READ(idx+1, sv, maxlen);
693     if (count > 0 && !maxlen)
694         strip_return(sv);
695     return count;
696 }
697 #endif
698
699 /*
700 =for apidoc lex_start
701
702 Creates and initialises a new lexer/parser state object, supplying
703 a context in which to lex and parse from a new source of Perl code.
704 A pointer to the new state object is placed in L</PL_parser>.  An entry
705 is made on the save stack so that upon unwinding, the new state object
706 will be destroyed and the former value of L</PL_parser> will be restored.
707 Nothing else need be done to clean up the parsing context.
708
709 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
710 non-null, provides a string (in SV form) containing code to be parsed.
711 A copy of the string is made, so subsequent modification of C<line>
712 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
713 from which code will be read to be parsed.  If both are non-null, the
714 code in C<line> comes first and must consist of complete lines of input,
715 and C<rsfp> supplies the remainder of the source.
716
717 The C<flags> parameter is reserved for future use.  Currently it is only
718 used by perl internally, so extensions should always pass zero.
719
720 =cut
721 */
722
723 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
724    can share filters with the current parser.
725    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
726    caller, hence isn't owned by the parser, so shouldn't be closed on parser
727    destruction. This is used to handle the case of defaulting to reading the
728    script from the standard input because no filename was given on the command
729    line (without getting confused by situation where STDIN has been closed, so
730    the script handle is opened on fd 0)  */
731
732 void
733 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
734 {
735     const char *s = NULL;
736     yy_parser *parser, *oparser;
737
738     if (flags && flags & ~LEX_START_FLAGS)
739         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
740
741     /* create and initialise a parser */
742
743     Newxz(parser, 1, yy_parser);
744     parser->old_parser = oparser = PL_parser;
745     PL_parser = parser;
746
747     parser->stack = NULL;
748     parser->stack_max1 = NULL;
749     parser->ps = NULL;
750
751     /* on scope exit, free this parser and restore any outer one */
752     SAVEPARSER(parser);
753     parser->saved_curcop = PL_curcop;
754
755     /* initialise lexer state */
756
757     parser->nexttoke = 0;
758     parser->error_count = oparser ? oparser->error_count : 0;
759     parser->copline = parser->preambling = NOLINE;
760     parser->lex_state = LEX_NORMAL;
761     parser->expect = XSTATE;
762     parser->rsfp = rsfp;
763     parser->recheck_utf8_validity = TRUE;
764     parser->rsfp_filters =
765       !(flags & LEX_START_SAME_FILTER) || !oparser
766         ? NULL
767         : MUTABLE_AV(SvREFCNT_inc(
768             oparser->rsfp_filters
769              ? oparser->rsfp_filters
770              : (oparser->rsfp_filters = newAV())
771           ));
772
773     Newx(parser->lex_brackstack, 120, char);
774     Newx(parser->lex_casestack, 12, char);
775     *parser->lex_casestack = '\0';
776     Newxz(parser->lex_shared, 1, LEXSHARED);
777
778     if (line) {
779         STRLEN len;
780         const U8* first_bad_char_loc;
781
782         s = SvPV_const(line, len);
783
784         if (   SvUTF8(line)
785             && UNLIKELY(! is_utf8_string_loc((U8 *) s,
786                                              SvCUR(line),
787                                              &first_bad_char_loc)))
788         {
789             _force_out_malformed_utf8_message(first_bad_char_loc,
790                                               (U8 *) s + SvCUR(line),
791                                               0,
792                                               1 /* 1 means die */ );
793             NOT_REACHED; /* NOTREACHED */
794         }
795
796         parser->linestr = flags & LEX_START_COPIED
797                             ? SvREFCNT_inc_simple_NN(line)
798                             : newSVpvn_flags(s, len, SvUTF8(line));
799         if (!rsfp)
800             sv_catpvs(parser->linestr, "\n;");
801     } else {
802         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
803     }
804
805     parser->oldoldbufptr =
806         parser->oldbufptr =
807         parser->bufptr =
808         parser->linestart = SvPVX(parser->linestr);
809     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
810     parser->last_lop = parser->last_uni = NULL;
811
812     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
813                                                         |LEX_DONT_CLOSE_RSFP));
814     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
815                                                         |LEX_DONT_CLOSE_RSFP));
816
817     parser->in_pod = parser->filtered = 0;
818 }
819
820
821 /* delete a parser object */
822
823 void
824 Perl_parser_free(pTHX_  const yy_parser *parser)
825 {
826     PERL_ARGS_ASSERT_PARSER_FREE;
827
828     PL_curcop = parser->saved_curcop;
829     SvREFCNT_dec(parser->linestr);
830
831     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
832         PerlIO_clearerr(parser->rsfp);
833     else if (parser->rsfp && (!parser->old_parser
834           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
835         PerlIO_close(parser->rsfp);
836     SvREFCNT_dec(parser->rsfp_filters);
837     SvREFCNT_dec(parser->lex_stuff);
838     SvREFCNT_dec(parser->lex_sub_repl);
839
840     Safefree(parser->lex_brackstack);
841     Safefree(parser->lex_casestack);
842     Safefree(parser->lex_shared);
843     PL_parser = parser->old_parser;
844     Safefree(parser);
845 }
846
847 void
848 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
849 {
850     I32 nexttoke = parser->nexttoke;
851     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
852     while (nexttoke--) {
853         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
854          && parser->nextval[nexttoke].opval
855          && parser->nextval[nexttoke].opval->op_slabbed
856          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
857             op_free(parser->nextval[nexttoke].opval);
858             parser->nextval[nexttoke].opval = NULL;
859         }
860     }
861 }
862
863
864 /*
865 =for apidoc AmnxUN|SV *|PL_parser-E<gt>linestr
866
867 Buffer scalar containing the chunk currently under consideration of the
868 text currently being lexed.  This is always a plain string scalar (for
869 which C<SvPOK> is true).  It is not intended to be used as a scalar by
870 normal scalar means; instead refer to the buffer directly by the pointer
871 variables described below.
872
873 The lexer maintains various C<char*> pointers to things in the
874 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
875 reallocated, all of these pointers must be updated.  Don't attempt to
876 do this manually, but rather use L</lex_grow_linestr> if you need to
877 reallocate the buffer.
878
879 The content of the text chunk in the buffer is commonly exactly one
880 complete line of input, up to and including a newline terminator,
881 but there are situations where it is otherwise.  The octets of the
882 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
883 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
884 flag on this scalar, which may disagree with it.
885
886 For direct examination of the buffer, the variable
887 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
888 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
889 of these pointers is usually preferable to examination of the scalar
890 through normal scalar means.
891
892 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufend
893
894 Direct pointer to the end of the chunk of text currently being lexed, the
895 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
896 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
897 always located at the end of the buffer, and does not count as part of
898 the buffer's contents.
899
900 =for apidoc AmnxUN|char *|PL_parser-E<gt>bufptr
901
902 Points to the current position of lexing inside the lexer buffer.
903 Characters around this point may be freely examined, within
904 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
905 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
906 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
907
908 Lexing code (whether in the Perl core or not) moves this pointer past
909 the characters that it consumes.  It is also expected to perform some
910 bookkeeping whenever a newline character is consumed.  This movement
911 can be more conveniently performed by the function L</lex_read_to>,
912 which handles newlines appropriately.
913
914 Interpretation of the buffer's octets can be abstracted out by
915 using the slightly higher-level functions L</lex_peek_unichar> and
916 L</lex_read_unichar>.
917
918 =for apidoc AmnxUN|char *|PL_parser-E<gt>linestart
919
920 Points to the start of the current line inside the lexer buffer.
921 This is useful for indicating at which column an error occurred, and
922 not much else.  This must be updated by any lexing code that consumes
923 a newline; the function L</lex_read_to> handles this detail.
924
925 =cut
926 */
927
928 /*
929 =for apidoc lex_bufutf8
930
931 Indicates whether the octets in the lexer buffer
932 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
933 of Unicode characters.  If not, they should be interpreted as Latin-1
934 characters.  This is analogous to the C<SvUTF8> flag for scalars.
935
936 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
937 contains valid UTF-8.  Lexing code must be robust in the face of invalid
938 encoding.
939
940 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
941 is significant, but not the whole story regarding the input character
942 encoding.  Normally, when a file is being read, the scalar contains octets
943 and its C<SvUTF8> flag is off, but the octets should be interpreted as
944 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
945 however, the scalar may have the C<SvUTF8> flag on, and in this case its
946 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
947 is in effect.  This logic may change in the future; use this function
948 instead of implementing the logic yourself.
949
950 =cut
951 */
952
953 bool
954 Perl_lex_bufutf8(pTHX)
955 {
956     return UTF;
957 }
958
959 /*
960 =for apidoc lex_grow_linestr
961
962 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
963 at least C<len> octets (including terminating C<NUL>).  Returns a
964 pointer to the reallocated buffer.  This is necessary before making
965 any direct modification of the buffer that would increase its length.
966 L</lex_stuff_pvn> provides a more convenient way to insert text into
967 the buffer.
968
969 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
970 this function updates all of the lexer's variables that point directly
971 into the buffer.
972
973 =cut
974 */
975
976 char *
977 Perl_lex_grow_linestr(pTHX_ STRLEN len)
978 {
979     SV *linestr;
980     char *buf;
981     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
982     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
983     bool current;
984
985     linestr = PL_parser->linestr;
986     buf = SvPVX(linestr);
987     if (len <= SvLEN(linestr))
988         return buf;
989
990     /* Is the lex_shared linestr SV the same as the current linestr SV?
991      * Only in this case does re_eval_start need adjusting, since it
992      * points within lex_shared->ls_linestr's buffer */
993     current = (   !PL_parser->lex_shared->ls_linestr
994                || linestr == PL_parser->lex_shared->ls_linestr);
995
996     bufend_pos = PL_parser->bufend - buf;
997     bufptr_pos = PL_parser->bufptr - buf;
998     oldbufptr_pos = PL_parser->oldbufptr - buf;
999     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1000     linestart_pos = PL_parser->linestart - buf;
1001     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1002     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1003     re_eval_start_pos = (current && PL_parser->lex_shared->re_eval_start) ?
1004                             PL_parser->lex_shared->re_eval_start - buf : 0;
1005
1006     buf = sv_grow(linestr, len);
1007
1008     PL_parser->bufend = buf + bufend_pos;
1009     PL_parser->bufptr = buf + bufptr_pos;
1010     PL_parser->oldbufptr = buf + oldbufptr_pos;
1011     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1012     PL_parser->linestart = buf + linestart_pos;
1013     if (PL_parser->last_uni)
1014         PL_parser->last_uni = buf + last_uni_pos;
1015     if (PL_parser->last_lop)
1016         PL_parser->last_lop = buf + last_lop_pos;
1017     if (current && PL_parser->lex_shared->re_eval_start)
1018         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
1019     return buf;
1020 }
1021
1022 /*
1023 =for apidoc lex_stuff_pvn
1024
1025 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1026 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1027 reallocating the buffer if necessary.  This means that lexing code that
1028 runs later will see the characters as if they had appeared in the input.
1029 It is not recommended to do this as part of normal parsing, and most
1030 uses of this facility run the risk of the inserted characters being
1031 interpreted in an unintended manner.
1032
1033 The string to be inserted is represented by C<len> octets starting
1034 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
1035 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
1036 The characters are recoded for the lexer buffer, according to how the
1037 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
1038 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
1039 function is more convenient.
1040
1041 =for apidoc Amnh||LEX_STUFF_UTF8
1042
1043 =cut
1044 */
1045
1046 void
1047 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
1048 {
1049     char *bufptr;
1050     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
1051     if (flags & ~(LEX_STUFF_UTF8))
1052         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
1053     if (UTF) {
1054         if (flags & LEX_STUFF_UTF8) {
1055             goto plain_copy;
1056         } else {
1057             STRLEN highhalf = variant_under_utf8_count((U8 *) pv,
1058                                                        (U8 *) pv + len);
1059             const char *p, *e = pv+len;;
1060             if (!highhalf)
1061                 goto plain_copy;
1062             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
1063             bufptr = PL_parser->bufptr;
1064             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
1065             SvCUR_set(PL_parser->linestr,
1066                 SvCUR(PL_parser->linestr) + len+highhalf);
1067             PL_parser->bufend += len+highhalf;
1068             for (p = pv; p != e; p++) {
1069                 append_utf8_from_native_byte(*p, (U8 **) &bufptr);
1070             }
1071         }
1072     } else {
1073         if (flags & LEX_STUFF_UTF8) {
1074             STRLEN highhalf = 0;
1075             const char *p, *e = pv+len;
1076             for (p = pv; p != e; p++) {
1077                 U8 c = (U8)*p;
1078                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1079                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1080                                 "non-Latin-1 character into Latin-1 input");
1081                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1082                     p++;
1083                     highhalf++;
1084                 } else assert(UTF8_IS_INVARIANT(c));
1085             }
1086             if (!highhalf)
1087                 goto plain_copy;
1088             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1089             bufptr = PL_parser->bufptr;
1090             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1091             SvCUR_set(PL_parser->linestr,
1092                 SvCUR(PL_parser->linestr) + len-highhalf);
1093             PL_parser->bufend += len-highhalf;
1094             p = pv;
1095             while (p < e) {
1096                 if (UTF8_IS_INVARIANT(*p)) {
1097                     *bufptr++ = *p;
1098                     p++;
1099                 }
1100                 else {
1101                     assert(p < e -1 );
1102                     *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1103                     p += 2;
1104                 }
1105             }
1106         } else {
1107           plain_copy:
1108             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1109             bufptr = PL_parser->bufptr;
1110             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1111             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1112             PL_parser->bufend += len;
1113             Copy(pv, bufptr, len, char);
1114         }
1115     }
1116 }
1117
1118 /*
1119 =for apidoc lex_stuff_pv
1120
1121 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1122 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1123 reallocating the buffer if necessary.  This means that lexing code that
1124 runs later will see the characters as if they had appeared in the input.
1125 It is not recommended to do this as part of normal parsing, and most
1126 uses of this facility run the risk of the inserted characters being
1127 interpreted in an unintended manner.
1128
1129 The string to be inserted is represented by octets starting at C<pv>
1130 and continuing to the first nul.  These octets are interpreted as either
1131 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1132 in C<flags>.  The characters are recoded for the lexer buffer, according
1133 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1134 If it is not convenient to nul-terminate a string to be inserted, the
1135 L</lex_stuff_pvn> function is more appropriate.
1136
1137 =cut
1138 */
1139
1140 void
1141 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1142 {
1143     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1144     lex_stuff_pvn(pv, strlen(pv), flags);
1145 }
1146
1147 /*
1148 =for apidoc lex_stuff_sv
1149
1150 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1151 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1152 reallocating the buffer if necessary.  This means that lexing code that
1153 runs later will see the characters as if they had appeared in the input.
1154 It is not recommended to do this as part of normal parsing, and most
1155 uses of this facility run the risk of the inserted characters being
1156 interpreted in an unintended manner.
1157
1158 The string to be inserted is the string value of C<sv>.  The characters
1159 are recoded for the lexer buffer, according to how the buffer is currently
1160 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1161 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1162 need to construct a scalar.
1163
1164 =cut
1165 */
1166
1167 void
1168 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1169 {
1170     char *pv;
1171     STRLEN len;
1172     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1173     if (flags)
1174         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1175     pv = SvPV(sv, len);
1176     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1177 }
1178
1179 /*
1180 =for apidoc lex_unstuff
1181
1182 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1183 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1184 This hides the discarded text from any lexing code that runs later,
1185 as if the text had never appeared.
1186
1187 This is not the normal way to consume lexed text.  For that, use
1188 L</lex_read_to>.
1189
1190 =cut
1191 */
1192
1193 void
1194 Perl_lex_unstuff(pTHX_ char *ptr)
1195 {
1196     char *buf, *bufend;
1197     STRLEN unstuff_len;
1198     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1199     buf = PL_parser->bufptr;
1200     if (ptr < buf)
1201         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1202     if (ptr == buf)
1203         return;
1204     bufend = PL_parser->bufend;
1205     if (ptr > bufend)
1206         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1207     unstuff_len = ptr - buf;
1208     Move(ptr, buf, bufend+1-ptr, char);
1209     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1210     PL_parser->bufend = bufend - unstuff_len;
1211 }
1212
1213 /*
1214 =for apidoc lex_read_to
1215
1216 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1217 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1218 performing the correct bookkeeping whenever a newline character is passed.
1219 This is the normal way to consume lexed text.
1220
1221 Interpretation of the buffer's octets can be abstracted out by
1222 using the slightly higher-level functions L</lex_peek_unichar> and
1223 L</lex_read_unichar>.
1224
1225 =cut
1226 */
1227
1228 void
1229 Perl_lex_read_to(pTHX_ char *ptr)
1230 {
1231     char *s;
1232     PERL_ARGS_ASSERT_LEX_READ_TO;
1233     s = PL_parser->bufptr;
1234     if (ptr < s || ptr > PL_parser->bufend)
1235         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1236     for (; s != ptr; s++)
1237         if (*s == '\n') {
1238             COPLINE_INC_WITH_HERELINES;
1239             PL_parser->linestart = s+1;
1240         }
1241     PL_parser->bufptr = ptr;
1242 }
1243
1244 /*
1245 =for apidoc lex_discard_to
1246
1247 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1248 up to C<ptr>.  The remaining content of the buffer will be moved, and
1249 all pointers into the buffer updated appropriately.  C<ptr> must not
1250 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1251 it is not permitted to discard text that has yet to be lexed.
1252
1253 Normally it is not necessarily to do this directly, because it suffices to
1254 use the implicit discarding behaviour of L</lex_next_chunk> and things
1255 based on it.  However, if a token stretches across multiple lines,
1256 and the lexing code has kept multiple lines of text in the buffer for
1257 that purpose, then after completion of the token it would be wise to
1258 explicitly discard the now-unneeded earlier lines, to avoid future
1259 multi-line tokens growing the buffer without bound.
1260
1261 =cut
1262 */
1263
1264 void
1265 Perl_lex_discard_to(pTHX_ char *ptr)
1266 {
1267     char *buf;
1268     STRLEN discard_len;
1269     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1270     buf = SvPVX(PL_parser->linestr);
1271     if (ptr < buf)
1272         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1273     if (ptr == buf)
1274         return;
1275     if (ptr > PL_parser->bufptr)
1276         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1277     discard_len = ptr - buf;
1278     if (PL_parser->oldbufptr < ptr)
1279         PL_parser->oldbufptr = ptr;
1280     if (PL_parser->oldoldbufptr < ptr)
1281         PL_parser->oldoldbufptr = ptr;
1282     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1283         PL_parser->last_uni = NULL;
1284     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1285         PL_parser->last_lop = NULL;
1286     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1287     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1288     PL_parser->bufend -= discard_len;
1289     PL_parser->bufptr -= discard_len;
1290     PL_parser->oldbufptr -= discard_len;
1291     PL_parser->oldoldbufptr -= discard_len;
1292     if (PL_parser->last_uni)
1293         PL_parser->last_uni -= discard_len;
1294     if (PL_parser->last_lop)
1295         PL_parser->last_lop -= discard_len;
1296 }
1297
1298 void
1299 Perl_notify_parser_that_changed_to_utf8(pTHX)
1300 {
1301     /* Called when $^H is changed to indicate that HINT_UTF8 has changed from
1302      * off to on.  At compile time, this has the effect of entering a 'use
1303      * utf8' section.  This means that any input was not previously checked for
1304      * UTF-8 (because it was off), but now we do need to check it, or our
1305      * assumptions about the input being sane could be wrong, and we could
1306      * segfault.  This routine just sets a flag so that the next time we look
1307      * at the input we do the well-formed UTF-8 check.  If we aren't in the
1308      * proper phase, there may not be a parser object, but if there is, setting
1309      * the flag is harmless */
1310
1311     if (PL_parser) {
1312         PL_parser->recheck_utf8_validity = TRUE;
1313     }
1314 }
1315
1316 /*
1317 =for apidoc lex_next_chunk
1318
1319 Reads in the next chunk of text to be lexed, appending it to
1320 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1321 looked to the end of the current chunk and wants to know more.  It is
1322 usual, but not necessary, for lexing to have consumed the entirety of
1323 the current chunk at this time.
1324
1325 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1326 chunk (i.e., the current chunk has been entirely consumed), normally the
1327 current chunk will be discarded at the same time that the new chunk is
1328 read in.  If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1329 will not be discarded.  If the current chunk has not been entirely
1330 consumed, then it will not be discarded regardless of the flag.
1331
1332 Returns true if some new text was added to the buffer, or false if the
1333 buffer has reached the end of the input text.
1334
1335 =for apidoc Amnh||LEX_KEEP_PREVIOUS
1336
1337 =cut
1338 */
1339
1340 #define LEX_FAKE_EOF 0x80000000
1341 #define LEX_NO_TERM  0x40000000 /* here-doc */
1342
1343 bool
1344 Perl_lex_next_chunk(pTHX_ U32 flags)
1345 {
1346     SV *linestr;
1347     char *buf;
1348     STRLEN old_bufend_pos, new_bufend_pos;
1349     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1350     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1351     bool got_some_for_debugger = 0;
1352     bool got_some;
1353
1354     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1355         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1356     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1357         return FALSE;
1358     linestr = PL_parser->linestr;
1359     buf = SvPVX(linestr);
1360     if (!(flags & LEX_KEEP_PREVIOUS)
1361           && PL_parser->bufptr == PL_parser->bufend)
1362     {
1363         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1364         linestart_pos = 0;
1365         if (PL_parser->last_uni != PL_parser->bufend)
1366             PL_parser->last_uni = NULL;
1367         if (PL_parser->last_lop != PL_parser->bufend)
1368             PL_parser->last_lop = NULL;
1369         last_uni_pos = last_lop_pos = 0;
1370         *buf = 0;
1371         SvCUR_set(linestr, 0);
1372     } else {
1373         old_bufend_pos = PL_parser->bufend - buf;
1374         bufptr_pos = PL_parser->bufptr - buf;
1375         oldbufptr_pos = PL_parser->oldbufptr - buf;
1376         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1377         linestart_pos = PL_parser->linestart - buf;
1378         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1379         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1380     }
1381     if (flags & LEX_FAKE_EOF) {
1382         goto eof;
1383     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1384         got_some = 0;
1385     } else if (filter_gets(linestr, old_bufend_pos)) {
1386         got_some = 1;
1387         got_some_for_debugger = 1;
1388     } else if (flags & LEX_NO_TERM) {
1389         got_some = 0;
1390     } else {
1391         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1392             SvPVCLEAR(linestr);
1393         eof:
1394         /* End of real input.  Close filehandle (unless it was STDIN),
1395          * then add implicit termination.
1396          */
1397         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1398             PerlIO_clearerr(PL_parser->rsfp);
1399         else if (PL_parser->rsfp)
1400             (void)PerlIO_close(PL_parser->rsfp);
1401         PL_parser->rsfp = NULL;
1402         PL_parser->in_pod = PL_parser->filtered = 0;
1403         if (!PL_in_eval && PL_minus_p) {
1404             sv_catpvs(linestr,
1405                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1406             PL_minus_n = PL_minus_p = 0;
1407         } else if (!PL_in_eval && PL_minus_n) {
1408             sv_catpvs(linestr, /*{*/";}");
1409             PL_minus_n = 0;
1410         } else
1411             sv_catpvs(linestr, ";");
1412         got_some = 1;
1413     }
1414     buf = SvPVX(linestr);
1415     new_bufend_pos = SvCUR(linestr);
1416     PL_parser->bufend = buf + new_bufend_pos;
1417     PL_parser->bufptr = buf + bufptr_pos;
1418
1419     if (UTF) {
1420         const U8* first_bad_char_loc;
1421         if (UNLIKELY(! is_utf8_string_loc(
1422                             (U8 *) PL_parser->bufptr,
1423                                    PL_parser->bufend - PL_parser->bufptr,
1424                                    &first_bad_char_loc)))
1425         {
1426             _force_out_malformed_utf8_message(first_bad_char_loc,
1427                                               (U8 *) PL_parser->bufend,
1428                                               0,
1429                                               1 /* 1 means die */ );
1430             NOT_REACHED; /* NOTREACHED */
1431         }
1432     }
1433
1434     PL_parser->oldbufptr = buf + oldbufptr_pos;
1435     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1436     PL_parser->linestart = buf + linestart_pos;
1437     if (PL_parser->last_uni)
1438         PL_parser->last_uni = buf + last_uni_pos;
1439     if (PL_parser->last_lop)
1440         PL_parser->last_lop = buf + last_lop_pos;
1441     if (PL_parser->preambling != NOLINE) {
1442         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1443         PL_parser->preambling = NOLINE;
1444     }
1445     if (   got_some_for_debugger
1446         && PERLDB_LINE_OR_SAVESRC
1447         && PL_curstash != PL_debstash)
1448     {
1449         /* debugger active and we're not compiling the debugger code,
1450          * so store the line into the debugger's array of lines
1451          */
1452         update_debugger_info(NULL, buf+old_bufend_pos,
1453             new_bufend_pos-old_bufend_pos);
1454     }
1455     return got_some;
1456 }
1457
1458 /*
1459 =for apidoc lex_peek_unichar
1460
1461 Looks ahead one (Unicode) character in the text currently being lexed.
1462 Returns the codepoint (unsigned integer value) of the next character,
1463 or -1 if lexing has reached the end of the input text.  To consume the
1464 peeked character, use L</lex_read_unichar>.
1465
1466 If the next character is in (or extends into) the next chunk of input
1467 text, the next chunk will be read in.  Normally the current chunk will be
1468 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1469 bit set, then the current chunk will not be discarded.
1470
1471 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1472 is encountered, an exception is generated.
1473
1474 =cut
1475 */
1476
1477 I32
1478 Perl_lex_peek_unichar(pTHX_ U32 flags)
1479 {
1480     char *s, *bufend;
1481     if (flags & ~(LEX_KEEP_PREVIOUS))
1482         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1483     s = PL_parser->bufptr;
1484     bufend = PL_parser->bufend;
1485     if (UTF) {
1486         U8 head;
1487         I32 unichar;
1488         STRLEN len, retlen;
1489         if (s == bufend) {
1490             if (!lex_next_chunk(flags))
1491                 return -1;
1492             s = PL_parser->bufptr;
1493             bufend = PL_parser->bufend;
1494         }
1495         head = (U8)*s;
1496         if (UTF8_IS_INVARIANT(head))
1497             return head;
1498         if (UTF8_IS_START(head)) {
1499             len = UTF8SKIP(&head);
1500             while ((STRLEN)(bufend-s) < len) {
1501                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1502                     break;
1503                 s = PL_parser->bufptr;
1504                 bufend = PL_parser->bufend;
1505             }
1506         }
1507         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1508         if (retlen == (STRLEN)-1) {
1509             _force_out_malformed_utf8_message((U8 *) s,
1510                                               (U8 *) bufend,
1511                                               0,
1512                                               1 /* 1 means die */ );
1513             NOT_REACHED; /* NOTREACHED */
1514         }
1515         return unichar;
1516     } else {
1517         if (s == bufend) {
1518             if (!lex_next_chunk(flags))
1519                 return -1;
1520             s = PL_parser->bufptr;
1521         }
1522         return (U8)*s;
1523     }
1524 }
1525
1526 /*
1527 =for apidoc lex_read_unichar
1528
1529 Reads the next (Unicode) character in the text currently being lexed.
1530 Returns the codepoint (unsigned integer value) of the character read,
1531 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1532 if lexing has reached the end of the input text.  To non-destructively
1533 examine the next character, use L</lex_peek_unichar> instead.
1534
1535 If the next character is in (or extends into) the next chunk of input
1536 text, the next chunk will be read in.  Normally the current chunk will be
1537 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1538 bit set, then the current chunk will not be discarded.
1539
1540 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1541 is encountered, an exception is generated.
1542
1543 =cut
1544 */
1545
1546 I32
1547 Perl_lex_read_unichar(pTHX_ U32 flags)
1548 {
1549     I32 c;
1550     if (flags & ~(LEX_KEEP_PREVIOUS))
1551         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1552     c = lex_peek_unichar(flags);
1553     if (c != -1) {
1554         if (c == '\n')
1555             COPLINE_INC_WITH_HERELINES;
1556         if (UTF)
1557             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1558         else
1559             ++(PL_parser->bufptr);
1560     }
1561     return c;
1562 }
1563
1564 /*
1565 =for apidoc lex_read_space
1566
1567 Reads optional spaces, in Perl style, in the text currently being
1568 lexed.  The spaces may include ordinary whitespace characters and
1569 Perl-style comments.  C<#line> directives are processed if encountered.
1570 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1571 at a non-space character (or the end of the input text).
1572
1573 If spaces extend into the next chunk of input text, the next chunk will
1574 be read in.  Normally the current chunk will be discarded at the same
1575 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1576 chunk will not be discarded.
1577
1578 =cut
1579 */
1580
1581 #define LEX_NO_INCLINE    0x40000000
1582 #define LEX_NO_NEXT_CHUNK 0x80000000
1583
1584 void
1585 Perl_lex_read_space(pTHX_ U32 flags)
1586 {
1587     char *s, *bufend;
1588     const bool can_incline = !(flags & LEX_NO_INCLINE);
1589     bool need_incline = 0;
1590     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1591         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1592     s = PL_parser->bufptr;
1593     bufend = PL_parser->bufend;
1594     while (1) {
1595         char c = *s;
1596         if (c == '#') {
1597             do {
1598                 c = *++s;
1599             } while (!(c == '\n' || (c == 0 && s == bufend)));
1600         } else if (c == '\n') {
1601             s++;
1602             if (can_incline) {
1603                 PL_parser->linestart = s;
1604                 if (s == bufend)
1605                     need_incline = 1;
1606                 else
1607                     incline(s, bufend);
1608             }
1609         } else if (isSPACE(c)) {
1610             s++;
1611         } else if (c == 0 && s == bufend) {
1612             bool got_more;
1613             line_t l;
1614             if (flags & LEX_NO_NEXT_CHUNK)
1615                 break;
1616             PL_parser->bufptr = s;
1617             l = CopLINE(PL_curcop);
1618             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1619             got_more = lex_next_chunk(flags);
1620             CopLINE_set(PL_curcop, l);
1621             s = PL_parser->bufptr;
1622             bufend = PL_parser->bufend;
1623             if (!got_more)
1624                 break;
1625             if (can_incline && need_incline && PL_parser->rsfp) {
1626                 incline(s, bufend);
1627                 need_incline = 0;
1628             }
1629         } else if (!c) {
1630             s++;
1631         } else {
1632             break;
1633         }
1634     }
1635     PL_parser->bufptr = s;
1636 }
1637
1638 /*
1639
1640 =for apidoc validate_proto
1641
1642 This function performs syntax checking on a prototype, C<proto>.
1643 If C<warn> is true, any illegal characters or mismatched brackets
1644 will trigger illegalproto warnings, declaring that they were
1645 detected in the prototype for C<name>.
1646
1647 The return value is C<true> if this is a valid prototype, and
1648 C<false> if it is not, regardless of whether C<warn> was C<true> or
1649 C<false>.
1650
1651 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1652
1653 =cut
1654
1655  */
1656
1657 bool
1658 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn, bool curstash)
1659 {
1660     STRLEN len, origlen;
1661     char *p;
1662     bool bad_proto = FALSE;
1663     bool in_brackets = FALSE;
1664     bool after_slash = FALSE;
1665     char greedy_proto = ' ';
1666     bool proto_after_greedy_proto = FALSE;
1667     bool must_be_last = FALSE;
1668     bool underscore = FALSE;
1669     bool bad_proto_after_underscore = FALSE;
1670
1671     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1672
1673     if (!proto)
1674         return TRUE;
1675
1676     p = SvPV(proto, len);
1677     origlen = len;
1678     for (; len--; p++) {
1679         if (!isSPACE(*p)) {
1680             if (must_be_last)
1681                 proto_after_greedy_proto = TRUE;
1682             if (underscore) {
1683                 if (!memCHRs(";@%", *p))
1684                     bad_proto_after_underscore = TRUE;
1685                 underscore = FALSE;
1686             }
1687             if (!memCHRs("$@%*;[]&\\_+", *p) || *p == '\0') {
1688                 bad_proto = TRUE;
1689             }
1690             else {
1691                 if (*p == '[')
1692                     in_brackets = TRUE;
1693                 else if (*p == ']')
1694                     in_brackets = FALSE;
1695                 else if ((*p == '@' || *p == '%')
1696                          && !after_slash
1697                          && !in_brackets )
1698                 {
1699                     must_be_last = TRUE;
1700                     greedy_proto = *p;
1701                 }
1702                 else if (*p == '_')
1703                     underscore = TRUE;
1704             }
1705             if (*p == '\\')
1706                 after_slash = TRUE;
1707             else
1708                 after_slash = FALSE;
1709         }
1710     }
1711
1712     if (warn) {
1713         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1714         p -= origlen;
1715         p = SvUTF8(proto)
1716             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1717                              origlen, UNI_DISPLAY_ISPRINT)
1718             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1719
1720         if (curstash && !memchr(SvPVX(name), ':', SvCUR(name))) {
1721             SV *name2 = sv_2mortal(newSVsv(PL_curstname));
1722             sv_catpvs(name2, "::");
1723             sv_catsv(name2, (SV *)name);
1724             name = name2;
1725         }
1726
1727         if (proto_after_greedy_proto)
1728             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1729                         "Prototype after '%c' for %" SVf " : %s",
1730                         greedy_proto, SVfARG(name), p);
1731         if (in_brackets)
1732             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1733                         "Missing ']' in prototype for %" SVf " : %s",
1734                         SVfARG(name), p);
1735         if (bad_proto)
1736             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1737                         "Illegal character in prototype for %" SVf " : %s",
1738                         SVfARG(name), p);
1739         if (bad_proto_after_underscore)
1740             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1741                         "Illegal character after '_' in prototype for %" SVf " : %s",
1742                         SVfARG(name), p);
1743     }
1744
1745     return (! (proto_after_greedy_proto || bad_proto) );
1746 }
1747
1748 /*
1749  * S_incline
1750  * This subroutine has nothing to do with tilting, whether at windmills
1751  * or pinball tables.  Its name is short for "increment line".  It
1752  * increments the current line number in CopLINE(PL_curcop) and checks
1753  * to see whether the line starts with a comment of the form
1754  *    # line 500 "foo.pm"
1755  * If so, it sets the current line number and file to the values in the comment.
1756  */
1757
1758 STATIC void
1759 S_incline(pTHX_ const char *s, const char *end)
1760 {
1761     const char *t;
1762     const char *n;
1763     const char *e;
1764     line_t line_num;
1765     UV uv;
1766
1767     PERL_ARGS_ASSERT_INCLINE;
1768
1769     assert(end >= s);
1770
1771     COPLINE_INC_WITH_HERELINES;
1772     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1773      && s+1 == PL_bufend && *s == ';') {
1774         /* fake newline in string eval */
1775         CopLINE_dec(PL_curcop);
1776         return;
1777     }
1778     if (*s++ != '#')
1779         return;
1780     while (SPACE_OR_TAB(*s))
1781         s++;
1782     if (memBEGINs(s, (STRLEN) (end - s), "line"))
1783         s += sizeof("line") - 1;
1784     else
1785         return;
1786     if (SPACE_OR_TAB(*s))
1787         s++;
1788     else
1789         return;
1790     while (SPACE_OR_TAB(*s))
1791         s++;
1792     if (!isDIGIT(*s))
1793         return;
1794
1795     n = s;
1796     while (isDIGIT(*s))
1797         s++;
1798     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1799         return;
1800     while (SPACE_OR_TAB(*s))
1801         s++;
1802     if (*s == '"' && (t = (char *) memchr(s+1, '"', end - s))) {
1803         s++;
1804         e = t + 1;
1805     }
1806     else {
1807         t = s;
1808         while (*t && !isSPACE(*t))
1809             t++;
1810         e = t;
1811     }
1812     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1813         e++;
1814     if (*e != '\n' && *e != '\0')
1815         return;         /* false alarm */
1816
1817     if (!grok_atoUV(n, &uv, &e))
1818         return;
1819     line_num = ((line_t)uv) - 1;
1820
1821     if (t - s > 0) {
1822         const STRLEN len = t - s;
1823
1824         if (!PL_rsfp && !PL_parser->filtered) {
1825             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1826              * to *{"::_<newfilename"} */
1827             /* However, the long form of evals is only turned on by the
1828                debugger - usually they're "(eval %lu)" */
1829             GV * const cfgv = CopFILEGV(PL_curcop);
1830             if (cfgv) {
1831                 char smallbuf[128];
1832                 STRLEN tmplen2 = len;
1833                 char *tmpbuf2;
1834                 GV *gv2;
1835
1836                 if (tmplen2 + 2 <= sizeof smallbuf)
1837                     tmpbuf2 = smallbuf;
1838                 else
1839                     Newx(tmpbuf2, tmplen2 + 2, char);
1840
1841                 tmpbuf2[0] = '_';
1842                 tmpbuf2[1] = '<';
1843
1844                 memcpy(tmpbuf2 + 2, s, tmplen2);
1845                 tmplen2 += 2;
1846
1847                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1848                 if (!isGV(gv2)) {
1849                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1850                     /* adjust ${"::_<newfilename"} to store the new file name */
1851                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1852                     /* The line number may differ. If that is the case,
1853                        alias the saved lines that are in the array.
1854                        Otherwise alias the whole array. */
1855                     if (CopLINE(PL_curcop) == line_num) {
1856                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1857                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1858                     }
1859                     else if (GvAV(cfgv)) {
1860                         AV * const av = GvAV(cfgv);
1861                         const line_t start = CopLINE(PL_curcop)+1;
1862                         SSize_t items = AvFILLp(av) - start;
1863                         if (items > 0) {
1864                             AV * const av2 = GvAVn(gv2);
1865                             SV **svp = AvARRAY(av) + start;
1866                             Size_t l = line_num+1;
1867                             while (items-- && l < SSize_t_MAX && l == (line_t)l)
1868                                 av_store(av2, (SSize_t)l++, SvREFCNT_inc(*svp++));
1869                         }
1870                     }
1871                 }
1872
1873                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1874             }
1875         }
1876         CopFILE_free(PL_curcop);
1877         CopFILE_setn(PL_curcop, s, len);
1878     }
1879     CopLINE_set(PL_curcop, line_num);
1880 }
1881
1882 STATIC void
1883 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1884 {
1885     AV *av = CopFILEAVx(PL_curcop);
1886     if (av) {
1887         SV * sv;
1888         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1889         else {
1890             sv = *av_fetch(av, 0, 1);
1891             SvUPGRADE(sv, SVt_PVMG);
1892         }
1893         if (!SvPOK(sv)) SvPVCLEAR(sv);
1894         if (orig_sv)
1895             sv_catsv(sv, orig_sv);
1896         else
1897             sv_catpvn(sv, buf, len);
1898         if (!SvIOK(sv)) {
1899             (void)SvIOK_on(sv);
1900             SvIV_set(sv, 0);
1901         }
1902         if (PL_parser->preambling == NOLINE)
1903             av_store(av, CopLINE(PL_curcop), sv);
1904     }
1905 }
1906
1907 /*
1908  * skipspace
1909  * Called to gobble the appropriate amount and type of whitespace.
1910  * Skips comments as well.
1911  * Returns the next character after the whitespace that is skipped.
1912  *
1913  * peekspace
1914  * Same thing, but look ahead without incrementing line numbers or
1915  * adjusting PL_linestart.
1916  */
1917
1918 #define skipspace(s) skipspace_flags(s, 0)
1919 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1920
1921 char *
1922 Perl_skipspace_flags(pTHX_ char *s, U32 flags)
1923 {
1924     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1925     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1926         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1927             s++;
1928     } else {
1929         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1930         PL_bufptr = s;
1931         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1932                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1933                     LEX_NO_NEXT_CHUNK : 0));
1934         s = PL_bufptr;
1935         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1936         if (PL_linestart > PL_bufptr)
1937             PL_bufptr = PL_linestart;
1938         return s;
1939     }
1940     return s;
1941 }
1942
1943 /*
1944  * S_check_uni
1945  * Check the unary operators to ensure there's no ambiguity in how they're
1946  * used.  An ambiguous piece of code would be:
1947  *     rand + 5
1948  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1949  * the +5 is its argument.
1950  */
1951
1952 STATIC void
1953 S_check_uni(pTHX)
1954 {
1955     const char *s;
1956
1957     if (PL_oldoldbufptr != PL_last_uni)
1958         return;
1959     while (isSPACE(*PL_last_uni))
1960         PL_last_uni++;
1961     s = PL_last_uni;
1962     while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF) || *s == '-')
1963         s += UTF ? UTF8SKIP(s) : 1;
1964     if (s < PL_bufptr && memchr(s, '(', PL_bufptr - s))
1965         return;
1966
1967     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1968                      "Warning: Use of \"%" UTF8f "\" without parentheses is ambiguous",
1969                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1970 }
1971
1972 /*
1973  * LOP : macro to build a list operator.  Its behaviour has been replaced
1974  * with a subroutine, S_lop() for which LOP is just another name.
1975  */
1976
1977 #define LOP(f,x) return lop(f,x,s)
1978
1979 /*
1980  * S_lop
1981  * Build a list operator (or something that might be one).  The rules:
1982  *  - if we have a next token, then it's a list operator (no parens) for
1983  *    which the next token has already been parsed; e.g.,
1984  *       sort foo @args
1985  *       sort foo (@args)
1986  *  - if the next thing is an opening paren, then it's a function
1987  *  - else it's a list operator
1988  */
1989
1990 STATIC I32
1991 S_lop(pTHX_ I32 f, U8 x, char *s)
1992 {
1993     PERL_ARGS_ASSERT_LOP;
1994
1995     pl_yylval.ival = f;
1996     CLINE;
1997     PL_bufptr = s;
1998     PL_last_lop = PL_oldbufptr;
1999     PL_last_lop_op = (OPCODE)f;
2000     if (PL_nexttoke)
2001         goto lstop;
2002     PL_expect = x;
2003     if (*s == '(')
2004         return REPORT(FUNC);
2005     s = skipspace(s);
2006     if (*s == '(')
2007         return REPORT(FUNC);
2008     else {
2009         lstop:
2010         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
2011             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
2012         return REPORT(LSTOP);
2013     }
2014 }
2015
2016 /*
2017  * S_force_next
2018  * When the lexer realizes it knows the next token (for instance,
2019  * it is reordering tokens for the parser) then it can call S_force_next
2020  * to know what token to return the next time the lexer is called.  Caller
2021  * will need to set PL_nextval[] and possibly PL_expect to ensure
2022  * the lexer handles the token correctly.
2023  */
2024
2025 STATIC void
2026 S_force_next(pTHX_ I32 type)
2027 {
2028 #ifdef DEBUGGING
2029     if (DEBUG_T_TEST) {
2030         PerlIO_printf(Perl_debug_log, "### forced token:\n");
2031         tokereport(type, &NEXTVAL_NEXTTOKE);
2032     }
2033 #endif
2034     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
2035     PL_nexttype[PL_nexttoke] = type;
2036     PL_nexttoke++;
2037 }
2038
2039 /*
2040  * S_postderef
2041  *
2042  * This subroutine handles postfix deref syntax after the arrow has already
2043  * been emitted.  @* $* etc. are emitted as two separate tokens right here.
2044  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
2045  * only the first, leaving yylex to find the next.
2046  */
2047
2048 static int
2049 S_postderef(pTHX_ int const funny, char const next)
2050 {
2051     assert(funny == DOLSHARP
2052         || memCHRs("$@%&*", funny)
2053         || funny == PERLY_SNAIL
2054         || funny == PERLY_AMPERSAND
2055     );
2056     if (next == '*') {
2057         PL_expect = XOPERATOR;
2058         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
2059             assert(PERLY_SNAIL == funny || '$' == funny || DOLSHARP == funny);
2060             PL_lex_state = LEX_INTERPEND;
2061             if (PERLY_SNAIL == funny)
2062                 force_next(POSTJOIN);
2063         }
2064         force_next(next);
2065         PL_bufptr+=2;
2066     }
2067     else {
2068         if (PERLY_SNAIL == funny && PL_lex_state == LEX_INTERPNORMAL
2069          && !PL_lex_brackets)
2070             PL_lex_dojoin = 2;
2071         PL_expect = XOPERATOR;
2072         PL_bufptr++;
2073     }
2074     return funny;
2075 }
2076
2077 void
2078 Perl_yyunlex(pTHX)
2079 {
2080     int yyc = PL_parser->yychar;
2081     if (yyc != YYEMPTY) {
2082         if (yyc) {
2083             NEXTVAL_NEXTTOKE = PL_parser->yylval;
2084             if (yyc == PERLY_BRACE_OPEN || yyc == HASHBRACK || yyc == PERLY_BRACKET_OPEN) {
2085                 PL_lex_allbrackets--;
2086                 PL_lex_brackets--;
2087                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
2088             } else if (yyc == '('/*)*/) {
2089                 PL_lex_allbrackets--;
2090                 yyc |= (2<<24);
2091             }
2092             force_next(yyc);
2093         }
2094         PL_parser->yychar = YYEMPTY;
2095     }
2096 }
2097
2098 STATIC SV *
2099 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
2100 {
2101     SV * const sv = newSVpvn_utf8(start, len,
2102                     ! IN_BYTES
2103                   &&  UTF
2104                   &&  len != 0
2105                   &&  is_utf8_non_invariant_string((const U8*)start, len));
2106     return sv;
2107 }
2108
2109 /*
2110  * S_force_word
2111  * When the lexer knows the next thing is a word (for instance, it has
2112  * just seen -> and it knows that the next char is a word char, then
2113  * it calls S_force_word to stick the next word into the PL_nexttoke/val
2114  * lookahead.
2115  *
2116  * Arguments:
2117  *   char *start : buffer position (must be within PL_linestr)
2118  *   int token   : PL_next* will be this type of bare word
2119  *                 (e.g., METHOD,BAREWORD)
2120  *   int check_keyword : if true, Perl checks to make sure the word isn't
2121  *       a keyword (do this if the word is a label, e.g. goto FOO)
2122  *   int allow_pack : if true, : characters will also be allowed (require,
2123  *       use, etc. do this)
2124  */
2125
2126 STATIC char *
2127 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2128 {
2129     char *s;
2130     STRLEN len;
2131
2132     PERL_ARGS_ASSERT_FORCE_WORD;
2133
2134     start = skipspace(start);
2135     s = start;
2136     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
2137         || (allow_pack && *s == ':' && s[1] == ':') )
2138     {
2139         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2140         if (check_keyword) {
2141           char *s2 = PL_tokenbuf;
2142           STRLEN len2 = len;
2143           if (allow_pack && memBEGINPs(s2, len, "CORE::")) {
2144             s2 += sizeof("CORE::") - 1;
2145             len2 -= sizeof("CORE::") - 1;
2146           }
2147           if (keyword(s2, len2, 0))
2148             return start;
2149         }
2150         if (token == METHOD) {
2151             s = skipspace(s);
2152             if (*s == '(')
2153                 PL_expect = XTERM;
2154             else {
2155                 PL_expect = XOPERATOR;
2156             }
2157         }
2158         NEXTVAL_NEXTTOKE.opval
2159             = newSVOP(OP_CONST,0,
2160                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2161         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2162         force_next(token);
2163     }
2164     return s;
2165 }
2166
2167 /*
2168  * S_force_ident
2169  * Called when the lexer wants $foo *foo &foo etc, but the program
2170  * text only contains the "foo" portion.  The first argument is a pointer
2171  * to the "foo", and the second argument is the type symbol to prefix.
2172  * Forces the next token to be a "BAREWORD".
2173  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2174  */
2175
2176 STATIC void
2177 S_force_ident(pTHX_ const char *s, int kind)
2178 {
2179     PERL_ARGS_ASSERT_FORCE_IDENT;
2180
2181     if (s[0]) {
2182         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2183         OP* const o = newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2184                                                                 UTF ? SVf_UTF8 : 0));
2185         NEXTVAL_NEXTTOKE.opval = o;
2186         force_next(BAREWORD);
2187         if (kind) {
2188             o->op_private = OPpCONST_ENTERED;
2189             /* XXX see note in pp_entereval() for why we forgo typo
2190                warnings if the symbol must be introduced in an eval.
2191                GSAR 96-10-12 */
2192             gv_fetchpvn_flags(s, len,
2193                               (PL_in_eval ? GV_ADDMULTI
2194                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2195                               kind == '$' ? SVt_PV :
2196                               kind == PERLY_SNAIL ? SVt_PVAV :
2197                               kind == '%' ? SVt_PVHV :
2198                               SVt_PVGV
2199                               );
2200         }
2201     }
2202 }
2203
2204 static void
2205 S_force_ident_maybe_lex(pTHX_ char pit)
2206 {
2207     NEXTVAL_NEXTTOKE.ival = pit;
2208     force_next('p');
2209 }
2210
2211 NV
2212 Perl_str_to_version(pTHX_ SV *sv)
2213 {
2214     NV retval = 0.0;
2215     NV nshift = 1.0;
2216     STRLEN len;
2217     const char *start = SvPV_const(sv,len);
2218     const char * const end = start + len;
2219     const bool utf = cBOOL(SvUTF8(sv));
2220
2221     PERL_ARGS_ASSERT_STR_TO_VERSION;
2222
2223     while (start < end) {
2224         STRLEN skip;
2225         UV n;
2226         if (utf)
2227             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2228         else {
2229             n = *(U8*)start;
2230             skip = 1;
2231         }
2232         retval += ((NV)n)/nshift;
2233         start += skip;
2234         nshift *= 1000;
2235     }
2236     return retval;
2237 }
2238
2239 /*
2240  * S_force_version
2241  * Forces the next token to be a version number.
2242  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2243  * and if "guessing" is TRUE, then no new token is created (and the caller
2244  * must use an alternative parsing method).
2245  */
2246
2247 STATIC char *
2248 S_force_version(pTHX_ char *s, int guessing)
2249 {
2250     OP *version = NULL;
2251     char *d;
2252
2253     PERL_ARGS_ASSERT_FORCE_VERSION;
2254
2255     s = skipspace(s);
2256
2257     d = s;
2258     if (*d == 'v')
2259         d++;
2260     if (isDIGIT(*d)) {
2261         while (isDIGIT(*d) || *d == '_' || *d == '.')
2262             d++;
2263         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2264             SV *ver;
2265             s = scan_num(s, &pl_yylval);
2266             version = pl_yylval.opval;
2267             ver = cSVOPx(version)->op_sv;
2268             if (SvPOK(ver) && !SvNIOK(ver)) {
2269                 SvUPGRADE(ver, SVt_PVNV);
2270                 SvNV_set(ver, str_to_version(ver));
2271                 SvNOK_on(ver);          /* hint that it is a version */
2272             }
2273         }
2274         else if (guessing) {
2275             return s;
2276         }
2277     }
2278
2279     /* NOTE: The parser sees the package name and the VERSION swapped */
2280     NEXTVAL_NEXTTOKE.opval = version;
2281     force_next(BAREWORD);
2282
2283     return s;
2284 }
2285
2286 /*
2287  * S_force_strict_version
2288  * Forces the next token to be a version number using strict syntax rules.
2289  */
2290
2291 STATIC char *
2292 S_force_strict_version(pTHX_ char *s)
2293 {
2294     OP *version = NULL;
2295     const char *errstr = NULL;
2296
2297     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2298
2299     while (isSPACE(*s)) /* leading whitespace */
2300         s++;
2301
2302     if (is_STRICT_VERSION(s,&errstr)) {
2303         SV *ver = newSV(0);
2304         s = (char *)scan_version(s, ver, 0);
2305         version = newSVOP(OP_CONST, 0, ver);
2306     }
2307     else if ((*s != ';' && *s != '{' && *s != '}' )
2308              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2309     {
2310         PL_bufptr = s;
2311         if (errstr)
2312             yyerror(errstr); /* version required */
2313         return s;
2314     }
2315
2316     /* NOTE: The parser sees the package name and the VERSION swapped */
2317     NEXTVAL_NEXTTOKE.opval = version;
2318     force_next(BAREWORD);
2319
2320     return s;
2321 }
2322
2323 /*
2324  * S_tokeq
2325  * Turns any \\ into \ in a quoted string passed in in 'sv', returning 'sv',
2326  * modified as necessary.  However, if HINT_NEW_STRING is on, 'sv' is
2327  * unchanged, and a new SV containing the modified input is returned.
2328  */
2329
2330 STATIC SV *
2331 S_tokeq(pTHX_ SV *sv)
2332 {
2333     char *s;
2334     char *send;
2335     char *d;
2336     SV *pv = sv;
2337
2338     PERL_ARGS_ASSERT_TOKEQ;
2339
2340     assert (SvPOK(sv));
2341     assert (SvLEN(sv));
2342     assert (!SvIsCOW(sv));
2343     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2344         goto finish;
2345     s = SvPVX(sv);
2346     send = SvEND(sv);
2347     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2348     while (s < send && !(*s == '\\' && s[1] == '\\'))
2349         s++;
2350     if (s == send)
2351         goto finish;
2352     d = s;
2353     if ( PL_hints & HINT_NEW_STRING ) {
2354         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2355                             SVs_TEMP | SvUTF8(sv));
2356     }
2357     while (s < send) {
2358         if (*s == '\\') {
2359             if (s + 1 < send && (s[1] == '\\'))
2360                 s++;            /* all that, just for this */
2361         }
2362         *d++ = *s++;
2363     }
2364     *d = '\0';
2365     SvCUR_set(sv, d - SvPVX_const(sv));
2366   finish:
2367     if ( PL_hints & HINT_NEW_STRING )
2368        return new_constant(NULL, 0, "q", sv, pv, "q", 1, NULL);
2369     return sv;
2370 }
2371
2372 /*
2373  * Now come three functions related to double-quote context,
2374  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2375  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2376  * interact with PL_lex_state, and create fake ( ... ) argument lists
2377  * to handle functions and concatenation.
2378  * For example,
2379  *   "foo\lbar"
2380  * is tokenised as
2381  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2382  */
2383
2384 /*
2385  * S_sublex_start
2386  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2387  *
2388  * Pattern matching will set PL_lex_op to the pattern-matching op to
2389  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2390  *
2391  * OP_CONST is easy--just make the new op and return.
2392  *
2393  * Everything else becomes a FUNC.
2394  *
2395  * Sets PL_lex_state to LEX_INTERPPUSH unless ival was OP_NULL or we
2396  * had an OP_CONST.  This just sets us up for a
2397  * call to S_sublex_push().
2398  */
2399
2400 STATIC I32
2401 S_sublex_start(pTHX)
2402 {
2403     const I32 op_type = pl_yylval.ival;
2404
2405     if (op_type == OP_NULL) {
2406         pl_yylval.opval = PL_lex_op;
2407         PL_lex_op = NULL;
2408         return THING;
2409     }
2410     if (op_type == OP_CONST) {
2411         SV *sv = PL_lex_stuff;
2412         PL_lex_stuff = NULL;
2413         sv = tokeq(sv);
2414
2415         if (SvTYPE(sv) == SVt_PVIV) {
2416             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2417             STRLEN len;
2418             const char * const p = SvPV_const(sv, len);
2419             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2420             SvREFCNT_dec(sv);
2421             sv = nsv;
2422         }
2423         pl_yylval.opval = newSVOP(op_type, 0, sv);
2424         return THING;
2425     }
2426
2427     PL_parser->lex_super_state = PL_lex_state;
2428     PL_parser->lex_sub_inwhat = (U16)op_type;
2429     PL_parser->lex_sub_op = PL_lex_op;
2430     PL_parser->sub_no_recover = FALSE;
2431     PL_parser->sub_error_count = PL_error_count;
2432     PL_lex_state = LEX_INTERPPUSH;
2433
2434     PL_expect = XTERM;
2435     if (PL_lex_op) {
2436         pl_yylval.opval = PL_lex_op;
2437         PL_lex_op = NULL;
2438         return PMFUNC;
2439     }
2440     else
2441         return FUNC;
2442 }
2443
2444 /*
2445  * S_sublex_push
2446  * Create a new scope to save the lexing state.  The scope will be
2447  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2448  * to the uc, lc, etc. found before.
2449  * Sets PL_lex_state to LEX_INTERPCONCAT.
2450  */
2451
2452 STATIC I32
2453 S_sublex_push(pTHX)
2454 {
2455     LEXSHARED *shared;
2456     const bool is_heredoc = PL_multi_close == '<';
2457     ENTER;
2458
2459     PL_lex_state = PL_parser->lex_super_state;
2460     SAVEI8(PL_lex_dojoin);
2461     SAVEI32(PL_lex_brackets);
2462     SAVEI32(PL_lex_allbrackets);
2463     SAVEI32(PL_lex_formbrack);
2464     SAVEI8(PL_lex_fakeeof);
2465     SAVEI32(PL_lex_casemods);
2466     SAVEI32(PL_lex_starts);
2467     SAVEI8(PL_lex_state);
2468     SAVESPTR(PL_lex_repl);
2469     SAVEVPTR(PL_lex_inpat);
2470     SAVEI16(PL_lex_inwhat);
2471     if (is_heredoc)
2472     {
2473         SAVECOPLINE(PL_curcop);
2474         SAVEI32(PL_multi_end);
2475         SAVEI32(PL_parser->herelines);
2476         PL_parser->herelines = 0;
2477     }
2478     SAVEIV(PL_multi_close);
2479     SAVEPPTR(PL_bufptr);
2480     SAVEPPTR(PL_bufend);
2481     SAVEPPTR(PL_oldbufptr);
2482     SAVEPPTR(PL_oldoldbufptr);
2483     SAVEPPTR(PL_last_lop);
2484     SAVEPPTR(PL_last_uni);
2485     SAVEPPTR(PL_linestart);
2486     SAVESPTR(PL_linestr);
2487     SAVEGENERICPV(PL_lex_brackstack);
2488     SAVEGENERICPV(PL_lex_casestack);
2489     SAVEGENERICPV(PL_parser->lex_shared);
2490     SAVEBOOL(PL_parser->lex_re_reparsing);
2491     SAVEI32(PL_copline);
2492
2493     /* The here-doc parser needs to be able to peek into outer lexing
2494        scopes to find the body of the here-doc.  So we put PL_linestr and
2495        PL_bufptr into lex_shared, to â€˜share’ those values.
2496      */
2497     PL_parser->lex_shared->ls_linestr = PL_linestr;
2498     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2499
2500     PL_linestr = PL_lex_stuff;
2501     PL_lex_repl = PL_parser->lex_sub_repl;
2502     PL_lex_stuff = NULL;
2503     PL_parser->lex_sub_repl = NULL;
2504
2505     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2506        set for an inner quote-like operator and then an error causes scope-
2507        popping.  We must not have a PL_lex_stuff value left dangling, as
2508        that breaks assumptions elsewhere.  See bug #123617.  */
2509     SAVEGENERICSV(PL_lex_stuff);
2510     SAVEGENERICSV(PL_parser->lex_sub_repl);
2511
2512     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2513         = SvPVX(PL_linestr);
2514     PL_bufend += SvCUR(PL_linestr);
2515     PL_last_lop = PL_last_uni = NULL;
2516     SAVEFREESV(PL_linestr);
2517     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2518
2519     PL_lex_dojoin = FALSE;
2520     PL_lex_brackets = PL_lex_formbrack = 0;
2521     PL_lex_allbrackets = 0;
2522     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2523     Newx(PL_lex_brackstack, 120, char);
2524     Newx(PL_lex_casestack, 12, char);
2525     PL_lex_casemods = 0;
2526     *PL_lex_casestack = '\0';
2527     PL_lex_starts = 0;
2528     PL_lex_state = LEX_INTERPCONCAT;
2529     if (is_heredoc)
2530         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2531     PL_copline = NOLINE;
2532
2533     Newxz(shared, 1, LEXSHARED);
2534     shared->ls_prev = PL_parser->lex_shared;
2535     PL_parser->lex_shared = shared;
2536
2537     PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2538     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2539     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2540         PL_lex_inpat = PL_parser->lex_sub_op;
2541     else
2542         PL_lex_inpat = NULL;
2543
2544     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2545     PL_in_eval &= ~EVAL_RE_REPARSING;
2546
2547     return SUBLEXSTART;
2548 }
2549
2550 /*
2551  * S_sublex_done
2552  * Restores lexer state after a S_sublex_push.
2553  */
2554
2555 STATIC I32
2556 S_sublex_done(pTHX)
2557 {
2558     if (!PL_lex_starts++) {
2559         SV * const sv = newSVpvs("");
2560         if (SvUTF8(PL_linestr))
2561             SvUTF8_on(sv);
2562         PL_expect = XOPERATOR;
2563         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
2564         return THING;
2565     }
2566
2567     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2568         PL_lex_state = LEX_INTERPCASEMOD;
2569         return yylex();
2570     }
2571
2572     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2573     assert(PL_lex_inwhat != OP_TRANSR);
2574     if (PL_lex_repl) {
2575         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2576         PL_linestr = PL_lex_repl;
2577         PL_lex_inpat = 0;
2578         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2579         PL_bufend += SvCUR(PL_linestr);
2580         PL_last_lop = PL_last_uni = NULL;
2581         PL_lex_dojoin = FALSE;
2582         PL_lex_brackets = 0;
2583         PL_lex_allbrackets = 0;
2584         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2585         PL_lex_casemods = 0;
2586         *PL_lex_casestack = '\0';
2587         PL_lex_starts = 0;
2588         if (SvEVALED(PL_lex_repl)) {
2589             PL_lex_state = LEX_INTERPNORMAL;
2590             PL_lex_starts++;
2591             /*  we don't clear PL_lex_repl here, so that we can check later
2592                 whether this is an evalled subst; that means we rely on the
2593                 logic to ensure sublex_done() is called again only via the
2594                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2595         }
2596         else {
2597             PL_lex_state = LEX_INTERPCONCAT;
2598             PL_lex_repl = NULL;
2599         }
2600         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2601             CopLINE(PL_curcop) +=
2602                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2603                  + PL_parser->herelines;
2604             PL_parser->herelines = 0;
2605         }
2606         return '/';
2607     }
2608     else {
2609         const line_t l = CopLINE(PL_curcop);
2610         LEAVE;
2611         if (PL_parser->sub_error_count != PL_error_count) {
2612             if (PL_parser->sub_no_recover) {
2613                 yyquit();
2614                 NOT_REACHED;
2615             }
2616         }
2617         if (PL_multi_close == '<')
2618             PL_parser->herelines += l - PL_multi_end;
2619         PL_bufend = SvPVX(PL_linestr);
2620         PL_bufend += SvCUR(PL_linestr);
2621         PL_expect = XOPERATOR;
2622         return SUBLEXEND;
2623     }
2624 }
2625
2626 HV *
2627 Perl_load_charnames(pTHX_ SV * char_name, const char * context,
2628                           const STRLEN context_len, const char ** error_msg)
2629 {
2630     /* Load the official _charnames module if not already there.  The
2631      * parameters are just to give info for any error messages generated:
2632      *  char_name   a name to look up which is the reason for loading this
2633      *  context     'char_name' in the context in the input in which it appears
2634      *  context_len how many bytes 'context' occupies
2635      *  error_msg   *error_msg will be set to any error
2636      *
2637      *  Returns the ^H table if success; otherwise NULL */
2638
2639     unsigned int i;
2640     HV * table;
2641     SV **cvp;
2642     SV * res;
2643
2644     PERL_ARGS_ASSERT_LOAD_CHARNAMES;
2645
2646     /* This loop is executed 1 1/2 times.  On the first time through, if it
2647      * isn't already loaded, try loading it, and iterate just once to see if it
2648      * worked.  */
2649     for (i = 0; i < 2; i++) {
2650         table = GvHV(PL_hintgv);                 /* ^H */
2651
2652         if (    table
2653             && (PL_hints & HINT_LOCALIZE_HH)
2654             && (cvp = hv_fetchs(table, "charnames", FALSE))
2655             &&  SvOK(*cvp))
2656         {
2657             return table;   /* Quit if already loaded */
2658         }
2659
2660         if (i == 0) {
2661             Perl_load_module(aTHX_
2662                 0,
2663                 newSVpvs("_charnames"),
2664
2665                 /* version parameter; no need to specify it, as if we get too early
2666                 * a version, will fail anyway, not being able to find 'charnames'
2667                 * */
2668                 NULL,
2669                 newSVpvs(":full"),
2670                 newSVpvs(":short"),
2671                 NULL);
2672         }
2673     }
2674
2675     /* Here, it failed; new_constant will give appropriate error messages */
2676     *error_msg = NULL;
2677     res = new_constant( NULL, 0, "charnames", char_name, NULL,
2678                         context, context_len, error_msg);
2679     SvREFCNT_dec(res);
2680
2681     return NULL;
2682 }
2683
2684 STATIC SV*
2685 S_get_and_check_backslash_N_name_wrapper(pTHX_ const char* s, const char* const e)
2686 {
2687     /* This justs wraps get_and_check_backslash_N_name() to output any error
2688      * message it returns. */
2689
2690     const char * error_msg = NULL;
2691     SV * result;
2692
2693     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME_WRAPPER;
2694
2695     /* charnames doesn't work well if there have been errors found */
2696     if (PL_error_count > 0) {
2697         return NULL;
2698     }
2699
2700     result = get_and_check_backslash_N_name(s, e, cBOOL(UTF), &error_msg);
2701
2702     if (error_msg) {
2703         yyerror_pv(error_msg, UTF ? SVf_UTF8 : 0);
2704     }
2705
2706     return result;
2707 }
2708
2709 SV*
2710 Perl_get_and_check_backslash_N_name(pTHX_ const char* s,
2711                                           const char* const e,
2712                                           const bool is_utf8,
2713                                           const char ** error_msg)
2714 {
2715     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2716      * interior, hence to the "}".  Finds what the name resolves to, returning
2717      * an SV* containing it; NULL if no valid one found.
2718      *
2719      * 'is_utf8' is TRUE if we know we want the result to be UTF-8 even if it
2720      * doesn't have to be. */
2721
2722     SV* char_name;
2723     SV* res;
2724     HV * table;
2725     SV **cvp;
2726     SV *cv;
2727     SV *rv;
2728     HV *stash;
2729
2730     /* Points to the beginning of the \N{... so that any messages include the
2731      * context of what's failing*/
2732     const char* context = s - 3;
2733     STRLEN context_len = e - context + 1; /* include all of \N{...} */
2734
2735
2736     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2737
2738     assert(e >= s);
2739     assert(s > (char *) 3);
2740
2741     char_name = newSVpvn_flags(s, e - s, (is_utf8) ? SVf_UTF8 : 0);
2742
2743     if (!SvCUR(char_name)) {
2744         SvREFCNT_dec_NN(char_name);
2745         /* diag_listed_as: Unknown charname '%s' */
2746         *error_msg = Perl_form(aTHX_ "Unknown charname ''");
2747         return NULL;
2748     }
2749
2750     /* Autoload the charnames module */
2751
2752     table = load_charnames(char_name, context, context_len, error_msg);
2753     if (table == NULL) {
2754         return NULL;
2755     }
2756
2757     *error_msg = NULL;
2758     res = new_constant( NULL, 0, "charnames", char_name, NULL,
2759                         context, context_len, error_msg);
2760     if (*error_msg) {
2761         *error_msg = Perl_form(aTHX_ "Unknown charname '%s'", SvPVX(char_name));
2762
2763         SvREFCNT_dec(res);
2764         return NULL;
2765     }
2766
2767     /* See if the charnames handler is the Perl core's, and if so, we can skip
2768      * the validation needed for a user-supplied one, as Perl's does its own
2769      * validation. */
2770     cvp = hv_fetchs(table, "charnames", FALSE);
2771     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2772         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2773     {
2774         const char * const name = HvNAME(stash);
2775          if (memEQs(name, HvNAMELEN(stash), "_charnames")) {
2776            return res;
2777        }
2778     }
2779
2780     /* Here, it isn't Perl's charname handler.  We can't rely on a
2781      * user-supplied handler to validate the input name.  For non-ut8 input,
2782      * look to see that the first character is legal.  Then loop through the
2783      * rest checking that each is a continuation */
2784
2785     /* This code makes the reasonable assumption that the only Latin1-range
2786      * characters that begin a character name alias are alphabetic, otherwise
2787      * would have to create a isCHARNAME_BEGIN macro */
2788
2789     if (! is_utf8) {
2790         if (! isALPHAU(*s)) {
2791             goto bad_charname;
2792         }
2793         s++;
2794         while (s < e) {
2795             if (! isCHARNAME_CONT(*s)) {
2796                 goto bad_charname;
2797             }
2798             if (*s == ' ' && *(s-1) == ' ') {
2799                 goto multi_spaces;
2800             }
2801             s++;
2802         }
2803     }
2804     else {
2805         /* Similarly for utf8.  For invariants can check directly; for other
2806          * Latin1, can calculate their code point and check; otherwise  use an
2807          * inversion list */
2808         if (UTF8_IS_INVARIANT(*s)) {
2809             if (! isALPHAU(*s)) {
2810                 goto bad_charname;
2811             }
2812             s++;
2813         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2814             if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2815                 goto bad_charname;
2816             }
2817             s += 2;
2818         }
2819         else {
2820             if (! _invlist_contains_cp(PL_utf8_charname_begin,
2821                                        utf8_to_uvchr_buf((U8 *) s,
2822                                                          (U8 *) e,
2823                                                          NULL)))
2824             {
2825                 goto bad_charname;
2826             }
2827             s += UTF8SKIP(s);
2828         }
2829
2830         while (s < e) {
2831             if (UTF8_IS_INVARIANT(*s)) {
2832                 if (! isCHARNAME_CONT(*s)) {
2833                     goto bad_charname;
2834                 }
2835                 if (*s == ' ' && *(s-1) == ' ') {
2836                     goto multi_spaces;
2837                 }
2838                 s++;
2839             }
2840             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2841                 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2842                 {
2843                     goto bad_charname;
2844                 }
2845                 s += 2;
2846             }
2847             else {
2848                 if (! _invlist_contains_cp(PL_utf8_charname_continue,
2849                                            utf8_to_uvchr_buf((U8 *) s,
2850                                                              (U8 *) e,
2851                                                              NULL)))
2852                 {
2853                     goto bad_charname;
2854                 }
2855                 s += UTF8SKIP(s);
2856             }
2857         }
2858     }
2859     if (*(s-1) == ' ') {
2860         /* diag_listed_as: charnames alias definitions may not contain
2861                            trailing white-space; marked by <-- HERE in %s
2862          */
2863         *error_msg = Perl_form(aTHX_
2864             "charnames alias definitions may not contain trailing "
2865             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2866             (int)(s - context + 1), context,
2867             (int)(e - s + 1), s + 1);
2868         return NULL;
2869     }
2870
2871     if (SvUTF8(res)) { /* Don't accept malformed charname value */
2872         const U8* first_bad_char_loc;
2873         STRLEN len;
2874         const char* const str = SvPV_const(res, len);
2875         if (UNLIKELY(! is_utf8_string_loc((U8 *) str, len,
2876                                           &first_bad_char_loc)))
2877         {
2878             _force_out_malformed_utf8_message(first_bad_char_loc,
2879                                               (U8 *) PL_parser->bufend,
2880                                               0,
2881                                               0 /* 0 means don't die */ );
2882             /* diag_listed_as: Malformed UTF-8 returned by \N{%s}
2883                                immediately after '%s' */
2884             *error_msg = Perl_form(aTHX_
2885                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2886                  (int) context_len, context,
2887                  (int) ((char *) first_bad_char_loc - str), str);
2888             return NULL;
2889         }
2890     }
2891
2892     return res;
2893
2894   bad_charname: {
2895
2896         /* The final %.*s makes sure that should the trailing NUL be missing
2897          * that this print won't run off the end of the string */
2898         /* diag_listed_as: Invalid character in \N{...}; marked by <-- HERE
2899                            in \N{%s} */
2900         *error_msg = Perl_form(aTHX_
2901             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2902             (int)(s - context + 1), context,
2903             (int)(e - s + 1), s + 1);
2904         return NULL;
2905     }
2906
2907   multi_spaces:
2908         /* diag_listed_as: charnames alias definitions may not contain a
2909                            sequence of multiple spaces; marked by <-- HERE
2910                            in %s */
2911         *error_msg = Perl_form(aTHX_
2912             "charnames alias definitions may not contain a sequence of "
2913             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2914             (int)(s - context + 1), context,
2915             (int)(e - s + 1), s + 1);
2916         return NULL;
2917 }
2918
2919 /*
2920   scan_const
2921
2922   Extracts the next constant part of a pattern, double-quoted string,
2923   or transliteration.  This is terrifying code.
2924
2925   For example, in parsing the double-quoted string "ab\x63$d", it would
2926   stop at the '$' and return an OP_CONST containing 'abc'.
2927
2928   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2929   processing a pattern (PL_lex_inpat is true), a transliteration
2930   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2931
2932   Returns a pointer to the character scanned up to. If this is
2933   advanced from the start pointer supplied (i.e. if anything was
2934   successfully parsed), will leave an OP_CONST for the substring scanned
2935   in pl_yylval. Caller must intuit reason for not parsing further
2936   by looking at the next characters herself.
2937
2938   In patterns:
2939     expand:
2940       \N{FOO}  => \N{U+hex_for_character_FOO}
2941       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2942
2943     pass through:
2944         all other \-char, including \N and \N{ apart from \N{ABC}
2945
2946     stops on:
2947         @ and $ where it appears to be a var, but not for $ as tail anchor
2948         \l \L \u \U \Q \E
2949         (?{  or  (??{
2950
2951   In transliterations:
2952     characters are VERY literal, except for - not at the start or end
2953     of the string, which indicates a range.  However some backslash sequences
2954     are recognized: \r, \n, and the like
2955                     \007 \o{}, \x{}, \N{}
2956     If all elements in the transliteration are below 256,
2957     scan_const expands the range to the full set of intermediate
2958     characters. If the range is in utf8, the hyphen is replaced with
2959     a certain range mark which will be handled by pmtrans() in op.c.
2960
2961   In double-quoted strings:
2962     backslashes:
2963       all those recognized in transliterations
2964       deprecated backrefs: \1 (in substitution replacements)
2965       case and quoting: \U \Q \E
2966     stops on @ and $
2967
2968   scan_const does *not* construct ops to handle interpolated strings.
2969   It stops processing as soon as it finds an embedded $ or @ variable
2970   and leaves it to the caller to work out what's going on.
2971
2972   embedded arrays (whether in pattern or not) could be:
2973       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2974
2975   $ in double-quoted strings must be the symbol of an embedded scalar.
2976
2977   $ in pattern could be $foo or could be tail anchor.  Assumption:
2978   it's a tail anchor if $ is the last thing in the string, or if it's
2979   followed by one of "()| \r\n\t"
2980
2981   \1 (backreferences) are turned into $1 in substitutions
2982
2983   The structure of the code is
2984       while (there's a character to process) {
2985           handle transliteration ranges
2986           skip regexp comments /(?#comment)/ and codes /(?{code})/
2987           skip #-initiated comments in //x patterns
2988           check for embedded arrays
2989           check for embedded scalars
2990           if (backslash) {
2991               deprecate \1 in substitution replacements
2992               handle string-changing backslashes \l \U \Q \E, etc.
2993               switch (what was escaped) {
2994                   handle \- in a transliteration (becomes a literal -)
2995                   if a pattern and not \N{, go treat as regular character
2996                   handle \132 (octal characters)
2997                   handle \x15 and \x{1234} (hex characters)
2998                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2999                   handle \cV (control characters)
3000                   handle printf-style backslashes (\f, \r, \n, etc)
3001               } (end switch)
3002               continue
3003           } (end if backslash)
3004           handle regular character
3005     } (end while character to read)
3006
3007 */
3008
3009 STATIC char *
3010 S_scan_const(pTHX_ char *start)
3011 {
3012     char *send = PL_bufend;             /* end of the constant */
3013     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
3014                                            on sizing. */
3015     char *s = start;                    /* start of the constant */
3016     char *d = SvPVX(sv);                /* destination for copies */
3017     bool dorange = FALSE;               /* are we in a translit range? */
3018     bool didrange = FALSE;              /* did we just finish a range? */
3019     bool in_charclass = FALSE;          /* within /[...]/ */
3020     bool s_is_utf8 = cBOOL(UTF);        /* Is the source string assumed to be
3021                                            UTF8?  But, this can show as true
3022                                            when the source isn't utf8, as for
3023                                            example when it is entirely composed
3024                                            of hex constants */
3025     bool d_is_utf8 = FALSE;             /* Output constant is UTF8 */
3026     STRLEN utf8_variant_count = 0;      /* When not in UTF-8, this counts the
3027                                            number of characters found so far
3028                                            that will expand (into 2 bytes)
3029                                            should we have to convert to
3030                                            UTF-8) */
3031     SV *res;                            /* result from charnames */
3032     STRLEN offset_to_max = 0;   /* The offset in the output to where the range
3033                                    high-end character is temporarily placed */
3034
3035     /* Does something require special handling in tr/// ?  This avoids extra
3036      * work in a less likely case.  As such, khw didn't feel it was worth
3037      * adding any branches to the more mainline code to handle this, which
3038      * means that this doesn't get set in some circumstances when things like
3039      * \x{100} get expanded out.  As a result there needs to be extra testing
3040      * done in the tr code */
3041     bool has_above_latin1 = FALSE;
3042
3043     /* Note on sizing:  The scanned constant is placed into sv, which is
3044      * initialized by newSV() assuming one byte of output for every byte of
3045      * input.  This routine expects newSV() to allocate an extra byte for a
3046      * trailing NUL, which this routine will append if it gets to the end of
3047      * the input.  There may be more bytes of input than output (eg., \N{LATIN
3048      * CAPITAL LETTER A}), or more output than input if the constant ends up
3049      * recoded to utf8, but each time a construct is found that might increase
3050      * the needed size, SvGROW() is called.  Its size parameter each time is
3051      * based on the best guess estimate at the time, namely the length used so
3052      * far, plus the length the current construct will occupy, plus room for
3053      * the trailing NUL, plus one byte for every input byte still unscanned */
3054
3055     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
3056                        before set */
3057 #ifdef EBCDIC
3058     int backslash_N = 0;            /* ? was the character from \N{} */
3059     int non_portable_endpoint = 0;  /* ? In a range is an endpoint
3060                                        platform-specific like \x65 */
3061 #endif
3062
3063     PERL_ARGS_ASSERT_SCAN_CONST;
3064
3065     assert(PL_lex_inwhat != OP_TRANSR);
3066
3067     /* Protect sv from errors and fatal warnings. */
3068     ENTER_with_name("scan_const");
3069     SAVEFREESV(sv);
3070
3071     /* A bunch of code in the loop below assumes that if s[n] exists and is not
3072      * NUL, then s[n+1] exists.  This assertion makes sure that assumption is
3073      * valid */
3074     assert(*send == '\0');
3075
3076     while (s < send
3077            || dorange   /* Handle tr/// range at right edge of input */
3078     ) {
3079
3080         /* get transliterations out of the way (they're most literal) */
3081         if (PL_lex_inwhat == OP_TRANS) {
3082
3083             /* But there isn't any special handling necessary unless there is a
3084              * range, so for most cases we just drop down and handle the value
3085              * as any other.  There are two exceptions.
3086              *
3087              * 1.  A hyphen indicates that we are actually going to have a
3088              *     range.  In this case, skip the '-', set a flag, then drop
3089              *     down to handle what should be the end range value.
3090              * 2.  After we've handled that value, the next time through, that
3091              *     flag is set and we fix up the range.
3092              *
3093              * Ranges entirely within Latin1 are expanded out entirely, in
3094              * order to make the transliteration a simple table look-up.
3095              * Ranges that extend above Latin1 have to be done differently, so
3096              * there is no advantage to expanding them here, so they are
3097              * stored here as Min, RANGE_INDICATOR, Max.  'RANGE_INDICATOR' is
3098              * a byte that can't occur in legal UTF-8, and hence can signify a
3099              * hyphen without any possible ambiguity.  On EBCDIC machines, if
3100              * the range is expressed as Unicode, the Latin1 portion is
3101              * expanded out even if the range extends above Latin1.  This is
3102              * because each code point in it has to be processed here
3103              * individually to get its native translation */
3104
3105             if (! dorange) {
3106
3107                 /* Here, we don't think we're in a range.  If the new character
3108                  * is not a hyphen; or if it is a hyphen, but it's too close to
3109                  * either edge to indicate a range, or if we haven't output any
3110                  * characters yet then it's a regular character. */
3111                 if (*s != '-' || s >= send - 1 || s == start || d == SvPVX(sv))
3112                 {
3113
3114                     /* A regular character.  Process like any other, but first
3115                      * clear any flags */
3116                     didrange = FALSE;
3117                     dorange = FALSE;
3118 #ifdef EBCDIC
3119                     non_portable_endpoint = 0;
3120                     backslash_N = 0;
3121 #endif
3122                     /* The tests here for being above Latin1 and similar ones
3123                      * in the following 'else' suffice to find all such
3124                      * occurences in the constant, except those added by a
3125                      * backslash escape sequence, like \x{100}.  Mostly, those
3126                      * set 'has_above_latin1' as appropriate */
3127                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3128                         has_above_latin1 = TRUE;
3129                     }
3130
3131                     /* Drops down to generic code to process current byte */
3132                 }
3133                 else {  /* Is a '-' in the context where it means a range */
3134                     if (didrange) { /* Something like y/A-C-Z// */
3135                         Perl_croak(aTHX_ "Ambiguous range in transliteration"
3136                                          " operator");
3137                     }
3138
3139                     dorange = TRUE;
3140
3141                     s++;    /* Skip past the hyphen */
3142
3143                     /* d now points to where the end-range character will be
3144                      * placed.  Drop down to get that character.  We'll finish
3145                      * processing the range the next time through the loop */
3146
3147                     if (s_is_utf8 && UTF8_IS_ABOVE_LATIN1(*s)) {
3148                         has_above_latin1 = TRUE;
3149                     }
3150
3151                     /* Drops down to generic code to process current byte */
3152                 }
3153             }  /* End of not a range */
3154             else {
3155                 /* Here we have parsed a range.  Now must handle it.  At this
3156                  * point:
3157                  * 'sv' is a SV* that contains the output string we are
3158                  *      constructing.  The final two characters in that string
3159                  *      are the range start and range end, in order.
3160                  * 'd'  points to just beyond the range end in the 'sv' string,
3161                  *      where we would next place something
3162                  */
3163                 char * max_ptr;
3164                 char * min_ptr;
3165                 IV range_min;
3166                 IV range_max;   /* last character in range */
3167                 STRLEN grow;
3168                 Size_t offset_to_min = 0;
3169                 Size_t extras = 0;
3170 #ifdef EBCDIC
3171                 bool convert_unicode;
3172                 IV real_range_max = 0;
3173 #endif
3174                 /* Get the code point values of the range ends. */
3175                 max_ptr = (d_is_utf8) ? (char *) utf8_hop( (U8*) d, -1) : d - 1;
3176                 offset_to_max = max_ptr - SvPVX_const(sv);
3177                 if (d_is_utf8) {
3178                     /* We know the utf8 is valid, because we just constructed
3179                      * it ourselves in previous loop iterations */
3180                     min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
3181                     range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
3182                     range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
3183
3184                     /* This compensates for not all code setting
3185                      * 'has_above_latin1', so that we don't skip stuff that
3186                      * should be executed */
3187                     if (range_max > 255) {
3188                         has_above_latin1 = TRUE;
3189                     }
3190                 }
3191                 else {
3192                     min_ptr = max_ptr - 1;
3193                     range_min = * (U8*) min_ptr;
3194                     range_max = * (U8*) max_ptr;
3195                 }
3196
3197                 /* If the range is just a single code point, like tr/a-a/.../,
3198                  * that code point is already in the output, twice.  We can
3199                  * just back up over the second instance and avoid all the rest
3200                  * of the work.  But if it is a variant character, it's been
3201                  * counted twice, so decrement.  (This unlikely scenario is
3202                  * special cased, like the one for a range of 2 code points
3203                  * below, only because the main-line code below needs a range
3204                  * of 3 or more to work without special casing.  Might as well
3205                  * get it out of the way now.) */
3206                 if (UNLIKELY(range_max == range_min)) {
3207                     d = max_ptr;
3208                     if (! d_is_utf8 && ! UVCHR_IS_INVARIANT(range_max)) {
3209                         utf8_variant_count--;
3210                     }
3211                     goto range_done;
3212                 }
3213
3214 #ifdef EBCDIC
3215                 /* On EBCDIC platforms, we may have to deal with portable
3216                  * ranges.  These happen if at least one range endpoint is a
3217                  * Unicode value (\N{...}), or if the range is a subset of
3218                  * [A-Z] or [a-z], and both ends are literal characters,
3219                  * like 'A', and not like \x{C1} */
3220                 convert_unicode =
3221                                cBOOL(backslash_N)   /* \N{} forces Unicode,
3222                                                        hence portable range */
3223                     || (     ! non_portable_endpoint
3224                         && ((  isLOWER_A(range_min) && isLOWER_A(range_max))
3225                            || (isUPPER_A(range_min) && isUPPER_A(range_max))));
3226                 if (convert_unicode) {
3227
3228                     /* Special handling is needed for these portable ranges.
3229                      * They are defined to be in Unicode terms, which includes
3230                      * all the Unicode code points between the end points.
3231                      * Convert to Unicode to get the Unicode range.  Later we
3232                      * will convert each code point in the range back to
3233                      * native.  */
3234                     range_min = NATIVE_TO_UNI(range_min);
3235                     range_max = NATIVE_TO_UNI(range_max);
3236                 }
3237 #endif
3238
3239                 if (range_min > range_max) {
3240 #ifdef EBCDIC
3241                     if (convert_unicode) {
3242                         /* Need to convert back to native for meaningful
3243                          * messages for this platform */
3244                         range_min = UNI_TO_NATIVE(range_min);
3245                         range_max = UNI_TO_NATIVE(range_max);
3246                     }
3247 #endif
3248                     /* Use the characters themselves for the error message if
3249                      * ASCII printables; otherwise some visible representation
3250                      * of them */
3251                     if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3252                         Perl_croak(aTHX_
3253                          "Invalid range \"%c-%c\" in transliteration operator",
3254                          (char)range_min, (char)range_max);
3255                     }
3256 #ifdef EBCDIC
3257                     else if (convert_unicode) {
3258         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3259                         Perl_croak(aTHX_
3260                            "Invalid range \"\\N{U+%04" UVXf "}-\\N{U+%04"
3261                            UVXf "}\" in transliteration operator",
3262                            range_min, range_max);
3263                     }
3264 #endif
3265                     else {
3266         /* diag_listed_as: Invalid range "%s" in transliteration operator */
3267                         Perl_croak(aTHX_
3268                            "Invalid range \"\\x{%04" UVXf "}-\\x{%04" UVXf "}\""
3269                            " in transliteration operator",
3270                            range_min, range_max);
3271                     }
3272                 }
3273
3274                 /* If the range is exactly two code points long, they are
3275                  * already both in the output */
3276                 if (UNLIKELY(range_min + 1 == range_max)) {
3277                     goto range_done;
3278                 }
3279
3280                 /* Here the range contains at least 3 code points */
3281
3282                 if (d_is_utf8) {
3283
3284                     /* If everything in the transliteration is below 256, we
3285                      * can avoid special handling later.  A translation table
3286                      * for each of those bytes is created by op.c.  So we
3287                      * expand out all ranges to their constituent code points.
3288                      * But if we've encountered something above 255, the
3289                      * expanding won't help, so skip doing that.  But if it's
3290                      * EBCDIC, we may have to look at each character below 256
3291                      * if we have to convert to/from Unicode values */
3292                     if (   has_above_latin1
3293 #ifdef EBCDIC
3294                         && (range_min > 255 || ! convert_unicode)
3295 #endif
3296                     ) {
3297                         const STRLEN off = d - SvPVX(sv);
3298                         const STRLEN extra = 1 + (send - s) + 1;
3299                         char *e;
3300
3301                         /* Move the high character one byte to the right; then
3302                          * insert between it and the range begin, an illegal
3303                          * byte which serves to indicate this is a range (using
3304                          * a '-' would be ambiguous). */
3305
3306                         if (off + extra > SvLEN(sv)) {
3307                             d = off + SvGROW(sv, off + extra);
3308                             max_ptr = d - off + offset_to_max;
3309                         }
3310
3311                         e = d++;
3312                         while (e-- > max_ptr) {
3313                             *(e + 1) = *e;
3314                         }
3315                         *(e + 1) = (char) RANGE_INDICATOR;
3316                         goto range_done;
3317                     }
3318
3319                     /* Here, we're going to expand out the range.  For EBCDIC
3320                      * the range can extend above 255 (not so in ASCII), so
3321                      * for EBCDIC, split it into the parts above and below
3322                      * 255/256 */
3323 #ifdef EBCDIC
3324                     if (range_max > 255) {
3325                         real_range_max = range_max;
3326                         range_max = 255;
3327                     }
3328 #endif
3329                 }
3330
3331                 /* Here we need to expand out the string to contain each
3332                  * character in the range.  Grow the output to handle this.
3333                  * For non-UTF8, we need a byte for each code point in the
3334                  * range, minus the three that we've already allocated for: the
3335                  * hyphen, the min, and the max.  For UTF-8, we need this
3336                  * plus an extra byte for each code point that occupies two
3337                  * bytes (is variant) when in UTF-8 (except we've already
3338                  * allocated for the end points, including if they are
3339                  * variants).  For ASCII platforms and Unicode ranges on EBCDIC
3340                  * platforms, it's easy to calculate a precise number.  To
3341                  * start, we count the variants in the range, which we need
3342                  * elsewhere in this function anyway.  (For the case where it
3343                  * isn't easy to calculate, 'extras' has been initialized to 0,
3344                  * and the calculation is done in a loop further down.) */
3345 #ifdef EBCDIC
3346                 if (convert_unicode)
3347 #endif
3348                 {
3349                     /* This is executed unconditionally on ASCII, and for
3350                      * Unicode ranges on EBCDIC.  Under these conditions, all
3351                      * code points above a certain value are variant; and none
3352                      * under that value are.  We just need to find out how much
3353                      * of the range is above that value.  We don't count the
3354                      * end points here, as they will already have been counted
3355                      * as they were parsed. */
3356                     if (range_min >= UTF_CONTINUATION_MARK) {
3357
3358                         /* The whole range is made up of variants */
3359                         extras = (range_max - 1) - (range_min + 1) + 1;
3360                     }
3361                     else if (range_max >= UTF_CONTINUATION_MARK) {
3362
3363                         /* Only the higher portion of the range is variants */
3364                         extras = (range_max - 1) - UTF_CONTINUATION_MARK + 1;
3365                     }
3366
3367                     utf8_variant_count += extras;
3368                 }
3369
3370                 /* The base growth is the number of code points in the range,
3371                  * not including the endpoints, which have already been sized
3372                  * for (and output).  We don't subtract for the hyphen, as it
3373                  * has been parsed but not output, and the SvGROW below is
3374                  * based only on what's been output plus what's left to parse.
3375                  * */
3376                 grow = (range_max - 1) - (range_min + 1) + 1;
3377
3378                 if (d_is_utf8) {
3379 #ifdef EBCDIC
3380                     /* In some cases in EBCDIC, we haven't yet calculated a
3381                      * precise amount needed for the UTF-8 variants.  Just
3382                      * assume the worst case, that everything will expand by a
3383                      * byte */
3384                     if (! convert_unicode) {
3385                         grow *= 2;
3386                     }
3387                     else
3388 #endif
3389                     {
3390                         /* Otherwise we know exactly how many variants there
3391                          * are in the range. */
3392                         grow += extras;
3393                     }
3394                 }
3395
3396                 /* Grow, but position the output to overwrite the range min end
3397                  * point, because in some cases we overwrite that */
3398                 SvCUR_set(sv, d - SvPVX_const(sv));
3399                 offset_to_min = min_ptr - SvPVX_const(sv);
3400
3401                 /* See Note on sizing above. */
3402                 d = offset_to_min + SvGROW(sv, SvCUR(sv)
3403                                              + (send - s)
3404                                              + grow
3405                                              + 1 /* Trailing NUL */ );
3406
3407                 /* Now, we can expand out the range. */
3408 #ifdef EBCDIC
3409                 if (convert_unicode) {
3410                     SSize_t i;
3411
3412                     /* Recall that the min and max are now in Unicode terms, so
3413                      * we have to convert each character to its native
3414                      * equivalent */
3415                     if (d_is_utf8) {
3416                         for (i = range_min; i <= range_max; i++) {
3417                             append_utf8_from_native_byte(
3418                                                     LATIN1_TO_NATIVE((U8) i),
3419                                                     (U8 **) &d);
3420                         }
3421                     }
3422                     else {
3423                         for (i = range_min; i <= range_max; i++) {
3424                             *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3425                         }
3426                     }
3427                 }
3428                 else
3429 #endif
3430                 /* Always gets run for ASCII, and sometimes for EBCDIC. */
3431                 {
3432                     /* Here, no conversions are necessary, which means that the
3433                      * first character in the range is already in 'd' and
3434                      * valid, so we can skip overwriting it */
3435                     if (d_is_utf8) {
3436                         SSize_t i;
3437                         d += UTF8SKIP(d);
3438                         for (i = range_min + 1; i <= range_max; i++) {
3439                             append_utf8_from_native_byte((U8) i, (U8 **) &d);
3440                         }
3441                     }
3442                     else {
3443                         SSize_t i;
3444                         d++;
3445                         assert(range_min + 1 <= range_max);
3446                         for (i = range_min + 1; i < range_max; i++) {
3447 #ifdef EBCDIC
3448                             /* In this case on EBCDIC, we haven't calculated
3449                              * the variants.  Do it here, as we go along */
3450                             if (! UVCHR_IS_INVARIANT(i)) {
3451                                 utf8_variant_count++;
3452                             }
3453 #endif
3454                             *d++ = (char)i;
3455                         }
3456
3457                         /* The range_max is done outside the loop so as to
3458                          * avoid having to special case not incrementing
3459                          * 'utf8_variant_count' on EBCDIC (it's already been
3460                          * counted when originally parsed) */
3461                         *d++ = (char) range_max;
3462                     }
3463                 }
3464
3465 #ifdef EBCDIC
3466                 /* If the original range extended above 255, add in that
3467                  * portion. */
3468                 if (real_range_max) {
3469                     *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3470                     *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3471                     if (real_range_max > 0x100) {
3472                         if (real_range_max > 0x101) {
3473                             *d++ = (char) RANGE_INDICATOR;
3474                         }
3475                         d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3476                     }
3477                 }
3478 #endif
3479
3480               range_done:
3481                 /* mark the range as done, and continue */
3482                 didrange = TRUE;
3483                 dorange = FALSE;
3484 #ifdef EBCDIC
3485                 non_portable_endpoint = 0;
3486                 backslash_N = 0;
3487 #endif
3488                 continue;
3489             } /* End of is a range */
3490         } /* End of transliteration.  Joins main code after these else's */
3491         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3492             char *s1 = s-1;
3493             int esc = 0;
3494             while (s1 >= start && *s1-- == '\\')
3495                 esc = !esc;
3496             if (!esc)
3497                 in_charclass = TRUE;
3498         }
3499         else if (*s == ']' && PL_lex_inpat && in_charclass) {
3500             char *s1 = s-1;
3501             int esc = 0;
3502             while (s1 >= start && *s1-- == '\\')
3503                 esc = !esc;
3504             if (!esc)
3505                 in_charclass = FALSE;
3506         }
3507             /* skip for regexp comments /(?#comment)/, except for the last
3508              * char, which will be done separately.  Stop on (?{..}) and
3509              * friends */
3510         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3511             if (s[2] == '#') {
3512                 if (s_is_utf8) {
3513                     PERL_UINT_FAST8_T  len = UTF8SKIP(s);
3514
3515                     while (s + len < send && *s != ')') {
3516                         Copy(s, d, len, U8);
3517                         d += len;
3518                         s += len;
3519                         len = UTF8_SAFE_SKIP(s, send);
3520                     }
3521                 }
3522                 else while (s+1 < send && *s != ')') {
3523                     *d++ = *s++;
3524                 }
3525             }
3526             else if (!PL_lex_casemods
3527                      && (    s[2] == '{' /* This should match regcomp.c */
3528                          || (s[2] == '?' && s[3] == '{')))
3529             {
3530                 break;
3531             }
3532         }
3533             /* likewise skip #-initiated comments in //x patterns */
3534         else if (*s == '#'
3535                  && PL_lex_inpat
3536                  && !in_charclass
3537                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3538         {
3539             while (s < send && *s != '\n')
3540                 *d++ = *s++;
3541         }
3542             /* no further processing of single-quoted regex */
3543         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3544             goto default_action;
3545
3546             /* check for embedded arrays
3547              * (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3548              */
3549         else if (*s == '@' && s[1]) {
3550             if (UTF
3551                ? isIDFIRST_utf8_safe(s+1, send)
3552                : isWORDCHAR_A(s[1]))
3553             {
3554                 break;
3555             }
3556             if (memCHRs(":'{$", s[1]))
3557                 break;
3558             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3559                 break; /* in regexp, neither @+ nor @- are interpolated */
3560         }
3561             /* check for embedded scalars.  only stop if we're sure it's a
3562              * variable.  */
3563         else if (*s == '$') {
3564             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3565                 break;
3566             if (s + 1 < send && !memCHRs("()| \r\n\t", s[1])) {
3567                 if (s[1] == '\\') {
3568                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3569                                    "Possible unintended interpolation of $\\ in regex");
3570                 }
3571                 break;          /* in regexp, $ might be tail anchor */
3572             }
3573         }
3574
3575         /* End of else if chain - OP_TRANS rejoin rest */
3576
3577         if (UNLIKELY(s >= send)) {
3578             assert(s == send);
3579             break;
3580         }
3581
3582         /* backslashes */
3583         if (*s == '\\' && s+1 < send) {
3584             char* e;    /* Can be used for ending '}', etc. */
3585
3586             s++;
3587
3588             /* warn on \1 - \9 in substitution replacements, but note that \11
3589              * is an octal; and \19 is \1 followed by '9' */
3590             if (PL_lex_inwhat == OP_SUBST
3591                 && !PL_lex_inpat
3592                 && isDIGIT(*s)
3593                 && *s != '0'
3594                 && !isDIGIT(s[1]))
3595             {
3596                 /* diag_listed_as: \%d better written as $%d */
3597                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3598                 *--s = '$';
3599                 break;
3600             }
3601
3602             /* string-change backslash escapes */
3603             if (PL_lex_inwhat != OP_TRANS && *s && memCHRs("lLuUEQF", *s)) {
3604                 --s;
3605                 break;
3606             }
3607             /* In a pattern, process \N, but skip any other backslash escapes.
3608              * This is because we don't want to translate an escape sequence
3609              * into a meta symbol and have the regex compiler use the meta
3610              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3611              * in spite of this, we do have to process \N here while the proper
3612              * charnames handler is in scope.  See bugs #56444 and #62056.
3613              *
3614              * There is a complication because \N in a pattern may also stand
3615              * for 'match a non-nl', and not mean a charname, in which case its
3616              * processing should be deferred to the regex compiler.  To be a
3617              * charname it must be followed immediately by a '{', and not look
3618              * like \N followed by a curly quantifier, i.e., not something like
3619              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3620              * quantifier */
3621             else if (PL_lex_inpat
3622                     && (*s != 'N'
3623                         || s[1] != '{'
3624                         || regcurly(s + 1)))
3625             {
3626                 *d++ = '\\';
3627                 goto default_action;
3628             }
3629
3630             switch (*s) {
3631             default:
3632                 {
3633                     if ((isALPHANUMERIC(*s)))
3634                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3635                                        "Unrecognized escape \\%c passed through",
3636                                        *s);
3637                     /* default action is to copy the quoted character */
3638                     goto default_action;
3639                 }
3640
3641             /* eg. \132 indicates the octal constant 0132 */
3642             case '0': case '1': case '2': case '3':
3643             case '4': case '5': case '6': case '7':
3644                 {
3645                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT
3646                               | PERL_SCAN_NOTIFY_ILLDIGIT;
3647                     STRLEN len = 3;
3648                     uv = grok_oct(s, &len, &flags, NULL);
3649                     s += len;
3650                     if (  (flags & PERL_SCAN_NOTIFY_ILLDIGIT)
3651                         && s < send
3652                         && isDIGIT(*s)  /* like \08, \178 */
3653                         && ckWARN(WARN_MISC))
3654                     {
3655                         Perl_warner(aTHX_ packWARN(WARN_MISC), "%s",
3656                             form_alien_digit_msg(8, len, s, send, UTF, FALSE));
3657                     }
3658                 }
3659                 goto NUM_ESCAPE_INSERT;
3660
3661             /* eg. \o{24} indicates the octal constant \024 */
3662             case 'o':
3663                 {
3664                     const char* error;
3665
3666                     if (! grok_bslash_o(&s, send,
3667                                                &uv, &error,
3668                                                NULL,
3669                                                FALSE, /* Not strict */
3670                                                FALSE, /* No illegal cp's */
3671                                                UTF))
3672                     {
3673                         yyerror(error);
3674                         uv = 0; /* drop through to ensure range ends are set */
3675                     }
3676                     goto NUM_ESCAPE_INSERT;
3677                 }
3678
3679             /* eg. \x24 indicates the hex constant 0x24 */
3680             case 'x':
3681                 {
3682                     const char* error;
3683
3684                     if (! grok_bslash_x(&s, send,
3685                                                &uv, &error,
3686                                                NULL,
3687                                                FALSE, /* Not strict */
3688                                                FALSE, /* No illegal cp's */
3689                                                UTF))
3690                     {
3691                         yyerror(error);
3692                         uv = 0; /* drop through to ensure range ends are set */
3693                     }
3694                 }
3695
3696               NUM_ESCAPE_INSERT:
3697                 /* Insert oct or hex escaped character. */
3698
3699                 /* Here uv is the ordinal of the next character being added */
3700                 if (UVCHR_IS_INVARIANT(uv)) {
3701                     *d++ = (char) uv;
3702                 }
3703                 else {
3704                     if (!d_is_utf8 && uv > 255) {
3705
3706                         /* Here, 'uv' won't fit unless we convert to UTF-8.
3707                          * If we've only seen invariants so far, all we have to
3708                          * do is turn on the flag */
3709                         if (utf8_variant_count == 0) {
3710                             SvUTF8_on(sv);
3711                         }
3712                         else {
3713                             SvCUR_set(sv, d - SvPVX_const(sv));
3714                             SvPOK_on(sv);
3715                             *d = '\0';
3716
3717                             sv_utf8_upgrade_flags_grow(
3718                                            sv,
3719                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3720
3721                                            /* Since we're having to grow here,
3722                                             * make sure we have enough room for
3723                                             * this escape and a NUL, so the
3724                                             * code immediately below won't have
3725                                             * to actually grow again */
3726                                           UVCHR_SKIP(uv)
3727                                         + (STRLEN)(send - s) + 1);
3728                             d = SvPVX(sv) + SvCUR(sv);
3729                         }
3730
3731                         has_above_latin1 = TRUE;
3732                         d_is_utf8 = TRUE;
3733                     }
3734
3735                     if (! d_is_utf8) {
3736                         *d++ = (char)uv;
3737                         utf8_variant_count++;
3738                     }
3739                     else {
3740                        /* Usually, there will already be enough room in 'sv'
3741                         * since such escapes are likely longer than any UTF-8
3742                         * sequence they can end up as.  This isn't the case on
3743                         * EBCDIC where \x{40000000} contains 12 bytes, and the
3744                         * UTF-8 for it contains 14.  And, we have to allow for
3745                         * a trailing NUL.  It probably can't happen on ASCII
3746                         * platforms, but be safe.  See Note on sizing above. */
3747                         const STRLEN needed = d - SvPVX(sv)
3748                                             + UVCHR_SKIP(uv)
3749                                             + (send - s)
3750                                             + 1;
3751                         if (UNLIKELY(needed > SvLEN(sv))) {
3752                             SvCUR_set(sv, d - SvPVX_const(sv));
3753                             d = SvCUR(sv) + SvGROW(sv, needed);
3754                         }
3755
3756                         d = (char*) uvchr_to_utf8_flags((U8*)d, uv,
3757                                                    (ckWARN(WARN_PORTABLE))
3758                                                    ? UNICODE_WARN_PERL_EXTENDED
3759                                                    : 0);
3760                     }
3761                 }
3762 #ifdef EBCDIC
3763                 non_portable_endpoint++;
3764 #endif
3765                 continue;
3766
3767             case 'N':
3768                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3769                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3770                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3771                  * GRAVE} (except y/// can't handle the latter, croaking).  For
3772                  * convenience all three forms are referred to as "named
3773                  * characters" below.
3774                  *
3775                  * For patterns, \N also can mean to match a non-newline.  Code
3776                  * before this 'switch' statement should already have handled
3777                  * this situation, and hence this code only has to deal with
3778                  * the named character cases.
3779                  *
3780                  * For non-patterns, the named characters are converted to
3781                  * their string equivalents.  In patterns, named characters are
3782                  * not converted to their ultimate forms for the same reasons
3783                  * that other escapes aren't (mainly that the ultimate
3784                  * character could be considered a meta-symbol by the regex
3785                  * compiler).  Instead, they are converted to the \N{U+...}
3786                  * form to get the value from the charnames that is in effect
3787                  * right now, while preserving the fact that it was a named
3788                  * character, so that the regex compiler knows this.
3789                  *
3790                  * The structure of this section of code (besides checking for
3791                  * errors and upgrading to utf8) is:
3792                  *    If the named character is of the form \N{U+...}, pass it
3793                  *      through if a pattern; otherwise convert the code point
3794                  *      to utf8
3795                  *    Otherwise must be some \N{NAME}: convert to
3796                  *      \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3797                  *
3798                  * Transliteration is an exception.  The conversion to utf8 is
3799                  * only done if the code point requires it to be representable.
3800                  *
3801                  * Here, 's' points to the 'N'; the test below is guaranteed to
3802                  * succeed if we are being called on a pattern, as we already
3803                  * know from a test above that the next character is a '{'.  A
3804                  * non-pattern \N must mean 'named character', which requires
3805                  * braces */
3806                 s++;
3807                 if (*s != '{') {
3808                     yyerror("Missing braces on \\N{}");
3809                     *d++ = '\0';
3810                     continue;
3811                 }
3812                 s++;
3813
3814                 /* If there is no matching '}', it is an error. */
3815                 if (! (e = (char *) memchr(s, '}', send - s))) {
3816                     if (! PL_lex_inpat) {
3817                         yyerror("Missing right brace on \\N{}");
3818                     } else {
3819                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3820                     }
3821                     yyquit(); /* Have exhausted the input. */
3822                 }
3823
3824                 /* Here it looks like a named character */
3825
3826                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3827                     s += 2;         /* Skip to next char after the 'U+' */
3828                     if (PL_lex_inpat) {
3829
3830                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3831                         /* Check the syntax.  */
3832                         const char *orig_s;
3833                         orig_s = s - 5;
3834                         if (!isXDIGIT(*s)) {
3835                           bad_NU:
3836                             yyerror(
3837                                 "Invalid hexadecimal number in \\N{U+...}"
3838                             );
3839                             s = e + 1;
3840                             *d++ = '\0';
3841                             continue;
3842                         }
3843                         while (++s < e) {
3844                             if (isXDIGIT(*s))
3845                                 continue;
3846                             else if ((*s == '.' || *s == '_')
3847                                   && isXDIGIT(s[1]))
3848                                 continue;
3849                             goto bad_NU;
3850                         }
3851
3852                         /* Pass everything through unchanged.
3853                          * +1 is for the '}' */
3854                         Copy(orig_s, d, e - orig_s + 1, char);
3855                         d += e - orig_s + 1;
3856                     }
3857                     else {  /* Not a pattern: convert the hex to string */
3858                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3859                                   | PERL_SCAN_SILENT_ILLDIGIT
3860                                   | PERL_SCAN_SILENT_OVERFLOW
3861                                   | PERL_SCAN_DISALLOW_PREFIX;
3862                         STRLEN len = e - s;
3863
3864                         uv = grok_hex(s, &len, &flags, NULL);
3865                         if (len == 0 || (len != (STRLEN)(e - s)))
3866                             goto bad_NU;
3867
3868                         if (    uv > MAX_LEGAL_CP
3869                             || (flags & PERL_SCAN_GREATER_THAN_UV_MAX))
3870                         {
3871                             yyerror(form_cp_too_large_msg(16, s, len, 0));
3872                             uv = 0; /* drop through to ensure range ends are
3873                                        set */
3874                         }
3875
3876                          /* For non-tr///, if the destination is not in utf8,
3877                           * unconditionally recode it to be so.  This is
3878                           * because \N{} implies Unicode semantics, and scalars
3879                           * have to be in utf8 to guarantee those semantics.
3880                           * tr/// doesn't care about Unicode rules, so no need
3881                           * there to upgrade to UTF-8 for small enough code
3882                           * points */
3883                         if (! d_is_utf8 && (   uv > 0xFF
3884                                            || PL_lex_inwhat != OP_TRANS))
3885                         {
3886                             /* See Note on sizing above.  */
3887                             const STRLEN extra = OFFUNISKIP(uv) + (send - e) + 1;
3888
3889                             SvCUR_set(sv, d - SvPVX_const(sv));
3890                             SvPOK_on(sv);
3891                             *d = '\0';
3892
3893                             if (utf8_variant_count == 0) {
3894                                 SvUTF8_on(sv);
3895                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
3896                             }
3897                             else {
3898                                 sv_utf8_upgrade_flags_grow(
3899                                                sv,
3900                                                SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3901                                                extra);
3902                                 d = SvPVX(sv) + SvCUR(sv);
3903                             }
3904
3905                             d_is_utf8 = TRUE;
3906                             has_above_latin1 = TRUE;
3907                         }
3908
3909                         /* Add the (Unicode) code point to the output. */
3910                         if (! d_is_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3911                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3912                         }
3913                         else {
3914                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv,
3915                                                    (ckWARN(WARN_PORTABLE))
3916                                                    ? UNICODE_WARN_PERL_EXTENDED
3917                                                    : 0);
3918                         }
3919                     }
3920                 }
3921                 else /* Here is \N{NAME} but not \N{U+...}. */
3922                      if (! (res = get_and_check_backslash_N_name_wrapper(s, e)))
3923                 {   /* Failed.  We should die eventually, but for now use a NUL
3924                        to keep parsing */
3925                     *d++ = '\0';
3926                 }
3927                 else {  /* Successfully evaluated the name */
3928                     STRLEN len;
3929                     const char *str = SvPV_const(res, len);
3930                     if (PL_lex_inpat) {
3931
3932                         if (! len) { /* The name resolved to an empty string */
3933                             const char empty_N[] = "\\N{_}";
3934                             Copy(empty_N, d, sizeof(empty_N) - 1, char);
3935                             d += sizeof(empty_N) - 1;
3936                         }
3937                         else {
3938                             /* In order to not lose information for the regex
3939                             * compiler, pass the result in the specially made
3940                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3941                             * the code points in hex of each character
3942                             * returned by charnames */
3943
3944                             const char *str_end = str + len;
3945                             const STRLEN off = d - SvPVX_const(sv);
3946
3947                             if (! SvUTF8(res)) {
3948                                 /* For the non-UTF-8 case, we can determine the
3949                                  * exact length needed without having to parse
3950                                  * through the string.  Each character takes up
3951                                  * 2 hex digits plus either a trailing dot or
3952                                  * the "}" */
3953                                 const char initial_text[] = "\\N{U+";
3954                                 const STRLEN initial_len = sizeof(initial_text)
3955                                                            - 1;
3956                                 d = off + SvGROW(sv, off
3957                                                     + 3 * len
3958
3959                                                     /* +1 for trailing NUL */
3960                                                     + initial_len + 1
3961
3962                                                     + (STRLEN)(send - e));
3963                                 Copy(initial_text, d, initial_len, char);
3964                                 d += initial_len;
3965                                 while (str < str_end) {
3966                                     char hex_string[4];
3967                                     int len =
3968                                         my_snprintf(hex_string,
3969                                                   sizeof(hex_string),
3970                                                   "%02X.",
3971
3972                                                   /* The regex compiler is
3973                                                    * expecting Unicode, not
3974                                                    * native */
3975                                                   NATIVE_TO_LATIN1(*str));
3976                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3977                                                            sizeof(hex_string));
3978                                     Copy(hex_string, d, 3, char);
3979                                     d += 3;
3980                                     str++;
3981                                 }
3982                                 d--;    /* Below, we will overwrite the final
3983                                            dot with a right brace */
3984                             }
3985                             else {
3986                                 STRLEN char_length; /* cur char's byte length */
3987
3988                                 /* and the number of bytes after this is
3989                                  * translated into hex digits */
3990                                 STRLEN output_length;
3991
3992                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3993                                  * for max('U+', '.'); and 1 for NUL */
3994                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3995
3996                                 /* Get the first character of the result. */
3997                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3998                                                         len,
3999                                                         &char_length,
4000                                                         UTF8_ALLOW_ANYUV);
4001                                 /* Convert first code point to Unicode hex,
4002                                  * including the boiler plate before it. */
4003                                 output_length =
4004                                     my_snprintf(hex_string, sizeof(hex_string),
4005                                              "\\N{U+%X",
4006                                              (unsigned int) NATIVE_TO_UNI(uv));
4007
4008                                 /* Make sure there is enough space to hold it */
4009                                 d = off + SvGROW(sv, off
4010                                                     + output_length
4011                                                     + (STRLEN)(send - e)
4012                                                     + 2);       /* '}' + NUL */
4013                                 /* And output it */
4014                                 Copy(hex_string, d, output_length, char);
4015                                 d += output_length;
4016
4017                                 /* For each subsequent character, append dot and
4018                                 * its Unicode code point in hex */
4019                                 while ((str += char_length) < str_end) {
4020                                     const STRLEN off = d - SvPVX_const(sv);
4021                                     U32 uv = utf8n_to_uvchr((U8 *) str,
4022                                                             str_end - str,
4023                                                             &char_length,
4024                                                             UTF8_ALLOW_ANYUV);
4025                                     output_length =
4026                                         my_snprintf(hex_string,
4027                                              sizeof(hex_string),
4028                                              ".%X",
4029                                              (unsigned int) NATIVE_TO_UNI(uv));
4030
4031                                     d = off + SvGROW(sv, off
4032                                                         + output_length
4033                                                         + (STRLEN)(send - e)
4034                                                         + 2);   /* '}' +  NUL */
4035                                     Copy(hex_string, d, output_length, char);
4036                                     d += output_length;
4037                                 }
4038                             }
4039
4040                             *d++ = '}'; /* Done.  Add the trailing brace */
4041                         }
4042                     }
4043                     else { /* Here, not in a pattern.  Convert the name to a
4044                             * string. */
4045
4046                         if (PL_lex_inwhat == OP_TRANS) {
4047                             str = SvPV_const(res, len);
4048                             if (len > ((SvUTF8(res))
4049                                        ? UTF8SKIP(str)
4050                                        : 1U))
4051                             {
4052                                 yyerror(Perl_form(aTHX_
4053                                     "%.*s must not be a named sequence"
4054                                     " in transliteration operator",
4055                                         /*  +1 to include the "}" */
4056                                     (int) (e + 1 - start), start));
4057                                 *d++ = '\0';
4058                                 goto end_backslash_N;
4059                             }
4060
4061                             if (SvUTF8(res) && UTF8_IS_ABOVE_LATIN1(*str)) {
4062                                 has_above_latin1 = TRUE;
4063                             }
4064
4065                         }
4066                         else if (! SvUTF8(res)) {
4067                             /* Make sure \N{} return is UTF-8.  This is because
4068                              * \N{} implies Unicode semantics, and scalars have
4069                              * to be in utf8 to guarantee those semantics; but
4070                              * not needed in tr/// */
4071                             sv_utf8_upgrade_flags(res, 0);
4072                             str = SvPV_const(res, len);
4073                         }
4074
4075                          /* Upgrade destination to be utf8 if this new
4076                           * component is */
4077                         if (! d_is_utf8 && SvUTF8(res)) {
4078                             /* See Note on sizing above.  */
4079                             const STRLEN extra = len + (send - s) + 1;
4080
4081                             SvCUR_set(sv, d - SvPVX_const(sv));
4082                             SvPOK_on(sv);
4083                             *d = '\0';
4084
4085                             if (utf8_variant_count == 0) {
4086                                 SvUTF8_on(sv);
4087                                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + extra);
4088                             }
4089                             else {
4090                                 sv_utf8_upgrade_flags_grow(sv,
4091                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4092                                                 extra);
4093                                 d = SvPVX(sv) + SvCUR(sv);
4094                             }
4095                             d_is_utf8 = TRUE;
4096                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
4097
4098                             /* See Note on sizing above.  (NOTE: SvCUR() is not
4099                              * set correctly here). */
4100                             const STRLEN extra = len + (send - e) + 1;
4101                             const STRLEN off = d - SvPVX_const(sv);
4102                             d = off + SvGROW(sv, off + extra);
4103                         }
4104                         Copy(str, d, len, char);
4105                         d += len;
4106                     }
4107
4108                     SvREFCNT_dec(res);
4109
4110                 } /* End \N{NAME} */
4111
4112               end_backslash_N:
4113 #ifdef EBCDIC
4114                 backslash_N++; /* \N{} is defined to be Unicode */
4115 #endif
4116                 s = e + 1;  /* Point to just after the '}' */
4117                 continue;
4118
4119             /* \c is a control character */
4120             case 'c':
4121                 s++;
4122                 if (s < send) {
4123                     const char * message;
4124
4125                     if (! grok_bslash_c(*s, (U8 *) d, &message, NULL)) {
4126                         yyerror(message);
4127                         yyquit();   /* Have always immediately croaked on
4128                                        errors in this */
4129                     }
4130                     d++;
4131                 }
4132                 else {
4133                     yyerror("Missing control char name in \\c");
4134                     yyquit();   /* Are at end of input, no sense continuing */
4135                 }
4136 #ifdef EBCDIC
4137                 non_portable_endpoint++;
4138 #endif
4139                 break;
4140
4141             /* printf-style backslashes, formfeeds, newlines, etc */
4142             case 'b':
4143                 *d++ = '\b';
4144                 break;
4145             case 'n':
4146                 *d++ = '\n';
4147                 break;
4148             case 'r':
4149                 *d++ = '\r';
4150                 break;
4151             case 'f':
4152                 *d++ = '\f';
4153                 break;
4154             case 't':
4155                 *d++ = '\t';
4156                 break;
4157             case 'e':
4158                 *d++ = ESC_NATIVE;
4159                 break;
4160             case 'a':
4161                 *d++ = '\a';
4162                 break;
4163             } /* end switch */
4164
4165             s++;
4166             continue;
4167         } /* end if (backslash) */
4168
4169     default_action:
4170         /* Just copy the input to the output, though we may have to convert
4171          * to/from UTF-8.
4172          *
4173          * If the input has the same representation in UTF-8 as not, it will be
4174          * a single byte, and we don't care about UTF8ness; just copy the byte */
4175         if (NATIVE_BYTE_IS_INVARIANT((U8)(*s))) {
4176             *d++ = *s++;
4177         }
4178         else if (! s_is_utf8 && ! d_is_utf8) {
4179             /* If neither source nor output is UTF-8, is also a single byte,
4180              * just copy it; but this byte counts should we later have to
4181              * convert to UTF-8 */
4182             *d++ = *s++;
4183             utf8_variant_count++;
4184         }
4185         else if (s_is_utf8 && d_is_utf8) {   /* Both UTF-8, can just copy */
4186             const STRLEN len = UTF8SKIP(s);
4187
4188             /* We expect the source to have already been checked for
4189              * malformedness */
4190             assert(isUTF8_CHAR((U8 *) s, (U8 *) send));
4191
4192             Copy(s, d, len, U8);
4193             d += len;
4194             s += len;
4195         }
4196         else if (s_is_utf8) { /* UTF8ness matters: convert output to utf8 */
4197             STRLEN need = send - s + 1; /* See Note on sizing above. */
4198
4199             SvCUR_set(sv, d - SvPVX_const(sv));
4200             SvPOK_on(sv);
4201             *d = '\0';
4202
4203             if (utf8_variant_count == 0) {
4204                 SvUTF8_on(sv);
4205                 d = SvCUR(sv) + SvGROW(sv, SvCUR(sv) + need);
4206             }
4207             else {
4208                 sv_utf8_upgrade_flags_grow(sv,
4209                                            SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
4210                                            need);
4211                 d = SvPVX(sv) + SvCUR(sv);
4212             }
4213             d_is_utf8 = TRUE;
4214             goto default_action; /* Redo, having upgraded so both are UTF-8 */
4215         }
4216         else {  /* UTF8ness matters: convert this non-UTF8 source char to
4217                    UTF-8 for output.  It will occupy 2 bytes, but don't include
4218                    the input byte since we haven't incremented 's' yet. See
4219                    Note on sizing above. */
4220             const STRLEN off = d - SvPVX(sv);
4221             const STRLEN extra = 2 + (send - s - 1) + 1;
4222             if (off + extra > SvLEN(sv)) {
4223                 d = off + SvGROW(sv, off + extra);
4224             }
4225             *d++ = UTF8_EIGHT_BIT_HI(*s);
4226             *d++ = UTF8_EIGHT_BIT_LO(*s);
4227             s++;
4228         }
4229     } /* while loop to process each character */
4230
4231     {
4232         const STRLEN off = d - SvPVX(sv);
4233
4234         /* See if room for the terminating NUL */
4235         if (UNLIKELY(off >= SvLEN(sv))) {
4236
4237 #ifndef DEBUGGING
4238
4239             if (off > SvLEN(sv))
4240 #endif
4241                 Perl_croak(aTHX_ "panic: constant overflowed allocated space,"
4242                         " %" UVuf " >= %" UVuf, (UV)off, (UV)SvLEN(sv));
4243
4244             /* Whew!  Here we don't have room for the terminating NUL, but
4245              * everything else so far has fit.  It's not too late to grow
4246              * to fit the NUL and continue on.  But it is a bug, as the code
4247              * above was supposed to have made room for this, so under
4248              * DEBUGGING builds, we panic anyway.  */
4249             d = off + SvGROW(sv, off + 1);
4250         }
4251     }
4252
4253     /* terminate the string and set up the sv */
4254     *d = '\0';
4255     SvCUR_set(sv, d - SvPVX_const(sv));
4256
4257     SvPOK_on(sv);
4258     if (d_is_utf8) {
4259         SvUTF8_on(sv);
4260     }
4261
4262     /* shrink the sv if we allocated more than we used */
4263     if (SvCUR(sv) + 5 < SvLEN(sv)) {
4264         SvPV_shrink_to_cur(sv);
4265     }
4266
4267     /* return the substring (via pl_yylval) only if we parsed anything */
4268     if (s > start) {
4269         char *s2 = start;
4270         for (; s2 < s; s2++) {
4271             if (*s2 == '\n')
4272                 COPLINE_INC_WITH_HERELINES;
4273         }
4274         SvREFCNT_inc_simple_void_NN(sv);
4275         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
4276             && ! PL_parser->lex_re_reparsing)
4277         {
4278             const char *const key = PL_lex_inpat ? "qr" : "q";
4279             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
4280             const char *type;
4281             STRLEN typelen;
4282
4283             if (PL_lex_inwhat == OP_TRANS) {
4284                 type = "tr";
4285                 typelen = 2;
4286             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
4287                 type = "s";
4288                 typelen = 1;
4289             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
4290                 type = "q";
4291                 typelen = 1;
4292             } else {
4293                 type = "qq";
4294                 typelen = 2;
4295             }
4296
4297             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
4298                                 type, typelen, NULL);
4299         }
4300         pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
4301     }
4302     LEAVE_with_name("scan_const");
4303     return s;
4304 }
4305
4306 /* S_intuit_more
4307  * Returns TRUE if there's more to the expression (e.g., a subscript),
4308  * FALSE otherwise.
4309  *
4310  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
4311  *
4312  * ->[ and ->{ return TRUE
4313  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
4314  * { and [ outside a pattern are always subscripts, so return TRUE
4315  * if we're outside a pattern and it's not { or [, then return FALSE
4316  * if we're in a pattern and the first char is a {
4317  *   {4,5} (any digits around the comma) returns FALSE
4318  * if we're in a pattern and the first char is a [
4319  *   [] returns FALSE
4320  *   [SOMETHING] has a funky algorithm to decide whether it's a
4321  *      character class or not.  It has to deal with things like
4322  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
4323  * anything else returns TRUE
4324  */
4325
4326 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
4327
4328 STATIC int
4329 S_intuit_more(pTHX_ char *s, char *e)
4330 {
4331     PERL_ARGS_ASSERT_INTUIT_MORE;
4332
4333     if (PL_lex_brackets)
4334         return TRUE;
4335     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
4336         return TRUE;
4337     if (*s == '-' && s[1] == '>'
4338      && FEATURE_POSTDEREF_QQ_IS_ENABLED
4339      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
4340         ||(s[2] == '@' && memCHRs("*[{",s[3])) ))
4341         return TRUE;
4342     if (*s != '{' && *s != '[')
4343         return FALSE;
4344     PL_parser->sub_no_recover = TRUE;
4345     if (!PL_lex_inpat)
4346         return TRUE;
4347
4348     /* In a pattern, so maybe we have {n,m}. */
4349     if (*s == '{') {
4350         if (regcurly(s)) {
4351             return FALSE;
4352         }
4353         return TRUE;
4354     }
4355
4356     /* On the other hand, maybe we have a character class */
4357
4358     s++;
4359     if (*s == ']' || *s == '^')
4360         return FALSE;
4361     else {
4362         /* this is terrifying, and it works */
4363         int weight;
4364         char seen[256];
4365         const char * const send = (char *) memchr(s, ']', e - s);
4366         unsigned char un_char, last_un_char;
4367         char tmpbuf[sizeof PL_tokenbuf * 4];
4368
4369         if (!send)              /* has to be an expression */
4370             return TRUE;
4371         weight = 2;             /* let's weigh the evidence */
4372
4373         if (*s == '$')
4374             weight -= 3;
4375         else if (isDIGIT(*s)) {
4376             if (s[1] != ']') {
4377                 if (isDIGIT(s[1]) && s[2] == ']')
4378                     weight -= 10;
4379             }
4380             else
4381                 weight -= 100;
4382         }
4383         Zero(seen,256,char);
4384         un_char = 255;
4385         for (; s < send; s++) {
4386             last_un_char = un_char;
4387             un_char = (unsigned char)*s;
4388             switch (*s) {
4389             case '@':
4390             case '&':
4391             case '$':
4392                 weight -= seen[un_char] * 10;
4393                 if (isWORDCHAR_lazy_if_safe(s+1, PL_bufend, UTF)) {
4394                     int len;
4395                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
4396                     len = (int)strlen(tmpbuf);
4397                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
4398                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
4399                         weight -= 100;
4400                     else
4401                         weight -= 10;
4402                 }
4403                 else if (*s == '$'
4404                          && s[1]
4405                          && memCHRs("[#!%*<>()-=",s[1]))
4406                 {
4407                     if (/*{*/ memCHRs("])} =",s[2]))
4408                         weight -= 10;
4409                     else
4410                         weight -= 1;
4411                 }
4412                 break;
4413             case '\\':
4414                 un_char = 254;
4415                 if (s[1]) {
4416                     if (memCHRs("wds]",s[1]))
4417                         weight += 100;
4418                     else if (seen[(U8)'\''] || seen[(U8)'"'])
4419                         weight += 1;
4420                     else if (memCHRs("rnftbxcav",s[1]))
4421                         weight += 40;
4422                     else if (isDIGIT(s[1])) {
4423                         weight += 40;
4424                         while (s[1] && isDIGIT(s[1]))
4425                             s++;
4426                     }
4427                 }
4428                 else
4429                     weight += 100;
4430                 break;
4431             case '-':
4432                 if (s[1] == '\\')
4433                     weight += 50;
4434                 if (memCHRs("aA01! ",last_un_char))
4435                     weight += 30;
4436                 if (memCHRs("zZ79~",s[1]))
4437                     weight += 30;
4438                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4439                     weight -= 5;        /* cope with negative subscript */
4440                 break;
4441             default:
4442                 if (!isWORDCHAR(last_un_char)
4443                     && !(last_un_char == '$' || last_un_char == '@'
4444                          || last_un_char == '&')
4445                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4446                     char *d = s;
4447                     while (isALPHA(*s))
4448                         s++;
4449                     if (keyword(d, s - d, 0))
4450                         weight -= 150;
4451                 }
4452                 if (un_char == last_un_char + 1)
4453                     weight += 5;
4454                 weight -= seen[un_char];
4455                 break;
4456             }
4457             seen[un_char]++;
4458         }
4459         if (weight >= 0)        /* probably a character class */
4460             return FALSE;
4461     }
4462
4463     return TRUE;
4464 }
4465
4466 /*
4467  * S_intuit_method
4468  *
4469  * Does all the checking to disambiguate
4470  *   foo bar
4471  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
4472  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4473  *
4474  * First argument is the stuff after the first token, e.g. "bar".
4475  *
4476  * Not a method if foo is a filehandle.
4477  * Not a method if foo is a subroutine prototyped to take a filehandle.
4478  * Not a method if it's really "Foo $bar"
4479  * Method if it's "foo $bar"
4480  * Not a method if it's really "print foo $bar"
4481  * Method if it's really "foo package::" (interpreted as package->foo)
4482  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4483  * Not a method if bar is a filehandle or package, but is quoted with
4484  *   =>
4485  */
4486
4487 STATIC int
4488 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4489 {
4490     char *s = start + (*start == '$');
4491     char tmpbuf[sizeof PL_tokenbuf];
4492     STRLEN len;
4493     GV* indirgv;
4494         /* Mustn't actually add anything to a symbol table.
4495            But also don't want to "initialise" any placeholder
4496            constants that might already be there into full
4497            blown PVGVs with attached PVCV.  */
4498     GV * const gv =
4499         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4500
4501     PERL_ARGS_ASSERT_INTUIT_METHOD;
4502
4503     if (!FEATURE_INDIRECT_IS_ENABLED)
4504         return 0;
4505
4506     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4507             return 0;
4508     if (cv && SvPOK(cv)) {
4509         const char *proto = CvPROTO(cv);
4510         if (proto) {
4511             while (*proto && (isSPACE(*proto) || *proto == ';'))
4512                 proto++;
4513             if (*proto == '*')
4514                 return 0;
4515         }
4516     }
4517
4518     if (*start == '$') {
4519         SSize_t start_off = start - SvPVX(PL_linestr);
4520         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4521             || isUPPER(*PL_tokenbuf))
4522             return 0;
4523         /* this could be $# */
4524         if (isSPACE(*s))
4525             s = skipspace(s);
4526         PL_bufptr = SvPVX(PL_linestr) + start_off;
4527         PL_expect = XREF;
4528         return *s == '(' ? FUNCMETH : METHOD;
4529     }
4530
4531     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4532     /* start is the beginning of the possible filehandle/object,
4533      * and s is the end of it
4534      * tmpbuf is a copy of it (but with single quotes as double colons)
4535      */
4536
4537     if (!keyword(tmpbuf, len, 0)) {
4538         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4539             len -= 2;
4540             tmpbuf[len] = '\0';
4541             goto bare_package;
4542         }
4543         indirgv = gv_fetchpvn_flags(tmpbuf, len,
4544                                     GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4545                                     SVt_PVCV);
4546         if (indirgv && SvTYPE(indirgv) != SVt_NULL
4547          && (!isGV(indirgv) || GvCVu(indirgv)))
4548             return 0;
4549         /* filehandle or package name makes it a method */
4550         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4551             s = skipspace(s);
4552             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4553                 return 0;       /* no assumptions -- "=>" quotes bareword */
4554       bare_package:
4555             NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0,
4556                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4557             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4558             PL_expect = XTERM;
4559             force_next(BAREWORD);
4560             PL_bufptr = s;
4561             return *s == '(' ? FUNCMETH : METHOD;
4562         }
4563     }
4564     return 0;
4565 }
4566
4567 /* Encoded script support. filter_add() effectively inserts a
4568  * 'pre-processing' function into the current source input stream.
4569  * Note that the filter function only applies to the current source file
4570  * (e.g., it will not affect files 'require'd or 'use'd by this one).
4571  *
4572  * The datasv parameter (which may be NULL) can be used to pass
4573  * private data to this instance of the filter. The filter function
4574  * can recover the SV using the FILTER_DATA macro and use it to
4575  * store private buffers and state information.
4576  *
4577  * The supplied datasv parameter is upgraded to a PVIO type
4578  * and the IoDIRP/IoANY field is used to store the function pointer,
4579  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4580  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4581  * private use must be set using malloc'd pointers.
4582  */
4583
4584 SV *
4585 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4586 {
4587     if (!funcp)
4588         return NULL;
4589
4590     if (!PL_parser)
4591         return NULL;
4592
4593     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4594         Perl_croak(aTHX_ "Source filters apply only to byte streams");
4595
4596     if (!PL_rsfp_filters)
4597         PL_rsfp_filters = newAV();
4598     if (!datasv)
4599         datasv = newSV(0);
4600     SvUPGRADE(datasv, SVt_PVIO);
4601     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4602     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4603     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4604                           FPTR2DPTR(void *, IoANY(datasv)),
4605                           SvPV_nolen(datasv)));
4606     av_unshift(PL_rsfp_filters, 1);
4607     av_store(PL_rsfp_filters, 0, datasv) ;
4608     if (
4609         !PL_parser->filtered
4610      && PL_parser->lex_flags & LEX_EVALBYTES
4611      && PL_bufptr < PL_bufend
4612     ) {
4613         const char *s = PL_bufptr;
4614         while (s < PL_bufend) {
4615             if (*s == '\n') {
4616                 SV *linestr = PL_parser->linestr;
4617                 char *buf = SvPVX(linestr);
4618                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4619                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4620                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4621                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4622                 STRLEN const last_uni_pos =
4623                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4624                 STRLEN const last_lop_pos =
4625                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4626                 av_push(PL_rsfp_filters, linestr);
4627                 PL_parser->linestr =
4628                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4629                 buf = SvPVX(PL_parser->linestr);
4630                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4631                 PL_parser->bufptr = buf + bufptr_pos;
4632                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4633                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4634                 PL_parser->linestart = buf + linestart_pos;
4635                 if (PL_parser->last_uni)
4636                     PL_parser->last_uni = buf + last_uni_pos;
4637                 if (PL_parser->last_lop)
4638                     PL_parser->last_lop = buf + last_lop_pos;
4639                 SvLEN_set(linestr, SvCUR(linestr));
4640                 SvCUR_set(linestr, s - SvPVX(linestr));
4641                 PL_parser->filtered = 1;
4642                 break;
4643             }
4644             s++;
4645         }
4646     }
4647     return(datasv);
4648 }
4649
4650
4651 /* Delete most recently added instance of this filter function. */
4652 void
4653 Perl_filter_del(pTHX_ filter_t funcp)
4654 {
4655     SV *datasv;
4656
4657     PERL_ARGS_ASSERT_FILTER_DEL;
4658
4659 #ifdef DEBUGGING
4660     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4661                           FPTR2DPTR(void*, funcp)));
4662 #endif
4663     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4664         return;
4665     /* if filter is on top of stack (usual case) just pop it off */
4666     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4667     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4668         sv_free(av_pop(PL_rsfp_filters));
4669
4670         return;
4671     }
4672     /* we need to search for the correct entry and clear it     */
4673     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4674 }
4675
4676
4677 /* Invoke the idxth filter function for the current rsfp.        */
4678 /* maxlen 0 = read one text line */
4679 I32
4680 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4681 {
4682     filter_t funcp;
4683     I32 ret;
4684     SV *datasv = NULL;
4685     /* This API is bad. It should have been using unsigned int for maxlen.
4686        Not sure if we want to change the API, but if not we should sanity
4687        check the value here.  */
4688     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4689
4690     PERL_ARGS_ASSERT_FILTER_READ;
4691
4692     if (!PL_parser || !PL_rsfp_filters)
4693         return -1;
4694     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4695         /* Provide a default input filter to make life easy.    */
4696         /* Note that we append to the line. This is handy.      */
4697         DEBUG_P(PerlIO_printf(Perl_debug_log,
4698                               "filter_read %d: from rsfp\n", idx));
4699         if (correct_length) {
4700             /* Want a block */
4701             int len ;
4702             const int old_len = SvCUR(buf_sv);
4703
4704             /* ensure buf_sv is large enough */
4705             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4706             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4707                                    correct_length)) <= 0) {
4708                 if (PerlIO_error(PL_rsfp))
4709                     return -1;          /* error */
4710                 else
4711                     return 0 ;          /* end of file */
4712             }
4713             SvCUR_set(buf_sv, old_len + len) ;
4714             SvPVX(buf_sv)[old_len + len] = '\0';
4715         } else {
4716             /* Want a line */
4717             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4718                 if (PerlIO_error(PL_rsfp))
4719                     return -1;          /* error */
4720                 else
4721                     return 0 ;          /* end of file */
4722             }
4723         }
4724         return SvCUR(buf_sv);
4725     }
4726     /* Skip this filter slot if filter has been deleted */
4727     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4728         DEBUG_P(PerlIO_printf(Perl_debug_log,
4729                               "filter_read %d: skipped (filter deleted)\n",
4730                               idx));
4731         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4732     }
4733     if (SvTYPE(datasv) != SVt_PVIO) {
4734         if (correct_length) {
4735             /* Want a block */
4736             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4737             if (!remainder) return 0; /* eof */
4738             if (correct_length > remainder) correct_length = remainder;
4739             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4740             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4741         } else {
4742             /* Want a line */
4743             const char *s = SvEND(datasv);
4744             const char *send = SvPVX(datasv) + SvLEN(datasv);
4745             while (s < send) {
4746                 if (*s == '\n') {
4747                     s++;
4748                     break;
4749                 }
4750                 s++;
4751             }
4752             if (s == send) return 0; /* eof */
4753             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4754             SvCUR_set(datasv, s-SvPVX(datasv));
4755         }
4756         return SvCUR(buf_sv);
4757     }
4758     /* Get function pointer hidden within datasv        */
4759     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4760     DEBUG_P(PerlIO_printf(Perl_debug_log,
4761                           "filter_read %d: via function %p (%s)\n",
4762                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4763     /* Call function. The function is expected to       */
4764     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4765     /* Return: <0:error, =0:eof, >0:not eof             */
4766     ENTER;
4767     save_scalar(PL_errgv);
4768     ret = (*funcp)(aTHX_ idx, buf_sv, correct_length);
4769     LEAVE;
4770     return ret;
4771 }
4772
4773 STATIC char *
4774 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4775 {
4776     PERL_ARGS_ASSERT_FILTER_GETS;
4777
4778 #ifdef PERL_CR_FILTER
4779     if (!PL_rsfp_filters) {
4780         filter_add(S_cr_textfilter,NULL);
4781     }
4782 #endif
4783     if (PL_rsfp_filters) {
4784         if (!append)
4785             SvCUR_set(sv, 0);   /* start with empty line        */
4786         if (FILTER_READ(0, sv, 0) > 0)
4787             return ( SvPVX(sv) ) ;
4788         else
4789             return NULL ;
4790     }
4791     else
4792         return (sv_gets(sv, PL_rsfp, append));
4793 }
4794
4795 STATIC HV *
4796 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4797 {
4798     GV *gv;
4799
4800     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4801
4802     if (memEQs(pkgname, len, "__PACKAGE__"))
4803         return PL_curstash;
4804
4805     if (len > 2
4806         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4807         && (gv = gv_fetchpvn_flags(pkgname,
4808                                    len,
4809                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4810     {
4811         return GvHV(gv);                        /* Foo:: */
4812     }
4813
4814     /* use constant CLASS => 'MyClass' */
4815     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4816     if (gv && GvCV(gv)) {
4817         SV * const sv = cv_const_sv(GvCV(gv));
4818         if (sv)
4819             return gv_stashsv(sv, 0);
4820     }
4821
4822     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4823 }
4824
4825
4826 STATIC char *
4827 S_tokenize_use(pTHX_ int is_use, char *s) {
4828     PERL_ARGS_ASSERT_TOKENIZE_USE;
4829
4830     if (PL_expect != XSTATE)
4831         /* diag_listed_as: "use" not allowed in expression */
4832         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4833                     is_use ? "use" : "no"));
4834     PL_expect = XTERM;
4835     s = skipspace(s);
4836     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4837         s = force_version(s, TRUE);
4838         if (*s == ';' || *s == '}'
4839                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4840             NEXTVAL_NEXTTOKE.opval = NULL;
4841             force_next(BAREWORD);
4842         }
4843         else if (*s == 'v') {
4844             s = force_word(s,BAREWORD,FALSE,TRUE);
4845             s = force_version(s, FALSE);
4846         }
4847     }
4848     else {
4849         s = force_word(s,BAREWORD,FALSE,TRUE);
4850         s = force_version(s, FALSE);
4851     }
4852     pl_yylval.ival = is_use;
4853     return s;
4854 }
4855 #ifdef DEBUGGING
4856     static const char* const exp_name[] =
4857         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4858           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4859           "SIGVAR", "TERMORDORDOR"
4860         };
4861 #endif
4862
4863 #define word_takes_any_delimiter(p,l) S_word_takes_any_delimiter(p,l)
4864 STATIC bool
4865 S_word_takes_any_delimiter(char *p, STRLEN len)
4866 {
4867     return (len == 1 && memCHRs("msyq", p[0]))
4868             || (len == 2
4869                 && ((p[0] == 't' && p[1] == 'r')
4870                     || (p[0] == 'q' && memCHRs("qwxr", p[1]))));
4871 }
4872
4873 static void
4874 S_check_scalar_slice(pTHX_ char *s)
4875 {
4876     s++;
4877     while (SPACE_OR_TAB(*s)) s++;
4878     if (*s == 'q' && s[1] == 'w' && !isWORDCHAR_lazy_if_safe(s+2,
4879                                                              PL_bufend,
4880                                                              UTF))
4881     {
4882         return;
4883     }
4884     while (    isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF)
4885            || (*s && memCHRs(" \t$#+-'\"", *s)))
4886     {
4887         s += UTF ? UTF8SKIP(s) : 1;
4888     }
4889     if (*s == '}' || *s == ']')
4890         pl_yylval.ival = OPpSLICEWARNING;
4891 }
4892
4893 #define lex_token_boundary() S_lex_token_boundary(aTHX)
4894 static void
4895 S_lex_token_boundary(pTHX)
4896 {
4897     PL_oldoldbufptr = PL_oldbufptr;
4898     PL_oldbufptr = PL_bufptr;
4899 }
4900
4901 #define vcs_conflict_marker(s) S_vcs_conflict_marker(aTHX_ s)
4902 static char *
4903 S_vcs_conflict_marker(pTHX_ char *s)
4904 {
4905     lex_token_boundary();
4906     PL_bufptr = s;
4907     yyerror("Version control conflict marker");
4908     while (s < PL_bufend && *s != '\n')
4909         s++;
4910     return s;
4911 }
4912
4913 static int
4914 yyl_sigvar(pTHX_ char *s)
4915 {
4916     /* we expect the sigil and optional var name part of a
4917      * signature element here. Since a '$' is not necessarily
4918      * followed by a var name, handle it specially here; the general
4919      * yylex code would otherwise try to interpret whatever follows
4920      * as a var; e.g. ($, ...) would be seen as the var '$,'
4921      */
4922
4923     U8 sigil;
4924
4925     s = skipspace(s);
4926     sigil = *s++;
4927     PL_bufptr = s; /* for error reporting */
4928     switch (sigil) {
4929     case '$':
4930     case '@':
4931     case '%':
4932         /* spot stuff that looks like an prototype */
4933         if (memCHRs("$:@%&*;\\[]", *s)) {
4934             yyerror("Illegal character following sigil in a subroutine signature");
4935             break;
4936         }
4937         /* '$#' is banned, while '$ # comment' isn't */
4938         if (*s == '#') {
4939             yyerror("'#' not allowed immediately following a sigil in a subroutine signature");
4940             break;
4941         }
4942         s = skipspace(s);
4943         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
4944             char *dest = PL_tokenbuf + 1;
4945             /* read var name, including sigil, into PL_tokenbuf */
4946             PL_tokenbuf[0] = sigil;
4947             parse_ident(&s, &dest, dest + sizeof(PL_tokenbuf) - 1,
4948                 0, cBOOL(UTF), FALSE, FALSE);
4949             *dest = '\0';
4950             assert(PL_tokenbuf[1]); /* we have a variable name */
4951         }
4952         else {
4953             *PL_tokenbuf = 0;
4954             PL_in_my = 0;
4955         }
4956
4957         s = skipspace(s);
4958         /* parse the = for the default ourselves to avoid '+=' etc being accepted here
4959          * as the ASSIGNOP, and exclude other tokens that start with =
4960          */
4961         if (*s == '=' && (!s[1] || memCHRs("=~>", s[1]) == 0)) {
4962             /* save now to report with the same context as we did when
4963              * all ASSIGNOPS were accepted */
4964             PL_oldbufptr = s;
4965
4966             ++s;
4967             NEXTVAL_NEXTTOKE.ival = 0;
4968             force_next(ASSIGNOP);
4969             PL_expect = XTERM;
4970         }
4971         else if (*s == ',' || *s == ')') {
4972             PL_expect = XOPERATOR;
4973         }
4974         else {
4975             /* make sure the context shows the unexpected character and
4976              * hopefully a bit more */
4977             if (*s) ++s;
4978             while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
4979                 s++;
4980             PL_bufptr = s; /* for error reporting */
4981             yyerror("Illegal operator following parameter in a subroutine signature");
4982             PL_in_my = 0;
4983         }
4984         if (*PL_tokenbuf) {
4985             NEXTVAL_NEXTTOKE.ival = sigil;
4986             force_next('p'); /* force a signature pending identifier */
4987         }
4988         break;
4989
4990     case ')':
4991         PL_expect = XBLOCK;
4992         break;
4993     case ',': /* handle ($a,,$b) */
4994         break;
4995
4996     default:
4997         PL_in_my = 0;
4998         yyerror("A signature parameter must start with '$', '@' or '%'");
4999         /* very crude error recovery: skip to likely next signature
5000          * element */
5001         while (*s && *s != '$' && *s != '@' && *s != '%' && *s != ')')
5002             s++;
5003         break;
5004     }
5005
5006     switch (sigil) {
5007         case ',': TOKEN (PERLY_COMMA);
5008         case '@': TOKEN (PERLY_SNAIL);
5009         default:  TOKEN (sigil);
5010     }
5011 }
5012
5013 static int
5014 yyl_dollar(pTHX_ char *s)
5015 {
5016     CLINE;
5017
5018     if (PL_expect == XPOSTDEREF) {
5019         if (s[1] == '#') {
5020             s++;
5021             POSTDEREF(DOLSHARP);
5022         }
5023         POSTDEREF('$');
5024     }
5025
5026     if (   s[1] == '#'
5027         && (   isIDFIRST_lazy_if_safe(s+2, PL_bufend, UTF)
5028             || memCHRs("{$:+-@", s[2])))
5029     {
5030         PL_tokenbuf[0] = '@';
5031         s = scan_ident(s + 1, PL_tokenbuf + 1,
5032                        sizeof PL_tokenbuf - 1, FALSE);
5033         if (PL_expect == XOPERATOR) {
5034             char *d = s;
5035             if (PL_bufptr > s) {
5036                 d = PL_bufptr-1;
5037                 PL_bufptr = PL_oldbufptr;
5038             }
5039             no_op("Array length", d);
5040         }
5041         if (!PL_tokenbuf[1])
5042             PREREF(DOLSHARP);
5043         PL_expect = XOPERATOR;
5044         force_ident_maybe_lex('#');
5045         TOKEN(DOLSHARP);
5046     }
5047
5048     PL_tokenbuf[0] = '$';
5049     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
5050     if (PL_expect == XOPERATOR) {
5051         char *d = s;
5052         if (PL_bufptr > s) {
5053             d = PL_bufptr-1;
5054             PL_bufptr = PL_oldbufptr;
5055         }
5056         no_op("Scalar", d);
5057     }
5058     if (!PL_tokenbuf[1]) {
5059         if (s == PL_bufend)
5060             yyerror("Final $ should be \\$ or $name");
5061         PREREF('$');
5062     }
5063
5064     {
5065         const char tmp = *s;
5066         if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
5067             s = skipspace(s);
5068
5069         if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
5070             && intuit_more(s, PL_bufend)) {
5071             if (*s == '[') {
5072                 PL_tokenbuf[0] = '@';
5073                 if (ckWARN(WARN_SYNTAX)) {
5074                     char *t = s+1;
5075
5076                     while ( t < PL_bufend ) {
5077                         if (isSPACE(*t)) {
5078                             do { t += UTF ? UTF8SKIP(t) : 1; } while (t < PL_bufend && isSPACE(*t));
5079                             /* consumed one or more space chars */
5080                         } else if (*t == '$' || *t == '@') {
5081                             /* could be more than one '$' like $$ref or @$ref */
5082                             do { t++; } while (t < PL_bufend && *t == '$');
5083
5084                             /* could be an abigail style identifier like $ foo */
5085                             while (t < PL_bufend && *t == ' ') t++;
5086
5087                             /* strip off the name of the var */
5088                             while (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
5089                                 t += UTF ? UTF8SKIP(t) : 1;
5090                             /* consumed a varname */
5091                         } else if (isDIGIT(*t)) {
5092                             /* deal with hex constants like 0x11 */
5093                             if (t[0] == '0' && t[1] == 'x') {
5094                                 t += 2;
5095                                 while (t < PL_bufend && isXDIGIT(*t)) t++;
5096                             } else {
5097                                 /* deal with decimal/octal constants like 1 and 0123 */
5098                                 do { t++; } while (isDIGIT(*t));
5099                                 if (t<PL_bufend && *t == '.') {
5100                                     do { t++; } while (isDIGIT(*t));
5101                                 }
5102                             }
5103                             /* consumed a number */
5104                         } else {
5105                             /* not a var nor a space nor a number */
5106                             break;
5107                         }
5108                     }
5109                     if (t < PL_bufend && *t++ == ',') {
5110                         PL_bufptr = skipspace(PL_bufptr); /* XXX can realloc */
5111                         while (t < PL_bufend && *t != ']')
5112                             t++;
5113                         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
5114                                     "Multidimensional syntax %" UTF8f " not supported",
5115                                     UTF8fARG(UTF,(int)((t - PL_bufptr) + 1), PL_bufptr));
5116                     }
5117                 }
5118             }
5119             else if (*s == '{') {
5120                 char *t;
5121                 PL_tokenbuf[0] = '%';
5122                 if (    strEQ(PL_tokenbuf+1, "SIG")
5123                     && ckWARN(WARN_SYNTAX)
5124                     && (t = (char *) memchr(s, '}', PL_bufend - s))
5125                     && (t = (char *) memchr(t, '=', PL_bufend - t)))
5126                 {
5127                     char tmpbuf[sizeof PL_tokenbuf];
5128                     do {
5129                         t++;
5130                     } while (isSPACE(*t));
5131                     if (isIDFIRST_lazy_if_safe(t, PL_bufend, UTF)) {
5132                         STRLEN len;
5133                         t = scan_word(t, tmpbuf, sizeof tmpbuf, TRUE,
5134                                         &len);
5135                         while (isSPACE(*t))
5136                             t++;
5137                         if (  *t == ';'
5138                             && get_cvn_flags(tmpbuf, len, UTF
5139                                                             ? SVf_UTF8
5140                                                             : 0))
5141                         {
5142                             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
5143                                 "You need to quote \"%" UTF8f "\"",
5144                                     UTF8fARG(UTF, len, tmpbuf));
5145                         }
5146                     }
5147                 }
5148             }
5149         }
5150
5151         PL_expect = XOPERATOR;
5152         if ((PL_lex_state == LEX_NORMAL || PL_lex_brackets) && isSPACE((char)tmp)) {
5153             const bool islop = (PL_last_lop == PL_oldoldbufptr);
5154             if (!islop || PL_last_lop_op == OP_GREPSTART)
5155                 PL_expect = XOPERATOR;
5156             else if (memCHRs("$@\"'`q", *s))
5157                 PL_expect = XTERM;              /* e.g. print $fh "foo" */
5158             else if (   memCHRs("&*<%", *s)
5159                      && isIDFIRST_lazy_if_safe(s+1, PL_bufend, UTF))
5160             {
5161                 PL_expect = XTERM;              /* e.g. print $fh &sub */
5162             }
5163             else if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5164                 char tmpbuf[sizeof PL_tokenbuf];
5165                 int t2;
5166                 STRLEN len;
5167                 scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
5168                 if ((t2 = keyword(tmpbuf, len, 0))) {
5169                     /* binary operators exclude handle interpretations */
5170                     switch (t2) {
5171                     case -KEY_x:
5172                     case -KEY_eq:
5173                     case -KEY_ne:
5174                     case -KEY_gt:
5175                     case -KEY_lt:
5176                     case -KEY_ge:
5177                     case -KEY_le:
5178                     case -KEY_cmp:
5179                         break;
5180                     default:
5181                         PL_expect = XTERM;      /* e.g. print $fh length() */
5182                         break;
5183                     }
5184                 }
5185                 else {
5186                     PL_expect = XTERM;  /* e.g. print $fh subr() */
5187                 }
5188             }
5189             else if (isDIGIT(*s))
5190                 PL_expect = XTERM;              /* e.g. print $fh 3 */
5191             else if (*s == '.' && isDIGIT(s[1]))
5192                 PL_expect = XTERM;              /* e.g. print $fh .3 */
5193             else if ((*s == '?' || *s == '-' || *s == '+')
5194                      && !isSPACE(s[1]) && s[1] != '=')
5195                 PL_expect = XTERM;              /* e.g. print $fh -1 */
5196             else if (*s == '/' && !isSPACE(s[1]) && s[1] != '='
5197                      && s[1] != '/')
5198                 PL_expect = XTERM;              /* e.g. print $fh /.../
5199                                                XXX except DORDOR operator
5200                                             */
5201             else if (*s == '<' && s[1] == '<' && !isSPACE(s[2])
5202                      && s[2] != '=')
5203                 PL_expect = XTERM;              /* print $fh <<"EOF" */
5204         }
5205     }
5206     force_ident_maybe_lex('$');
5207     TOKEN('$');
5208 }
5209
5210 static int
5211 yyl_sub(pTHX_ char *s, const int key)
5212 {
5213     char * const tmpbuf = PL_tokenbuf + 1;
5214     bool have_name, have_proto;
5215     STRLEN len;
5216     SV *format_name = NULL;
5217     bool is_sigsub = FEATURE_SIGNATURES_IS_ENABLED;
5218
5219     SSize_t off = s-SvPVX(PL_linestr);
5220     char *d;
5221
5222     s = skipspace(s); /* can move PL_linestr */
5223
5224     d = SvPVX(PL_linestr)+off;
5225
5226     SAVEBOOL(PL_parser->sig_seen);
5227     PL_parser->sig_seen = FALSE;
5228
5229     if (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
5230         || *s == '\''
5231         || (*s == ':' && s[1] == ':'))
5232     {
5233
5234         PL_expect = XATTRBLOCK;
5235         d = scan_word(s, tmpbuf, sizeof PL_tokenbuf - 1, TRUE,
5236                       &len);
5237         if (key == KEY_format)
5238             format_name = S_newSV_maybe_utf8(aTHX_ s, d - s);
5239         *PL_tokenbuf = '&';
5240         if (memchr(tmpbuf, ':', len) || key != KEY_sub
5241          || pad_findmy_pvn(
5242                 PL_tokenbuf, len + 1, 0
5243             ) != NOT_IN_PAD)
5244             sv_setpvn(PL_subname, tmpbuf, len);
5245         else {
5246             sv_setsv(PL_subname,PL_curstname);
5247             sv_catpvs(PL_subname,"::");
5248             sv_catpvn(PL_subname,tmpbuf,len);
5249         }
5250         if (SvUTF8(PL_linestr))
5251             SvUTF8_on(PL_subname);
5252         have_name = TRUE;
5253
5254         s = skipspace(d);
5255     }
5256     else {
5257         if (key == KEY_my || key == KEY_our || key==KEY_state) {
5258             *d = '\0';
5259             /* diag_listed_as: Missing name in "%s sub" */
5260             Perl_croak(aTHX_
5261                       "Missing name in \"%s\"", PL_bufptr);
5262         }
5263         PL_expect = XATTRTERM;
5264         sv_setpvs(PL_subname,"?");
5265         have_name = FALSE;
5266     }
5267
5268     if (key == KEY_format) {
5269         if (format_name) {
5270             NEXTVAL_NEXTTOKE.opval
5271                 = newSVOP(OP_CONST,0, format_name);
5272             NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
5273             force_next(BAREWORD);
5274         }
5275         PREBLOCK(FORMAT);
5276     }
5277
5278     /* Look for a prototype */
5279     if (*s == '(' && !is_sigsub) {
5280         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5281         if (!s)
5282             Perl_croak(aTHX_ "Prototype not terminated");
5283         COPLINE_SET_FROM_MULTI_END;
5284         (void)validate_proto(PL_subname, PL_lex_stuff,
5285                              ckWARN(WARN_ILLEGALPROTO), 0);
5286         have_proto = TRUE;
5287
5288         s = skipspace(s);
5289     }
5290     else
5291         have_proto = FALSE;
5292
5293     if (  !(*s == ':' && s[1] != ':')
5294         && (*s != '{' && *s != '(') && key != KEY_format)
5295     {
5296         assert(key == KEY_sub || key == KEY_AUTOLOAD ||
5297                key == KEY_DESTROY || key == KEY_BEGIN ||
5298                key == KEY_UNITCHECK || key == KEY_CHECK ||
5299                key == KEY_INIT || key == KEY_END ||
5300                key == KEY_my || key == KEY_state ||
5301                key == KEY_our);
5302         if (!have_name)
5303             Perl_croak(aTHX_ "Illegal declaration of anonymous subroutine");
5304         else if (*s != ';' && *s != '}')
5305             Perl_croak(aTHX_ "Illegal declaration of subroutine %" SVf, SVfARG(PL_subname));
5306     }
5307
5308     if (have_proto) {
5309         NEXTVAL_NEXTTOKE.opval =
5310             newSVOP(OP_CONST, 0, PL_lex_stuff);
5311         PL_lex_stuff = NULL;
5312         force_next(THING);
5313     }
5314     if (!have_name) {
5315         if (PL_curstash)
5316             sv_setpvs(PL_subname, "__ANON__");
5317         else
5318             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5319         if (is_sigsub)
5320             TOKEN(ANON_SIGSUB);
5321         else
5322             TOKEN(ANONSUB);
5323     }
5324     force_ident_maybe_lex('&');
5325     if (is_sigsub)
5326         TOKEN(SIGSUB);
5327     else
5328         TOKEN(SUB);
5329 }
5330
5331 static int
5332 yyl_interpcasemod(pTHX_ char *s)
5333 {
5334 #ifdef DEBUGGING
5335     if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
5336         Perl_croak(aTHX_
5337                    "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
5338                    PL_bufptr, PL_bufend, *PL_bufptr);
5339 #endif
5340
5341     if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
5342         /* if at a \E */
5343         if (PL_lex_casemods) {
5344             const char oldmod = PL_lex_casestack[--PL_lex_casemods];
5345             PL_lex_casestack[PL_lex_casemods] = '\0';
5346
5347             if (PL_bufptr != PL_bufend
5348                 && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
5349                     || oldmod == 'F')) {
5350                 PL_bufptr += 2;
5351                 PL_lex_state = LEX_INTERPCONCAT;
5352             }
5353             PL_lex_allbrackets--;
5354             return REPORT(')');
5355         }
5356         else if ( PL_bufptr != PL_bufend && PL_bufptr[1] == 'E' ) {
5357            /* Got an unpaired \E */
5358            Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
5359                     "Useless use of \\E");
5360         }
5361         if (PL_bufptr != PL_bufend)
5362             PL_bufptr += 2;
5363         PL_lex_state = LEX_INTERPCONCAT;
5364         return yylex();
5365     }
5366     else {
5367         DEBUG_T({
5368             PerlIO_printf(Perl_debug_log, "### Saw case modifier\n");
5369         });
5370         s = PL_bufptr + 1;
5371         if (s[1] == '\\' && s[2] == 'E') {
5372             PL_bufptr = s + 3;
5373             PL_lex_state = LEX_INTERPCONCAT;
5374             return yylex();
5375         }
5376         else {
5377             I32 tmp;
5378             if (   memBEGINs(s, (STRLEN) (PL_bufend - s), "L\\u")
5379                 || memBEGINs(s, (STRLEN) (PL_bufend - s), "U\\l"))
5380             {
5381                 tmp = *s, *s = s[2], s[2] = (char)tmp;  /* misordered... */
5382             }
5383             if ((*s == 'L' || *s == 'U' || *s == 'F')
5384                 && (strpbrk(PL_lex_casestack, "LUF")))
5385             {
5386                 PL_lex_casestack[--PL_lex_casemods] = '\0';
5387                 PL_lex_allbrackets--;
5388                 return REPORT(')');
5389             }
5390             if (PL_lex_casemods > 10)
5391                 Renew(PL_lex_casestack, PL_lex_casemods + 2, char);
5392             PL_lex_casestack[PL_lex_casemods++] = *s;
5393             PL_lex_casestack[PL_lex_casemods] = '\0';
5394             PL_lex_state = LEX_INTERPCONCAT;
5395             NEXTVAL_NEXTTOKE.ival = 0;
5396             force_next((2<<24)|'(');
5397             if (*s == 'l')
5398                 NEXTVAL_NEXTTOKE.ival = OP_LCFIRST;
5399             else if (*s == 'u')
5400                 NEXTVAL_NEXTTOKE.ival = OP_UCFIRST;
5401             else if (*s == 'L')
5402                 NEXTVAL_NEXTTOKE.ival = OP_LC;
5403             else if (*s == 'U')
5404                 NEXTVAL_NEXTTOKE.ival = OP_UC;
5405             else if (*s == 'Q')
5406                 NEXTVAL_NEXTTOKE.ival = OP_QUOTEMETA;
5407             else if (*s == 'F')
5408                 NEXTVAL_NEXTTOKE.ival = OP_FC;
5409             else
5410                 Perl_croak(aTHX_ "panic: yylex, *s=%u", *s);
5411             PL_bufptr = s + 1;
5412         }
5413         force_next(FUNC);
5414         if (PL_lex_starts) {
5415             s = PL_bufptr;
5416             PL_lex_starts = 0;
5417             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
5418             if (PL_lex_casemods == 1 && PL_lex_inpat)
5419                 TOKEN(PERLY_COMMA);
5420             else
5421                 AopNOASSIGN(OP_CONCAT);
5422         }
5423         else
5424             return yylex();
5425     }
5426 }
5427
5428 static int
5429 yyl_secondclass_keyword(pTHX_ char *s, STRLEN len, int key, I32 *orig_keyword,
5430                         GV **pgv, GV ***pgvp)
5431 {
5432     GV *ogv = NULL;     /* override (winner) */
5433     GV *hgv = NULL;     /* hidden (loser) */
5434     GV *gv = *pgv;
5435
5436     if (PL_expect != XOPERATOR && (*s != ':' || s[1] != ':')) {
5437         CV *cv;
5438         if ((gv = gv_fetchpvn_flags(PL_tokenbuf, len,
5439                                     (UTF ? SVf_UTF8 : 0)|GV_NOTQUAL,
5440                                     SVt_PVCV))
5441             && (cv = GvCVu(gv)))
5442         {
5443             if (GvIMPORTED_CV(gv))
5444                 ogv = gv;
5445             else if (! CvMETHOD(cv))
5446                 hgv = gv;
5447         }
5448         if (!ogv
5449             && (*pgvp = (GV**)hv_fetch(PL_globalstash, PL_tokenbuf, len, FALSE))
5450             && (gv = **pgvp)
5451             && (isGV_with_GP(gv)
5452                 ? GvCVu(gv) && GvIMPORTED_CV(gv)
5453                 :   SvPCS_IMPORTED(gv)
5454                 && (gv_init(gv, PL_globalstash, PL_tokenbuf,
5455                                                          len, 0), 1)))
5456         {
5457             ogv = gv;
5458         }
5459     }
5460
5461     *pgv = gv;
5462
5463     if (ogv) {
5464         *orig_keyword = key;
5465         return 0;               /* overridden by import or by GLOBAL */
5466     }
5467     else if (gv && !*pgvp
5468              && -key==KEY_lock  /* XXX generalizable kludge */
5469              && GvCVu(gv))
5470     {
5471         return 0;               /* any sub overrides "weak" keyword */
5472     }
5473     else {                      /* no override */
5474         key = -key;
5475         if (key == KEY_dump) {
5476             Perl_croak(aTHX_ "dump() must be written as CORE::dump() as of Perl 5.30");
5477         }
5478         *pgv = NULL;
5479         *pgvp = 0;
5480         if (hgv && key != KEY_x)        /* never ambiguous */
5481             Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
5482                            "Ambiguous call resolved as CORE::%s(), "
5483                            "qualify as such or use &",
5484                            GvENAME(hgv));
5485         return key;
5486     }
5487 }
5488
5489 static int
5490 yyl_qw(pTHX_ char *s, STRLEN len)
5491 {
5492     OP *words = NULL;
5493
5494     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
5495     if (!s)
5496         missingterm(NULL, 0);
5497
5498     COPLINE_SET_FROM_MULTI_END;
5499     PL_expect = XOPERATOR;
5500     if (SvCUR(PL_lex_stuff)) {
5501         int warned_comma = !ckWARN(WARN_QW);
5502         int warned_comment = warned_comma;
5503         char *d = SvPV_force(PL_lex_stuff, len);
5504         while (len) {
5505             for (; isSPACE(*d) && len; --len, ++d)
5506                 /**/;
5507             if (len) {
5508                 SV *sv;
5509                 const char *b = d;
5510                 if (!warned_comma || !warned_comment) {
5511                     for (; !isSPACE(*d) && len; --len, ++d) {
5512                         if (!warned_comma && *d == ',') {
5513                             Perl_warner(aTHX_ packWARN(WARN_QW),
5514                                 "Possible attempt to separate words with commas");
5515                             ++warned_comma;
5516                         }
5517                         else if (!warned_comment && *d == '#') {
5518                             Perl_warner(aTHX_ packWARN(WARN_QW),
5519                                 "Possible attempt to put comments in qw() list");
5520                             ++warned_comment;
5521                         }
5522                     }
5523                 }
5524                 else {
5525                     for (; !isSPACE(*d) && len; --len, ++d)
5526                         /**/;
5527                 }
5528                 sv = newSVpvn_utf8(b, d-b, DO_UTF8(PL_lex_stuff));
5529                 words = op_append_elem(OP_LIST, words,
5530                                        newSVOP(OP_CONST, 0, tokeq(sv)));
5531             }
5532         }
5533     }
5534     if (!words)
5535         words = newNULLLIST();
5536     SvREFCNT_dec_NN(PL_lex_stuff);
5537     PL_lex_stuff = NULL;
5538     PL_expect = XOPERATOR;
5539     pl_yylval.opval = sawparens(words);
5540     TOKEN(QWLIST);
5541 }
5542
5543 static int
5544 yyl_hyphen(pTHX_ char *s)
5545 {
5546     if (s[1] && isALPHA(s[1]) && !isWORDCHAR(s[2])) {
5547         I32 ftst = 0;
5548         char tmp;
5549
5550         s++;
5551         PL_bufptr = s;
5552         tmp = *s++;
5553
5554         while (s < PL_bufend && SPACE_OR_TAB(*s))
5555             s++;
5556
5557         if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=>")) {
5558             s = force_word(PL_bufptr,BAREWORD,FALSE,FALSE);
5559             DEBUG_T( { printbuf("### Saw unary minus before =>, forcing word %s\n", s); } );
5560             OPERATOR(PERLY_MINUS);              /* unary minus */
5561         }
5562         switch (tmp) {
5563         case 'r': ftst = OP_FTEREAD;    break;
5564         case 'w': ftst = OP_FTEWRITE;   break;
5565         case 'x': ftst = OP_FTEEXEC;    break;
5566         case 'o': ftst = OP_FTEOWNED;   break;
5567         case 'R': ftst = OP_FTRREAD;    break;
5568         case 'W': ftst = OP_FTRWRITE;   break;
5569         case 'X': ftst = OP_FTREXEC;    break;
5570         case 'O': ftst = OP_FTROWNED;   break;
5571         case 'e': ftst = OP_FTIS;       break;
5572         case 'z': ftst = OP_FTZERO;     break;
5573         case 's': ftst = OP_FTSIZE;     break;
5574         case 'f': ftst = OP_FTFILE;     break;
5575         case 'd': ftst = OP_FTDIR;      break;
5576         case 'l': ftst = OP_FTLINK;     break;
5577         case 'p': ftst = OP_FTPIPE;     break;
5578         case 'S': ftst = OP_FTSOCK;     break;
5579         case 'u': ftst = OP_FTSUID;     break;
5580         case 'g': ftst = OP_FTSGID;     break;
5581         case 'k': ftst = OP_FTSVTX;     break;
5582         case 'b': ftst = OP_FTBLK;      break;
5583         case 'c': ftst = OP_FTCHR;      break;
5584         case 't': ftst = OP_FTTTY;      break;
5585         case 'T': ftst = OP_FTTEXT;     break;
5586         case 'B': ftst = OP_FTBINARY;   break;
5587         case 'M': case 'A': case 'C':
5588             gv_fetchpvs("\024", GV_ADD|GV_NOTQUAL, SVt_PV);
5589             switch (tmp) {
5590             case 'M': ftst = OP_FTMTIME; break;
5591             case 'A': ftst = OP_FTATIME; break;
5592             case 'C': ftst = OP_FTCTIME; break;
5593             default:                     break;
5594             }
5595             break;
5596         default:
5597             break;
5598         }
5599         if (ftst) {
5600             PL_last_uni = PL_oldbufptr;
5601             PL_last_lop_op = (OPCODE)ftst;
5602             DEBUG_T( {
5603                 PerlIO_printf(Perl_debug_log, "### Saw file test %c\n", (int)tmp);
5604             } );
5605             FTST(ftst);
5606         }
5607         else {
5608             /* Assume it was a minus followed by a one-letter named
5609              * subroutine call (or a -bareword), then. */
5610             DEBUG_T( {
5611                 PerlIO_printf(Perl_debug_log,
5612                     "### '-%c' looked like a file test but was not\n",
5613                     (int) tmp);
5614             } );
5615             s = --PL_bufptr;
5616         }
5617     }
5618     {
5619         const char tmp = *s++;
5620         if (*s == tmp) {
5621             s++;
5622             if (PL_expect == XOPERATOR)
5623                 TERM(POSTDEC);
5624             else
5625                 OPERATOR(PREDEC);
5626         }
5627         else if (*s == '>') {
5628             s++;
5629             s = skipspace(s);
5630             if (((*s == '$' || *s == '&') && s[1] == '*')
5631               ||(*s == '$' && s[1] == '#' && s[2] == '*')
5632               ||((*s == '@' || *s == '%') && memCHRs("*[{", s[1]))
5633               ||(*s == '*' && (s[1] == '*' || s[1] == '{'))
5634              )
5635             {
5636                 PL_expect = XPOSTDEREF;
5637                 TOKEN(ARROW);
5638             }
5639             if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5640                 s = force_word(s,METHOD,FALSE,TRUE);
5641                 TOKEN(ARROW);
5642             }
5643             else if (*s == '$')
5644                 OPERATOR(ARROW);
5645             else
5646                 TERM(ARROW);
5647         }
5648         if (PL_expect == XOPERATOR) {
5649             if (*s == '='
5650                 && !PL_lex_allbrackets
5651                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5652             {
5653                 s--;
5654                 TOKEN(0);
5655             }
5656             Aop(OP_SUBTRACT);
5657         }
5658         else {
5659             if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5660                 check_uni();
5661             OPERATOR(PERLY_MINUS);              /* unary minus */
5662         }
5663     }
5664 }
5665
5666 static int
5667 yyl_plus(pTHX_ char *s)
5668 {
5669     const char tmp = *s++;
5670     if (*s == tmp) {
5671         s++;
5672         if (PL_expect == XOPERATOR)
5673             TERM(POSTINC);
5674         else
5675             OPERATOR(PREINC);
5676     }
5677     if (PL_expect == XOPERATOR) {
5678         if (*s == '='
5679             && !PL_lex_allbrackets
5680             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5681         {
5682             s--;
5683             TOKEN(0);
5684         }
5685         Aop(OP_ADD);
5686     }
5687     else {
5688         if (isSPACE(*s) || !isSPACE(*PL_bufptr))
5689             check_uni();
5690         OPERATOR(PERLY_PLUS);
5691     }
5692 }
5693
5694 static int
5695 yyl_star(pTHX_ char *s)
5696 {
5697     if (PL_expect == XPOSTDEREF)
5698         POSTDEREF('*');
5699
5700     if (PL_expect != XOPERATOR) {
5701         s = scan_ident(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE);
5702         PL_expect = XOPERATOR;
5703         force_ident(PL_tokenbuf, '*');
5704         if (!*PL_tokenbuf)
5705             PREREF('*');
5706         TERM('*');
5707     }
5708
5709     s++;
5710     if (*s == '*') {
5711         s++;
5712         if (*s == '=' && !PL_lex_allbrackets
5713             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5714         {
5715             s -= 2;
5716             TOKEN(0);
5717         }
5718         PWop(OP_POW);
5719     }
5720
5721     if (*s == '='
5722         && !PL_lex_allbrackets
5723         && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5724     {
5725         s--;
5726         TOKEN(0);
5727     }
5728
5729     Mop(OP_MULTIPLY);
5730 }
5731
5732 static int
5733 yyl_percent(pTHX_ char *s)
5734 {
5735     if (PL_expect == XOPERATOR) {
5736         if (s[1] == '='
5737             && !PL_lex_allbrackets
5738             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
5739         {
5740             TOKEN(0);
5741         }
5742         ++s;
5743         Mop(OP_MODULO);
5744     }
5745     else if (PL_expect == XPOSTDEREF)
5746         POSTDEREF('%');
5747
5748     PL_tokenbuf[0] = '%';
5749     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
5750     pl_yylval.ival = 0;
5751     if (!PL_tokenbuf[1]) {
5752         PREREF('%');
5753     }
5754     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
5755         && intuit_more(s, PL_bufend)) {
5756         if (*s == '[')
5757             PL_tokenbuf[0] = '@';
5758     }
5759     PL_expect = XOPERATOR;
5760     force_ident_maybe_lex('%');
5761     TERM('%');
5762 }
5763
5764 static int
5765 yyl_caret(pTHX_ char *s)
5766 {
5767     char *d = s;
5768     const bool bof = cBOOL(FEATURE_BITWISE_IS_ENABLED);
5769     if (bof && s[1] == '.')
5770         s++;
5771     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
5772             (s[1] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE))
5773     {
5774         s = d;
5775         TOKEN(0);
5776     }
5777     s++;
5778     BOop(bof ? d == s-2 ? OP_SBIT_XOR : OP_NBIT_XOR : OP_BIT_XOR);
5779 }
5780
5781 static int
5782 yyl_colon(pTHX_ char *s)
5783 {
5784     OP *attrs;
5785
5786     switch (PL_expect) {
5787     case XOPERATOR:
5788         if (!PL_in_my || (PL_lex_state != LEX_NORMAL && !PL_lex_brackets))
5789             break;
5790         PL_bufptr = s;  /* update in case we back off */
5791         if (*s == '=') {
5792             Perl_croak(aTHX_
5793                        "Use of := for an empty attribute list is not allowed");
5794         }
5795         goto grabattrs;
5796     case XATTRBLOCK:
5797         PL_expect = XBLOCK;
5798         goto grabattrs;
5799     case XATTRTERM:
5800         PL_expect = XTERMBLOCK;
5801      grabattrs:
5802         /* NB: as well as parsing normal attributes, we also end up
5803          * here if there is something looking like attributes
5804          * following a signature (which is illegal, but used to be
5805          * legal in 5.20..5.26). If the latter, we still parse the
5806          * attributes so that error messages(s) are less confusing,
5807          * but ignore them (parser->sig_seen).
5808          */
5809         s = skipspace(s);
5810         attrs = NULL;
5811         while (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
5812             bool sig = PL_parser->sig_seen;
5813             I32 tmp;
5814             SV *sv;
5815             STRLEN len;
5816             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
5817             if (isLOWER(*s) && (tmp = keyword(PL_tokenbuf, len, 0))) {
5818                 if (tmp < 0) tmp = -tmp;
5819                 switch (tmp) {
5820                 case KEY_or:
5821                 case KEY_and:
5822                 case KEY_for:
5823                 case KEY_foreach:
5824                 case KEY_unless:
5825                 case KEY_if:
5826                 case KEY_while:
5827                 case KEY_until:
5828                     goto got_attrs;
5829                 default:
5830                     break;
5831                 }
5832             }
5833             sv = newSVpvn_flags(s, len, UTF ? SVf_UTF8 : 0);
5834             if (*d == '(') {
5835                 d = scan_str(d,TRUE,TRUE,FALSE,NULL);
5836                 if (!d) {
5837                     if (attrs)
5838                         op_free(attrs);
5839                     sv_free(sv);
5840                     Perl_croak(aTHX_ "Unterminated attribute parameter in attribute list");
5841                 }
5842                 COPLINE_SET_FROM_MULTI_END;
5843             }
5844             if (PL_lex_stuff) {
5845                 sv_catsv(sv, PL_lex_stuff);
5846                 attrs = op_append_elem(OP_LIST, attrs,
5847                                     newSVOP(OP_CONST, 0, sv));
5848                 SvREFCNT_dec_NN(PL_lex_stuff);
5849                 PL_lex_stuff = NULL;
5850             }
5851             else {
5852                 /* NOTE: any CV attrs applied here need to be part of
5853                    the CVf_BUILTIN_ATTRS define in cv.h! */
5854                 if (!PL_in_my && memEQs(SvPVX(sv), len, "lvalue")) {
5855                     sv_free(sv);
5856                     if (!sig)
5857                         CvLVALUE_on(PL_compcv);
5858                 }
5859                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "method")) {
5860                     sv_free(sv);
5861                     if (!sig)
5862                         CvMETHOD_on(PL_compcv);
5863                 }
5864                 else if (!PL_in_my && memEQs(SvPVX(sv), len, "const")) {
5865                     sv_free(sv);
5866                     if (!sig) {
5867                         Perl_ck_warner_d(aTHX_
5868                             packWARN(WARN_EXPERIMENTAL__CONST_ATTR),
5869                            ":const is experimental"
5870                         );
5871                         CvANONCONST_on(PL_compcv);
5872                         if (!CvANON(PL_compcv))
5873                             yyerror(":const is not permitted on named "
5874                                     "subroutines");
5875                     }
5876                 }
5877                 /* After we've set the flags, it could be argued that
5878                    we don't need to do the attributes.pm-based setting
5879                    process, and shouldn't bother appending recognized
5880                    flags.  To experiment with that, uncomment the
5881                    following "else".  (Note that's already been
5882                    uncommented.  That keeps the above-applied built-in
5883                    attributes from being intercepted (and possibly
5884                    rejected) by a package's attribute routines, but is
5885                    justified by the performance win for the common case
5886                    of applying only built-in attributes.) */
5887                 else
5888                     attrs = op_append_elem(OP_LIST, attrs,
5889                                         newSVOP(OP_CONST, 0,
5890                                                 sv));
5891             }
5892             s = skipspace(d);
5893             if (*s == ':' && s[1] != ':')
5894                 s = skipspace(s+1);
5895             else if (s == d)
5896                 break;  /* require real whitespace or :'s */
5897             /* XXX losing whitespace on sequential attributes here */
5898         }
5899
5900         if (*s != ';'
5901             && *s != '}'
5902             && !(PL_expect == XOPERATOR
5903                  ? (*s == '=' ||  *s == ')')
5904                  : (*s == '{' ||  *s == '(')))
5905         {
5906             const char q = ((*s == '\'') ? '"' : '\'');
5907             /* If here for an expression, and parsed no attrs, back off. */
5908             if (PL_expect == XOPERATOR && !attrs) {
5909                 s = PL_bufptr;
5910                 break;
5911             }
5912             /* MUST advance bufptr here to avoid bogus "at end of line"
5913                context messages from yyerror().
5914             */
5915             PL_bufptr = s;
5916             yyerror( (const char *)
5917                      (*s
5918                       ? Perl_form(aTHX_ "Invalid separator character "
5919                                   "%c%c%c in attribute list", q, *s, q)
5920                       : "Unterminated attribute list" ) );
5921             if (attrs)
5922                 op_free(attrs);
5923             OPERATOR(PERLY_COLON);
5924         }
5925
5926     got_attrs:
5927         if (PL_parser->sig_seen) {
5928             /* see comment about about sig_seen and parser error
5929              * handling */
5930             if (attrs)
5931                 op_free(attrs);
5932             Perl_croak(aTHX_ "Subroutine attributes must come "
5933                              "before the signature");
5934         }
5935         if (attrs) {
5936             NEXTVAL_NEXTTOKE.opval = attrs;
5937             force_next(THING);
5938         }
5939         TOKEN(COLONATTR);
5940     }
5941
5942     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING) {
5943         s--;
5944         TOKEN(0);
5945     }
5946
5947     PL_lex_allbrackets--;
5948     OPERATOR(PERLY_COLON);
5949 }
5950
5951 static int
5952 yyl_subproto(pTHX_ char *s, CV *cv)
5953 {
5954     STRLEN protolen = CvPROTOLEN(cv);
5955     const char *proto = CvPROTO(cv);
5956     bool optional;
5957
5958     proto = S_strip_spaces(aTHX_ proto, &protolen);
5959     if (!protolen)
5960         TERM(FUNC0SUB);
5961     if ((optional = *proto == ';')) {
5962         do {
5963             proto++;
5964         } while (*proto == ';');
5965     }
5966
5967     if (
5968         (
5969             (
5970                 *proto == '$' || *proto == '_'
5971              || *proto == '*' || *proto == '+'
5972             )
5973          && proto[1] == '\0'
5974         )
5975      || (
5976          *proto == '\\' && proto[1] && proto[2] == '\0'
5977         )
5978     ) {
5979         UNIPROTO(UNIOPSUB,optional);
5980     }
5981
5982     if (*proto == '\\' && proto[1] == '[') {
5983         const char *p = proto + 2;
5984         while(*p && *p != ']')
5985             ++p;
5986         if(*p == ']' && !p[1])
5987             UNIPROTO(UNIOPSUB,optional);
5988     }
5989
5990     if (*proto == '&' && *s == '{') {
5991         if (PL_curstash)
5992             sv_setpvs(PL_subname, "__ANON__");
5993         else
5994             sv_setpvs(PL_subname, "__ANON__::__ANON__");
5995         if (!PL_lex_allbrackets
5996             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
5997         {
5998             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
5999         }
6000         PREBLOCK(LSTOPSUB);
6001     }
6002
6003     return KEY_NULL;
6004 }
6005
6006 static int
6007 yyl_leftcurly(pTHX_ char *s, const U8 formbrack)
6008 {
6009     char *d;
6010     if (PL_lex_brackets > 100) {
6011         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
6012     }
6013
6014     switch (PL_expect) {
6015     case XTERM:
6016     case XTERMORDORDOR:
6017         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6018         PL_lex_allbrackets++;
6019         OPERATOR(HASHBRACK);
6020     case XOPERATOR:
6021         while (s < PL_bufend && SPACE_OR_TAB(*s))
6022             s++;
6023         d = s;
6024         PL_tokenbuf[0] = '\0';
6025         if (d < PL_bufend && *d == '-') {
6026             PL_tokenbuf[0] = '-';
6027             d++;
6028             while (d < PL_bufend && SPACE_OR_TAB(*d))
6029                 d++;
6030         }
6031         if (d < PL_bufend && isIDFIRST_lazy_if_safe(d, PL_bufend, UTF)) {
6032             STRLEN len;
6033             d = scan_word(d, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
6034                           FALSE, &len);
6035             while (d < PL_bufend && SPACE_OR_TAB(*d))
6036                 d++;
6037             if (*d == '}') {
6038                 const char minus = (PL_tokenbuf[0] == '-');
6039                 s = force_word(s + minus, BAREWORD, FALSE, TRUE);
6040                 if (minus)
6041                     force_next(PERLY_MINUS);
6042             }
6043         }
6044         /* FALLTHROUGH */
6045     case XATTRTERM:
6046     case XTERMBLOCK:
6047         PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6048         PL_lex_allbrackets++;
6049         PL_expect = XSTATE;
6050         break;
6051     case XATTRBLOCK:
6052     case XBLOCK:
6053         PL_lex_brackstack[PL_lex_brackets++] = XSTATE;
6054         PL_lex_allbrackets++;
6055         PL_expect = XSTATE;
6056         break;
6057     case XBLOCKTERM:
6058         PL_lex_brackstack[PL_lex_brackets++] = XTERM;
6059         PL_lex_allbrackets++;
6060         PL_expect = XSTATE;
6061         break;
6062     default: {
6063             const char *t;
6064             if (PL_oldoldbufptr == PL_last_lop)
6065                 PL_lex_brackstack[PL_lex_brackets++] = XTERM;
6066             else
6067                 PL_lex_brackstack[PL_lex_brackets++] = XOPERATOR;
6068             PL_lex_allbrackets++;
6069             s = skipspace(s);
6070             if (*s == '}') {
6071                 if (PL_expect == XREF && PL_lex_state == LEX_INTERPNORMAL) {
6072                     PL_expect = XTERM;
6073                     /* This hack is to get the ${} in the message. */
6074                     PL_bufptr = s+1;
6075                     yyerror("syntax error");
6076                     break;
6077                 }
6078                 OPERATOR(HASHBRACK);
6079             }
6080             if (PL_expect == XREF && PL_oldoldbufptr != PL_last_lop) {
6081                 /* ${...} or @{...} etc., but not print {...}
6082                  * Skip the disambiguation and treat this as a block.
6083                  */
6084                 goto block_expectation;
6085             }
6086             /* This hack serves to disambiguate a pair of curlies
6087              * as being a block or an anon hash.  Normally, expectation
6088              * determines that, but in cases where we're not in a
6089              * position to expect anything in particular (like inside
6090              * eval"") we have to resolve the ambiguity.  This code
6091              * covers the case where the first term in the curlies is a
6092              * quoted string.  Most other cases need to be explicitly
6093              * disambiguated by prepending a "+" before the opening
6094              * curly in order to force resolution as an anon hash.
6095              *
6096              * XXX should probably propagate the outer expectation
6097              * into eval"" to rely less on this hack, but that could
6098              * potentially break current behavior of eval"".
6099              * GSAR 97-07-21
6100              */
6101             t = s;
6102             if (*s == '\'' || *s == '"' || *s == '`') {
6103                 /* common case: get past first string, handling escapes */
6104                 for (t++; t < PL_bufend && *t != *s;)
6105                     if (*t++ == '\\')
6106                         t++;
6107                 t++;
6108             }
6109             else if (*s == 'q') {
6110                 if (++t < PL_bufend
6111                     && (!isWORDCHAR(*t)
6112                         || ((*t == 'q' || *t == 'x') && ++t < PL_bufend
6113                             && !isWORDCHAR(*t))))
6114                 {
6115                     /* skip q//-like construct */
6116                     const char *tmps;
6117                     char open, close, term;
6118                     I32 brackets = 1;
6119
6120                     while (t < PL_bufend && isSPACE(*t))
6121                         t++;
6122                     /* check for q => */
6123                     if (t+1 < PL_bufend && t[0] == '=' && t[1] == '>') {
6124                         OPERATOR(HASHBRACK);
6125                     }
6126                     term = *t;
6127                     open = term;
6128                     if (term && (tmps = memCHRs("([{< )]}> )]}>",term)))
6129                         term = tmps[5];
6130                     close = term;
6131                     if (open == close)
6132                         for (t++; t < PL_bufend; t++) {
6133                             if (*t == '\\' && t+1 < PL_bufend && open != '\\')
6134                                 t++;
6135                             else if (*t == open)
6136                                 break;
6137                         }
6138                     else {
6139                         for (t++; t < PL_bufend; t++) {
6140                             if (*t == '\\' && t+1 < PL_bufend)
6141                                 t++;
6142                             else if (*t == close && --brackets <= 0)
6143                                 break;
6144                             else if (*t == open)
6145                                 brackets++;
6146                         }
6147                     }
6148                     t++;
6149                 }
6150                 else
6151                     /* skip plain q word */
6152                     while (   t < PL_bufend
6153                            && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6154                     {
6155                         t += UTF ? UTF8SKIP(t) : 1;
6156                     }
6157             }
6158             else if (isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF)) {
6159                 t += UTF ? UTF8SKIP(t) : 1;
6160                 while (   t < PL_bufend
6161                        && isWORDCHAR_lazy_if_safe(t, PL_bufend, UTF))
6162                 {
6163                     t += UTF ? UTF8SKIP(t) : 1;
6164                 }
6165             }
6166             while (t < PL_bufend && isSPACE(*t))
6167                 t++;
6168             /* if comma follows first term, call it an anon hash */
6169             /* XXX it could be a comma expression with loop modifiers */
6170             if (t < PL_bufend && ((*t == ',' && (*s == 'q' || !isLOWER(*s)))
6171                                || (*t == '=' && t[1] == '>')))
6172                 OPERATOR(HASHBRACK);
6173             if (PL_expect == XREF) {
6174               block_expectation:
6175                 /* If there is an opening brace or 'sub:', treat it
6176                    as a term to make ${{...}}{k} and &{sub:attr...}
6177                    dwim.  Otherwise, treat it as a statement, so
6178                    map {no strict; ...} works.
6179                  */
6180                 s = skipspace(s);
6181                 if (*s == '{') {
6182                     PL_expect = XTERM;
6183                     break;
6184                 }
6185                 if (memBEGINs(s, (STRLEN) (PL_bufend - s), "sub")) {
6186                     PL_bufptr = s;
6187                     d = s + 3;
6188                     d = skipspace(d);
6189                     s = PL_bufptr;
6190                     if (*d == ':') {
6191                         PL_expect = XTERM;
6192                         break;
6193                     }
6194                 }
6195                 PL_expect = XSTATE;
6196             }
6197             else {
6198                 PL_lex_brackstack[PL_lex_brackets-1] = XSTATE;
6199                 PL_expect = XSTATE;
6200             }
6201         }
6202         break;
6203     }
6204
6205     pl_yylval.ival = CopLINE(PL_curcop);
6206     PL_copline = NOLINE;   /* invalidate current command line number */
6207     TOKEN(formbrack ? PERLY_EQUAL_SIGN : PERLY_BRACE_OPEN);
6208 }
6209
6210 static int
6211 yyl_rightcurly(pTHX_ char *s, const U8 formbrack)
6212 {
6213     assert(s != PL_bufend);
6214     s++;
6215
6216     if (PL_lex_brackets <= 0)
6217         /* diag_listed_as: Unmatched right %s bracket */
6218         yyerror("Unmatched right curly bracket");
6219     else
6220         PL_expect = (expectation)PL_lex_brackstack[--PL_lex_brackets];
6221
6222     PL_lex_allbrackets--;
6223
6224     if (PL_lex_state == LEX_INTERPNORMAL) {
6225         if (PL_lex_brackets == 0) {
6226             if (PL_expect & XFAKEBRACK) {
6227                 PL_expect &= XENUMMASK;
6228                 PL_lex_state = LEX_INTERPEND;
6229                 PL_bufptr = s;
6230                 return yylex(); /* ignore fake brackets */
6231             }
6232             if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6233              && SvEVALED(PL_lex_repl))
6234                 PL_lex_state = LEX_INTERPEND;
6235             else if (*s == '-' && s[1] == '>')
6236                 PL_lex_state = LEX_INTERPENDMAYBE;
6237             else if (*s != '[' && *s != '{')
6238                 PL_lex_state = LEX_INTERPEND;
6239         }
6240     }
6241
6242     if (PL_expect & XFAKEBRACK) {
6243         PL_expect &= XENUMMASK;
6244         PL_bufptr = s;
6245         return yylex();         /* ignore fake brackets */
6246     }
6247
6248     force_next(formbrack ? PERLY_DOT : PERLY_BRACE_CLOSE);
6249     if (formbrack) LEAVE_with_name("lex_format");
6250     if (formbrack == 2) { /* means . where arguments were expected */
6251         force_next(PERLY_SEMICOLON);
6252         TOKEN(FORMRBRACK);
6253     }
6254
6255     TOKEN(PERLY_SEMICOLON);
6256 }
6257
6258 static int
6259 yyl_ampersand(pTHX_ char *s)
6260 {
6261     if (PL_expect == XPOSTDEREF)
6262         POSTDEREF(PERLY_AMPERSAND);
6263
6264     s++;
6265     if (*s++ == '&') {
6266         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6267                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6268             s -= 2;
6269             TOKEN(0);
6270         }
6271         AOPERATOR(ANDAND);
6272     }
6273     s--;
6274
6275     if (PL_expect == XOPERATOR) {
6276         char *d;
6277         bool bof;
6278         if (   PL_bufptr == PL_linestart
6279             && ckWARN(WARN_SEMICOLON)
6280             && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
6281         {
6282             CopLINE_dec(PL_curcop);
6283             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
6284             CopLINE_inc(PL_curcop);
6285         }
6286         d = s;
6287         if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6288             s++;
6289         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6290                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6291             s = d;
6292             s--;
6293             TOKEN(0);
6294         }
6295         if (d == s)
6296             BAop(bof ? OP_NBIT_AND : OP_BIT_AND);
6297         else
6298             BAop(OP_SBIT_AND);
6299     }
6300
6301     PL_tokenbuf[0] = '&';
6302     s = scan_ident(s - 1, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, TRUE);
6303     pl_yylval.ival = (OPpENTERSUB_AMPER<<8);
6304
6305     if (PL_tokenbuf[1])
6306         force_ident_maybe_lex('&');
6307     else
6308         PREREF(PERLY_AMPERSAND);
6309
6310     TERM(PERLY_AMPERSAND);
6311 }
6312
6313 static int
6314 yyl_verticalbar(pTHX_ char *s)
6315 {
6316     char *d;
6317     bool bof;
6318
6319     s++;
6320     if (*s++ == '|') {
6321         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6322                 (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC)) {
6323             s -= 2;
6324             TOKEN(0);
6325         }
6326         AOPERATOR(OROR);
6327     }
6328
6329     s--;
6330     d = s;
6331     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.')
6332         s++;
6333
6334     if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6335             (*s == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_BITWISE)) {
6336         s = d - 1;
6337         TOKEN(0);
6338     }
6339
6340     BOop(bof ? s == d ? OP_NBIT_OR : OP_SBIT_OR : OP_BIT_OR);
6341 }
6342
6343 static int
6344 yyl_bang(pTHX_ char *s)
6345 {
6346     const char tmp = *s++;
6347     if (tmp == '=') {
6348         /* was this !=~ where !~ was meant?
6349          * warn on m:!=~\s+([/?]|[msy]\W|tr\W): */
6350
6351         if (*s == '~' && ckWARN(WARN_SYNTAX)) {
6352             const char *t = s+1;
6353
6354             while (t < PL_bufend && isSPACE(*t))
6355                 ++t;
6356
6357             if (*t == '/' || *t == '?'
6358                 || ((*t == 'm' || *t == 's' || *t == 'y')
6359                     && !isWORDCHAR(t[1]))
6360                 || (*t == 't' && t[1] == 'r' && !isWORDCHAR(t[2])))
6361                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
6362                             "!=~ should be !~");
6363         }
6364
6365         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6366             s -= 2;
6367             TOKEN(0);
6368         }
6369
6370         ChEop(OP_NE);
6371     }
6372
6373     if (tmp == '~')
6374         PMop(OP_NOT);
6375
6376     s--;
6377     OPERATOR(PERLY_EXCLAMATION_MARK);
6378 }
6379
6380 static int
6381 yyl_snail(pTHX_ char *s)
6382 {
6383     if (PL_expect == XPOSTDEREF)
6384         POSTDEREF(PERLY_SNAIL);
6385     PL_tokenbuf[0] = '@';
6386     s = scan_ident(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1, FALSE);
6387     if (PL_expect == XOPERATOR) {
6388         char *d = s;
6389         if (PL_bufptr > s) {
6390             d = PL_bufptr-1;
6391             PL_bufptr = PL_oldbufptr;
6392         }
6393         no_op("Array", d);
6394     }
6395     pl_yylval.ival = 0;
6396     if (!PL_tokenbuf[1]) {
6397         PREREF(PERLY_SNAIL);
6398     }
6399     if (PL_lex_state == LEX_NORMAL || PL_lex_brackets)
6400         s = skipspace(s);
6401     if (   (PL_expect != XREF || PL_oldoldbufptr == PL_last_lop)
6402         && intuit_more(s, PL_bufend))
6403     {
6404         if (*s == '{')
6405             PL_tokenbuf[0] = '%';
6406
6407         /* Warn about @ where they meant $. */
6408         if (*s == '[' || *s == '{') {
6409             if (ckWARN(WARN_SYNTAX)) {
6410                 S_check_scalar_slice(aTHX_ s);
6411             }
6412         }
6413     }
6414     PL_expect = XOPERATOR;
6415     force_ident_maybe_lex('@');
6416     TERM(PERLY_SNAIL);
6417 }
6418
6419 static int
6420 yyl_slash(pTHX_ char *s)
6421 {
6422     if ((PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR) && s[1] == '/') {
6423         if (!PL_lex_allbrackets && PL_lex_fakeeof >=
6424                 (s[2] == '=' ? LEX_FAKEEOF_ASSIGN : LEX_FAKEEOF_LOGIC))
6425             TOKEN(0);
6426         s += 2;
6427         AOPERATOR(DORDOR);
6428     }
6429     else if (PL_expect == XOPERATOR) {
6430         s++;
6431         if (*s == '=' && !PL_lex_allbrackets
6432             && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
6433         {
6434             s--;
6435             TOKEN(0);
6436         }
6437         Mop(OP_DIVIDE);
6438     }
6439     else {
6440         /* Disable warning on "study /blah/" */
6441         if (    PL_oldoldbufptr == PL_last_uni
6442             && (   *PL_last_uni != 's' || s - PL_last_uni < 5
6443                 || memNE(PL_last_uni, "study", 5)
6444                 || isWORDCHAR_lazy_if_safe(PL_last_uni+5, PL_bufend, UTF)
6445          ))
6446             check_uni();
6447         s = scan_pat(s,OP_MATCH);
6448         TERM(sublex_start());
6449     }
6450 }
6451
6452 static int
6453 yyl_leftsquare(pTHX_ char *s)
6454 {
6455     if (PL_lex_brackets > 100)
6456         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
6457     PL_lex_brackstack[PL_lex_brackets++] = 0;
6458     PL_lex_allbrackets++;
6459     s++;
6460     OPERATOR(PERLY_BRACKET_OPEN);
6461 }
6462
6463 static int
6464 yyl_rightsquare(pTHX_ char *s)
6465 {
6466     if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
6467         TOKEN(0);
6468     s++;
6469     if (PL_lex_brackets <= 0)
6470         /* diag_listed_as: Unmatched right %s bracket */
6471         yyerror("Unmatched right square bracket");
6472     else
6473         --PL_lex_brackets;
6474     PL_lex_allbrackets--;
6475     if (PL_lex_state == LEX_INTERPNORMAL) {
6476         if (PL_lex_brackets == 0) {
6477             if (*s == '-' && s[1] == '>')
6478                 PL_lex_state = LEX_INTERPENDMAYBE;
6479             else if (*s != '[' && *s != '{')
6480                 PL_lex_state = LEX_INTERPEND;
6481         }
6482     }
6483     TERM(PERLY_BRACKET_CLOSE);
6484 }
6485
6486 static int
6487 yyl_tilde(pTHX_ char *s)
6488 {
6489     bool bof;
6490     if (s[1] == '~' && (PL_expect == XOPERATOR || PL_expect == XTERMORDORDOR)) {
6491         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
6492             TOKEN(0);
6493         s += 2;
6494         Perl_ck_warner_d(aTHX_
6495             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
6496             "Smartmatch is experimental");
6497         NCEop(OP_SMARTMATCH);
6498     }
6499     s++;
6500     if ((bof = FEATURE_BITWISE_IS_ENABLED) && *s == '.') {
6501         s++;
6502         BCop(OP_SCOMPLEMENT);
6503     }
6504     BCop(bof ? OP_NCOMPLEMENT : OP_COMPLEMENT);
6505 }
6506
6507 static int
6508 yyl_leftparen(pTHX_ char *s)
6509 {
6510     if (PL_last_lop == PL_oldoldbufptr || PL_last_uni == PL_oldoldbufptr)
6511         PL_oldbufptr = PL_oldoldbufptr;         /* allow print(STDOUT 123) */
6512     else
6513         PL_expect = XTERM;
6514     s = skipspace(s);
6515     PL_lex_allbrackets++;
6516     TOKEN('(');
6517 }
6518
6519 static int
6520 yyl_rightparen(pTHX_ char *s)
6521 {
6522     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_CLOSING)
6523         TOKEN(0);
6524     s++;
6525     PL_lex_allbrackets--;
6526     s = skipspace(s);
6527     if (*s == '{')
6528         PREBLOCK(')');
6529     TERM(')');
6530 }
6531
6532 static int
6533 yyl_leftpointy(pTHX_ char *s)
6534 {
6535     char tmp;
6536
6537     if (PL_expect != XOPERATOR) {
6538         if (s[1] != '<' && !memchr(s,'>', PL_bufend - s))
6539             check_uni();
6540         if (s[1] == '<' && s[2] != '>')
6541             s = scan_heredoc(s);
6542         else
6543             s = scan_inputsymbol(s);
6544         PL_expect = XOPERATOR;
6545         TOKEN(sublex_start());
6546     }
6547
6548     s++;
6549
6550     tmp = *s++;
6551     if (tmp == '<') {
6552         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6553             s -= 2;
6554             TOKEN(0);
6555         }
6556         SHop(OP_LEFT_SHIFT);
6557     }
6558     if (tmp == '=') {
6559         tmp = *s++;
6560         if (tmp == '>') {
6561             if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6562                 s -= 3;
6563                 TOKEN(0);
6564             }
6565             NCEop(OP_NCMP);
6566         }
6567         s--;
6568         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6569             s -= 2;
6570             TOKEN(0);
6571         }
6572         ChRop(OP_LE);
6573     }
6574
6575     s--;
6576     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6577         s--;
6578         TOKEN(0);
6579     }
6580
6581     ChRop(OP_LT);
6582 }
6583
6584 static int
6585 yyl_rightpointy(pTHX_ char *s)
6586 {
6587     const char tmp = *s++;
6588
6589     if (tmp == '>') {
6590         if (*s == '=' && !PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
6591             s -= 2;
6592             TOKEN(0);
6593         }
6594         SHop(OP_RIGHT_SHIFT);
6595     }
6596     else if (tmp == '=') {
6597         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6598             s -= 2;
6599             TOKEN(0);
6600         }
6601         ChRop(OP_GE);
6602     }
6603
6604     s--;
6605     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE) {
6606         s--;
6607         TOKEN(0);
6608     }
6609
6610     ChRop(OP_GT);
6611 }
6612
6613 static int
6614 yyl_sglquote(pTHX_ char *s)
6615 {
6616     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6617     if (!s)
6618         missingterm(NULL, 0);
6619     COPLINE_SET_FROM_MULTI_END;
6620     DEBUG_T( { printbuf("### Saw string before %s\n", s); } );
6621     if (PL_expect == XOPERATOR) {
6622         no_op("String",s);
6623     }
6624     pl_yylval.ival = OP_CONST;
6625     TERM(sublex_start());
6626 }
6627
6628 static int
6629 yyl_dblquote(pTHX_ char *s)
6630 {
6631     char *d;
6632     STRLEN len;
6633     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6634     DEBUG_T( {
6635         if (s)
6636             printbuf("### Saw string before %s\n", s);
6637         else
6638             PerlIO_printf(Perl_debug_log,
6639                          "### Saw unterminated string\n");
6640     } );
6641     if (PL_expect == XOPERATOR) {
6642             no_op("String",s);
6643     }
6644     if (!s)
6645         missingterm(NULL, 0);
6646     pl_yylval.ival = OP_CONST;
6647     /* FIXME. I think that this can be const if char *d is replaced by
6648        more localised variables.  */
6649     for (d = SvPV(PL_lex_stuff, len); len; len--, d++) {
6650         if (*d == '$' || *d == '@' || *d == '\\' || !UTF8_IS_INVARIANT((U8)*d)) {
6651             pl_yylval.ival = OP_STRINGIFY;
6652             break;
6653         }
6654     }
6655     if (pl_yylval.ival == OP_CONST)
6656         COPLINE_SET_FROM_MULTI_END;
6657     TERM(sublex_start());
6658 }
6659
6660 static int
6661 yyl_backtick(pTHX_ char *s)
6662 {
6663     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
6664     DEBUG_T( {
6665         if (s)
6666             printbuf("### Saw backtick string before %s\n", s);
6667         else
6668             PerlIO_printf(Perl_debug_log,
6669                          "### Saw unterminated backtick string\n");
6670     } );
6671     if (PL_expect == XOPERATOR)
6672         no_op("Backticks",s);
6673     if (!s)
6674         missingterm(NULL, 0);
6675     pl_yylval.ival = OP_BACKTICK;
6676     TERM(sublex_start());
6677 }
6678
6679 static int
6680 yyl_backslash(pTHX_ char *s)
6681 {
6682     if (PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr && isDIGIT(*s))
6683         Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX),"Can't use \\%c to mean $%c in expression",
6684                        *s, *s);
6685     if (PL_expect == XOPERATOR)
6686         no_op("Backslash",s);
6687     OPERATOR(REFGEN);
6688 }
6689
6690 static void
6691 yyl_data_handle(pTHX)
6692 {
6693     HV * const stash = PL_tokenbuf[2] == 'D' && PL_curstash
6694                             ? PL_curstash
6695                             : PL_defstash;
6696     GV *gv = (GV *)*hv_fetchs(stash, "DATA", 1);
6697
6698     if (!isGV(gv))
6699         gv_init(gv,stash,"DATA",4,0);
6700
6701     GvMULTI_on(gv);
6702     if (!GvIO(gv))
6703         GvIOp(gv) = newIO();
6704     IoIFP(GvIOp(gv)) = PL_rsfp;
6705
6706     /* Mark this internal pseudo-handle as clean */
6707     IoFLAGS(GvIOp(gv)) |= IOf_UNTAINT;
6708     if ((PerlIO*)PL_rsfp == PerlIO_stdin())
6709         IoTYPE(GvIOp(gv)) = IoTYPE_STD;
6710     else
6711         IoTYPE(GvIOp(gv)) = IoTYPE_RDONLY;
6712
6713 #if defined(WIN32) && !defined(PERL_TEXTMODE_SCRIPTS)
6714     /* if the script was opened in binmode, we need to revert
6715      * it to text mode for compatibility; but only iff it has CRs
6716      * XXX this is a questionable hack at best. */
6717     if (PL_bufend-PL_bufptr > 2
6718         && PL_bufend[-1] == '\n' && PL_bufend[-2] == '\r')
6719     {
6720         Off_t loc = 0;
6721         if (IoTYPE(GvIOp(gv)) == IoTYPE_RDONLY) {
6722             loc = PerlIO_tell(PL_rsfp);
6723             (void)PerlIO_seek(PL_rsfp, 0L, 0);
6724         }
6725         if (PerlLIO_setmode(RSFP_FILENO, O_TEXT) != -1) {
6726             if (loc > 0)
6727                 PerlIO_seek(PL_rsfp, loc, 0);
6728         }
6729     }
6730 #endif
6731
6732 #ifdef PERLIO_LAYERS
6733     if (!IN_BYTES) {
6734         if (UTF)
6735             PerlIO_apply_layers(aTHX_ PL_rsfp, NULL, ":utf8");
6736     }
6737 #endif
6738
6739     PL_rsfp = NULL;
6740 }
6741
6742 PERL_STATIC_NO_RET void yyl_croak_unrecognised(pTHX_ char*)
6743     __attribute__noreturn__;
6744
6745 PERL_STATIC_NO_RET void
6746 yyl_croak_unrecognised(pTHX_ char *s)
6747 {
6748     SV *dsv = newSVpvs_flags("", SVs_TEMP);
6749     const char *c;
6750     char *d;
6751     STRLEN len;
6752
6753     if (UTF) {
6754         STRLEN skiplen = UTF8SKIP(s);
6755         STRLEN stravail = PL_bufend - s;
6756         c = sv_uni_display(dsv, newSVpvn_flags(s,
6757                                                skiplen > stravail ? stravail : skiplen,
6758                                                SVs_TEMP | SVf_UTF8),
6759                            10, UNI_DISPLAY_ISPRINT);
6760     }
6761     else {
6762         c = Perl_form(aTHX_ "\\x%02X", (unsigned char)*s);
6763     }
6764
6765     if (s >= PL_linestart) {
6766         d = PL_linestart;
6767     }
6768     else {
6769         /* somehow (probably due to a parse failure), PL_linestart has advanced
6770          * pass PL_bufptr, get a reasonable beginning of line
6771          */
6772         d = s;
6773         while (d > SvPVX(PL_linestr) && d[-1] && d[-1] != '\n')
6774             --d;
6775     }
6776     len = UTF ? Perl_utf8_length(aTHX_ (U8 *) d, (U8 *) s) : (STRLEN) (s - d);
6777     if (len > UNRECOGNIZED_PRECEDE_COUNT) {
6778         d = UTF ? (char *) utf8_hop_back((U8 *) s, -UNRECOGNIZED_PRECEDE_COUNT, (U8 *)d) : s - UNRECOGNIZED_PRECEDE_COUNT;
6779     }
6780
6781     Perl_croak(aTHX_  "Unrecognized character %s; marked by <-- HERE after %" UTF8f "<-- HERE near column %d", c,
6782                       UTF8fARG(UTF, (s - d), d),
6783                      (int) len + 1);
6784 }
6785
6786 static int
6787 yyl_require(pTHX_ char *s, I32 orig_keyword)
6788 {
6789     s = skipspace(s);
6790     if (isDIGIT(*s)) {
6791         s = force_version(s, FALSE);
6792     }
6793     else if (*s != 'v' || !isDIGIT(s[1])
6794             || (s = force_version(s, TRUE), *s == 'v'))
6795     {
6796         *PL_tokenbuf = '\0';
6797         s = force_word(s,BAREWORD,TRUE,TRUE);
6798         if (isIDFIRST_lazy_if_safe(PL_tokenbuf,
6799                                    PL_tokenbuf + sizeof(PL_tokenbuf),
6800                                    UTF))
6801         {
6802             gv_stashpvn(PL_tokenbuf, strlen(PL_tokenbuf),
6803                         GV_ADD | (UTF ? SVf_UTF8 : 0));
6804         }
6805         else if (*s == '<')
6806             yyerror("<> at require-statement should be quotes");
6807     }
6808
6809     if (orig_keyword == KEY_require)
6810         pl_yylval.ival = 1;
6811     else
6812         pl_yylval.ival = 0;
6813
6814     PL_expect = PL_nexttoke ? XOPERATOR : XTERM;
6815     PL_bufptr = s;
6816     PL_last_uni = PL_oldbufptr;
6817     PL_last_lop_op = OP_REQUIRE;
6818     s = skipspace(s);
6819     return REPORT( (int)REQUIRE );
6820 }
6821
6822 static int
6823 yyl_foreach(pTHX_ char *s)
6824 {
6825     if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
6826         return REPORT(0);
6827     pl_yylval.ival = CopLINE(PL_curcop);
6828     s = skipspace(s);
6829     if (PL_expect == XSTATE && isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6830         char *p = s;
6831         SSize_t s_off = s - SvPVX(PL_linestr);
6832         STRLEN len;
6833
6834         if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "my") && isSPACE(p[2])) {
6835             p += 2;
6836         }
6837         else if (memBEGINPs(p, (STRLEN) (PL_bufend - p), "our") && isSPACE(p[3])) {
6838             p += 3;
6839         }
6840
6841         p = skipspace(p);
6842         /* skip optional package name, as in "for my abc $x (..)" */
6843         if (isIDFIRST_lazy_if_safe(p, PL_bufend, UTF)) {
6844             p = scan_word(p, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6845             p = skipspace(p);
6846         }
6847         if (*p != '$' && *p != '\\')
6848             Perl_croak(aTHX_ "Missing $ on loop variable");
6849
6850         /* The buffer may have been reallocated, update s */
6851         s = SvPVX(PL_linestr) + s_off;
6852     }
6853     OPERATOR(FOR);
6854 }
6855
6856 static int
6857 yyl_do(pTHX_ char *s, I32 orig_keyword)
6858 {
6859     s = skipspace(s);
6860     if (*s == '{')
6861         PRETERMBLOCK(DO);
6862     if (*s != '\'') {
6863         char *d;
6864         STRLEN len;
6865         *PL_tokenbuf = '&';
6866         d = scan_word(s, PL_tokenbuf + 1, sizeof PL_tokenbuf - 1,
6867                       1, &len);
6868         if (len && memNEs(PL_tokenbuf+1, len, "CORE")
6869          && !keyword(PL_tokenbuf + 1, len, 0)) {
6870             SSize_t off = s-SvPVX(PL_linestr);
6871             d = skipspace(d);
6872             s = SvPVX(PL_linestr)+off;
6873             if (*d == '(') {
6874                 force_ident_maybe_lex('&');
6875                 s = d;
6876             }
6877         }
6878     }
6879     if (orig_keyword == KEY_do)
6880         pl_yylval.ival = 1;
6881     else
6882         pl_yylval.ival = 0;
6883     OPERATOR(DO);
6884 }
6885
6886 static int
6887 yyl_my(pTHX_ char *s, I32 my)
6888 {
6889     if (PL_in_my) {
6890         PL_bufptr = s;
6891         yyerror(Perl_form(aTHX_
6892                           "Can't redeclare \"%s\" in \"%s\"",
6893                            my       == KEY_my    ? "my" :
6894                            my       == KEY_state ? "state" : "our",
6895                            PL_in_my == KEY_my    ? "my" :
6896                            PL_in_my == KEY_state ? "state" : "our"));
6897     }
6898     PL_in_my = (U16)my;
6899     s = skipspace(s);
6900     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
6901         STRLEN len;
6902         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, TRUE, &len);
6903         if (memEQs(PL_tokenbuf, len, "sub"))
6904             return yyl_sub(aTHX_ s, my);
6905         PL_in_my_stash = find_in_my_stash(PL_tokenbuf, len);
6906         if (!PL_in_my_stash) {
6907             char tmpbuf[1024];
6908             int i;
6909             PL_bufptr = s;
6910             i = my_snprintf(tmpbuf, sizeof(tmpbuf), "No such class %.1000s", PL_tokenbuf);
6911             PERL_MY_SNPRINTF_POST_GUARD(i, sizeof(tmpbuf));
6912             yyerror_pv(tmpbuf, UTF ? SVf_UTF8 : 0);
6913         }
6914     }
6915     else if (*s == '\\') {
6916         if (!FEATURE_MYREF_IS_ENABLED)
6917             Perl_croak(aTHX_ "The experimental declared_refs "
6918                              "feature is not enabled");
6919         Perl_ck_warner_d(aTHX_
6920              packWARN(WARN_EXPERIMENTAL__DECLARED_REFS),
6921             "Declaring references is experimental");
6922     }
6923     OPERATOR(MY);
6924 }
6925
6926 static int yyl_try(pTHX_ char*);
6927
6928 static bool
6929 yyl_eol_needs_semicolon(pTHX_ char **ps)
6930 {
6931     char *s = *ps;
6932     if (PL_lex_state != LEX_NORMAL
6933         || (PL_in_eval && !PL_rsfp && !PL_parser->filtered))
6934     {
6935         const bool in_comment = *s == '#';
6936         char *d;
6937         if (*s == '#' && s == PL_linestart && PL_in_eval
6938          && !PL_rsfp && !PL_parser->filtered) {
6939             /* handle eval qq[#line 1 "foo"\n ...] */
6940             CopLINE_dec(PL_curcop);
6941             incline(s, PL_bufend);
6942         }
6943         d = s;
6944         while (d < PL_bufend && *d != '\n')
6945             d++;
6946         if (d < PL_bufend)
6947             d++;
6948         s = d;
6949         if (in_comment && d == PL_bufend
6950             && PL_lex_state == LEX_INTERPNORMAL
6951             && PL_lex_inwhat == OP_SUBST && PL_lex_repl == PL_linestr
6952             && SvEVALED(PL_lex_repl) && d[-1] == '}') s--;
6953         else
6954             incline(s, PL_bufend);
6955         if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
6956             PL_lex_state = LEX_FORMLINE;
6957             force_next(FORMRBRACK);
6958             *ps = s;
6959             return TRUE;
6960         }
6961     }
6962     else {
6963         while (s < PL_bufend && *s != '\n')
6964             s++;
6965         if (s < PL_bufend) {
6966             s++;
6967             if (s < PL_bufend)
6968                 incline(s, PL_bufend);
6969         }
6970     }
6971     *ps = s;
6972     return FALSE;
6973 }
6974
6975 static int
6976 yyl_fake_eof(pTHX_ U32 fake_eof, bool bof, char *s)
6977 {
6978     char *d;
6979
6980     goto start;
6981
6982     do {
6983         fake_eof = 0;
6984         bof = cBOOL(PL_rsfp);
6985       start:
6986
6987         PL_bufptr = PL_bufend;
6988         COPLINE_INC_WITH_HERELINES;
6989         if (!lex_next_chunk(fake_eof)) {
6990             CopLINE_dec(PL_curcop);
6991             s = PL_bufptr;
6992             TOKEN(PERLY_SEMICOLON);     /* not infinite loop because rsfp is NULL now */
6993         }
6994         CopLINE_dec(PL_curcop);
6995         s = PL_bufptr;
6996         /* If it looks like the start of a BOM or raw UTF-16,
6997          * check if it in fact is. */
6998         if (bof && PL_rsfp
6999             && (   *s == 0
7000                 || *(U8*)s == BOM_UTF8_FIRST_BYTE
7001                 || *(U8*)s >= 0xFE
7002                 || s[1] == 0))
7003         {
7004             Off_t offset = (IV)PerlIO_tell(PL_rsfp);
7005             bof = (offset == (Off_t)SvCUR(PL_linestr));
7006 #if defined(PERLIO_USING_CRLF) && defined(PERL_TEXTMODE_SCRIPTS)
7007             /* offset may include swallowed CR */
7008             if (!bof)
7009                 bof = (offset == (Off_t)SvCUR(PL_linestr)+1);
7010 #endif
7011             if (bof) {
7012                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7013                 s = swallow_bom((U8*)s);
7014             }
7015         }
7016         if (PL_parser->in_pod) {
7017             /* Incest with pod. */
7018             if (    memBEGINPs(s, (STRLEN) (PL_bufend - s), "=cut")
7019                 && !isALPHA(s[4]))
7020             {
7021                 SvPVCLEAR(PL_linestr);
7022                 PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
7023                 PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7024                 PL_last_lop = PL_last_uni = NULL;
7025                 PL_parser->in_pod = 0;
7026             }
7027         }
7028         if (PL_rsfp || PL_parser->filtered)
7029             incline(s, PL_bufend);
7030     } while (PL_parser->in_pod);
7031
7032     PL_oldoldbufptr = PL_oldbufptr = PL_bufptr = PL_linestart = s;
7033     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7034     PL_last_lop = PL_last_uni = NULL;
7035     if (CopLINE(PL_curcop) == 1) {
7036         while (s < PL_bufend && isSPACE(*s))
7037             s++;
7038         if (*s == ':' && s[1] != ':') /* for csh execing sh scripts */
7039             s++;
7040         d = NULL;
7041         if (!PL_in_eval) {
7042             if (*s == '#' && *(s+1) == '!')
7043                 d = s + 2;
7044 #ifdef ALTERNATE_SHEBANG
7045             else {
7046                 static char const as[] = ALTERNATE_SHEBANG;
7047                 if (*s == as[0] && strnEQ(s, as, sizeof(as) - 1))
7048                     d = s + (sizeof(as) - 1);
7049             }
7050 #endif /* ALTERNATE_SHEBANG */
7051         }
7052         if (d) {
7053             char *ipath;
7054             char *ipathend;
7055
7056             while (isSPACE(*d))
7057                 d++;
7058             ipath = d;
7059             while (*d && !isSPACE(*d))
7060                 d++;
7061             ipathend = d;
7062
7063 #ifdef ARG_ZERO_IS_SCRIPT
7064             if (ipathend > ipath) {
7065                 /*
7066                  * HP-UX (at least) sets argv[0] to the script name,
7067                  * which makes $^X incorrect.  And Digital UNIX and Linux,
7068                  * at least, set argv[0] to the basename of the Perl
7069                  * interpreter. So, having found "#!", we'll set it right.
7070                  */
7071                 SV* copfilesv = CopFILESV(PL_curcop);
7072                 if (copfilesv) {
7073                     SV * const x =
7074                         GvSV(gv_fetchpvs("\030", GV_ADD|GV_NOTQUAL,
7075                                          SVt_PV)); /* $^X */
7076                     assert(SvPOK(x) || SvGMAGICAL(x));
7077                     if (sv_eq(x, copfilesv)) {
7078                         sv_setpvn(x, ipath, ipathend - ipath);
7079                         SvSETMAGIC(x);
7080                     }
7081                     else {
7082                         STRLEN blen;
7083                         STRLEN llen;
7084                         const char *bstart = SvPV_const(copfilesv, blen);
7085                         const char * const lstart = SvPV_const(x, llen);
7086                         if (llen < blen) {
7087                             bstart += blen - llen;
7088                             if (strnEQ(bstart, lstart, llen) && bstart[-1] == '/') {
7089                                 sv_setpvn(x, ipath, ipathend - ipath);
7090                                 SvSETMAGIC(x);
7091                             }
7092                         }
7093                     }
7094                 }
7095                 else {
7096                     /* Anything to do if no copfilesv? */
7097                 }
7098                 TAINT_NOT;      /* $^X is always tainted, but that's OK */
7099             }
7100 #endif /* ARG_ZERO_IS_SCRIPT */
7101
7102             /*
7103              * Look for options.
7104              */
7105             d = instr(s,"perl -");
7106             if (!d) {
7107                 d = instr(s,"perl");
7108 #if defined(DOSISH)
7109                 /* avoid getting into infinite loops when shebang
7110                  * line contains "Perl" rather than "perl" */
7111                 if (!d) {
7112                     for (d = ipathend-4; d >= ipath; --d) {
7113                         if (isALPHA_FOLD_EQ(*d, 'p')
7114                             && !ibcmp(d, "perl", 4))
7115                         {
7116                             break;
7117                         }
7118                     }
7119                     if (d < ipath)
7120                         d = NULL;
7121                 }
7122 #endif
7123             }
7124 #ifdef ALTERNATE_SHEBANG
7125             /*
7126              * If the ALTERNATE_SHEBANG on this system starts with a
7127              * character that can be part of a Perl expression, then if
7128              * we see it but not "perl", we're probably looking at the
7129              * start of Perl code, not a request to hand off to some
7130              * other interpreter.  Similarly, if "perl" is there, but
7131              * not in the first 'word' of the line, we assume the line
7132              * contains the start of the Perl program.
7133              */
7134             if (d && *s != '#') {
7135                 const char *c = ipath;
7136                 while (*c && !memCHRs("; \t\r\n\f\v#", *c))
7137                     c++;
7138                 if (c < d)
7139                     d = NULL;   /* "perl" not in first word; ignore */
7140                 else
7141                     *s = '#';   /* Don't try to parse shebang line */
7142             }
7143 #endif /* ALTERNATE_SHEBANG */
7144             if (!d
7145                 && *s == '#'
7146                 && ipathend > ipath
7147                 && !PL_minus_c
7148                 && !instr(s,"indir")
7149                 && instr(PL_origargv[0],"perl"))
7150             {
7151                 char **newargv;
7152
7153                 *ipathend = '\0';
7154                 s = ipathend + 1;
7155                 while (s < PL_bufend && isSPACE(*s))
7156                     s++;
7157                 if (s < PL_bufend) {
7158                     Newx(newargv,PL_origargc+3,char*);
7159                     newargv[1] = s;
7160                     while (s < PL_bufend && !isSPACE(*s))
7161                         s++;
7162                     *s = '\0';
7163                     Copy(PL_origargv+1, newargv+2, PL_origargc+1, char*);
7164                 }
7165                 else
7166                     newargv = PL_origargv;
7167                 newargv[0] = ipath;
7168                 PERL_FPU_PRE_EXEC
7169                 PerlProc_execv(ipath, EXEC_ARGV_CAST(newargv));
7170                 PERL_FPU_POST_EXEC
7171                 Perl_croak(aTHX_ "Can't exec %s", ipath);
7172             }
7173             if (d) {
7174                 while (*d && !isSPACE(*d))
7175                     d++;
7176                 while (SPACE_OR_TAB(*d))
7177                     d++;
7178
7179                 if (*d++ == '-') {
7180                     const bool switches_done = PL_doswitches;
7181                     const U32 oldpdb = PL_perldb;
7182                     const bool oldn = PL_minus_n;
7183                     const bool oldp = PL_minus_p;
7184                     const char *d1 = d;
7185
7186                     do {
7187                         bool baduni = FALSE;
7188                         if (*d1 == 'C') {
7189                             const char *d2 = d1 + 1;
7190                             if (parse_unicode_opts((const char **)&d2)
7191                                 != PL_unicode)
7192                                 baduni = TRUE;
7193                         }
7194                         if (baduni || isALPHA_FOLD_EQ(*d1, 'M')) {
7195                             const char * const m = d1;
7196                             while (*d1 && !isSPACE(*d1))
7197                                 d1++;
7198                             Perl_croak(aTHX_ "Too late for \"-%.*s\" option",
7199                                   (int)(d1 - m), m);
7200                         }
7201                         d1 = moreswitches(d1);
7202                     } while (d1);
7203                     if (PL_doswitches && !switches_done) {
7204                         int argc = PL_origargc;
7205                         char **argv = PL_origargv;
7206                         do {
7207                             argc--,argv++;
7208                         } while (argc && argv[0][0] == '-' && argv[0][1]);
7209                         init_argv_symbols(argc,argv);
7210                     }
7211                     if (   (PERLDB_LINE_OR_SAVESRC && !oldpdb)
7212                         || ((PL_minus_n || PL_minus_p) && !(oldn || oldp)))
7213                           /* if we have already added "LINE: while (<>) {",
7214                              we must not do it again */
7215                     {
7216                         SvPVCLEAR(PL_linestr);
7217                         PL_bufptr = PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
7218                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
7219                         PL_last_lop = PL_last_uni = NULL;
7220                         PL_preambled = FALSE;
7221                         if (PERLDB_LINE_OR_SAVESRC)
7222                             (void)gv_fetchfile(PL_origfilename);
7223                         return YYL_RETRY;
7224                     }
7225                 }
7226             }
7227         }
7228     }
7229
7230     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
7231         PL_lex_state = LEX_FORMLINE;
7232         force_next(FORMRBRACK);
7233         TOKEN(PERLY_SEMICOLON);
7234     }
7235
7236     PL_bufptr = s;
7237     return YYL_RETRY;
7238 }
7239
7240 static int
7241 yyl_fatcomma(pTHX_ char *s, STRLEN len)
7242 {
7243     CLINE;
7244     pl_yylval.opval
7245         = newSVOP(OP_CONST, 0,
7246                        S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
7247     pl_yylval.opval->op_private = OPpCONST_BARE;
7248     TERM(BAREWORD);
7249 }
7250
7251 static int
7252 yyl_safe_bareword(pTHX_ char *s, const char lastchar)
7253 {
7254     if ((lastchar == '*' || lastchar == '%' || lastchar == '&')
7255         && PL_parser->saw_infix_sigil)
7256     {
7257         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7258                          "Operator or semicolon missing before %c%" UTF8f,
7259                          lastchar,
7260                          UTF8fARG(UTF, strlen(PL_tokenbuf),
7261                                   PL_tokenbuf));
7262         Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
7263                          "Ambiguous use of %c resolved as operator %c",
7264                          lastchar, lastchar);
7265     }
7266     TOKEN(BAREWORD);
7267 }
7268
7269 static int
7270 yyl_constant_op(pTHX_ char *s, SV *sv, CV *cv, OP *rv2cv_op, PADOFFSET off)
7271 {
7272     if (sv) {
7273         op_free(rv2cv_op);
7274         SvREFCNT_dec(((SVOP*)pl_yylval.opval)->op_sv);
7275         ((SVOP*)pl_yylval.opval)->op_sv = SvREFCNT_inc_simple(sv);
7276         if (SvTYPE(sv) == SVt_PVAV)
7277             pl_yylval.opval = newUNOP(OP_RV2AV, OPf_PARENS,
7278                                       pl_yylval.opval);
7279         else {
7280             pl_yylval.opval->op_private = 0;
7281             pl_yylval.opval->op_folded = 1;
7282             pl_yylval.opval->op_flags |= OPf_SPECIAL;
7283         }
7284         TOKEN(BAREWORD);
7285     }
7286
7287     op_free(pl_yylval.opval);
7288     pl_yylval.opval =
7289         off ? newCVREF(0, rv2cv_op) : rv2cv_op;
7290     pl_yylval.opval->op_private |= OPpENTERSUB_NOPAREN;
7291     PL_last_lop = PL_oldbufptr;
7292     PL_last_lop_op = OP_ENTERSUB;
7293
7294     /* Is there a prototype? */
7295     if (SvPOK(cv)) {
7296         int k = yyl_subproto(aTHX_ s, cv);
7297         if (k != KEY_NULL)
7298             return k;
7299     }
7300
7301     NEXTVAL_NEXTTOKE.opval = pl_yylval.opval;
7302     PL_expect = XTERM;
7303     force_next(off ? PRIVATEREF : BAREWORD);
7304     if (!PL_lex_allbrackets
7305         && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7306     {
7307         PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7308     }
7309
7310     TOKEN(NOAMP);
7311 }
7312
7313 /* Honour "reserved word" warnings, and enforce strict subs */
7314 static void
7315 yyl_strictwarn_bareword(pTHX_ const char lastchar)
7316 {
7317     /* after "print" and similar functions (corresponding to
7318      * "F? L" in opcode.pl), whatever wasn't already parsed as
7319      * a filehandle should be subject to "strict subs".
7320      * Likewise for the optional indirect-object argument to system
7321      * or exec, which can't be a bareword */
7322     if ((PL_last_lop_op == OP_PRINT
7323             || PL_last_lop_op == OP_PRTF
7324             || PL_last_lop_op == OP_SAY
7325             || PL_last_lop_op == OP_SYSTEM
7326             || PL_last_lop_op == OP_EXEC)
7327         && (PL_hints & HINT_STRICT_SUBS))
7328     {
7329         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7330     }
7331
7332     if (lastchar != '-' && ckWARN(WARN_RESERVED)) {
7333         char *d = PL_tokenbuf;
7334         while (isLOWER(*d))
7335             d++;
7336         if (!*d && !gv_stashpv(PL_tokenbuf, UTF ? SVf_UTF8 : 0)) {
7337             /* PL_warn_reserved is constant */
7338             GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
7339             Perl_warner(aTHX_ packWARN(WARN_RESERVED), PL_warn_reserved,
7340                         PL_tokenbuf);
7341             GCC_DIAG_RESTORE_STMT;
7342         }
7343     }
7344 }
7345
7346 static int
7347 yyl_just_a_word(pTHX_ char *s, STRLEN len, I32 orig_keyword, struct code c)
7348 {
7349     int pkgname = 0;
7350     const char lastchar = (PL_bufptr == PL_oldoldbufptr ? 0 : PL_bufptr[-1]);
7351     bool safebw;
7352     bool no_op_error = FALSE;
7353     /* Use this var to track whether intuit_method has been
7354        called.  intuit_method returns 0 or > 255.  */
7355     int key = 1;
7356
7357     if (PL_expect == XOPERATOR) {
7358         if (PL_bufptr == PL_linestart) {
7359             CopLINE_dec(PL_curcop);
7360             Perl_warner(aTHX_ packWARN(WARN_SEMICOLON), "%s", PL_warn_nosemi);
7361             CopLINE_inc(PL_curcop);
7362         }
7363         else
7364             /* We want to call no_op with s pointing after the
7365                bareword, so defer it.  But we want it to come
7366                before the Bad name croak.  */
7367             no_op_error = TRUE;
7368     }
7369
7370     /* Get the rest if it looks like a package qualifier */
7371
7372     if (*s == '\'' || (*s == ':' && s[1] == ':')) {
7373         STRLEN morelen;
7374         s = scan_word(s, PL_tokenbuf + len, sizeof PL_tokenbuf - len,
7375                       TRUE, &morelen);
7376         if (no_op_error) {
7377             no_op("Bareword",s);
7378             no_op_error = FALSE;
7379         }
7380         if (!morelen)
7381             Perl_croak(aTHX_ "Bad name after %" UTF8f "%s",
7382                     UTF8fARG(UTF, len, PL_tokenbuf),
7383                     *s == '\'' ? "'" : "::");
7384         len += morelen;
7385         pkgname = 1;
7386     }
7387
7388     if (no_op_error)
7389         no_op("Bareword",s);
7390
7391     /* See if the name is "Foo::",
7392        in which case Foo is a bareword
7393        (and a package name). */
7394
7395     if (len > 2 && PL_tokenbuf[len - 2] == ':' && PL_tokenbuf[len - 1] == ':') {
7396         if (ckWARN(WARN_BAREWORD)
7397             && ! gv_fetchpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0, SVt_PVHV))
7398             Perl_warner(aTHX_ packWARN(WARN_BAREWORD),
7399                         "Bareword \"%" UTF8f
7400                         "\" refers to nonexistent package",
7401                         UTF8fARG(UTF, len, PL_tokenbuf));
7402         len -= 2;
7403         PL_tokenbuf[len] = '\0';
7404         c.gv = NULL;
7405         c.gvp = 0;
7406         safebw = TRUE;
7407     }
7408     else {
7409         safebw = FALSE;
7410     }
7411
7412     /* if we saw a global override before, get the right name */
7413
7414     if (!c.sv)
7415         c.sv = S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len);
7416     if (c.gvp) {
7417         SV *sv = newSVpvs("CORE::GLOBAL::");
7418         sv_catsv(sv, c.sv);
7419         SvREFCNT_dec(c.sv);
7420         c.sv = sv;
7421     }
7422
7423     /* Presume this is going to be a bareword of some sort. */
7424     CLINE;
7425     pl_yylval.opval = newSVOP(OP_CONST, 0, c.sv);
7426     pl_yylval.opval->op_private = OPpCONST_BARE;
7427
7428     /* And if "Foo::", then that's what it certainly is. */
7429     if (safebw)
7430         return yyl_safe_bareword(aTHX_ s, lastchar);
7431
7432     if (!c.off) {
7433         OP *const_op = newSVOP(OP_CONST, 0, SvREFCNT_inc_NN(c.sv));
7434         const_op->op_private = OPpCONST_BARE;
7435         c.rv2cv_op = newCVREF(OPpMAY_RETURN_CONSTANT<<8, const_op);
7436         c.cv = c.lex
7437             ? isGV(c.gv)
7438                 ? GvCV(c.gv)
7439                 : SvROK(c.gv) && SvTYPE(SvRV(c.gv)) == SVt_PVCV
7440                     ? (CV *)SvRV(c.gv)
7441                     : ((CV *)c.gv)
7442             : rv2cv_op_cv(c.rv2cv_op, RV2CVOPCV_RETURN_STUB);
7443     }
7444
7445     /* See if it's the indirect object for a list operator. */
7446
7447     if (PL_oldoldbufptr
7448         && PL_oldoldbufptr < PL_bufptr
7449         && (PL_oldoldbufptr == PL_last_lop
7450             || PL_oldoldbufptr == PL_last_uni)
7451         && /* NO SKIPSPACE BEFORE HERE! */
7452            (PL_expect == XREF
7453             || ((PL_opargs[PL_last_lop_op] >> OASHIFT)& 7)
7454                                                    == OA_FILEREF))
7455     {
7456         bool immediate_paren = *s == '(';
7457         SSize_t s_off;
7458
7459         /* (Now we can afford to cross potential line boundary.) */
7460         s = skipspace(s);
7461
7462         /* intuit_method() can indirectly call lex_next_chunk(),
7463          * invalidating s
7464          */
7465         s_off = s - SvPVX(PL_linestr);
7466         /* Two barewords in a row may indicate method call. */
7467         if (   (   isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)
7468                 || *s == '$')
7469             && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7470         {
7471             /* the code at method: doesn't use s */
7472             goto method;
7473         }
7474         s = SvPVX(PL_linestr) + s_off;
7475
7476         /* If not a declared subroutine, it's an indirect object. */
7477         /* (But it's an indir obj regardless for sort.) */
7478         /* Also, if "_" follows a filetest operator, it's a bareword */
7479
7480         if (
7481             ( !immediate_paren && (PL_last_lop_op == OP_SORT
7482              || (!c.cv
7483                  && (PL_last_lop_op != OP_MAPSTART
7484                      && PL_last_lop_op != OP_GREPSTART))))
7485            || (PL_tokenbuf[0] == '_' && PL_tokenbuf[1] == '\0'
7486                 && ((PL_opargs[PL_last_lop_op] & OA_CLASS_MASK)
7487                                                 == OA_FILESTATOP))
7488            )
7489         {
7490             PL_expect = (PL_last_lop == PL_oldoldbufptr) ? XTERM : XOPERATOR;
7491             yyl_strictwarn_bareword(aTHX_ lastchar);
7492             op_free(c.rv2cv_op);
7493             return yyl_safe_bareword(aTHX_ s, lastchar);
7494         }
7495     }
7496
7497     PL_expect = XOPERATOR;
7498     s = skipspace(s);
7499
7500     /* Is this a word before a => operator? */
7501     if (*s == '=' && s[1] == '>' && !pkgname) {
7502         op_free(c.rv2cv_op);
7503         CLINE;
7504         if (c.gvp || (c.lex && !c.off)) {
7505             assert (cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7506             /* This is our own scalar, created a few lines
7507                above, so this is safe. */
7508             SvREADONLY_off(c.sv);
7509             sv_setpv(c.sv, PL_tokenbuf);
7510             if (UTF && !IN_BYTES
7511              && is_utf8_string((U8*)PL_tokenbuf, len))
7512                   SvUTF8_on(c.sv);
7513             SvREADONLY_on(c.sv);
7514         }
7515         TERM(BAREWORD);
7516     }
7517
7518     /* If followed by a paren, it's certainly a subroutine. */
7519     if (*s == '(') {
7520         CLINE;
7521         if (c.cv) {
7522             char *d = s + 1;
7523             while (SPACE_OR_TAB(*d))
7524                 d++;
7525             if (*d == ')' && (c.sv = cv_const_sv_or_av(c.cv)))
7526                 return yyl_constant_op(aTHX_ d + 1, c.sv, c.cv, c.rv2cv_op, c.off);
7527         }
7528         NEXTVAL_NEXTTOKE.opval =
7529             c.off ? c.rv2cv_op : pl_yylval.opval;
7530         if (c.off)
7531              op_free(pl_yylval.opval), force_next(PRIVATEREF);
7532         else op_free(c.rv2cv_op),      force_next(BAREWORD);
7533         pl_yylval.ival = 0;
7534         TOKEN(PERLY_AMPERSAND);
7535     }
7536
7537     /* If followed by var or block, call it a method (unless sub) */
7538
7539     if ((*s == '$' || *s == '{') && !c.cv && FEATURE_INDIRECT_IS_ENABLED) {
7540         op_free(c.rv2cv_op);
7541         PL_last_lop = PL_oldbufptr;
7542         PL_last_lop_op = OP_METHOD;
7543         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7544             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7545         PL_expect = XBLOCKTERM;
7546         PL_bufptr = s;
7547         return REPORT(METHOD);
7548     }
7549
7550     /* If followed by a bareword, see if it looks like indir obj. */
7551
7552     if (   key == 1
7553         && !orig_keyword
7554         && (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF) || *s == '$')
7555         && (key = intuit_method(s, c.lex ? NULL : c.sv, c.cv)))
7556     {
7557       method:
7558         if (c.lex && !c.off) {
7559             assert(cSVOPx(pl_yylval.opval)->op_sv == c.sv);
7560             SvREADONLY_off(c.sv);
7561             sv_setpvn(c.sv, PL_tokenbuf, len);
7562             if (UTF && !IN_BYTES
7563              && is_utf8_string((U8*)PL_tokenbuf, len))
7564                 SvUTF8_on(c.sv);
7565             else SvUTF8_off(c.sv);
7566         }
7567         op_free(c.rv2cv_op);
7568         if (key == METHOD && !PL_lex_allbrackets
7569             && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
7570         {
7571             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
7572         }
7573         return REPORT(key);
7574     }
7575
7576     /* Not a method, so call it a subroutine (if defined) */
7577
7578     if (c.cv) {
7579         /* Check for a constant sub */
7580         c.sv = cv_const_sv_or_av(c.cv);
7581         return yyl_constant_op(aTHX_ s, c.sv, c.cv, c.rv2cv_op, c.off);
7582     }
7583
7584     /* Call it a bare word */
7585
7586     if (PL_hints & HINT_STRICT_SUBS)
7587         pl_yylval.opval->op_private |= OPpCONST_STRICT;
7588     else
7589         yyl_strictwarn_bareword(aTHX_ lastchar);
7590
7591     op_free(c.rv2cv_op);
7592
7593     return yyl_safe_bareword(aTHX_ s, lastchar);
7594 }
7595
7596 static int
7597 yyl_word_or_keyword(pTHX_ char *s, STRLEN len, I32 key, I32 orig_keyword, struct code c)
7598 {
7599     switch (key) {
7600     default:                    /* not a keyword */
7601         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7602
7603     case KEY___FILE__:
7604         FUN0OP( newSVOP(OP_CONST, 0, newSVpv(CopFILE(PL_curcop),0)) );
7605
7606     case KEY___LINE__:
7607         FUN0OP(
7608             newSVOP(OP_CONST, 0,
7609                 Perl_newSVpvf(aTHX_ "%" IVdf, (IV)CopLINE(PL_curcop)))
7610         );
7611
7612     case KEY___PACKAGE__:
7613         FUN0OP(
7614             newSVOP(OP_CONST, 0, (PL_curstash
7615                                      ? newSVhek(HvNAME_HEK(PL_curstash))
7616                                      : &PL_sv_undef))
7617         );
7618
7619     case KEY___DATA__:
7620     case KEY___END__:
7621         if (PL_rsfp && (!PL_in_eval || PL_tokenbuf[2] == 'D'))
7622             yyl_data_handle(aTHX);
7623         return yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s);
7624
7625     case KEY___SUB__:
7626         FUN0OP(CvCLONE(PL_compcv)
7627                     ? newOP(OP_RUNCV, 0)
7628                     : newPVOP(OP_RUNCV,0,NULL));
7629
7630     case KEY_AUTOLOAD:
7631     case KEY_DESTROY:
7632     case KEY_BEGIN:
7633     case KEY_UNITCHECK:
7634     case KEY_CHECK:
7635     case KEY_INIT:
7636     case KEY_END:
7637         if (PL_expect == XSTATE)
7638             return yyl_sub(aTHX_ PL_bufptr, key);
7639         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
7640
7641     case KEY_abs:
7642         UNI(OP_ABS);
7643
7644     case KEY_alarm:
7645         UNI(OP_ALARM);
7646
7647     case KEY_accept:
7648         LOP(OP_ACCEPT,XTERM);
7649
7650     case KEY_and:
7651         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
7652             return REPORT(0);
7653         OPERATOR(ANDOP);
7654
7655     case KEY_atan2:
7656         LOP(OP_ATAN2,XTERM);
7657
7658     case KEY_bind:
7659         LOP(OP_BIND,XTERM);
7660
7661     case KEY_binmode:
7662         LOP(OP_BINMODE,XTERM);
7663
7664     case KEY_bless:
7665         LOP(OP_BLESS,XTERM);
7666
7667     case KEY_break:
7668         FUN0(OP_BREAK);
7669
7670     case KEY_chop:
7671         UNI(OP_CHOP);
7672
7673     case KEY_continue:
7674         /* We have to disambiguate the two senses of
7675           "continue". If the next token is a '{' then
7676           treat it as the start of a continue block;
7677           otherwise treat it as a control operator.
7678          */
7679         s = skipspace(s);
7680         if (*s == '{')
7681             PREBLOCK(CONTINUE);
7682         else
7683             FUN0(OP_CONTINUE);
7684
7685     case KEY_chdir:
7686         /* may use HOME */
7687         (void)gv_fetchpvs("ENV", GV_ADD|GV_NOTQUAL, SVt_PVHV);
7688         UNI(OP_CHDIR);
7689
7690     case KEY_close:
7691         UNI(OP_CLOSE);
7692
7693     case KEY_closedir:
7694         UNI(OP_CLOSEDIR);
7695
7696     case KEY_cmp:
7697         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7698             return REPORT(0);
7699         NCEop(OP_SCMP);
7700
7701     case KEY_caller:
7702         UNI(OP_CALLER);
7703
7704     case KEY_crypt:
7705
7706         LOP(OP_CRYPT,XTERM);
7707
7708     case KEY_chmod:
7709         LOP(OP_CHMOD,XTERM);
7710
7711     case KEY_chown:
7712         LOP(OP_CHOWN,XTERM);
7713
7714     case KEY_connect:
7715         LOP(OP_CONNECT,XTERM);
7716
7717     case KEY_chr:
7718         UNI(OP_CHR);
7719
7720     case KEY_cos:
7721         UNI(OP_COS);
7722
7723     case KEY_chroot:
7724         UNI(OP_CHROOT);
7725
7726     case KEY_default:
7727         PREBLOCK(DEFAULT);
7728
7729     case KEY_do:
7730         return yyl_do(aTHX_ s, orig_keyword);
7731
7732     case KEY_die:
7733         PL_hints |= HINT_BLOCK_SCOPE;
7734         LOP(OP_DIE,XTERM);
7735
7736     case KEY_defined:
7737         UNI(OP_DEFINED);
7738
7739     case KEY_delete:
7740         UNI(OP_DELETE);
7741
7742     case KEY_dbmopen:
7743         Perl_populate_isa(aTHX_ STR_WITH_LEN("AnyDBM_File::ISA"),
7744                           STR_WITH_LEN("NDBM_File::"),
7745                           STR_WITH_LEN("DB_File::"),
7746                           STR_WITH_LEN("GDBM_File::"),
7747                           STR_WITH_LEN("SDBM_File::"),
7748                           STR_WITH_LEN("ODBM_File::"),
7749                           NULL);
7750         LOP(OP_DBMOPEN,XTERM);
7751
7752     case KEY_dbmclose:
7753         UNI(OP_DBMCLOSE);
7754
7755     case KEY_dump:
7756         LOOPX(OP_DUMP);
7757
7758     case KEY_else:
7759         PREBLOCK(ELSE);
7760
7761     case KEY_elsif:
7762         pl_yylval.ival = CopLINE(PL_curcop);
7763         OPERATOR(ELSIF);
7764
7765     case KEY_eq:
7766         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7767             return REPORT(0);
7768         ChEop(OP_SEQ);
7769
7770     case KEY_exists:
7771         UNI(OP_EXISTS);
7772
7773     case KEY_exit:
7774         UNI(OP_EXIT);
7775
7776     case KEY_eval:
7777         s = skipspace(s);
7778         if (*s == '{') { /* block eval */
7779             PL_expect = XTERMBLOCK;
7780             UNIBRACK(OP_ENTERTRY);
7781         }
7782         else { /* string eval */
7783             PL_expect = XTERM;
7784             UNIBRACK(OP_ENTEREVAL);
7785         }
7786
7787     case KEY_evalbytes:
7788         PL_expect = XTERM;
7789         UNIBRACK(-OP_ENTEREVAL);
7790
7791     case KEY_eof:
7792         UNI(OP_EOF);
7793
7794     case KEY_exp:
7795         UNI(OP_EXP);
7796
7797     case KEY_each:
7798         UNI(OP_EACH);
7799
7800     case KEY_exec:
7801         LOP(OP_EXEC,XREF);
7802
7803     case KEY_endhostent:
7804         FUN0(OP_EHOSTENT);
7805
7806     case KEY_endnetent:
7807         FUN0(OP_ENETENT);
7808
7809     case KEY_endservent:
7810         FUN0(OP_ESERVENT);
7811
7812     case KEY_endprotoent:
7813         FUN0(OP_EPROTOENT);
7814
7815     case KEY_endpwent:
7816         FUN0(OP_EPWENT);
7817
7818     case KEY_endgrent:
7819         FUN0(OP_EGRENT);
7820
7821     case KEY_for:
7822     case KEY_foreach:
7823         return yyl_foreach(aTHX_ s);
7824
7825     case KEY_formline:
7826         LOP(OP_FORMLINE,XTERM);
7827
7828     case KEY_fork:
7829         FUN0(OP_FORK);
7830
7831     case KEY_fc:
7832         UNI(OP_FC);
7833
7834     case KEY_fcntl:
7835         LOP(OP_FCNTL,XTERM);
7836
7837     case KEY_fileno:
7838         UNI(OP_FILENO);
7839
7840     case KEY_flock:
7841         LOP(OP_FLOCK,XTERM);
7842
7843     case KEY_gt:
7844         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7845             return REPORT(0);
7846         ChRop(OP_SGT);
7847
7848     case KEY_ge:
7849         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7850             return REPORT(0);
7851         ChRop(OP_SGE);
7852
7853     case KEY_grep:
7854         LOP(OP_GREPSTART, XREF);
7855
7856     case KEY_goto:
7857         LOOPX(OP_GOTO);
7858
7859     case KEY_gmtime:
7860         UNI(OP_GMTIME);
7861
7862     case KEY_getc:
7863         UNIDOR(OP_GETC);
7864
7865     case KEY_getppid:
7866         FUN0(OP_GETPPID);
7867
7868     case KEY_getpgrp:
7869         UNI(OP_GETPGRP);
7870
7871     case KEY_getpriority:
7872         LOP(OP_GETPRIORITY,XTERM);
7873
7874     case KEY_getprotobyname:
7875         UNI(OP_GPBYNAME);
7876
7877     case KEY_getprotobynumber:
7878         LOP(OP_GPBYNUMBER,XTERM);
7879
7880     case KEY_getprotoent:
7881         FUN0(OP_GPROTOENT);
7882
7883     case KEY_getpwent:
7884         FUN0(OP_GPWENT);
7885
7886     case KEY_getpwnam:
7887         UNI(OP_GPWNAM);
7888
7889     case KEY_getpwuid:
7890         UNI(OP_GPWUID);
7891
7892     case KEY_getpeername:
7893         UNI(OP_GETPEERNAME);
7894
7895     case KEY_gethostbyname:
7896         UNI(OP_GHBYNAME);
7897
7898     case KEY_gethostbyaddr:
7899         LOP(OP_GHBYADDR,XTERM);
7900
7901     case KEY_gethostent:
7902         FUN0(OP_GHOSTENT);
7903
7904     case KEY_getnetbyname:
7905         UNI(OP_GNBYNAME);
7906
7907     case KEY_getnetbyaddr:
7908         LOP(OP_GNBYADDR,XTERM);
7909
7910     case KEY_getnetent:
7911         FUN0(OP_GNETENT);
7912
7913     case KEY_getservbyname:
7914         LOP(OP_GSBYNAME,XTERM);
7915
7916     case KEY_getservbyport:
7917         LOP(OP_GSBYPORT,XTERM);
7918
7919     case KEY_getservent:
7920         FUN0(OP_GSERVENT);
7921
7922     case KEY_getsockname:
7923         UNI(OP_GETSOCKNAME);
7924
7925     case KEY_getsockopt:
7926         LOP(OP_GSOCKOPT,XTERM);
7927
7928     case KEY_getgrent:
7929         FUN0(OP_GGRENT);
7930
7931     case KEY_getgrnam:
7932         UNI(OP_GGRNAM);
7933
7934     case KEY_getgrgid:
7935         UNI(OP_GGRGID);
7936
7937     case KEY_getlogin:
7938         FUN0(OP_GETLOGIN);
7939
7940     case KEY_given:
7941         pl_yylval.ival = CopLINE(PL_curcop);
7942         Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
7943                          "given is experimental");
7944         OPERATOR(GIVEN);
7945
7946     case KEY_glob:
7947         LOP( orig_keyword==KEY_glob ? -OP_GLOB : OP_GLOB, XTERM );
7948
7949     case KEY_hex:
7950         UNI(OP_HEX);
7951
7952     case KEY_if:
7953         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
7954             return REPORT(0);
7955         pl_yylval.ival = CopLINE(PL_curcop);
7956         OPERATOR(IF);
7957
7958     case KEY_index:
7959         LOP(OP_INDEX,XTERM);
7960
7961     case KEY_int:
7962         UNI(OP_INT);
7963
7964     case KEY_ioctl:
7965         LOP(OP_IOCTL,XTERM);
7966
7967     case KEY_isa:
7968         Perl_ck_warner_d(aTHX_
7969             packWARN(WARN_EXPERIMENTAL__ISA), "isa is experimental");
7970         NCRop(OP_ISA);
7971
7972     case KEY_join:
7973         LOP(OP_JOIN,XTERM);
7974
7975     case KEY_keys:
7976         UNI(OP_KEYS);
7977
7978     case KEY_kill:
7979         LOP(OP_KILL,XTERM);
7980
7981     case KEY_last:
7982         LOOPX(OP_LAST);
7983
7984     case KEY_lc:
7985         UNI(OP_LC);
7986
7987     case KEY_lcfirst:
7988         UNI(OP_LCFIRST);
7989
7990     case KEY_local:
7991         OPERATOR(LOCAL);
7992
7993     case KEY_length:
7994         UNI(OP_LENGTH);
7995
7996     case KEY_lt:
7997         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
7998             return REPORT(0);
7999         ChRop(OP_SLT);
8000
8001     case KEY_le:
8002         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8003             return REPORT(0);
8004         ChRop(OP_SLE);
8005
8006     case KEY_localtime:
8007         UNI(OP_LOCALTIME);
8008
8009     case KEY_log:
8010         UNI(OP_LOG);
8011
8012     case KEY_link:
8013         LOP(OP_LINK,XTERM);
8014
8015     case KEY_listen:
8016         LOP(OP_LISTEN,XTERM);
8017
8018     case KEY_lock:
8019         UNI(OP_LOCK);
8020
8021     case KEY_lstat:
8022         UNI(OP_LSTAT);
8023
8024     case KEY_m:
8025         s = scan_pat(s,OP_MATCH);
8026         TERM(sublex_start());
8027
8028     case KEY_map:
8029         LOP(OP_MAPSTART, XREF);
8030
8031     case KEY_mkdir:
8032         LOP(OP_MKDIR,XTERM);
8033
8034     case KEY_msgctl:
8035         LOP(OP_MSGCTL,XTERM);
8036
8037     case KEY_msgget:
8038         LOP(OP_MSGGET,XTERM);
8039
8040     case KEY_msgrcv:
8041         LOP(OP_MSGRCV,XTERM);
8042
8043     case KEY_msgsnd:
8044         LOP(OP_MSGSND,XTERM);
8045
8046     case KEY_our:
8047     case KEY_my:
8048     case KEY_state:
8049         return yyl_my(aTHX_ s, key);
8050
8051     case KEY_next:
8052         LOOPX(OP_NEXT);
8053
8054     case KEY_ne:
8055         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8056             return REPORT(0);
8057         ChEop(OP_SNE);
8058
8059     case KEY_no:
8060         s = tokenize_use(0, s);
8061         TOKEN(USE);
8062
8063     case KEY_not:
8064         if (*s == '(' || (s = skipspace(s), *s == '('))
8065             FUN1(OP_NOT);
8066         else {
8067             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
8068                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
8069             OPERATOR(NOTOP);
8070         }
8071
8072     case KEY_open:
8073         s = skipspace(s);
8074         if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
8075             const char *t;
8076             char *d = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8077             for (t=d; isSPACE(*t);)
8078                 t++;
8079             if ( *t && memCHRs("|&*+-=!?:.", *t) && ckWARN_d(WARN_PRECEDENCE)
8080                 /* [perl #16184] */
8081                 && !(t[0] == '=' && t[1] == '>')
8082                 && !(t[0] == ':' && t[1] == ':')
8083                 && !keyword(s, d-s, 0)
8084             ) {
8085                 Perl_warner(aTHX_ packWARN(WARN_PRECEDENCE),
8086                    "Precedence problem: open %" UTF8f " should be open(%" UTF8f ")",
8087                     UTF8fARG(UTF, d-s, s), UTF8fARG(UTF, d-s, s));
8088             }
8089         }
8090         LOP(OP_OPEN,XTERM);
8091
8092     case KEY_or:
8093         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8094             return REPORT(0);
8095         pl_yylval.ival = OP_OR;
8096         OPERATOR(OROP);
8097
8098     case KEY_ord:
8099         UNI(OP_ORD);
8100
8101     case KEY_oct:
8102         UNI(OP_OCT);
8103
8104     case KEY_opendir:
8105         LOP(OP_OPEN_DIR,XTERM);
8106
8107     case KEY_print:
8108         checkcomma(s,PL_tokenbuf,"filehandle");
8109         LOP(OP_PRINT,XREF);
8110
8111     case KEY_printf:
8112         checkcomma(s,PL_tokenbuf,"filehandle");
8113         LOP(OP_PRTF,XREF);
8114
8115     case KEY_prototype:
8116         UNI(OP_PROTOTYPE);
8117
8118     case KEY_push:
8119         LOP(OP_PUSH,XTERM);
8120
8121     case KEY_pop:
8122         UNIDOR(OP_POP);
8123
8124     case KEY_pos:
8125         UNIDOR(OP_POS);
8126
8127     case KEY_pack:
8128         LOP(OP_PACK,XTERM);
8129
8130     case KEY_package:
8131         s = force_word(s,BAREWORD,FALSE,TRUE);
8132         s = skipspace(s);
8133         s = force_strict_version(s);
8134         PREBLOCK(PACKAGE);
8135
8136     case KEY_pipe:
8137         LOP(OP_PIPE_OP,XTERM);
8138
8139     case KEY_q:
8140         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8141         if (!s)
8142             missingterm(NULL, 0);
8143         COPLINE_SET_FROM_MULTI_END;
8144         pl_yylval.ival = OP_CONST;
8145         TERM(sublex_start());
8146
8147     case KEY_quotemeta:
8148         UNI(OP_QUOTEMETA);
8149
8150     case KEY_qw:
8151         return yyl_qw(aTHX_ s, len);
8152
8153     case KEY_qq:
8154         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8155         if (!s)
8156             missingterm(NULL, 0);
8157         pl_yylval.ival = OP_STRINGIFY;
8158         if (SvIVX(PL_lex_stuff) == '\'')
8159             SvIV_set(PL_lex_stuff, 0);  /* qq'$foo' should interpolate */
8160         TERM(sublex_start());
8161
8162     case KEY_qr:
8163         s = scan_pat(s,OP_QR);
8164         TERM(sublex_start());
8165
8166     case KEY_qx:
8167         s = scan_str(s,FALSE,FALSE,FALSE,NULL);
8168         if (!s)
8169             missingterm(NULL, 0);
8170         pl_yylval.ival = OP_BACKTICK;
8171         TERM(sublex_start());
8172
8173     case KEY_return:
8174         OLDLOP(OP_RETURN);
8175
8176     case KEY_require:
8177         return yyl_require(aTHX_ s, orig_keyword);
8178
8179     case KEY_reset:
8180         UNI(OP_RESET);
8181
8182     case KEY_redo:
8183         LOOPX(OP_REDO);
8184
8185     case KEY_rename:
8186         LOP(OP_RENAME,XTERM);
8187
8188     case KEY_rand:
8189         UNI(OP_RAND);
8190
8191     case KEY_rmdir:
8192         UNI(OP_RMDIR);
8193
8194     case KEY_rindex:
8195         LOP(OP_RINDEX,XTERM);
8196
8197     case KEY_read:
8198         LOP(OP_READ,XTERM);
8199
8200     case KEY_readdir:
8201         UNI(OP_READDIR);
8202
8203     case KEY_readline:
8204         UNIDOR(OP_READLINE);
8205
8206     case KEY_readpipe:
8207         UNIDOR(OP_BACKTICK);
8208
8209     case KEY_rewinddir:
8210         UNI(OP_REWINDDIR);
8211
8212     case KEY_recv:
8213         LOP(OP_RECV,XTERM);
8214
8215     case KEY_reverse:
8216         LOP(OP_REVERSE,XTERM);
8217
8218     case KEY_readlink:
8219         UNIDOR(OP_READLINK);
8220
8221     case KEY_ref:
8222         UNI(OP_REF);
8223
8224     case KEY_s:
8225         s = scan_subst(s);
8226         if (pl_yylval.opval)
8227             TERM(sublex_start());
8228         else
8229             TOKEN(1);   /* force error */
8230
8231     case KEY_say:
8232         checkcomma(s,PL_tokenbuf,"filehandle");
8233         LOP(OP_SAY,XREF);
8234
8235     case KEY_chomp:
8236         UNI(OP_CHOMP);
8237
8238     case KEY_scalar:
8239         UNI(OP_SCALAR);
8240
8241     case KEY_select:
8242         LOP(OP_SELECT,XTERM);
8243
8244     case KEY_seek:
8245         LOP(OP_SEEK,XTERM);
8246
8247     case KEY_semctl:
8248         LOP(OP_SEMCTL,XTERM);
8249
8250     case KEY_semget:
8251         LOP(OP_SEMGET,XTERM);
8252
8253     case KEY_semop:
8254         LOP(OP_SEMOP,XTERM);
8255
8256     case KEY_send:
8257         LOP(OP_SEND,XTERM);
8258
8259     case KEY_setpgrp:
8260         LOP(OP_SETPGRP,XTERM);
8261
8262     case KEY_setpriority:
8263         LOP(OP_SETPRIORITY,XTERM);
8264
8265     case KEY_sethostent:
8266         UNI(OP_SHOSTENT);
8267
8268     case KEY_setnetent:
8269         UNI(OP_SNETENT);
8270
8271     case KEY_setservent:
8272         UNI(OP_SSERVENT);
8273
8274     case KEY_setprotoent:
8275         UNI(OP_SPROTOENT);
8276
8277     case KEY_setpwent:
8278         FUN0(OP_SPWENT);
8279
8280     case KEY_setgrent:
8281         FUN0(OP_SGRENT);
8282
8283     case KEY_seekdir:
8284         LOP(OP_SEEKDIR,XTERM);
8285
8286     case KEY_setsockopt:
8287         LOP(OP_SSOCKOPT,XTERM);
8288
8289     case KEY_shift:
8290         UNIDOR(OP_SHIFT);
8291
8292     case KEY_shmctl:
8293         LOP(OP_SHMCTL,XTERM);
8294
8295     case KEY_shmget:
8296         LOP(OP_SHMGET,XTERM);
8297
8298     case KEY_shmread:
8299         LOP(OP_SHMREAD,XTERM);
8300
8301     case KEY_shmwrite:
8302         LOP(OP_SHMWRITE,XTERM);
8303
8304     case KEY_shutdown:
8305         LOP(OP_SHUTDOWN,XTERM);
8306
8307     case KEY_sin:
8308         UNI(OP_SIN);
8309
8310     case KEY_sleep:
8311         UNI(OP_SLEEP);
8312
8313     case KEY_socket:
8314         LOP(OP_SOCKET,XTERM);
8315
8316     case KEY_socketpair:
8317         LOP(OP_SOCKPAIR,XTERM);
8318
8319     case KEY_sort:
8320         checkcomma(s,PL_tokenbuf,"subroutine name");
8321         s = skipspace(s);
8322         PL_expect = XTERM;
8323         s = force_word(s,BAREWORD,TRUE,TRUE);
8324         LOP(OP_SORT,XREF);
8325
8326     case KEY_split:
8327         LOP(OP_SPLIT,XTERM);
8328
8329     case KEY_sprintf:
8330         LOP(OP_SPRINTF,XTERM);
8331
8332     case KEY_splice:
8333         LOP(OP_SPLICE,XTERM);
8334
8335     case KEY_sqrt:
8336         UNI(OP_SQRT);
8337
8338     case KEY_srand:
8339         UNI(OP_SRAND);
8340
8341     case KEY_stat:
8342         UNI(OP_STAT);
8343
8344     case KEY_study:
8345         UNI(OP_STUDY);
8346
8347     case KEY_substr:
8348         LOP(OP_SUBSTR,XTERM);
8349
8350     case KEY_format:
8351     case KEY_sub:
8352         return yyl_sub(aTHX_ s, key);
8353
8354     case KEY_system:
8355         LOP(OP_SYSTEM,XREF);
8356
8357     case KEY_symlink:
8358         LOP(OP_SYMLINK,XTERM);
8359
8360     case KEY_syscall:
8361         LOP(OP_SYSCALL,XTERM);
8362
8363     case KEY_sysopen:
8364         LOP(OP_SYSOPEN,XTERM);
8365
8366     case KEY_sysseek:
8367         LOP(OP_SYSSEEK,XTERM);
8368
8369     case KEY_sysread:
8370         LOP(OP_SYSREAD,XTERM);
8371
8372     case KEY_syswrite:
8373         LOP(OP_SYSWRITE,XTERM);
8374
8375     case KEY_tr:
8376     case KEY_y:
8377         s = scan_trans(s);
8378         TERM(sublex_start());
8379
8380     case KEY_tell:
8381         UNI(OP_TELL);
8382
8383     case KEY_telldir:
8384         UNI(OP_TELLDIR);
8385
8386     case KEY_tie:
8387         LOP(OP_TIE,XTERM);
8388
8389     case KEY_tied:
8390         UNI(OP_TIED);
8391
8392     case KEY_time:
8393         FUN0(OP_TIME);
8394
8395     case KEY_times:
8396         FUN0(OP_TMS);
8397
8398     case KEY_truncate:
8399         LOP(OP_TRUNCATE,XTERM);
8400
8401     case KEY_uc:
8402         UNI(OP_UC);
8403
8404     case KEY_ucfirst:
8405         UNI(OP_UCFIRST);
8406
8407     case KEY_untie:
8408         UNI(OP_UNTIE);
8409
8410     case KEY_until:
8411         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8412             return REPORT(0);
8413         pl_yylval.ival = CopLINE(PL_curcop);
8414         OPERATOR(UNTIL);
8415
8416     case KEY_unless:
8417         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8418             return REPORT(0);
8419         pl_yylval.ival = CopLINE(PL_curcop);
8420         OPERATOR(UNLESS);
8421
8422     case KEY_unlink:
8423         LOP(OP_UNLINK,XTERM);
8424
8425     case KEY_undef:
8426         UNIDOR(OP_UNDEF);
8427
8428     case KEY_unpack:
8429         LOP(OP_UNPACK,XTERM);
8430
8431     case KEY_utime:
8432         LOP(OP_UTIME,XTERM);
8433
8434     case KEY_umask:
8435         UNIDOR(OP_UMASK);
8436
8437     case KEY_unshift:
8438         LOP(OP_UNSHIFT,XTERM);
8439
8440     case KEY_use:
8441         s = tokenize_use(1, s);
8442         TOKEN(USE);
8443
8444     case KEY_values:
8445         UNI(OP_VALUES);
8446
8447     case KEY_vec:
8448         LOP(OP_VEC,XTERM);
8449
8450     case KEY_when:
8451         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8452             return REPORT(0);
8453         pl_yylval.ival = CopLINE(PL_curcop);
8454         Perl_ck_warner_d(aTHX_
8455             packWARN(WARN_EXPERIMENTAL__SMARTMATCH),
8456             "when is experimental");
8457         OPERATOR(WHEN);
8458
8459     case KEY_while:
8460         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8461             return REPORT(0);
8462         pl_yylval.ival = CopLINE(PL_curcop);
8463         OPERATOR(WHILE);
8464
8465     case KEY_warn:
8466         PL_hints |= HINT_BLOCK_SCOPE;
8467         LOP(OP_WARN,XTERM);
8468
8469     case KEY_wait:
8470         FUN0(OP_WAIT);
8471
8472     case KEY_waitpid:
8473         LOP(OP_WAITPID,XTERM);
8474
8475     case KEY_wantarray:
8476         FUN0(OP_WANTARRAY);
8477
8478     case KEY_write:
8479         /* Make sure $^L is defined. 0x0C is CTRL-L on ASCII platforms, and
8480          * we use the same number on EBCDIC */
8481         gv_fetchpvs("\x0C", GV_ADD|GV_NOTQUAL, SVt_PV);
8482         UNI(OP_ENTERWRITE);
8483
8484     case KEY_x:
8485         if (PL_expect == XOPERATOR) {
8486             if (*s == '=' && !PL_lex_allbrackets
8487                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
8488             {
8489                 return REPORT(0);
8490             }
8491             Mop(OP_REPEAT);
8492         }
8493         check_uni();
8494         return yyl_just_a_word(aTHX_ s, len, orig_keyword, c);
8495
8496     case KEY_xor:
8497         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_LOWLOGIC)
8498             return REPORT(0);
8499         pl_yylval.ival = OP_XOR;
8500         OPERATOR(OROP);
8501     }
8502 }
8503
8504 static int
8505 yyl_key_core(pTHX_ char *s, STRLEN len, struct code c)
8506 {
8507     I32 key = 0;
8508     I32 orig_keyword = 0;
8509     STRLEN olen = len;
8510     char *d = s;
8511     s += 2;
8512     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8513     if ((*s == ':' && s[1] == ':')
8514         || (!(key = keyword(PL_tokenbuf, len, 1)) && *s == '\''))
8515     {
8516         Copy(PL_bufptr, PL_tokenbuf, olen, char);
8517         return yyl_just_a_word(aTHX_ d, olen, 0, c);
8518     }
8519     if (!key)
8520         Perl_croak(aTHX_ "CORE::%" UTF8f " is not a keyword",
8521                           UTF8fARG(UTF, len, PL_tokenbuf));
8522     if (key < 0)
8523         key = -key;
8524     else if (key == KEY_require || key == KEY_do
8525           || key == KEY_glob)
8526         /* that's a way to remember we saw "CORE::" */
8527         orig_keyword = key;
8528
8529     /* Known to be a reserved word at this point */
8530     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8531 }
8532
8533 static int
8534 yyl_keylookup(pTHX_ char *s, GV *gv)
8535 {
8536     STRLEN len;
8537     bool anydelim;
8538     I32 key;
8539     struct code c = no_code;
8540     I32 orig_keyword = 0;
8541     char *d;
8542
8543     c.gv = gv;
8544
8545     PL_bufptr = s;
8546     s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &len);
8547
8548     /* Some keywords can be followed by any delimiter, including ':' */
8549     anydelim = word_takes_any_delimiter(PL_tokenbuf, len);
8550
8551     /* x::* is just a word, unless x is "CORE" */
8552     if (!anydelim && *s == ':' && s[1] == ':') {
8553         if (memEQs(PL_tokenbuf, len, "CORE"))
8554             return yyl_key_core(aTHX_ s, len, c);
8555         return yyl_just_a_word(aTHX_ s, len, 0, c);
8556     }
8557
8558     d = s;
8559     while (d < PL_bufend && isSPACE(*d))
8560             d++;        /* no comments skipped here, or s### is misparsed */
8561
8562     /* Is this a word before a => operator? */
8563     if (*d == '=' && d[1] == '>') {
8564         return yyl_fatcomma(aTHX_ s, len);
8565     }
8566
8567     /* Check for plugged-in keyword */
8568     {
8569         OP *o;
8570         int result;
8571         char *saved_bufptr = PL_bufptr;
8572         PL_bufptr = s;
8573         result = PL_keyword_plugin(aTHX_ PL_tokenbuf, len, &o);
8574         s = PL_bufptr;
8575         if (result == KEYWORD_PLUGIN_DECLINE) {
8576             /* not a plugged-in keyword */
8577             PL_bufptr = saved_bufptr;
8578         } else if (result == KEYWORD_PLUGIN_STMT) {
8579             pl_yylval.opval = o;
8580             CLINE;
8581             if (!PL_nexttoke) PL_expect = XSTATE;
8582             return REPORT(PLUGSTMT);
8583         } else if (result == KEYWORD_PLUGIN_EXPR) {
8584             pl_yylval.opval = o;
8585             CLINE;
8586             if (!PL_nexttoke) PL_expect = XOPERATOR;
8587             return REPORT(PLUGEXPR);
8588         } else {
8589             Perl_croak(aTHX_ "Bad plugin affecting keyword '%s'", PL_tokenbuf);
8590         }
8591     }
8592
8593     /* Is this a label? */
8594     if (!anydelim && PL_expect == XSTATE
8595           && d < PL_bufend && *d == ':' && *(d + 1) != ':') {
8596         s = d + 1;
8597         pl_yylval.opval =
8598             newSVOP(OP_CONST, 0,
8599                 newSVpvn_flags(PL_tokenbuf, len, UTF ? SVf_UTF8 : 0));
8600         CLINE;
8601         TOKEN(LABEL);
8602     }
8603
8604     /* Check for lexical sub */
8605     if (PL_expect != XOPERATOR) {
8606         char tmpbuf[sizeof PL_tokenbuf + 1];
8607         *tmpbuf = '&';
8608         Copy(PL_tokenbuf, tmpbuf+1, len, char);
8609         c.off = pad_findmy_pvn(tmpbuf, len+1, 0);
8610         if (c.off != NOT_IN_PAD) {
8611             assert(c.off); /* we assume this is boolean-true below */
8612             if (PAD_COMPNAME_FLAGS_isOUR(c.off)) {
8613                 HV *  const stash = PAD_COMPNAME_OURSTASH(c.off);
8614                 HEK * const stashname = HvNAME_HEK(stash);
8615                 c.sv = newSVhek(stashname);
8616                 sv_catpvs(c.sv, "::");
8617                 sv_catpvn_flags(c.sv, PL_tokenbuf, len,
8618                                 (UTF ? SV_CATUTF8 : SV_CATBYTES));
8619                 c.gv = gv_fetchsv(c.sv, GV_NOADD_NOINIT | SvUTF8(c.sv),
8620                                   SVt_PVCV);
8621                 c.off = 0;
8622                 if (!c.gv) {
8623                     sv_free(c.sv);
8624                     c.sv = NULL;
8625                     return yyl_just_a_word(aTHX_ s, len, 0, c);
8626                 }
8627             }
8628             else {
8629                 c.rv2cv_op = newOP(OP_PADANY, 0);
8630                 c.rv2cv_op->op_targ = c.off;
8631                 c.cv = find_lexical_cv(c.off);
8632             }
8633             c.lex = TRUE;
8634             return yyl_just_a_word(aTHX_ s, len, 0, c);
8635         }
8636         c.off = 0;
8637     }
8638
8639     /* Check for built-in keyword */
8640     key = keyword(PL_tokenbuf, len, 0);
8641
8642     if (key < 0)
8643         key = yyl_secondclass_keyword(aTHX_ s, len, key, &orig_keyword, &c.gv, &c.gvp);
8644
8645     if (key && key != KEY___DATA__ && key != KEY___END__
8646      && (!anydelim || *s != '#')) {
8647         /* no override, and not s### either; skipspace is safe here
8648          * check for => on following line */
8649         bool arrow;
8650         STRLEN bufoff = PL_bufptr - SvPVX(PL_linestr);
8651         STRLEN   soff = s         - SvPVX(PL_linestr);
8652         s = peekspace(s);
8653         arrow = *s == '=' && s[1] == '>';
8654         PL_bufptr = SvPVX(PL_linestr) + bufoff;
8655         s         = SvPVX(PL_linestr) +   soff;
8656         if (arrow)
8657             return yyl_fatcomma(aTHX_ s, len);
8658     }
8659
8660     return yyl_word_or_keyword(aTHX_ s, len, key, orig_keyword, c);
8661 }
8662
8663 static int
8664 yyl_try(pTHX_ char *s)
8665 {
8666     char *d;
8667     GV *gv = NULL;
8668     int tok;
8669
8670   retry:
8671     switch (*s) {
8672     default:
8673         if (UTF ? isIDFIRST_utf8_safe(s, PL_bufend) : isALNUMC(*s)) {
8674             if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
8675                 return tok;
8676             goto retry_bufptr;
8677         }
8678         yyl_croak_unrecognised(aTHX_ s);
8679
8680     case 4:
8681     case 26:
8682         /* emulate EOF on ^D or ^Z */
8683         if ((tok = yyl_fake_eof(aTHX_ LEX_FAKE_EOF, FALSE, s)) != YYL_RETRY)
8684             return tok;
8685     retry_bufptr:
8686         s = PL_bufptr;
8687         goto retry;
8688
8689     case 0:
8690         if ((!PL_rsfp || PL_lex_inwhat)
8691          && (!PL_parser->filtered || s+1 < PL_bufend)) {
8692             PL_last_uni = 0;
8693             PL_last_lop = 0;
8694             if (PL_lex_brackets
8695                 && PL_lex_brackstack[PL_lex_brackets-1] != XFAKEEOF)
8696             {
8697                 yyerror((const char *)
8698                         (PL_lex_formbrack
8699                          ? "Format not terminated"
8700                          : "Missing right curly or square bracket"));
8701             }
8702             DEBUG_T({
8703                 PerlIO_printf(Perl_debug_log, "### Tokener got EOF\n");
8704             });
8705             TOKEN(0);
8706         }
8707         if (s++ < PL_bufend)
8708             goto retry;  /* ignore stray nulls */
8709         PL_last_uni = 0;
8710         PL_last_lop = 0;
8711         if (!PL_in_eval && !PL_preambled) {
8712             PL_preambled = TRUE;
8713             if (PL_perldb) {
8714                 /* Generate a string of Perl code to load the debugger.
8715                  * If PERL5DB is set, it will return the contents of that,
8716                  * otherwise a compile-time require of perl5db.pl.  */
8717
8718                 const char * const pdb = PerlEnv_getenv("PERL5DB");
8719
8720                 if (pdb) {
8721                     sv_setpv(PL_linestr, pdb);
8722                     sv_catpvs(PL_linestr,";");
8723                 } else {
8724                     SETERRNO(0,SS_NORMAL);
8725                     sv_setpvs(PL_linestr, "BEGIN { require 'perl5db.pl' };");
8726                 }
8727                 PL_parser->preambling = CopLINE(PL_curcop);
8728             } else
8729                 SvPVCLEAR(PL_linestr);
8730             if (PL_preambleav) {
8731                 SV **svp = AvARRAY(PL_preambleav);
8732                 SV **const end = svp + AvFILLp(PL_preambleav);
8733                 while(svp <= end) {
8734                     sv_catsv(PL_linestr, *svp);
8735                     ++svp;
8736                     sv_catpvs(PL_linestr, ";");
8737                 }
8738                 sv_free(MUTABLE_SV(PL_preambleav));
8739                 PL_preambleav = NULL;
8740             }
8741             if (PL_minus_E)
8742                 sv_catpvs(PL_linestr,
8743                           "use feature ':" STRINGIFY(PERL_REVISION) "." STRINGIFY(PERL_VERSION) "';");
8744             if (PL_minus_n || PL_minus_p) {
8745                 sv_catpvs(PL_linestr, "LINE: while (<>) {"/*}*/);
8746                 if (PL_minus_l)
8747                     sv_catpvs(PL_linestr,"chomp;");
8748                 if (PL_minus_a) {
8749                     if (PL_minus_F) {
8750                         if (   (   *PL_splitstr == '/'
8751                                 || *PL_splitstr == '\''
8752                                 || *PL_splitstr == '"')
8753                             && strchr(PL_splitstr + 1, *PL_splitstr))
8754                         {
8755                             /* strchr is ok, because -F pattern can't contain
8756                              * embeddded NULs */
8757                             Perl_sv_catpvf(aTHX_ PL_linestr, "our @F=split(%s);", PL_splitstr);
8758                         }
8759                         else {
8760                             /* "q\0${splitstr}\0" is legal perl. Yes, even NUL
8761                                bytes can be used as quoting characters.  :-) */
8762                             const char *splits = PL_splitstr;
8763                             sv_catpvs(PL_linestr, "our @F=split(q\0");
8764                             do {
8765                                 /* Need to \ \s  */
8766                                 if (*splits == '\\')
8767                                     sv_catpvn(PL_linestr, splits, 1);
8768                                 sv_catpvn(PL_linestr, splits, 1);
8769                             } while (*splits++);
8770                             /* This loop will embed the trailing NUL of
8771                                PL_linestr as the last thing it does before
8772                                terminating.  */
8773                             sv_catpvs(PL_linestr, ");");
8774                         }
8775                     }
8776                     else
8777                         sv_catpvs(PL_linestr,"our @F=split(' ');");
8778                 }
8779             }
8780             sv_catpvs(PL_linestr, "\n");
8781             PL_oldoldbufptr = PL_oldbufptr = s = PL_linestart = SvPVX(PL_linestr);
8782             PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
8783             PL_last_lop = PL_last_uni = NULL;
8784             if (PERLDB_LINE_OR_SAVESRC && PL_curstash != PL_debstash)
8785                 update_debugger_info(PL_linestr, NULL, 0);
8786             goto retry;
8787         }
8788         if ((tok = yyl_fake_eof(aTHX_ 0, cBOOL(PL_rsfp), s)) != YYL_RETRY)
8789             return tok;
8790         goto retry_bufptr;
8791
8792     case '\r':
8793 #ifdef PERL_STRICT_CR
8794         Perl_warn(aTHX_ "Illegal character \\%03o (carriage return)", '\r');
8795         Perl_croak(aTHX_
8796       "\t(Maybe you didn't strip carriage returns after a network transfer?)\n");
8797 #endif
8798     case ' ': case '\t': case '\f': case '\v':
8799         s++;
8800         goto retry;
8801
8802     case '#':
8803     case '\n': {
8804         const bool needs_semicolon = yyl_eol_needs_semicolon(aTHX_ &s);
8805         if (needs_semicolon)
8806             TOKEN(PERLY_SEMICOLON);
8807         else
8808             goto retry;
8809     }
8810
8811     case '-':
8812         return yyl_hyphen(aTHX_ s);
8813
8814     case '+':
8815         return yyl_plus(aTHX_ s);
8816
8817     case '*':
8818         return yyl_star(aTHX_ s);
8819
8820     case '%':
8821         return yyl_percent(aTHX_ s);
8822
8823     case '^':
8824         return yyl_caret(aTHX_ s);
8825
8826     case '[':
8827         return yyl_leftsquare(aTHX_ s);
8828
8829     case '~':
8830         return yyl_tilde(aTHX_ s);
8831
8832     case ',':
8833         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8834             TOKEN(0);
8835         s++;
8836         OPERATOR(PERLY_COMMA);
8837     case ':':
8838         if (s[1] == ':')
8839             return yyl_just_a_word(aTHX_ s, 0, 0, no_code);
8840         return yyl_colon(aTHX_ s + 1);
8841
8842     case '(':
8843         return yyl_leftparen(aTHX_ s + 1);
8844
8845     case ';':
8846         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_NONEXPR)
8847             TOKEN(0);
8848         CLINE;
8849         s++;
8850         PL_expect = XSTATE;
8851         TOKEN(PERLY_SEMICOLON);
8852
8853     case ')':
8854         return yyl_rightparen(aTHX_ s);
8855
8856     case ']':
8857         return yyl_rightsquare(aTHX_ s);
8858
8859     case '{':
8860         return yyl_leftcurly(aTHX_ s + 1, 0);
8861
8862     case '}':
8863         if (PL_lex_brackets && PL_lex_brackstack[PL_lex_brackets-1] == XFAKEEOF)
8864             TOKEN(0);
8865         return yyl_rightcurly(aTHX_ s, 0);
8866
8867     case '&':
8868         return yyl_ampersand(aTHX_ s);
8869
8870     case '|':
8871         return yyl_verticalbar(aTHX_ s);
8872
8873     case '=':
8874         if (s[1] == '=' && (s == PL_linestart || s[-1] == '\n')
8875             && memBEGINs(s + 2, (STRLEN) (PL_bufend - (s + 2)), "====="))
8876         {
8877             s = vcs_conflict_marker(s + 7);
8878             goto retry;
8879         }
8880
8881         s++;
8882         {
8883             const char tmp = *s++;
8884             if (tmp == '=') {
8885                 if (!PL_lex_allbrackets
8886                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMPARE)
8887                 {
8888                     s -= 2;
8889                     TOKEN(0);
8890                 }
8891                 ChEop(OP_EQ);
8892             }
8893             if (tmp == '>') {
8894                 if (!PL_lex_allbrackets
8895                     && PL_lex_fakeeof >= LEX_FAKEEOF_COMMA)
8896                 {
8897                     s -= 2;
8898                     TOKEN(0);
8899                 }
8900                 OPERATOR(PERLY_COMMA);
8901             }
8902             if (tmp == '~')
8903                 PMop(OP_MATCH);
8904             if (tmp && isSPACE(*s) && ckWARN(WARN_SYNTAX)
8905                 && memCHRs("+-*/%.^&|<",tmp))
8906                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
8907                             "Reversed %c= operator",(int)tmp);
8908             s--;
8909             if (PL_expect == XSTATE
8910                 && isALPHA(tmp)
8911                 && (s == PL_linestart+1 || s[-2] == '\n') )
8912             {
8913                 if (   (PL_in_eval && !PL_rsfp && !PL_parser->filtered)
8914                     || PL_lex_state != LEX_NORMAL)
8915                 {
8916                     d = PL_bufend;
8917                     while (s < d) {
8918                         if (*s++ == '\n') {
8919                             incline(s, PL_bufend);
8920                             if (memBEGINs(s, (STRLEN) (PL_bufend - s), "=cut"))
8921                             {
8922                                 s = (char *) memchr(s,'\n', d - s);
8923                                 if (s)
8924                                     s++;
8925                                 else
8926                                     s = d;
8927                                 incline(s, PL_bufend);
8928                                 goto retry;
8929                             }
8930                         }
8931                     }
8932                     goto retry;
8933                 }
8934                 s = PL_bufend;
8935                 PL_parser->in_pod = 1;
8936                 goto retry;
8937             }
8938         }
8939         if (PL_expect == XBLOCK) {
8940             const char *t = s;
8941 #ifdef PERL_STRICT_CR
8942             while (SPACE_OR_TAB(*t))
8943 #else
8944             while (SPACE_OR_TAB(*t) || *t == '\r')
8945 #endif
8946                 t++;
8947             if (*t == '\n' || *t == '#') {
8948                 ENTER_with_name("lex_format");
8949                 SAVEI8(PL_parser->form_lex_state);
8950                 SAVEI32(PL_lex_formbrack);
8951                 PL_parser->form_lex_state = PL_lex_state;
8952                 PL_lex_formbrack = PL_lex_brackets + 1;
8953                 PL_parser->sub_error_count = PL_error_count;
8954                 return yyl_leftcurly(aTHX_ s, 1);
8955             }
8956         }
8957         if (!PL_lex_allbrackets && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN) {
8958             s--;
8959             TOKEN(0);
8960         }
8961         pl_yylval.ival = 0;
8962         OPERATOR(ASSIGNOP);
8963
8964         case '!':
8965         return yyl_bang(aTHX_ s + 1);
8966
8967     case '<':
8968         if (s[1] == '<' && (s == PL_linestart || s[-1] == '\n')
8969             && memBEGINs(s + 2, (STRLEN) (PL_bufend - (s + 2)), "<<<<<"))
8970         {
8971             s = vcs_conflict_marker(s + 7);
8972             goto retry;
8973         }
8974         return yyl_leftpointy(aTHX_ s);
8975
8976     case '>':
8977         if (s[1] == '>' && (s == PL_linestart || s[-1] == '\n')
8978             && memBEGINs(s + 2, (STRLEN) (PL_bufend - (s + 2)), ">>>>>"))
8979         {
8980             s = vcs_conflict_marker(s + 7);
8981             goto retry;
8982         }
8983         return yyl_rightpointy(aTHX_ s + 1);
8984
8985     case '$':
8986         return yyl_dollar(aTHX_ s);
8987
8988     case '@':
8989         return yyl_snail(aTHX_ s);
8990
8991     case '/':                   /* may be division, defined-or, or pattern */
8992         return yyl_slash(aTHX_ s);
8993
8994      case '?':                  /* conditional */
8995         s++;
8996         if (!PL_lex_allbrackets
8997             && PL_lex_fakeeof >= LEX_FAKEEOF_IFELSE)
8998         {
8999             s--;
9000             TOKEN(0);
9001         }
9002         PL_lex_allbrackets++;
9003         OPERATOR(PERLY_QUESTION_MARK);
9004
9005     case '.':
9006         if (PL_lex_formbrack && PL_lex_brackets == PL_lex_formbrack
9007 #ifdef PERL_STRICT_CR
9008             && s[1] == '\n'
9009 #else
9010             && (s[1] == '\n' || (s[1] == '\r' && s[2] == '\n'))
9011 #endif
9012             && (s == PL_linestart || s[-1] == '\n') )
9013         {
9014             PL_expect = XSTATE;
9015             /* formbrack==2 means dot seen where arguments expected */
9016             return yyl_rightcurly(aTHX_ s, 2);
9017         }
9018         if (PL_expect == XSTATE && s[1] == '.' && s[2] == '.') {
9019             s += 3;
9020             OPERATOR(YADAYADA);
9021         }
9022         if (PL_expect == XOPERATOR || !isDIGIT(s[1])) {
9023             char tmp = *s++;
9024             if (*s == tmp) {
9025                 if (!PL_lex_allbrackets
9026                     && PL_lex_fakeeof >= LEX_FAKEEOF_RANGE)
9027                 {
9028                     s--;
9029                     TOKEN(0);
9030                 }
9031                 s++;
9032                 if (*s == tmp) {
9033                     s++;
9034                     pl_yylval.ival = OPf_SPECIAL;
9035                 }
9036                 else
9037                     pl_yylval.ival = 0;
9038                 OPERATOR(DOTDOT);
9039             }
9040             if (*s == '=' && !PL_lex_allbrackets
9041                 && PL_lex_fakeeof >= LEX_FAKEEOF_ASSIGN)
9042             {
9043                 s--;
9044                 TOKEN(0);
9045             }
9046             Aop(OP_CONCAT);
9047         }
9048         /* FALLTHROUGH */
9049     case '0': case '1': case '2': case '3': case '4':
9050     case '5': case '6': case '7': case '8': case '9':
9051         s = scan_num(s, &pl_yylval);
9052         DEBUG_T( { printbuf("### Saw number in %s\n", s); } );
9053         if (PL_expect == XOPERATOR)
9054             no_op("Number",s);
9055         TERM(THING);
9056
9057     case '\'':
9058         return yyl_sglquote(aTHX_ s);
9059
9060     case '"':
9061         return yyl_dblquote(aTHX_ s);
9062
9063     case '`':
9064         return yyl_backtick(aTHX_ s);
9065
9066     case '\\':
9067         return yyl_backslash(aTHX_ s + 1);
9068
9069     case 'v':
9070         if (isDIGIT(s[1]) && PL_expect != XOPERATOR) {
9071             char *start = s + 2;
9072             while (isDIGIT(*start) || *start == '_')
9073                 start++;
9074             if (*start == '.' && isDIGIT(start[1])) {
9075                 s = scan_num(s, &pl_yylval);
9076                 TERM(THING);
9077             }
9078             else if ((*start == ':' && start[1] == ':')
9079                      || (PL_expect == XSTATE && *start == ':')) {
9080                 if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
9081                     return tok;
9082                 goto retry_bufptr;
9083             }
9084             else if (PL_expect == XSTATE) {
9085                 d = start;
9086                 while (d < PL_bufend && isSPACE(*d)) d++;
9087                 if (*d == ':') {
9088                     if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
9089                         return tok;
9090                     goto retry_bufptr;
9091                 }
9092             }
9093             /* avoid v123abc() or $h{v1}, allow C<print v10;> */
9094             if (!isALPHA(*start) && (PL_expect == XTERM
9095                         || PL_expect == XREF || PL_expect == XSTATE
9096                         || PL_expect == XTERMORDORDOR)) {
9097                 GV *const gv = gv_fetchpvn_flags(s, start - s,
9098                                                     UTF ? SVf_UTF8 : 0, SVt_PVCV);
9099                 if (!gv) {
9100                     s = scan_num(s, &pl_yylval);
9101                     TERM(THING);
9102                 }
9103             }
9104         }
9105         if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
9106             return tok;
9107         goto retry_bufptr;
9108
9109     case 'x':
9110         if (isDIGIT(s[1]) && PL_expect == XOPERATOR) {
9111             s++;
9112             Mop(OP_REPEAT);
9113         }
9114         if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
9115             return tok;
9116         goto retry_bufptr;
9117
9118     case '_':
9119     case 'a': case 'A':
9120     case 'b': case 'B':
9121     case 'c': case 'C':
9122     case 'd': case 'D':
9123     case 'e': case 'E':
9124     case 'f': case 'F':
9125     case 'g': case 'G':
9126     case 'h': case 'H':
9127     case 'i': case 'I':
9128     case 'j': case 'J':
9129     case 'k': case 'K':
9130     case 'l': case 'L':
9131     case 'm': case 'M':
9132     case 'n': case 'N':
9133     case 'o': case 'O':
9134     case 'p': case 'P':
9135     case 'q': case 'Q':
9136     case 'r': case 'R':
9137     case 's': case 'S':
9138     case 't': case 'T':
9139     case 'u': case 'U':
9140               case 'V':
9141     case 'w': case 'W':
9142               case 'X':
9143     case 'y': case 'Y':
9144     case 'z': case 'Z':
9145         if ((tok = yyl_keylookup(aTHX_ s, gv)) != YYL_RETRY)
9146             return tok;
9147         goto retry_bufptr;
9148     }
9149 }
9150
9151
9152 /*
9153   yylex
9154
9155   Works out what to call the token just pulled out of the input
9156   stream.  The yacc parser takes care of taking the ops we return and
9157   stitching them into a tree.
9158
9159   Returns:
9160     The type of the next token
9161
9162   Structure:
9163       Check if we have already built the token; if so, use it.
9164       Switch based on the current state:
9165           - if we have a case modifier in a string, deal with that
9166           - handle other cases of interpolation inside a string
9167           - scan the next line if we are inside a format
9168       In the normal state, switch on the next character:
9169           - default:
9170             if alphabetic, go to key lookup
9171             unrecognized character - croak
9172           - 0/4/26: handle end-of-line or EOF
9173           - cases for whitespace
9174           - \n and #: handle comments and line numbers
9175           - various operators, brackets and sigils
9176           - numbers
9177           - quotes
9178           - 'v': vstrings (or go to key lookup)
9179           - 'x' repetition operator (or go to key lookup)
9180           - other ASCII alphanumerics (key lookup begins here):
9181               word before => ?
9182               keyword plugin
9183               scan built-in keyword (but do nothing with it yet)
9184               check for statement label
9185               check for lexical subs
9186                   return yyl_just_a_word if there is one
9187               see whether built-in keyword is overridden
9188               switch on keyword number:
9189                   - default: return yyl_just_a_word:
9190                       not a built-in keyword; handle bareword lookup
9191                       disambiguate between method and sub call
9192                       fall back to bareword
9193                   - cases for built-in keywords
9194 */
9195
9196 #ifdef NETWARE
9197 #define RSFP_FILENO (PL_rsfp)
9198 #else
9199 #define RSFP_FILENO (PerlIO_fileno(PL_rsfp))
9200 #endif
9201
9202
9203 int
9204 Perl_yylex(pTHX)
9205 {
9206     char *s = PL_bufptr;
9207
9208     if (UNLIKELY(PL_parser->recheck_utf8_validity)) {
9209         const U8* first_bad_char_loc;
9210         if (UTF && UNLIKELY(! is_utf8_string_loc((U8 *) PL_bufptr,
9211                                                         PL_bufend - PL_bufptr,
9212                                                         &first_bad_char_loc)))
9213         {
9214             _force_out_malformed_utf8_message(first_bad_char_loc,
9215                                               (U8 *) PL_bufend,
9216                                               0,
9217                                               1 /* 1 means die */ );
9218             NOT_REACHED; /* NOTREACHED */
9219         }
9220         PL_parser->recheck_utf8_validity = FALSE;
9221     }
9222     DEBUG_T( {
9223         SV* tmp = newSVpvs("");
9224         PerlIO_printf(Perl_debug_log, "### %" IVdf ":LEX_%s/X%s %s\n",
9225             (IV)CopLINE(PL_curcop),
9226             lex_state_names[PL_lex_state],
9227             exp_name[PL_expect],
9228             pv_display(tmp, s, strlen(s), 0, 60));
9229         SvREFCNT_dec(tmp);
9230     } );
9231
9232     /* when we've already built the next token, just pull it out of the queue */
9233     if (PL_nexttoke) {
9234         PL_nexttoke--;
9235         pl_yylval = PL_nextval[PL_nexttoke];
9236         {
9237             I32 next_type;
9238             next_type = PL_nexttype[PL_nexttoke];
9239             if (next_type & (7<<24)) {
9240                 if (next_type & (1<<24)) {
9241                     if (PL_lex_brackets > 100)
9242                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
9243                     PL_lex_brackstack[PL_lex_brackets++] =
9244                         (char) ((next_type >> 16) & 0xff);
9245                 }
9246                 if (next_type & (2<<24))
9247                     PL_lex_allbrackets++;
9248                 if (next_type & (4<<24))
9249                     PL_lex_allbrackets--;
9250                 next_type &= 0xffff;
9251             }
9252             return REPORT(next_type == 'p' ? pending_ident() : next_type);
9253         }
9254     }
9255
9256     switch (PL_lex_state) {
9257     case LEX_NORMAL:
9258     case LEX_INTERPNORMAL:
9259         break;
9260
9261     /* interpolated case modifiers like \L \U, including \Q and \E.
9262        when we get here, PL_bufptr is at the \
9263     */
9264     case LEX_INTERPCASEMOD:
9265         /* handle \E or end of string */
9266         return yyl_interpcasemod(aTHX_ s);
9267
9268     case LEX_INTERPPUSH:
9269         return REPORT(sublex_push());
9270
9271     case LEX_INTERPSTART:
9272         if (PL_bufptr == PL_bufend)
9273             return REPORT(sublex_done());
9274         DEBUG_T({
9275             if(*PL_bufptr != '(')
9276                 PerlIO_printf(Perl_debug_log, "### Interpolated variable\n");
9277         });
9278         PL_expect = XTERM;
9279         /* for /@a/, we leave the joining for the regex engine to do
9280          * (unless we're within \Q etc) */
9281         PL_lex_dojoin = (*PL_bufptr == '@'
9282                             && (!PL_lex_inpat || PL_lex_casemods));
9283         PL_lex_state = LEX_INTERPNORMAL;
9284         if (PL_lex_dojoin) {
9285             NEXTVAL_NEXTTOKE.ival = 0;
9286             force_next(PERLY_COMMA);
9287             force_ident("\"", '$');
9288             NEXTVAL_NEXTTOKE.ival = 0;
9289             force_next('$');
9290             NEXTVAL_NEXTTOKE.ival = 0;
9291             force_next((2<<24)|'(');
9292             NEXTVAL_NEXTTOKE.ival = OP_JOIN;    /* emulate join($", ...) */
9293             force_next(FUNC);
9294         }
9295         /* Convert (?{...}) and friends to 'do {...}' */
9296         if (PL_lex_inpat && *PL_bufptr == '(') {
9297             PL_parser->lex_shared->re_eval_start = PL_bufptr;
9298             PL_bufptr += 2;
9299             if (*PL_bufptr != '{')
9300                 PL_bufptr++;
9301             PL_expect = XTERMBLOCK;
9302             force_next(DO);
9303         }
9304
9305         if (PL_lex_starts++) {
9306             s = PL_bufptr;
9307             /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9308             if (!PL_lex_casemods && PL_lex_inpat)
9309                 TOKEN(PERLY_COMMA);
9310             else
9311                 AopNOASSIGN(OP_CONCAT);
9312         }
9313         return yylex();
9314
9315     case LEX_INTERPENDMAYBE:
9316         if (intuit_more(PL_bufptr, PL_bufend)) {
9317             PL_lex_state = LEX_INTERPNORMAL;    /* false alarm, more expr */
9318             break;
9319         }
9320         /* FALLTHROUGH */
9321
9322     case LEX_INTERPEND:
9323         if (PL_lex_dojoin) {
9324             const U8 dojoin_was = PL_lex_dojoin;
9325             PL_lex_dojoin = FALSE;
9326             PL_lex_state = LEX_INTERPCONCAT;
9327             PL_lex_allbrackets--;
9328             return REPORT(dojoin_was == 1 ? (int)')' : (int)POSTJOIN);
9329         }
9330         if (PL_lex_inwhat == OP_SUBST && PL_linestr == PL_lex_repl
9331             && SvEVALED(PL_lex_repl))
9332         {
9333             if (PL_bufptr != PL_bufend)
9334                 Perl_croak(aTHX_ "Bad evalled substitution pattern");
9335             PL_lex_repl = NULL;
9336         }
9337         /* Paranoia.  re_eval_start is adjusted when S_scan_heredoc sets
9338            re_eval_str.  If the here-doc body’s length equals the previous
9339            value of re_eval_start, re_eval_start will now be null.  So
9340            check re_eval_str as well. */
9341         if (PL_parser->lex_shared->re_eval_start
9342          || PL_parser->lex_shared->re_eval_str) {
9343             SV *sv;
9344             if (*PL_bufptr != ')')
9345                 Perl_croak(aTHX_ "Sequence (?{...}) not terminated with ')'");
9346             PL_bufptr++;
9347             /* having compiled a (?{..}) expression, return the original
9348              * text too, as a const */
9349             if (PL_parser->lex_shared->re_eval_str) {
9350                 sv = PL_parser->lex_shared->re_eval_str;
9351                 PL_parser->lex_shared->re_eval_str = NULL;
9352                 SvCUR_set(sv,
9353                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9354                 SvPV_shrink_to_cur(sv);
9355             }
9356             else sv = newSVpvn(PL_parser->lex_shared->re_eval_start,
9357                          PL_bufptr - PL_parser->lex_shared->re_eval_start);
9358             NEXTVAL_NEXTTOKE.opval =
9359                     newSVOP(OP_CONST, 0,
9360                                  sv);
9361             force_next(THING);
9362             PL_parser->lex_shared->re_eval_start = NULL;
9363             PL_expect = XTERM;
9364             return REPORT(PERLY_COMMA);
9365         }
9366
9367         /* FALLTHROUGH */
9368     case LEX_INTERPCONCAT:
9369 #ifdef DEBUGGING
9370         if (PL_lex_brackets)
9371             Perl_croak(aTHX_ "panic: INTERPCONCAT, lex_brackets=%ld",
9372                        (long) PL_lex_brackets);
9373 #endif
9374         if (PL_bufptr == PL_bufend)
9375             return REPORT(sublex_done());
9376
9377         /* m'foo' still needs to be parsed for possible (?{...}) */
9378         if (SvIVX(PL_linestr) == '\'' && !PL_lex_inpat) {
9379             SV *sv = newSVsv(PL_linestr);
9380             sv = tokeq(sv);
9381             pl_yylval.opval = newSVOP(OP_CONST, 0, sv);
9382             s = PL_bufend;
9383         }
9384         else {
9385             int save_error_count = PL_error_count;
9386
9387             s = scan_const(PL_bufptr);
9388
9389             /* Set flag if this was a pattern and there were errors.  op.c will
9390              * refuse to compile a pattern with this flag set.  Otherwise, we
9391              * could get segfaults, etc. */
9392             if (PL_lex_inpat && PL_error_count > save_error_count) {
9393                 ((PMOP*)PL_lex_inpat)->op_pmflags |= PMf_HAS_ERROR;
9394             }
9395             if (*s == '\\')
9396                 PL_lex_state = LEX_INTERPCASEMOD;
9397             else
9398                 PL_lex_state = LEX_INTERPSTART;
9399         }
9400
9401         if (s != PL_bufptr) {
9402             NEXTVAL_NEXTTOKE = pl_yylval;
9403             PL_expect = XTERM;
9404             force_next(THING);
9405             if (PL_lex_starts++) {
9406                 /* commas only at base level: /$a\Ub$c/ => ($a,uc(b.$c)) */
9407                 if (!PL_lex_casemods && PL_lex_inpat)
9408                     TOKEN(PERLY_COMMA);
9409                 else
9410                     AopNOASSIGN(OP_CONCAT);
9411             }
9412             else {
9413                 PL_bufptr = s;
9414                 return yylex();
9415             }
9416         }
9417
9418         return yylex();
9419     case LEX_FORMLINE:
9420         if (PL_parser->sub_error_count != PL_error_count) {
9421             /* There was an error parsing a formline, which tends to
9422                mess up the parser.
9423                Unlike interpolated sub-parsing, we can't treat any of
9424                these as recoverable, so no need to check sub_no_recover.
9425             */
9426             yyquit();
9427         }
9428         assert(PL_lex_formbrack);
9429         s = scan_formline(PL_bufptr);
9430         if (!PL_lex_formbrack)
9431             return yyl_rightcurly(aTHX_ s, 1);
9432         PL_bufptr = s;
9433         return yylex();
9434     }
9435
9436     /* We really do *not* want PL_linestr ever becoming a COW. */
9437     assert (!SvIsCOW(PL_linestr));
9438     s = PL_bufptr;
9439     PL_oldoldbufptr = PL_oldbufptr;
9440     PL_oldbufptr = s;
9441
9442     if (PL_in_my == KEY_sigvar) {
9443         PL_parser->saw_infix_sigil = 0;
9444         return yyl_sigvar(aTHX_ s);
9445     }
9446
9447     {
9448         /* yyl_try() and its callees might consult PL_parser->saw_infix_sigil.
9449            On its return, we then need to set it to indicate whether the token
9450            we just encountered was an infix operator that (if we hadn't been
9451            expecting an operator) have been a sigil.
9452         */
9453         bool expected_operator = (PL_expect == XOPERATOR);
9454         int ret = yyl_try(aTHX_ s);
9455         switch (pl_yylval.ival) {
9456         case OP_BIT_AND:
9457         case OP_MODULO:
9458         case OP_MULTIPLY:
9459         case OP_NBIT_AND:
9460             if (expected_operator) {
9461                 PL_parser->saw_infix_sigil = 1;
9462                 break;
9463             }
9464             /* FALLTHROUGH */
9465         default:
9466             PL_parser->saw_infix_sigil = 0;
9467         }
9468         return ret;
9469     }
9470 }
9471
9472
9473 /*
9474   S_pending_ident
9475
9476   Looks up an identifier in the pad or in a package
9477
9478   PL_in_my == KEY_sigvar indicates that this is a subroutine signature variable
9479   rather than a plain pad var.
9480
9481   Returns:
9482     PRIVATEREF if this is a lexical name.
9483     BAREWORD   if this belongs to a package.
9484
9485   Structure:
9486       if we're in a my declaration
9487           croak if they tried to say my($foo::bar)
9488           build the ops for a my() declaration
9489       if it's an access to a my() variable
9490           build ops for access to a my() variable
9491       if in a dq string, and they've said @foo and we can't find @foo
9492           warn
9493       build ops for a bareword
9494 */
9495
9496 static int
9497 S_pending_ident(pTHX)
9498 {
9499     PADOFFSET tmp = 0;
9500     const char pit = (char)pl_yylval.ival;
9501     const STRLEN tokenbuf_len = strlen(PL_tokenbuf);
9502     /* All routes through this function want to know if there is a colon.  */
9503     const char *const has_colon = (const char*) memchr (PL_tokenbuf, ':', tokenbuf_len);
9504
9505     DEBUG_T({ PerlIO_printf(Perl_debug_log,
9506           "### Pending identifier '%s'\n", PL_tokenbuf); });
9507     assert(tokenbuf_len >= 2);
9508
9509     /* if we're in a my(), we can't allow dynamics here.
9510        $foo'bar has already been turned into $foo::bar, so
9511        just check for colons.
9512
9513        if it's a legal name, the OP is a PADANY.
9514     */
9515     if (PL_in_my) {
9516         if (PL_in_my == KEY_our) {      /* "our" is merely analogous to "my" */
9517             if (has_colon)
9518                 /* diag_listed_as: No package name allowed for variable %s
9519                                    in "our" */
9520                 yyerror_pv(Perl_form(aTHX_ "No package name allowed for "
9521                                   "%s %s in \"our\"",
9522                                   *PL_tokenbuf=='&' ? "subroutine" : "variable",
9523                                   PL_tokenbuf), UTF ? SVf_UTF8 : 0);
9524             tmp = allocmy(PL_tokenbuf, tokenbuf_len, UTF ? SVf_UTF8 : 0);
9525         }
9526         else {
9527             OP *o;
9528             if (has_colon) {
9529                 /* "my" variable %s can't be in a package */
9530                 /* PL_no_myglob is constant */
9531                 GCC_DIAG_IGNORE_STMT(-Wformat-nonliteral);
9532                 yyerror_pv(Perl_form(aTHX_ PL_no_myglob,
9533                             PL_in_my == KEY_my ? "my" : "state",
9534                             *PL_tokenbuf == '&' ? "subroutine" : "variable",
9535                             PL_tokenbuf),
9536                             UTF ? SVf_UTF8 : 0);
9537                 GCC_DIAG_RESTORE_STMT;
9538             }
9539
9540             if (PL_in_my == KEY_sigvar) {
9541                 /* A signature 'padop' needs in addition, an op_first to
9542                  * point to a child sigdefelem, and an extra field to hold
9543                  * the signature index. We can achieve both by using an
9544                  * UNOP_AUX and (ab)using the op_aux field to hold the
9545                  * index. If we ever need more fields, use a real malloced
9546                  * aux strut instead.
9547                  */
9548                 o = newUNOP_AUX(OP_ARGELEM, 0, NULL,
9549                                     INT2PTR(UNOP_AUX_item *,
9550                                         (PL_parser->sig_elems)));
9551                 o->op_private |= (  PL_tokenbuf[0] == '$' ? OPpARGELEM_SV
9552                                   : PL_tokenbuf[0] == '@' ? OPpARGELEM_AV
9553                                   :                         OPpARGELEM_HV);
9554             }
9555             else
9556                 o = newOP(OP_PADANY, 0);
9557             o->op_targ = allocmy(PL_tokenbuf, tokenbuf_len,
9558                                                         UTF ? SVf_UTF8 : 0);
9559             if (PL_in_my == KEY_sigvar)
9560                 PL_in_my = 0;
9561
9562             pl_yylval.opval = o;
9563             return PRIVATEREF;
9564         }
9565     }
9566
9567     /*
9568        build the ops for accesses to a my() variable.
9569     */
9570
9571     if (!has_colon) {
9572         if (!PL_in_my)
9573             tmp = pad_findmy_pvn(PL_tokenbuf, tokenbuf_len,
9574                                  0);
9575         if (tmp != NOT_IN_PAD) {
9576             /* might be an "our" variable" */
9577             if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
9578                 /* build ops for a bareword */
9579                 HV *  const stash = PAD_COMPNAME_OURSTASH(tmp);
9580                 HEK * const stashname = HvNAME_HEK(stash);
9581                 SV *  const sym = newSVhek(stashname);
9582                 sv_catpvs(sym, "::");
9583                 sv_catpvn_flags(sym, PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0, (UTF ? SV_CATUTF8 : SV_CATBYTES ));
9584                 pl_yylval.opval = newSVOP(OP_CONST, 0, sym);
9585                 pl_yylval.opval->op_private = OPpCONST_ENTERED;
9586                 if (pit != '&')
9587                   gv_fetchsv(sym,
9588                     GV_ADDMULTI,
9589                     ((PL_tokenbuf[0] == '$') ? SVt_PV
9590                      : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9591                      : SVt_PVHV));
9592                 return BAREWORD;
9593             }
9594
9595             pl_yylval.opval = newOP(OP_PADANY, 0);
9596             pl_yylval.opval->op_targ = tmp;
9597             return PRIVATEREF;
9598         }
9599     }
9600
9601     /*
9602        Whine if they've said @foo or @foo{key} in a doublequoted string,
9603        and @foo (or %foo) isn't a variable we can find in the symbol
9604        table.
9605     */
9606     if (ckWARN(WARN_AMBIGUOUS)
9607         && pit == '@'
9608         && PL_lex_state != LEX_NORMAL
9609         && !PL_lex_brackets)
9610     {
9611         GV *const gv = gv_fetchpvn_flags(PL_tokenbuf + 1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9612                                          ( UTF ? SVf_UTF8 : 0 ) | GV_ADDMG,
9613                                          SVt_PVAV);
9614         if ((!gv || ((PL_tokenbuf[0] == '@') ? !GvAV(gv) : !GvHV(gv)))
9615            )
9616         {
9617             /* Downgraded from fatal to warning 20000522 mjd */
9618             Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
9619                         "Possible unintended interpolation of %" UTF8f
9620                         " in string",
9621                         UTF8fARG(UTF, tokenbuf_len, PL_tokenbuf));
9622         }
9623     }
9624
9625     /* build ops for a bareword */
9626     pl_yylval.opval = newSVOP(OP_CONST, 0,
9627                                    newSVpvn_flags(PL_tokenbuf + 1,
9628                                                       tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9629                                                       UTF ? SVf_UTF8 : 0 ));
9630     pl_yylval.opval->op_private = OPpCONST_ENTERED;
9631     if (pit != '&')
9632         gv_fetchpvn_flags(PL_tokenbuf+1, tokenbuf_len > 0 ? tokenbuf_len - 1 : 0,
9633                      (PL_in_eval ? GV_ADDMULTI : GV_ADD)
9634                      | ( UTF ? SVf_UTF8 : 0 ),
9635                      ((PL_tokenbuf[0] == '$') ? SVt_PV
9636                       : (PL_tokenbuf[0] == '@') ? SVt_PVAV
9637                       : SVt_PVHV));
9638     return BAREWORD;
9639 }
9640
9641 STATIC void
9642 S_checkcomma(pTHX_ const char *s, const char *name, const char *what)
9643 {
9644     PERL_ARGS_ASSERT_CHECKCOMMA;
9645
9646     if (*s == ' ' && s[1] == '(') {     /* XXX gotta be a better way */
9647         if (ckWARN(WARN_SYNTAX)) {
9648             int level = 1;
9649             const char *w;
9650             for (w = s+2; *w && level; w++) {
9651                 if (*w == '(')
9652                     ++level;
9653                 else if (*w == ')')
9654                     --level;
9655             }
9656             while (isSPACE(*w))
9657                 ++w;
9658             /* the list of chars below is for end of statements or
9659              * block / parens, boolean operators (&&, ||, //) and branch
9660              * constructs (or, and, if, until, unless, while, err, for).
9661              * Not a very solid hack... */
9662             if (!*w || !memCHRs(";&/|})]oaiuwef!=", *w))
9663                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9664                             "%s (...) interpreted as function",name);
9665         }
9666     }
9667     while (s < PL_bufend && isSPACE(*s))
9668         s++;
9669     if (*s == '(')
9670         s++;
9671     while (s < PL_bufend && isSPACE(*s))
9672         s++;
9673     if (isIDFIRST_lazy_if_safe(s, PL_bufend, UTF)) {
9674         const char * const w = s;
9675         s += UTF ? UTF8SKIP(s) : 1;
9676         while (isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
9677             s += UTF ? UTF8SKIP(s) : 1;
9678         while (s < PL_bufend && isSPACE(*s))
9679             s++;
9680         if (*s == ',') {
9681             GV* gv;
9682             if (keyword(w, s - w, 0))
9683                 return;
9684
9685             gv = gv_fetchpvn_flags(w, s - w, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
9686             if (gv && GvCVu(gv))
9687                 return;
9688             if (s - w <= 254) {
9689                 PADOFFSET off;
9690                 char tmpbuf[256];
9691                 Copy(w, tmpbuf+1, s - w, char);
9692                 *tmpbuf = '&';
9693                 off = pad_findmy_pvn(tmpbuf, s-w+1, 0);
9694                 if (off != NOT_IN_PAD) return;
9695             }
9696             Perl_croak(aTHX_ "No comma allowed after %s", what);
9697         }
9698     }
9699 }
9700
9701 /* S_new_constant(): do any overload::constant lookup.
9702
9703    Either returns sv, or mortalizes/frees sv and returns a new SV*.
9704    Best used as sv=new_constant(..., sv, ...).
9705    If s, pv are NULL, calls subroutine with one argument,
9706    and <type> is used with error messages only.
9707    <type> is assumed to be well formed UTF-8.
9708
9709    If error_msg is not NULL, *error_msg will be set to any error encountered.
9710    Otherwise yyerror() will be used to output it */
9711
9712 STATIC SV *
9713 S_new_constant(pTHX_ const char *s, STRLEN len, const char *key, STRLEN keylen,
9714                SV *sv, SV *pv, const char *type, STRLEN typelen,
9715                const char ** error_msg)
9716 {
9717     dSP;
9718     HV * table = GvHV(PL_hintgv);                /* ^H */
9719     SV *res;
9720     SV *errsv = NULL;
9721     SV **cvp;
9722     SV *cv, *typesv;
9723     const char *why1 = "", *why2 = "", *why3 = "";
9724     const char * optional_colon = ":";  /* Only some messages have a colon */
9725     char *msg;
9726
9727     PERL_ARGS_ASSERT_NEW_CONSTANT;
9728     /* We assume that this is true: */
9729     assert(type || s);
9730
9731     sv_2mortal(sv);                     /* Parent created it permanently */
9732
9733     if (   ! table
9734         || ! (PL_hints & HINT_LOCALIZE_HH))
9735     {
9736         why1 = "unknown";
9737         optional_colon = "";
9738         goto report;
9739     }
9740
9741     cvp = hv_fetch(table, key, keylen, FALSE);
9742     if (!cvp || !SvOK(*cvp)) {
9743         why1 = "$^H{";
9744         why2 = key;
9745         why3 = "} is not defined";
9746         goto report;
9747     }
9748
9749     cv = *cvp;
9750     if (!pv && s)
9751         pv = newSVpvn_flags(s, len, SVs_TEMP);
9752     if (type && pv)
9753         typesv = newSVpvn_flags(type, typelen, SVs_TEMP);
9754     else
9755         typesv = &PL_sv_undef;
9756
9757     PUSHSTACKi(PERLSI_OVERLOAD);
9758     ENTER ;
9759     SAVETMPS;
9760
9761     PUSHMARK(SP) ;
9762     EXTEND(sp, 3);
9763     if (pv)
9764         PUSHs(pv);
9765     PUSHs(sv);
9766     if (pv)
9767         PUSHs(typesv);
9768     PUTBACK;
9769     call_sv(cv, G_SCALAR | ( PL_in_eval ? 0 : G_EVAL));
9770
9771     SPAGAIN ;
9772
9773     /* Check the eval first */
9774     if (!PL_in_eval && ((errsv = ERRSV), SvTRUE_NN(errsv))) {
9775         STRLEN errlen;
9776         const char * errstr;
9777         sv_catpvs(errsv, "Propagated");
9778         errstr = SvPV_const(errsv, errlen);
9779         yyerror_pvn(errstr, errlen, 0); /* Duplicates the message inside eval */
9780         (void)POPs;
9781         res = SvREFCNT_inc_simple_NN(sv);
9782     }
9783     else {
9784         res = POPs;
9785         SvREFCNT_inc_simple_void_NN(res);
9786     }
9787
9788     PUTBACK ;
9789     FREETMPS ;
9790     LEAVE ;
9791     POPSTACK;
9792
9793     if (SvOK(res)) {
9794         return res;
9795     }
9796
9797     sv = res;
9798     (void)sv_2mortal(sv);
9799
9800     why1 = "Call to &{$^H{";
9801     why2 = key;
9802     why3 = "}} did not return a defined value";
9803
9804   report:
9805
9806     msg = Perl_form(aTHX_ "Constant(%.*s)%s %s%s%s",
9807                         (int)(type ? typelen : len),
9808                         (type ? type: s),
9809                         optional_colon,
9810                         why1, why2, why3);
9811     if (error_msg) {
9812         *error_msg = msg;
9813     }
9814     else {
9815         yyerror_pv(msg, UTF ? SVf_UTF8 : 0);
9816     }
9817     return SvREFCNT_inc_simple_NN(sv);
9818 }
9819
9820 PERL_STATIC_INLINE void
9821 S_parse_ident(pTHX_ char **s, char **d, char * const e, int allow_package,
9822                     bool is_utf8, bool check_dollar, bool tick_warn)
9823 {
9824     int saw_tick = 0;
9825     const char *olds = *s;
9826     PERL_ARGS_ASSERT_PARSE_IDENT;
9827
9828     while (*s < PL_bufend) {
9829         if (*d >= e)
9830             Perl_croak(aTHX_ "%s", ident_too_long);
9831         if (is_utf8 && isIDFIRST_utf8_safe(*s, PL_bufend)) {
9832              /* The UTF-8 case must come first, otherwise things
9833              * like c\N{COMBINING TILDE} would start failing, as the
9834              * isWORDCHAR_A case below would gobble the 'c' up.
9835              */
9836
9837             char *t = *s + UTF8SKIP(*s);
9838             while (isIDCONT_utf8_safe((const U8*) t, (const U8*) PL_bufend)) {
9839                 t += UTF8SKIP(t);
9840             }
9841             if (*d + (t - *s) > e)
9842                 Perl_croak(aTHX_ "%s", ident_too_long);
9843             Copy(*s, *d, t - *s, char);
9844             *d += t - *s;
9845             *s = t;
9846         }
9847         else if ( isWORDCHAR_A(**s) ) {
9848             do {
9849                 *(*d)++ = *(*s)++;
9850             } while (isWORDCHAR_A(**s) && *d < e);
9851         }
9852         else if (   allow_package
9853                  && **s == '\''
9854                  && isIDFIRST_lazy_if_safe((*s)+1, PL_bufend, is_utf8))
9855         {
9856             *(*d)++ = ':';
9857             *(*d)++ = ':';
9858             (*s)++;
9859             saw_tick++;
9860         }
9861         else if (allow_package && **s == ':' && (*s)[1] == ':'
9862            /* Disallow things like Foo::$bar. For the curious, this is
9863             * the code path that triggers the "Bad name after" warning
9864             * when looking for barewords.
9865             */
9866            && !(check_dollar && (*s)[2] == '$')) {
9867             *(*d)++ = *(*s)++;
9868             *(*d)++ = *(*s)++;
9869         }
9870         else
9871             break;
9872     }
9873     if (UNLIKELY(tick_warn && saw_tick && PL_lex_state == LEX_INTERPNORMAL
9874               && !PL_lex_brackets && ckWARN(WARN_SYNTAX))) {
9875         char *this_d;
9876         char *d2;
9877         Newx(this_d, *s - olds + saw_tick + 2, char); /* +2 for $# */
9878         d2 = this_d;
9879         SAVEFREEPV(this_d);
9880         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9881                          "Old package separator used in string");
9882         if (olds[-1] == '#')
9883             *d2++ = olds[-2];
9884         *d2++ = olds[-1];
9885         while (olds < *s) {
9886             if (*olds == '\'') {
9887                 *d2++ = '\\';
9888                 *d2++ = *olds++;
9889             }
9890             else
9891                 *d2++ = *olds++;
9892         }
9893         Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
9894                          "\t(Did you mean \"%" UTF8f "\" instead?)\n",
9895                           UTF8fARG(is_utf8, d2-this_d, this_d));
9896     }
9897     return;
9898 }
9899
9900 /* Returns a NUL terminated string, with the length of the string written to
9901    *slp
9902    */
9903 char *
9904 Perl_scan_word(pTHX_ char *s, char *dest, STRLEN destlen, int allow_package, STRLEN *slp)
9905 {
9906     char *d = dest;
9907     char * const e = d + destlen - 3;  /* two-character token, ending NUL */
9908     bool is_utf8 = cBOOL(UTF);
9909
9910     PERL_ARGS_ASSERT_SCAN_WORD;
9911
9912     parse_ident(&s, &d, e, allow_package, is_utf8, TRUE, FALSE);
9913     *d = '\0';
9914     *slp = d - dest;
9915     return s;
9916 }
9917
9918 /* Is the byte 'd' a legal single character identifier name?  'u' is true
9919  * iff Unicode semantics are to be used.  The legal ones are any of:
9920  *  a) all ASCII characters except:
9921  *          1) control and space-type ones, like NUL, SOH, \t, and SPACE;
9922  *          2) '{'
9923  *     The final case currently doesn't get this far in the program, so we
9924  *     don't test for it.  If that were to change, it would be ok to allow it.
9925  *  b) When not under Unicode rules, any upper Latin1 character
9926  *  c) Otherwise, when unicode rules are used, all XIDS characters.
9927  *
9928  *      Because all ASCII characters have the same representation whether
9929  *      encoded in UTF-8 or not, we can use the foo_A macros below and '\0' and
9930  *      '{' without knowing if is UTF-8 or not. */
9931 #define VALID_LEN_ONE_IDENT(s, e, is_utf8)                                  \
9932     (isGRAPH_A(*(s)) || ((is_utf8)                                          \
9933                          ? isIDFIRST_utf8_safe(s, e)                        \
9934                          : (isGRAPH_L1(*s)                                  \
9935                             && LIKELY((U8) *(s) != LATIN1_TO_NATIVE(0xAD)))))
9936
9937 STATIC char *
9938 S_scan_ident(pTHX_ char *s, char *dest, STRLEN destlen, I32 ck_uni)
9939 {
9940     I32 herelines = PL_parser->herelines;
9941     SSize_t bracket = -1;
9942     char funny = *s++;
9943     char *d = dest;
9944     char * const e = d + destlen - 3;    /* two-character token, ending NUL */
9945     bool is_utf8 = cBOOL(UTF);
9946     I32 orig_copline = 0, tmp_copline = 0;
9947
9948     PERL_ARGS_ASSERT_SCAN_IDENT;
9949
9950     if (isSPACE(*s) || !*s)
9951         s = skipspace(s);
9952     if (isDIGIT(*s)) { /* handle $0 and $1 $2 and $10 and etc */
9953         bool is_zero= *s == '0' ? TRUE : FALSE;
9954         char *digit_start= d;
9955         *d++ = *s++;
9956         while (s < PL_bufend && isDIGIT(*s)) {
9957             if (d >= e)
9958                 Perl_croak(aTHX_ "%s", ident_too_long);
9959             *d++ = *s++;
9960         } 
9961         if (is_zero && d - digit_start > 1)
9962             Perl_croak(aTHX_ ident_var_zero_multi_digit);
9963     }
9964     else {  /* See if it is a "normal" identifier */
9965         parse_ident(&s, &d, e, 1, is_utf8, FALSE, TRUE);
9966     }
9967     *d = '\0';
9968     d = dest;
9969     if (*d) {
9970         /* Either a digit variable, or parse_ident() found an identifier
9971            (anything valid as a bareword), so job done and return.  */
9972         if (PL_lex_state != LEX_NORMAL)
9973             PL_lex_state = LEX_INTERPENDMAYBE;
9974         return s;
9975     }
9976
9977     /* Here, it is not a run-of-the-mill identifier name */
9978
9979     if (*s == '$' && s[1]
9980         && (   isIDFIRST_lazy_if_safe(s+1, PL_bufend, is_utf8)
9981             || isDIGIT_A((U8)s[1])
9982             || s[1] == '$'
9983             || s[1] == '{'
9984             || memBEGINs(s+1, (STRLEN) (PL_bufend - (s+1)), "::")) )
9985     {
9986         /* Dereferencing a value in a scalar variable.
9987            The alternatives are different syntaxes for a scalar variable.
9988            Using ' as a leading package separator isn't allowed. :: is.   */
9989         return s;
9990     }
9991     /* Handle the opening { of @{...}, &{...}, *{...}, %{...}, ${...}  */
9992     if (*s == '{') {
9993         bracket = s - SvPVX(PL_linestr);
9994         s++;
9995         orig_copline = CopLINE(PL_curcop);
9996         if (s < PL_bufend && isSPACE(*s)) {
9997             s = skipspace(s);
9998         }
9999     }
10000     if ((s <= PL_bufend - ((is_utf8)
10001                           ? UTF8SKIP(s)
10002                           : 1))
10003         && VALID_LEN_ONE_IDENT(s, PL_bufend, is_utf8))
10004     {
10005         if (is_utf8) {
10006             const STRLEN skip = UTF8SKIP(s);
10007             STRLEN i;
10008             d[skip] = '\0';
10009             for ( i = 0; i < skip; i++ )
10010                 d[i] = *s++;
10011         }
10012         else {
10013             *d = *s++;
10014             /* special case to handle ${10}, ${11} the same way we handle ${1} etc */
10015             if (isDIGIT(*d)) {
10016                 bool is_zero= *d == '0' ? TRUE : FALSE;
10017                 char *digit_start= d;
10018                 while (s < PL_bufend && isDIGIT(*s)) {
10019                     d++;
10020                     if (d >= e)
10021                         Perl_croak(aTHX_ "%s", ident_too_long);
10022                     *d= *s++;
10023                 }
10024                 if (is_zero && d - digit_start > 1)
10025                     Perl_croak(aTHX_ ident_var_zero_multi_digit);
10026             }
10027             d[1] = '\0';
10028         }
10029     }
10030     /* Convert $^F, ${^F} and the ^F of ${^FOO} to control characters */
10031     if (*d == '^' && *s && isCONTROLVAR(*s)) {
10032         *d = toCTRL(*s);
10033         s++;
10034     }
10035     /* Warn about ambiguous code after unary operators if {...} notation isn't
10036        used.  There's no difference in ambiguity; it's merely a heuristic
10037        about when not to warn.  */
10038     else if (ck_uni && bracket == -1)
10039         check_uni();
10040     if (bracket != -1) {
10041         bool skip;
10042         char *s2;
10043         /* If we were processing {...} notation then...  */
10044         if (isIDFIRST_lazy_if_safe(d, e, is_utf8)
10045             || (!isPRINT(*d) /* isCNTRL(d), plus all non-ASCII */
10046                  && isWORDCHAR(*s))
10047         ) {
10048             /* note we have to check for a normal identifier first,
10049              * as it handles utf8 symbols, and only after that has
10050              * been ruled out can we look at the caret words */
10051             if (isIDFIRST_lazy_if_safe(d, e, is_utf8) ) {
10052                 /* if it starts as a valid identifier, assume that it is one.
10053                    (the later check for } being at the expected point will trap
10054                    cases where this doesn't pan out.)  */
10055                 d += is_utf8 ? UTF8SKIP(d) : 1;
10056                 parse_ident(&s, &d, e, 1, is_utf8, TRUE, TRUE);
10057                 *d = '\0';
10058             }
10059             else { /* caret word: ${^Foo} ${^CAPTURE[0]} */
10060                 d++;
10061                 while (isWORDCHAR(*s) && d < e) {
10062                     *d++ = *s++;
10063                 }
10064                 if (d >= e)
10065                     Perl_croak(aTHX_ "%s", ident_too_long);
10066                 *d = '\0';
10067             }
10068             tmp_copline = CopLINE(PL_curcop);
10069             if (s < PL_bufend && isSPACE(*s)) {
10070                 s = skipspace(s);
10071             }
10072             if ((*s == '[' || (*s == '{' && strNE(dest, "sub")))) {
10073                 /* ${foo[0]} and ${foo{bar}} and ${^CAPTURE[0]} notation.  */
10074                 if (ckWARN(WARN_AMBIGUOUS) && keyword(dest, d - dest, 0)) {
10075                     const char * const brack =
10076                         (const char *)
10077                         ((*s == '[') ? "[...]" : "{...}");
10078                     orig_copline = CopLINE(PL_curcop);
10079                     CopLINE_set(PL_curcop, tmp_copline);
10080    /* diag_listed_as: Ambiguous use of %c{%s[...]} resolved to %c%s[...] */
10081                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
10082                         "Ambiguous use of %c{%s%s} resolved to %c%s%s",
10083                         funny, dest, brack, funny, dest, brack);
10084                     CopLINE_set(PL_curcop, orig_copline);
10085                 }
10086                 bracket++;
10087                 PL_lex_brackstack[PL_lex_brackets++] = (char)(XOPERATOR | XFAKEBRACK);
10088                 PL_lex_allbrackets++;
10089                 return s;
10090             }
10091         }
10092
10093         if ( !tmp_copline )
10094             tmp_copline = CopLINE(PL_curcop);
10095         if ((skip = s < PL_bufend && isSPACE(*s))) {
10096             /* Avoid incrementing line numbers or resetting PL_linestart,
10097                in case we have to back up.  */
10098             STRLEN s_off = s - SvPVX(PL_linestr);
10099             s2 = peekspace(s);
10100             s = SvPVX(PL_linestr) + s_off;
10101         }
10102         else
10103             s2 = s;
10104
10105         /* Expect to find a closing } after consuming any trailing whitespace.
10106          */
10107         if (*s2 == '}') {
10108             /* Now increment line numbers if applicable.  */
10109             if (skip)
10110                 s = skipspace(s);
10111             s++;
10112             if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
10113                 PL_lex_state = LEX_INTERPEND;
10114                 PL_expect = XREF;
10115             }
10116             if (PL_lex_state == LEX_NORMAL || PL_lex_brackets) {
10117                 if (ckWARN(WARN_AMBIGUOUS)
10118                     && (keyword(dest, d - dest, 0)
10119                         || get_cvn_flags(dest, d - dest, is_utf8
10120                            ? SVf_UTF8
10121                            : 0)))
10122                 {
10123                     SV *tmp = newSVpvn_flags( dest, d - dest,
10124                                         SVs_TEMP | (is_utf8 ? SVf_UTF8 : 0) );
10125                     if (funny == '#')
10126                         funny = '@';
10127                     orig_copline = CopLINE(PL_curcop);
10128                     CopLINE_set(PL_curcop, tmp_copline);
10129                     Perl_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
10130                         "Ambiguous use of %c{%" SVf "} resolved to %c%" SVf,
10131                         funny, SVfARG(tmp), funny, SVfARG(tmp));
10132                     CopLINE_set(PL_curcop, orig_copline);
10133                 }
10134             }
10135         }
10136         else {
10137             /* Didn't find the closing } at the point we expected, so restore
10138                state such that the next thing to process is the opening { and */
10139             s = SvPVX(PL_linestr) + bracket; /* let the parser handle it */
10140             CopLINE_set(PL_curcop, orig_copline);
10141             PL_parser->herelines = herelines;
10142             *dest = '\0';
10143             PL_parser->sub_no_recover = TRUE;
10144         }
10145     }
10146     else if (   PL_lex_state == LEX_INTERPNORMAL
10147              && !PL_lex_brackets
10148              && !intuit_more(s, PL_bufend))
10149         PL_lex_state = LEX_INTERPEND;
10150     return s;
10151 }
10152
10153 static bool
10154 S_pmflag(pTHX_ const char* const valid_flags, U32 * pmfl, char** s, char* charset, unsigned int * x_mod_count) {
10155
10156     /* Adds, subtracts to/from 'pmfl' based on the next regex modifier flag
10157      * found in the parse starting at 's', based on the subset that are valid
10158      * in this context input to this routine in 'valid_flags'. Advances s.
10159      * Returns TRUE if the input should be treated as a valid flag, so the next
10160      * char may be as well; otherwise FALSE. 'charset' should point to a NUL
10161      * upon first call on the current regex.  This routine will set it to any
10162      * charset modifier found.  The caller shouldn't change it.  This way,
10163      * another charset modifier encountered in the parse can be detected as an
10164      * error, as we have decided to allow only one */
10165
10166     const char c = **s;
10167     STRLEN charlen = UTF ? UTF8SKIP(*s) : 1;
10168
10169     if ( charlen != 1 || ! strchr(valid_flags, c) ) {
10170         if (isWORDCHAR_lazy_if_safe( *s, PL_bufend, UTF)) {
10171             yyerror_pv(Perl_form(aTHX_ "Unknown regexp modifier \"/%.*s\"", (int)charlen, *s),
10172                        UTF ? SVf_UTF8 : 0);
10173             (*s) += charlen;
10174             /* Pretend that it worked, so will continue processing before
10175              * dieing */
10176             return TRUE;
10177         }
10178         return FALSE;
10179     }
10180
10181     switch (c) {
10182
10183         CASE_STD_PMMOD_FLAGS_PARSE_SET(pmfl, *x_mod_count);
10184         case GLOBAL_PAT_MOD:      *pmfl |= PMf_GLOBAL; break;
10185         case CONTINUE_PAT_MOD:    *pmfl |= PMf_CONTINUE; break;
10186         case ONCE_PAT_MOD:        *pmfl |= PMf_KEEP; break;
10187         case KEEPCOPY_PAT_MOD:    *pmfl |= RXf_PMf_KEEPCOPY; break;
10188         case NONDESTRUCT_PAT_MOD: *pmfl |= PMf_NONDESTRUCT; break;
10189         case LOCALE_PAT_MOD:
10190             if (*charset) {
10191                 goto multiple_charsets;
10192             }
10193             set_regex_charset(pmfl, REGEX_LOCALE_CHARSET);
10194             *charset = c;
10195             break;
10196         case UNICODE_PAT_MOD:
10197             if (*charset) {
10198                 goto multiple_charsets;
10199             }
10200             set_regex_charset(pmfl, REGEX_UNICODE_CHARSET);
10201             *charset = c;
10202             break;
10203         case ASCII_RESTRICT_PAT_MOD:
10204             if (! *charset) {
10205                 set_regex_charset(pmfl, REGEX_ASCII_RESTRICTED_CHARSET);
10206             }
10207             else {
10208
10209                 /* Error if previous modifier wasn't an 'a', but if it was, see
10210                  * if, and accept, a second occurrence (only) */
10211                 if (*charset != 'a'
10212                     || get_regex_charset(*pmfl)
10213                         != REGEX_ASCII_RESTRICTED_CHARSET)
10214                 {
10215                         goto multiple_charsets;
10216                 }
10217                 set_regex_charset(pmfl, REGEX_ASCII_MORE_RESTRICTED_CHARSET);
10218             }
10219             *charset = c;
10220             break;
10221         case DEPENDS_PAT_MOD:
10222             if (*charset) {
10223                 goto multiple_charsets;
10224             }
10225             set_regex_charset(pmfl, REGEX_DEPENDS_CHARSET);
10226             *charset = c;
10227             break;
10228     }
10229
10230     (*s)++;
10231     return TRUE;
10232
10233     multiple_charsets:
10234         if (*charset != c) {
10235             yyerror(Perl_form(aTHX_ "Regexp modifiers \"/%c\" and \"/%c\" are mutually exclusive", *charset, c));
10236         }
10237         else if (c == 'a') {
10238   /* diag_listed_as: Regexp modifier "/%c" may appear a maximum of twice */
10239             yyerror("Regexp modifier \"/a\" may appear a maximum of twice");
10240         }
10241         else {
10242             yyerror(Perl_form(aTHX_ "Regexp modifier \"/%c\" may not appear twice", c));
10243         }
10244
10245         /* Pretend that it worked, so will continue processing before dieing */
10246         (*s)++;
10247         return TRUE;
10248 }
10249
10250 STATIC char *
10251 S_scan_pat(pTHX_ char *start, I32 type)
10252 {
10253     PMOP *pm;
10254     char *s;
10255     const char * const valid_flags =
10256         (const char *)((type == OP_QR) ? QR_PAT_MODS : M_PAT_MODS);
10257     char charset = '\0';    /* character set modifier */
10258     unsigned int x_mod_count = 0;
10259
10260     PERL_ARGS_ASSERT_SCAN_PAT;
10261
10262     s = scan_str(start,TRUE,FALSE, (PL_in_eval & EVAL_RE_REPARSING), NULL);
10263     if (!s)
10264         Perl_croak(aTHX_ "Search pattern not terminated");
10265
10266     pm = (PMOP*)newPMOP(type, 0);
10267     if (PL_multi_open == '?') {
10268         /* This is the only point in the code that sets PMf_ONCE:  */
10269         pm->op_pmflags |= PMf_ONCE;
10270
10271         /* Hence it's safe to do this bit of PMOP book-keeping here, which
10272            allows us to restrict the list needed by reset to just the ??
10273            matches.  */
10274         assert(type != OP_TRANS);
10275         if (PL_curstash) {
10276             MAGIC *mg = mg_find((const SV *)PL_curstash, PERL_MAGIC_symtab);
10277             U32 elements;
10278             if (!mg) {
10279                 mg = sv_magicext(MUTABLE_SV(PL_curstash), 0, PERL_MAGIC_symtab, 0, 0,
10280                                  0);
10281             }
10282             elements = mg->mg_len / sizeof(PMOP**);
10283             Renewc(mg->mg_ptr, elements + 1, PMOP*, char);
10284             ((PMOP**)mg->mg_ptr) [elements++] = pm;
10285             mg->mg_len = elements * sizeof(PMOP**);
10286             PmopSTASH_set(pm,PL_curstash);
10287         }
10288     }
10289
10290     /* if qr/...(?{..}).../, then need to parse the pattern within a new
10291      * anon CV. False positives like qr/[(?{]/ are harmless */
10292
10293     if (type == OP_QR) {
10294         STRLEN len;
10295         char *e, *p = SvPV(PL_lex_stuff, len);
10296         e = p + len;
10297         for (; p < e; p++) {
10298             if (p[0] == '(' && p[1] == '?'
10299                 && (p[2] == '{' || (p[2] == '?' && p[3] == '{')))
10300             {
10301                 pm->op_pmflags |= PMf_HAS_CV;
10302                 break;
10303             }
10304         }
10305         pm->op_pmflags |= PMf_IS_QR;
10306     }
10307
10308     while (*s && S_pmflag(aTHX_ valid_flags, &(pm->op_pmflags),
10309                                 &s, &charset, &x_mod_count))
10310     {};
10311     /* issue a warning if /c is specified,but /g is not */
10312     if ((pm->op_pmflags & PMf_CONTINUE) && !(pm->op_pmflags & PMf_GLOBAL))
10313     {
10314         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP),
10315                        "Use of /c modifier is meaningless without /g" );
10316     }
10317
10318     PL_lex_op = (OP*)pm;
10319     pl_yylval.ival = OP_MATCH;
10320     return s;
10321 }
10322
10323 STATIC char *
10324 S_scan_subst(pTHX_ char *start)
10325 {
10326     char *s;
10327     PMOP *pm;
10328     I32 first_start;
10329     line_t first_line;
10330     line_t linediff = 0;
10331     I32 es = 0;
10332     char charset = '\0';    /* character set modifier */
10333     unsigned int x_mod_count = 0;
10334     char *t;
10335
10336     PERL_ARGS_ASSERT_SCAN_SUBST;
10337
10338     pl_yylval.ival = OP_NULL;
10339
10340     s = scan_str(start, TRUE, FALSE, FALSE, &t);
10341
10342     if (!s)
10343         Perl_croak(aTHX_ "Substitution pattern not terminated");
10344
10345     s = t;
10346
10347     first_start = PL_multi_start;
10348     first_line = CopLINE(PL_curcop);
10349     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10350     if (!s) {
10351         SvREFCNT_dec_NN(PL_lex_stuff);
10352         PL_lex_stuff = NULL;
10353         Perl_croak(aTHX_ "Substitution replacement not terminated");
10354     }
10355     PL_multi_start = first_start;       /* so whole substitution is taken together */
10356
10357     pm = (PMOP*)newPMOP(OP_SUBST, 0);
10358
10359
10360     while (*s) {
10361         if (*s == EXEC_PAT_MOD) {
10362             s++;
10363             es++;
10364         }
10365         else if (! S_pmflag(aTHX_ S_PAT_MODS, &(pm->op_pmflags),
10366                                   &s, &charset, &x_mod_count))
10367         {
10368             break;
10369         }
10370     }
10371
10372     if ((pm->op_pmflags & PMf_CONTINUE)) {
10373         Perl_ck_warner(aTHX_ packWARN(WARN_REGEXP), "Use of /c modifier is meaningless in s///" );
10374     }
10375
10376     if (es) {
10377         SV * const repl = newSVpvs("");
10378
10379         PL_multi_end = 0;
10380         pm->op_pmflags |= PMf_EVAL;
10381         for (; es > 1; es--) {
10382             sv_catpvs(repl, "eval ");
10383         }
10384         sv_catpvs(repl, "do {");
10385         sv_catsv(repl, PL_parser->lex_sub_repl);
10386         sv_catpvs(repl, "}");
10387         SvREFCNT_dec(PL_parser->lex_sub_repl);
10388         PL_parser->lex_sub_repl = repl;
10389     }
10390
10391
10392     linediff = CopLINE(PL_curcop) - first_line;
10393     if (linediff)
10394         CopLINE_set(PL_curcop, first_line);
10395
10396     if (linediff || es) {
10397         /* the IVX field indicates that the replacement string is a s///e;
10398          * the NVX field indicates how many src code lines the replacement
10399          * spreads over */
10400         sv_upgrade(PL_parser->lex_sub_repl, SVt_PVNV);
10401         ((XPVNV*)SvANY(PL_parser->lex_sub_repl))->xnv_u.xnv_lines = linediff;
10402         ((XPVIV*)SvANY(PL_parser->lex_sub_repl))->xiv_u.xivu_eval_seen =
10403                                                                     cBOOL(es);
10404     }
10405
10406     PL_lex_op = (OP*)pm;
10407     pl_yylval.ival = OP_SUBST;
10408     return s;
10409 }
10410
10411 STATIC char *
10412 S_scan_trans(pTHX_ char *start)
10413 {
10414     char* s;
10415     OP *o;
10416     U8 squash;
10417     U8 del;
10418     U8 complement;
10419     bool nondestruct = 0;
10420     char *t;
10421
10422     PERL_ARGS_ASSERT_SCAN_TRANS;
10423
10424     pl_yylval.ival = OP_NULL;
10425
10426     s = scan_str(start,FALSE,FALSE,FALSE,&t);
10427     if (!s)
10428         Perl_croak(aTHX_ "Transliteration pattern not terminated");
10429
10430     s = t;
10431
10432     s = scan_str(s,FALSE,FALSE,FALSE,NULL);
10433     if (!s) {
10434         SvREFCNT_dec_NN(PL_lex_stuff);
10435         PL_lex_stuff = NULL;
10436         Perl_croak(aTHX_ "Transliteration replacement not terminated");
10437     }
10438
10439     complement = del = squash = 0;
10440     while (1) {
10441         switch (*s) {
10442         case 'c':
10443             complement = OPpTRANS_COMPLEMENT;
10444             break;
10445         case 'd':
10446             del = OPpTRANS_DELETE;
10447             break;
10448         case 's':
10449             squash = OPpTRANS_SQUASH;
10450             break;
10451         case 'r':
10452             nondestruct = 1;
10453             break;
10454         default:
10455             goto no_more;
10456         }
10457         s++;
10458     }
10459   no_more:
10460
10461     o = newPVOP(nondestruct ? OP_TRANSR : OP_TRANS, 0, (char*)NULL);
10462     o->op_private &= ~OPpTRANS_ALL;
10463     o->op_private |= del|squash|complement;
10464
10465     PL_lex_op = o;
10466     pl_yylval.ival = nondestruct ? OP_TRANSR : OP_TRANS;
10467
10468
10469     return s;
10470 }
10471
10472 /* scan_heredoc
10473    Takes a pointer to the first < in <<FOO.
10474    Returns a pointer to the byte following <<FOO.
10475
10476    This function scans a heredoc, which involves different methods
10477    depending on whether we are in a string eval, quoted construct, etc.
10478    This is because PL_linestr could containing a single line of input, or
10479    a whole string being evalled, or the contents of the current quote-
10480    like operator.
10481
10482    The two basic methods are:
10483     - Steal lines from the input stream
10484     - Scan the heredoc in PL_linestr and remove it therefrom
10485
10486    In a file scope or filtered eval, the first method is used; in a
10487    string eval, the second.
10488
10489    In a quote-like operator, we have to choose between the two,
10490    depending on where we can find a newline.  We peek into outer lex-
10491    ing scopes until we find one with a newline in it.  If we reach the
10492    outermost lexing scope and it is a file, we use the stream method.
10493    Otherwise it is treated as an eval.
10494 */
10495
10496 STATIC char *
10497 S_scan_heredoc(pTHX_ char *s)
10498 {
10499     I32 op_type = OP_SCALAR;
10500     I32 len;
10501     SV *tmpstr;
10502     char term;
10503     char *d;
10504     char *e;
10505     char *peek;
10506     char *indent = 0;
10507     I32 indent_len = 0;
10508     bool indented = FALSE;
10509     const bool infile = PL_rsfp || PL_parser->filtered;
10510     const line_t origline = CopLINE(PL_curcop);
10511     LEXSHARED *shared = PL_parser->lex_shared;
10512
10513     PERL_ARGS_ASSERT_SCAN_HEREDOC;
10514
10515     s += 2;
10516     d = PL_tokenbuf + 1;
10517     e = PL_tokenbuf + sizeof PL_tokenbuf - 1;
10518     *PL_tokenbuf = '\n';
10519     peek = s;
10520
10521     if (*peek == '~') {
10522         indented = TRUE;
10523         peek++; s++;
10524     }
10525
10526     while (SPACE_OR_TAB(*peek))
10527         peek++;
10528
10529     if (*peek == '`' || *peek == '\'' || *peek =='"') {
10530         s = peek;
10531         term = *s++;
10532         s = delimcpy(d, e, s, PL_bufend, term, &len);
10533         if (s == PL_bufend)
10534             Perl_croak(aTHX_ "Unterminated delimiter for here document");
10535         d += len;
10536         s++;
10537     }
10538     else {
10539         if (*s == '\\')
10540             /* <<\FOO is equivalent to <<'FOO' */
10541             s++, term = '\'';
10542         else
10543             term = '"';
10544
10545         if (! isWORDCHAR_lazy_if_safe(s, PL_bufend, UTF))
10546             Perl_croak(aTHX_ "Use of bare << to mean <<\"\" is forbidden");
10547
10548         peek = s;
10549
10550         while (isWORDCHAR_lazy_if_safe(peek, PL_bufend, UTF)) {
10551             peek += UTF ? UTF8SKIP(peek) : 1;
10552         }
10553
10554         len = (peek - s >= e - d) ? (e - d) : (peek - s);
10555         Copy(s, d, len, char);
10556         s += len;
10557         d += len;
10558     }
10559
10560     if (d >= PL_tokenbuf + sizeof PL_tokenbuf - 1)
10561         Perl_croak(aTHX_ "Delimiter for here document is too long");
10562
10563     *d++ = '\n';
10564     *d = '\0';
10565     len = d - PL_tokenbuf;
10566
10567 #ifndef PERL_STRICT_CR
10568     d = (char *) memchr(s, '\r', PL_bufend - s);
10569     if (d) {
10570         char * const olds = s;
10571         s = d;
10572         while (s < PL_bufend) {
10573             if (*s == '\r') {
10574                 *d++ = '\n';
10575                 if (*++s == '\n')
10576                     s++;
10577             }
10578             else if (*s == '\n' && s[1] == '\r') {      /* \015\013 on a mac? */
10579                 *d++ = *s++;
10580                 s++;
10581             }
10582             else
10583                 *d++ = *s++;
10584         }
10585         *d = '\0';
10586         PL_bufend = d;
10587         SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10588         s = olds;
10589     }
10590 #endif
10591
10592     tmpstr = newSV_type(SVt_PVIV);
10593     SvGROW(tmpstr, 80);
10594     if (term == '\'') {
10595         op_type = OP_CONST;
10596         SvIV_set(tmpstr, -1);
10597     }
10598     else if (term == '`') {
10599         op_type = OP_BACKTICK;
10600         SvIV_set(tmpstr, '\\');
10601     }
10602
10603     PL_multi_start = origline + 1 + PL_parser->herelines;
10604     PL_multi_open = PL_multi_close = '<';
10605
10606     /* inside a string eval or quote-like operator */
10607     if (!infile || PL_lex_inwhat) {
10608         SV *linestr;
10609         char *bufend;
10610         char * const olds = s;
10611         PERL_CONTEXT * const cx = CX_CUR();
10612         /* These two fields are not set until an inner lexing scope is
10613            entered.  But we need them set here. */
10614         shared->ls_bufptr  = s;
10615         shared->ls_linestr = PL_linestr;
10616
10617         if (PL_lex_inwhat) {
10618             /* Look for a newline.  If the current buffer does not have one,
10619              peek into the line buffer of the parent lexing scope, going
10620              up as many levels as necessary to find one with a newline
10621              after bufptr.
10622             */
10623             while (!(s = (char *)memchr(
10624                                 (void *)shared->ls_bufptr, '\n',
10625                                 SvEND(shared->ls_linestr)-shared->ls_bufptr
10626                 )))
10627             {
10628                 shared = shared->ls_prev;
10629                 /* shared is only null if we have gone beyond the outermost
10630                    lexing scope.  In a file, we will have broken out of the
10631                    loop in the previous iteration.  In an eval, the string buf-
10632                    fer ends with "\n;", so the while condition above will have
10633                    evaluated to false.  So shared can never be null.  Or so you
10634                    might think.  Odd syntax errors like s;@{<<; can gobble up
10635                    the implicit semicolon at the end of a flie, causing the
10636                    file handle to be closed even when we are not in a string
10637                    eval.  So shared may be null in that case.
10638                    (Closing '>>}' here to balance the earlier open brace for
10639                    editors that look for matched pairs.) */
10640                 if (UNLIKELY(!shared))
10641                     goto interminable;
10642                 /* A LEXSHARED struct with a null ls_prev pointer is the outer-
10643                    most lexing scope.  In a file, shared->ls_linestr at that
10644                    level is just one line, so there is no body to steal. */
10645                 if (infile && !shared->ls_prev) {
10646                     s = olds;
10647                     goto streaming;
10648                 }
10649             }
10650         }
10651         else {  /* eval or we've already hit EOF */
10652             s = (char*)memchr((void*)s, '\n', PL_bufend - s);
10653             if (!s)
10654                 goto interminable;
10655         }
10656
10657         linestr = shared->ls_linestr;
10658         bufend = SvEND(linestr);
10659         d = s;
10660         if (indented) {
10661             char *myolds = s;
10662
10663             while (s < bufend - len + 1) {
10664                 if (*s++ == '\n')
10665                     ++PL_parser->herelines;
10666
10667                 if (memEQ(s, PL_tokenbuf + 1, len - 1)) {
10668                     char *backup = s;
10669                     indent_len = 0;
10670
10671                     /* Only valid if it's preceded by whitespace only */
10672                     while (backup != myolds && --backup >= myolds) {
10673                         if (! SPACE_OR_TAB(*backup)) {
10674                             break;
10675                         }
10676                         indent_len++;
10677                     }
10678
10679                     /* No whitespace or all! */
10680                     if (backup == s || *backup == '\n') {
10681                         Newx(indent, indent_len + 1, char);
10682                         memcpy(indent, backup + 1, indent_len);
10683                         indent[indent_len] = 0;
10684                         s--; /* before our delimiter */
10685                         PL_parser->herelines--; /* this line doesn't count */
10686                         break;
10687                     }
10688                 }
10689             }
10690         }
10691         else {
10692             while (s < bufend - len + 1
10693                    && memNE(s,PL_tokenbuf,len) )
10694             {
10695                 if (*s++ == '\n')
10696                     ++PL_parser->herelines;
10697             }
10698         }
10699
10700         if (s >= bufend - len + 1) {
10701             goto interminable;
10702         }
10703
10704         sv_setpvn(tmpstr,d+1,s-d);
10705         s += len - 1;
10706         /* the preceding stmt passes a newline */
10707         PL_parser->herelines++;
10708
10709         /* s now points to the newline after the heredoc terminator.
10710            d points to the newline before the body of the heredoc.
10711          */
10712
10713         /* We are going to modify linestr in place here, so set
10714            aside copies of the string if necessary for re-evals or
10715            (caller $n)[6]. */
10716         /* See the Paranoia note in case LEX_INTERPEND in yylex, for why we
10717            check shared->re_eval_str. */
10718         if (shared->re_eval_start || shared->re_eval_str) {
10719             /* Set aside the rest of the regexp */
10720             if (!shared->re_eval_str)
10721                 shared->re_eval_str =
10722                        newSVpvn(shared->re_eval_start,
10723                                 bufend - shared->re_eval_start);
10724             shared->re_eval_start -= s-d;
10725         }
10726
10727         if (cxstack_ix >= 0
10728             && CxTYPE(cx) == CXt_EVAL
10729             && CxOLD_OP_TYPE(cx) == OP_ENTEREVAL
10730             && cx->blk_eval.cur_text == linestr)
10731         {
10732             cx->blk_eval.cur_text = newSVsv(linestr);
10733             cx->blk_u16 |= 0x40; /* indicate cur_text is ref counted */
10734         }
10735
10736         /* Copy everything from s onwards back to d. */
10737         Move(s,d,bufend-s + 1,char);
10738         SvCUR_set(linestr, SvCUR(linestr) - (s-d));
10739         /* Setting PL_bufend only applies when we have not dug deeper
10740            into other scopes, because sublex_done sets PL_bufend to
10741            SvEND(PL_linestr). */
10742         if (shared == PL_parser->lex_shared)
10743             PL_bufend = SvEND(linestr);
10744         s = olds;
10745     }
10746     else {
10747         SV *linestr_save;
10748         char *oldbufptr_save;
10749         char *oldoldbufptr_save;
10750       streaming:
10751         SvPVCLEAR(tmpstr);   /* avoid "uninitialized" warning */
10752         term = PL_tokenbuf[1];
10753         len--;
10754         linestr_save = PL_linestr; /* must restore this afterwards */
10755         d = s;                   /* and this */
10756         oldbufptr_save = PL_oldbufptr;
10757         oldoldbufptr_save = PL_oldoldbufptr;
10758         PL_linestr = newSVpvs("");
10759         PL_bufend = SvPVX(PL_linestr);
10760
10761         while (1) {
10762             PL_bufptr = PL_bufend;
10763             CopLINE_set(PL_curcop,
10764                         origline + 1 + PL_parser->herelines);
10765
10766             if (   !lex_next_chunk(LEX_NO_TERM)
10767                 && (!SvCUR(tmpstr) || SvEND(tmpstr)[-1] != '\n'))
10768             {
10769                 /* Simply freeing linestr_save might seem simpler here, as it
10770                    does not matter what PL_linestr points to, since we are
10771                    about to croak; but in a quote-like op, linestr_save
10772                    will have been prospectively freed already, via
10773                    SAVEFREESV(PL_linestr) in sublex_push, so it’s easier to
10774                    restore PL_linestr. */
10775                 SvREFCNT_dec_NN(PL_linestr);
10776                 PL_linestr = linestr_save;
10777                 PL_oldbufptr = oldbufptr_save;
10778                 PL_oldoldbufptr = oldoldbufptr_save;
10779                 goto interminable;
10780             }
10781
10782             CopLINE_set(PL_curcop, origline);
10783
10784             if (!SvCUR(PL_linestr) || PL_bufend[-1] != '\n') {
10785                 s = lex_grow_linestr(SvLEN(PL_linestr) + 3);
10786                 /* ^That should be enough to avoid this needing to grow:  */
10787                 sv_catpvs(PL_linestr, "\n\0");
10788                 assert(s == SvPVX(PL_linestr));
10789                 PL_bufend = SvEND(PL_linestr);
10790             }
10791
10792             s = PL_bufptr;
10793             PL_parser->herelines++;
10794             PL_last_lop = PL_last_uni = NULL;
10795
10796 #ifndef PERL_STRICT_CR
10797             if (PL_bufend - PL_linestart >= 2) {
10798                 if (   (PL_bufend[-2] == '\r' && PL_bufend[-1] == '\n')
10799                     || (PL_bufend[-2] == '\n' && PL_bufend[-1] == '\r'))
10800                 {
10801                     PL_bufend[-2] = '\n';
10802                     PL_bufend--;
10803                     SvCUR_set(PL_linestr, PL_bufend - SvPVX_const(PL_linestr));
10804                 }
10805                 else if (PL_bufend[-1] == '\r')
10806                     PL_bufend[-1] = '\n';
10807             }
10808             else if (PL_bufend - PL_linestart == 1 && PL_bufend[-1] == '\r')
10809                 PL_bufend[-1] = '\n';
10810 #endif
10811
10812             if (indented && (PL_bufend-s) >= len) {
10813                 char * found = ninstr(s, PL_bufend, (PL_tokenbuf + 1), (PL_tokenbuf +1 + len));
10814
10815                 if (found) {
10816                     char *backup = found;
10817                     indent_len = 0;
10818
10819                     /* Only valid if it's preceded by whitespace only */
10820                     while (backup != s && --backup >= s) {
10821                         if (! SPACE_OR_TAB(*backup)) {
10822                             break;
10823                         }
10824                         indent_len++;
10825                     }
10826
10827                     /* All whitespace or none! */
10828                     if (backup == found || SPACE_OR_TAB(*backup)) {
10829                         Newx(indent, indent_len + 1, char);
10830                         memcpy(indent, backup, indent_len);
10831                         indent[indent_len] = 0;
10832                         SvREFCNT_dec(PL_linestr);
10833                         PL_linestr = linestr_save;
10834                         PL_linestart = SvPVX(linestr_save);
10835                         PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10836                         PL_oldbufptr = oldbufptr_save;
10837                         PL_oldoldbufptr = oldoldbufptr_save;
10838                         s = d;
10839                         break;
10840                     }
10841                 }
10842
10843                 /* Didn't find it */
10844                 sv_catsv(tmpstr,PL_linestr);
10845             }
10846             else {
10847                 if (*s == term && PL_bufend-s >= len
10848                     && memEQ(s,PL_tokenbuf + 1,len))
10849                 {
10850                     SvREFCNT_dec(PL_linestr);
10851                     PL_linestr = linestr_save;
10852                     PL_linestart = SvPVX(linestr_save);
10853                     PL_bufend = SvPVX(PL_linestr) + SvCUR(PL_linestr);
10854                     PL_oldbufptr = oldbufptr_save;
10855                     PL_oldoldbufptr = oldoldbufptr_save;
10856                     s = d;
10857                     break;
10858                 }
10859                 else {
10860                     sv_catsv(tmpstr,PL_linestr);
10861                 }
10862             }
10863         } /* while (1) */
10864     }
10865
10866     PL_multi_end = origline + PL_parser->herelines;
10867
10868     if (indented && indent) {
10869         STRLEN linecount = 1;
10870         STRLEN herelen = SvCUR(tmpstr);
10871         char *ss = SvPVX(tmpstr);
10872         char *se = ss + herelen;
10873         SV *newstr = newSV(herelen+1);
10874         SvPOK_on(newstr);
10875
10876         /* Trim leading whitespace */
10877         while (ss < se) {
10878             /* newline only? Copy and move on */
10879             if (*ss == '\n') {
10880                 sv_catpvs(newstr,"\n");
10881                 ss++;
10882                 linecount++;
10883
10884             /* Found our indentation? Strip it */
10885             }
10886             else if (se - ss >= indent_len
10887                        && memEQ(ss, indent, indent_len))
10888             {
10889                 STRLEN le = 0;
10890                 ss += indent_len;
10891
10892                 while ((ss + le) < se && *(ss + le) != '\n')
10893                     le++;
10894
10895                 sv_catpvn(newstr, ss, le);
10896                 ss += le;
10897
10898             /* Line doesn't begin with our indentation? Croak */
10899             }
10900             else {
10901                 Safefree(indent);
10902                 Perl_croak(aTHX_
10903                     "Indentation on line %d of here-doc doesn't match delimiter",
10904                     (int)linecount
10905                 );
10906             }
10907         } /* while */
10908
10909         /* avoid sv_setsv() as we dont wan't to COW here */
10910         sv_setpvn(tmpstr,SvPVX(newstr),SvCUR(newstr));
10911         Safefree(indent);
10912         SvREFCNT_dec_NN(newstr);
10913     }
10914
10915     if (SvCUR(tmpstr) + 5 < SvLEN(tmpstr)) {
10916         SvPV_shrink_to_cur(tmpstr);
10917     }
10918
10919     if (!IN_BYTES) {
10920         if (UTF && is_utf8_string((U8*)SvPVX_const(tmpstr), SvCUR(tmpstr)))
10921             SvUTF8_on(tmpstr);
10922     }
10923
10924     PL_lex_stuff = tmpstr;
10925     pl_yylval.ival = op_type;
10926     return s;
10927
10928   interminable:
10929     if (indent)
10930         Safefree(indent);
10931     SvREFCNT_dec(tmpstr);
10932     CopLINE_set(PL_curcop, origline);
10933     missingterm(PL_tokenbuf + 1, sizeof(PL_tokenbuf) - 1);
10934 }
10935
10936
10937 /* scan_inputsymbol
10938    takes: position of first '<' in input buffer
10939    returns: position of first char following the matching '>' in
10940             input buffer
10941    side-effects: pl_yylval and lex_op are set.
10942
10943    This code handles:
10944
10945    <>           read from ARGV
10946    <<>>         read from ARGV without magic open
10947    <FH>         read from filehandle
10948    <pkg::FH>    read from package qualified filehandle
10949    <pkg'FH>     read from package qualified filehandle
10950    <$fh>        read from filehandle in $fh
10951    <*.h>        filename glob
10952
10953 */
10954
10955 STATIC char *
10956 S_scan_inputsymbol(pTHX_ char *start)
10957 {
10958     char *s = start;            /* current position in buffer */
10959     char *end;
10960     I32 len;
10961     bool nomagicopen = FALSE;
10962     char *d = PL_tokenbuf;                                      /* start of temp holding space */
10963     const char * const e = PL_tokenbuf + sizeof PL_tokenbuf;    /* end of temp holding space */
10964
10965     PERL_ARGS_ASSERT_SCAN_INPUTSYMBOL;
10966
10967     end = (char *) memchr(s, '\n', PL_bufend - s);
10968     if (!end)
10969         end = PL_bufend;
10970     if (s[1] == '<' && s[2] == '>' && s[3] == '>') {
10971         nomagicopen = TRUE;
10972         *d = '\0';
10973         len = 0;
10974         s += 3;
10975     }
10976     else
10977         s = delimcpy(d, e, s + 1, end, '>', &len);      /* extract until > */
10978
10979     /* die if we didn't have space for the contents of the <>,
10980        or if it didn't end, or if we see a newline
10981     */
10982
10983     if (len >= (I32)sizeof PL_tokenbuf)
10984         Perl_croak(aTHX_ "Excessively long <> operator");
10985     if (s >= end)
10986         Perl_croak(aTHX_ "Unterminated <> operator");
10987
10988     s++;
10989
10990     /* check for <$fh>
10991        Remember, only scalar variables are interpreted as filehandles by
10992        this code.  Anything more complex (e.g., <$fh{$num}>) will be
10993        treated as a glob() call.
10994        This code makes use of the fact that except for the $ at the front,
10995        a scalar variable and a filehandle look the same.
10996     */
10997     if (*d == '$' && d[1]) d++;
10998
10999     /* allow <Pkg'VALUE> or <Pkg::VALUE> */
11000     while (isWORDCHAR_lazy_if_safe(d, e, UTF) || *d == '\'' || *d == ':') {
11001         d += UTF ? UTF8SKIP(d) : 1;
11002     }
11003
11004     /* If we've tried to read what we allow filehandles to look like, and
11005        there's still text left, then it must be a glob() and not a getline.
11006        Use scan_str to pull out the stuff between the <> and treat it
11007        as nothing more than a string.
11008     */
11009
11010     if (d - PL_tokenbuf != len) {
11011         pl_yylval.ival = OP_GLOB;
11012         s = scan_str(start,FALSE,FALSE,FALSE,NULL);
11013         if (!s)
11014            Perl_croak(aTHX_ "Glob not terminated");
11015         return s;
11016     }
11017     else {
11018         bool readline_overriden = FALSE;
11019         GV *gv_readline;
11020         /* we're in a filehandle read situation */
11021         d = PL_tokenbuf;
11022
11023         /* turn <> into <ARGV> */
11024         if (!len)
11025             Copy("ARGV",d,5,char);
11026
11027         /* Check whether readline() is overriden */
11028         if ((gv_readline = gv_override("readline",8)))
11029             readline_overriden = TRUE;
11030
11031         /* if <$fh>, create the ops to turn the variable into a
11032            filehandle
11033         */
11034         if (*d == '$') {
11035             /* try to find it in the pad for this block, otherwise find
11036                add symbol table ops
11037             */
11038             const PADOFFSET tmp = pad_findmy_pvn(d, len, 0);
11039             if (tmp != NOT_IN_PAD) {
11040                 if (PAD_COMPNAME_FLAGS_isOUR(tmp)) {
11041                     HV * const stash = PAD_COMPNAME_OURSTASH(tmp);
11042                     HEK * const stashname = HvNAME_HEK(stash);
11043                     SV * const sym = sv_2mortal(newSVhek(stashname));
11044                     sv_catpvs(sym, "::");
11045                     sv_catpv(sym, d+1);
11046                     d = SvPVX(sym);
11047                     goto intro_sym;
11048                 }
11049                 else {
11050                     OP * const o = newOP(OP_PADSV, 0);
11051                     o->op_targ = tmp;
11052                     PL_lex_op = readline_overriden
11053                         ? newUNOP(OP_ENTERSUB, OPf_STACKED,
11054                                 op_append_elem(OP_LIST, o,
11055                                     newCVREF(0, newGVOP(OP_GV,0,gv_readline))))
11056                         : newUNOP(OP_READLINE, 0, o);
11057                 }
11058             }
11059             else {
11060                 GV *gv;
11061                 ++d;
11062               intro_sym:
11063                 gv = gv_fetchpv(d,
11064                                 GV_ADDMULTI | ( UTF ? SVf_UTF8 : 0 ),
11065                                 SVt_PV);
11066                 PL_lex_op = readline_overriden
11067                     ? newUNOP(OP_ENTERSUB, OPf_STACKED,
11068                             op_append_elem(OP_LIST,
11069                                 newUNOP(OP_RV2SV, 0, newGVOP(OP_GV, 0, gv)),
11070                                 newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
11071                     : newUNOP(OP_READLINE, 0,
11072                             newUNOP(OP_RV2SV, 0,
11073                                 newGVOP(OP_GV, 0, gv)));
11074             }
11075             /* we created the ops in PL_lex_op, so make pl_yylval.ival a null op */
11076             pl_yylval.ival = OP_NULL;
11077         }
11078
11079         /* If it's none of the above, it must be a literal filehandle
11080            (<Foo::BAR> or <FOO>) so build a simple readline OP */
11081         else {
11082             GV * const gv = gv_fetchpv(d, GV_ADD | ( UTF ? SVf_UTF8 : 0 ), SVt_PVIO);
11083             PL_lex_op = readline_overriden
11084                 ? newUNOP(OP_ENTERSUB, OPf_STACKED,
11085                         op_append_elem(OP_LIST,
11086                             newGVOP(OP_GV, 0, gv),
11087                             newCVREF(0, newGVOP(OP_GV, 0, gv_readline))))
11088                 : newUNOP(OP_READLINE, nomagicopen ? OPf_SPECIAL : 0, newGVOP(OP_GV, 0, gv));
11089             pl_yylval.ival = OP_NULL;
11090         }
11091     }
11092
11093     return s;
11094 }
11095
11096
11097 /* scan_str
11098    takes:
11099         start                   position in buffer
11100         keep_bracketed_quoted   preserve \ quoting of embedded delimiters, but
11101                                 only if they are of the open/close form
11102         keep_delims             preserve the delimiters around the string
11103         re_reparse              compiling a run-time /(?{})/:
11104                                    collapse // to /,  and skip encoding src
11105         delimp                  if non-null, this is set to the position of
11106                                 the closing delimiter, or just after it if
11107                                 the closing and opening delimiters differ
11108                                 (i.e., the opening delimiter of a substitu-
11109                                 tion replacement)
11110    returns: position to continue reading from buffer
11111    side-effects: multi_start, multi_close, lex_repl or lex_stuff, and
11112         updates the read buffer.
11113
11114    This subroutine pulls a string out of the input.  It is called for:
11115         q               single quotes           q(literal text)
11116         '               single quotes           'literal text'
11117         qq              double quotes           qq(interpolate $here please)
11118         "               double quotes           "interpolate $here please"
11119         qx              backticks               qx(/bin/ls -l)
11120         `               backticks               `/bin/ls -l`
11121         qw              quote words             @EXPORT_OK = qw( func() $spam )
11122         m//             regexp match            m/this/
11123         s///            regexp substitute       s/this/that/
11124         tr///           string transliterate    tr/this/that/
11125         y///            string transliterate    y/this/that/
11126         ($*@)           sub prototypes          sub foo ($)
11127         (stuff)         sub attr parameters     sub foo : attr(stuff)
11128         <>              readline or globs       <FOO>, <>, <$fh>, or <*.c>
11129
11130    In most of these cases (all but <>, patterns and transliterate)
11131    yylex() calls scan_str().  m// makes yylex() call scan_pat() which
11132    calls scan_str().  s/// makes yylex() call scan_subst() which calls
11133    scan_str().  tr/// and y/// make yylex() call scan_trans() which
11134    calls scan_str().
11135
11136    It skips whitespace before the string starts, and treats the first
11137    character as the delimiter.  If the delimiter is one of ([{< then
11138    the corresponding "close" character )]}> is used as the closing
11139    delimiter.  It allows quoting of delimiters, and if the string has
11140    balanced delimiters ([{<>}]) it allows nesting.
11141
11142    On success, the SV with the resulting string is put into lex_stuff or,
11143    if that is already non-NULL, into lex_repl. The second case occurs only
11144    when parsing the RHS of the special constructs s/// and tr/// (y///).
11145    For convenience, the terminating delimiter character is stuffed into
11146    SvIVX of the SV.
11147 */
11148
11149 char *
11150 Perl_scan_str(pTHX_ char *start, int keep_bracketed_quoted, int keep_delims, int re_reparse,
11151                  char **delimp
11152     )
11153 {
11154     SV *sv;                     /* scalar value: string */
11155     const char *tmps;           /* temp string, used for delimiter matching */
11156     char *s = start;            /* current position in the buffer */
11157     char term;                  /* terminating character */
11158     char *to;                   /* current position in the sv's data */
11159     I32 brackets = 1;           /* bracket nesting level */
11160     bool d_is_utf8 = FALSE;     /* is there any utf8 content? */
11161     IV termcode;                /* terminating char. code */
11162     U8 termstr[UTF8_MAXBYTES+1]; /* terminating string */
11163     STRLEN termlen;             /* length of terminating string */
11164     line_t herelines;
11165
11166     /* The delimiters that have a mirror-image closing one */
11167     const char * opening_delims = "([{<";
11168     const char * closing_delims = ")]}>";
11169
11170     /* The only non-UTF character that isn't a stand alone grapheme is
11171      * white-space, hence can't be a delimiter. */
11172     const char * non_grapheme_msg = "Use of unassigned code point or"
11173                                     " non-standalone grapheme for a delimiter"
11174                                     " is not allowed";
11175     PERL_ARGS_ASSERT_SCAN_STR;
11176
11177     /* skip space before the delimiter */
11178     if (isSPACE(*s)) {
11179         s = skipspace(s);
11180     }
11181
11182     /* mark where we are, in case we need to report errors */
11183     CLINE;
11184
11185     /* after skipping whitespace, the next character is the terminator */
11186     term = *s;
11187     if (!UTF || UTF8_IS_INVARIANT(term)) {
11188         termcode = termstr[0] = term;
11189         termlen = 1;
11190     }
11191     else {
11192         termcode = utf8_to_uvchr_buf((U8*)s, (U8*)PL_bufend, &termlen);
11193         if (UTF && UNLIKELY(! is_grapheme((U8 *) start,
11194                                            (U8 *) s,
11195                                            (U8 *) PL_bufend,
11196                                                   termcode)))
11197         {
11198             yyerror(non_grapheme_msg);
11199         }
11200
11201         Copy(s, termstr, termlen, U8);
11202     }
11203
11204     /* mark where we are */
11205     PL_multi_start = CopLINE(PL_curcop);
11206     PL_multi_open = termcode;
11207     herelines = PL_parser->herelines;
11208
11209     /* If the delimiter has a mirror-image closing one, get it */
11210     if (term && (tmps = strchr(opening_delims, term))) {
11211         termcode = termstr[0] = term = closing_delims[tmps - opening_delims];
11212     }
11213
11214     PL_multi_close = termcode;
11215
11216     if (PL_multi_open == PL_multi_close) {
11217         keep_bracketed_quoted = FALSE;
11218     }
11219
11220     /* create a new SV to hold the contents.  79 is the SV's initial length.
11221        What a random number. */
11222     sv = newSV_type(SVt_PVIV);
11223     SvGROW(sv, 80);
11224     SvIV_set(sv, termcode);
11225     (void)SvPOK_only(sv);               /* validate pointer */
11226
11227     /* move past delimiter and try to read a complete string */
11228     if (keep_delims)
11229         sv_catpvn(sv, s, termlen);
11230     s += termlen;
11231     for (;;) {
11232         /* extend sv if need be */
11233         SvGROW(sv, SvCUR(sv) + (PL_bufend - s) + 1);
11234         /* set 'to' to the next character in the sv's string */
11235         to = SvPVX(sv)+SvCUR(sv);
11236
11237         /* if open delimiter is the close delimiter read unbridle */
11238         if (PL_multi_open == PL_multi_close) {
11239             for (; s < PL_bufend; s++,to++) {
11240                 /* embedded newlines increment the current line number */
11241                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11242                     COPLINE_INC_WITH_HERELINES;
11243                 /* handle quoted delimiters */
11244                 if (*s == '\\' && s+1 < PL_bufend && term != '\\') {
11245                     if (!keep_bracketed_quoted
11246                         && (s[1] == term
11247                             || (re_reparse && s[1] == '\\'))
11248                     )
11249                         s++;
11250                     else /* any other quotes are simply copied straight through */
11251                         *to++ = *s++;
11252                 }
11253                 /* terminate when run out of buffer (the for() condition), or
11254                    have found the terminator */
11255                 else if (*s == term) {  /* First byte of terminator matches */
11256                     if (termlen == 1)   /* If is the only byte, are done */
11257                         break;
11258
11259                     /* If the remainder of the terminator matches, also are
11260                      * done, after checking that is a separate grapheme */
11261                     if (   s + termlen <= PL_bufend
11262                         && memEQ(s + 1, (char*)termstr + 1, termlen - 1))
11263                     {
11264                         if (   UTF
11265                             && UNLIKELY(! is_grapheme((U8 *) start,
11266                                                        (U8 *) s,
11267                                                        (U8 *) PL_bufend,
11268                                                               termcode)))
11269                         {
11270                             yyerror(non_grapheme_msg);
11271                         }
11272                         break;
11273                     }
11274                 }
11275                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF) {
11276                     d_is_utf8 = TRUE;
11277                 }
11278
11279                 *to = *s;
11280             }
11281         }
11282
11283         /* if the terminator isn't the same as the start character (e.g.,
11284            matched brackets), we have to allow more in the quoting, and
11285            be prepared for nested brackets.
11286         */
11287         else {
11288             /* read until we run out of string, or we find the terminator */
11289             for (; s < PL_bufend; s++,to++) {
11290                 /* embedded newlines increment the line count */
11291                 if (*s == '\n' && !PL_rsfp && !PL_parser->filtered)
11292                     COPLINE_INC_WITH_HERELINES;
11293                 /* backslashes can escape the open or closing characters */
11294                 if (*s == '\\' && s+1 < PL_bufend) {
11295                     if (!keep_bracketed_quoted
11296                        && ( ((UV)s[1] == PL_multi_open)
11297                          || ((UV)s[1] == PL_multi_close) ))
11298                     {
11299                         s++;
11300                     }
11301                     else
11302                         *to++ = *s++;
11303                 }
11304                 /* allow nested opens and closes */
11305                 else if ((UV)*s == PL_multi_close && --brackets <= 0)
11306                     break;
11307                 else if ((UV)*s == PL_multi_open)
11308                     brackets++;
11309                 else if (!d_is_utf8 && !UTF8_IS_INVARIANT((U8)*s) && UTF)
11310                     d_is_utf8 = TRUE;
11311                 *to = *s;
11312             }
11313         }
11314         /* terminate the copied string and update the sv's end-of-string */
11315         *to = '\0';
11316         SvCUR_set(sv, to - SvPVX_const(sv));
11317
11318         /*
11319          * this next chunk reads more into the buffer if we're not done yet
11320          */
11321
11322         if (s < PL_bufend)
11323             break;              /* handle case where we are done yet :-) */
11324
11325 #ifndef PERL_STRICT_CR
11326         if (to - SvPVX_const(sv) >= 2) {
11327             if (   (to[-2] == '\r' && to[-1] == '\n')
11328                 || (to[-2] == '\n' && to[-1] == '\r'))
11329             {
11330                 to[-2] = '\n';
11331                 to--;
11332                 SvCUR_set(sv, to - SvPVX_const(sv));
11333             }
11334             else if (to[-1] == '\r')
11335                 to[-1] = '\n';
11336         }
11337         else if (to - SvPVX_const(sv) == 1 && to[-1] == '\r')
11338             to[-1] = '\n';
11339 #endif
11340
11341         /* if we're out of file, or a read fails, bail and reset the current
11342            line marker so we can report where the unterminated string began
11343         */
11344         COPLINE_INC_WITH_HERELINES;
11345         PL_bufptr = PL_bufend;
11346         if (!lex_next_chunk(0)) {
11347             sv_free(sv);
11348             CopLINE_set(PL_curcop, (line_t)PL_multi_start);
11349             return NULL;
11350         }
11351         s = start = PL_bufptr;
11352     }
11353
11354     /* at this point, we have successfully read the delimited string */
11355
11356     if (keep_delims)
11357             sv_catpvn(sv, s, termlen);
11358     s += termlen;
11359
11360     if (d_is_utf8)
11361         SvUTF8_on(sv);
11362
11363     PL_multi_end = CopLINE(PL_curcop);
11364     CopLINE_set(PL_curcop, PL_multi_start);
11365     PL_parser->herelines = herelines;
11366
11367     /* if we allocated too much space, give some back */
11368     if (SvCUR(sv) + 5 < SvLEN(sv)) {
11369         SvLEN_set(sv, SvCUR(sv) + 1);
11370         SvPV_shrink_to_cur(sv);
11371     }
11372
11373     /* decide whether this is the first or second quoted string we've read
11374        for this op
11375     */
11376
11377     if (PL_lex_stuff)
11378         PL_parser->lex_sub_repl = sv;
11379     else
11380         PL_lex_stuff = sv;
11381     if (delimp) *delimp = PL_multi_open == PL_multi_close ? s-termlen : s;
11382     return s;
11383 }
11384
11385 /*
11386   scan_num
11387   takes: pointer to position in buffer
11388   returns: pointer to new position in buffer
11389   side-effects: builds ops for the constant in pl_yylval.op
11390
11391   Read a number in any of the formats that Perl accepts:
11392
11393   \d(_?\d)*(\.(\d(_?\d)*)?)?[Ee][\+\-]?(\d(_?\d)*)      12 12.34 12.
11394   \.\d(_?\d)*[Ee][\+\-]?(\d(_?\d)*)                     .34
11395   0b[01](_?[01])*                                       binary integers
11396   0o?[0-7](_?[0-7])*                                    octal integers
11397   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*                         hexadecimal integers
11398   0x[0-9A-Fa-f](_?[0-9A-Fa-f])*(?:\.\d*)?p[+-]?[0-9]+   hexadecimal floats
11399
11400   Like most scan_ routines, it uses the PL_tokenbuf buffer to hold the
11401   thing it reads.
11402
11403   If it reads a number without a decimal point or an exponent, it will
11404   try converting the number to an integer and see if it can do so
11405   without loss of precision.
11406 */
11407
11408 char *
11409 Perl_scan_num(pTHX_ const char *start, YYSTYPE* lvalp)
11410 {
11411     const char *s = start;      /* current position in buffer */
11412     char *d;                    /* destination in temp buffer */
11413     char *e;                    /* end of temp buffer */
11414     NV nv;                              /* number read, as a double */
11415     SV *sv = NULL;                      /* place to put the converted number */
11416     bool floatit;                       /* boolean: int or float? */
11417     const char *lastub = NULL;          /* position of last underbar */
11418     static const char* const number_too_long = "Number too long";
11419     bool warned_about_underscore = 0;
11420     I32 shift; /* shift per digit for hex/oct/bin, hoisted here for fp */
11421 #define WARN_ABOUT_UNDERSCORE() \
11422         do { \
11423             if (!warned_about_underscore) { \
11424                 warned_about_underscore = 1; \
11425                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), \
11426                                "Misplaced _ in number"); \
11427             } \
11428         } while(0)
11429     /* Hexadecimal floating point.
11430      *
11431      * In many places (where we have quads and NV is IEEE 754 double)
11432      * we can fit the mantissa bits of a NV into an unsigned quad.
11433      * (Note that UVs might not be quads even when we have quads.)
11434      * This will not work everywhere, though (either no quads, or
11435      * using long doubles), in which case we have to resort to NV,
11436      * which will probably mean horrible loss of precision due to
11437      * multiple fp operations. */
11438     bool hexfp = FALSE;
11439     int total_bits = 0;
11440     int significant_bits = 0;
11441 #if NVSIZE == 8 && defined(HAS_QUAD) && defined(Uquad_t)
11442 #  define HEXFP_UQUAD
11443     Uquad_t hexfp_uquad = 0;
11444     int hexfp_frac_bits = 0;
11445 #else
11446 #  define HEXFP_NV
11447     NV hexfp_nv = 0.0;
11448 #endif
11449     NV hexfp_mult = 1.0;
11450     UV high_non_zero = 0; /* highest digit */
11451     int non_zero_integer_digits = 0;
11452     bool new_octal = FALSE;     /* octal with "0o" prefix */
11453
11454     PERL_ARGS_ASSERT_SCAN_NUM;
11455
11456     /* We use the first character to decide what type of number this is */
11457
11458     switch (*s) {
11459     default:
11460         Perl_croak(aTHX_ "panic: scan_num, *s=%d", *s);
11461
11462     /* if it starts with a 0, it could be an octal number, a decimal in
11463        0.13 disguise, or a hexadecimal number, or a binary number. */
11464     case '0':
11465         {
11466           /* variables:
11467              u          holds the "number so far"
11468              overflowed was the number more than we can hold?
11469
11470              Shift is used when we add a digit.  It also serves as an "are
11471              we in octal/hex/binary?" indicator to disallow hex characters
11472              when in octal mode.
11473            */
11474             NV n = 0.0;
11475             UV u = 0;
11476             bool overflowed = FALSE;
11477             bool just_zero  = TRUE;     /* just plain 0 or binary number? */
11478             bool has_digs = FALSE;
11479             static const NV nvshift[5] = { 1.0, 2.0, 4.0, 8.0, 16.0 };
11480             static const char* const bases[5] =
11481               { "", "binary", "", "octal", "hexadecimal" };
11482             static const char* const Bases[5] =
11483               { "", "Binary", "", "Octal", "Hexadecimal" };
11484             static const char* const maxima[5] =
11485               { "",
11486                 "0b11111111111111111111111111111111",
11487                 "",
11488                 "037777777777",
11489                 "0xffffffff" };
11490
11491             /* check for hex */
11492             if (isALPHA_FOLD_EQ(s[1], 'x')) {
11493                 shift = 4;
11494                 s += 2;
11495                 just_zero = FALSE;
11496             } else if (isALPHA_FOLD_EQ(s[1], 'b')) {
11497                 shift = 1;
11498                 s += 2;
11499                 just_zero = FALSE;
11500             }
11501             /* check for a decimal in disguise */
11502             else if (s[1] == '.' || isALPHA_FOLD_EQ(s[1], 'e'))
11503                 goto decimal;
11504             /* so it must be octal */
11505             else {
11506                 shift = 3;
11507                 s++;
11508                 if (isALPHA_FOLD_EQ(*s, 'o')) {
11509                     s++;
11510                     just_zero = FALSE;
11511                     new_octal = TRUE;
11512                 }
11513             }
11514
11515             if (*s == '_') {
11516                 WARN_ABOUT_UNDERSCORE();
11517                lastub = s++;
11518             }
11519
11520             /* read the rest of the number */
11521             for (;;) {
11522                 /* x is used in the overflow test,
11523                    b is the digit we're adding on. */
11524                 UV x, b;
11525
11526                 switch (*s) {
11527
11528                 /* if we don't mention it, we're done */
11529                 default:
11530                     goto out;
11531
11532                 /* _ are ignored -- but warned about if consecutive */
11533                 case '_':
11534                     if (lastub && s == lastub + 1)
11535                         WARN_ABOUT_UNDERSCORE();
11536                     lastub = s++;
11537                     break;
11538
11539                 /* 8 and 9 are not octal */
11540                 case '8': case '9':
11541                     if (shift == 3)
11542                         yyerror(Perl_form(aTHX_ "Illegal octal digit '%c'", *s));
11543                     /* FALLTHROUGH */
11544
11545                 /* octal digits */
11546                 case '2': case '3': case '4':
11547                 case '5': case '6': case '7':
11548                     if (shift == 1)
11549                         yyerror(Perl_form(aTHX_ "Illegal binary digit '%c'", *s));
11550                     /* FALLTHROUGH */
11551
11552                 case '0': case '1':
11553                     b = *s++ & 15;              /* ASCII digit -> value of digit */
11554                     goto digit;
11555
11556                 /* hex digits */
11557                 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
11558                 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
11559                     /* make sure they said 0x */
11560                     if (shift != 4)
11561                         goto out;
11562                     b = (*s++ & 7) + 9;
11563
11564                     /* Prepare to put the digit we have onto the end
11565                        of the number so far.  We check for overflows.
11566                     */
11567
11568                   digit:
11569                     just_zero = FALSE;
11570                     has_digs = TRUE;
11571                     if (!overflowed) {
11572                         assert(shift >= 0);
11573                         x = u << shift; /* make room for the digit */
11574
11575                         total_bits += shift;
11576
11577                         if ((x >> shift) != u
11578                             && !(PL_hints & HINT_NEW_BINARY)) {
11579                             overflowed = TRUE;
11580                             n = (NV) u;
11581                             Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
11582                                              "Integer overflow in %s number",
11583                                              bases[shift]);
11584                         } else
11585                             u = x | b;          /* add the digit to the end */
11586                     }
11587                     if (overflowed) {
11588                         n *= nvshift[shift];
11589                         /* If an NV has not enough bits in its
11590                          * mantissa to represent an UV this summing of
11591                          * small low-order numbers is a waste of time
11592                          * (because the NV cannot preserve the
11593                          * low-order bits anyway): we could just
11594                          * remember when did we overflow and in the
11595                          * end just multiply n by the right
11596                          * amount. */
11597                         n += (NV) b;
11598                     }
11599
11600                     if (high_non_zero == 0 && b > 0)
11601                         high_non_zero = b;
11602
11603                     if (high_non_zero)
11604                         non_zero_integer_digits++;
11605
11606                     /* this could be hexfp, but peek ahead
11607                      * to avoid matching ".." */
11608                     if (UNLIKELY(HEXFP_PEEK(s))) {
11609                         goto out;
11610                     }
11611
11612                     break;
11613                 }
11614             }
11615
11616           /* if we get here, we had success: make a scalar value from
11617              the number.
11618           */
11619           out:
11620
11621             /* final misplaced underbar check */
11622             if (s[-1] == '_')
11623                 WARN_ABOUT_UNDERSCORE();
11624
11625             if (UNLIKELY(HEXFP_PEEK(s))) {
11626                 /* Do sloppy (on the underbars) but quick detection
11627                  * (and value construction) for hexfp, the decimal
11628                  * detection will shortly be more thorough with the
11629                  * underbar checks. */
11630                 const char* h = s;
11631                 significant_bits = non_zero_integer_digits * shift;
11632 #ifdef HEXFP_UQUAD
11633                 hexfp_uquad = u;
11634 #else /* HEXFP_NV */
11635                 hexfp_nv = u;
11636 #endif
11637                 /* Ignore the leading zero bits of
11638                  * the high (first) non-zero digit. */
11639                 if (high_non_zero) {
11640                     if (high_non_zero < 0x8)
11641                         significant_bits--;
11642                     if (high_non_zero < 0x4)
11643                         significant_bits--;
11644                     if (high_non_zero < 0x2)
11645                         significant_bits--;
11646                 }
11647
11648                 if (*h == '.') {
11649 #ifdef HEXFP_NV
11650                     NV nv_mult = 1.0;
11651 #endif
11652                     bool accumulate = TRUE;
11653                     U8 b;
11654                     int lim = 1 << shift;
11655                     for (h++; ((isXDIGIT(*h) && (b = XDIGIT_VALUE(*h)) < lim) ||
11656                                *h == '_'); h++) {
11657                         if (isXDIGIT(*h)) {
11658                             significant_bits += shift;
11659 #ifdef HEXFP_UQUAD
11660                             if (accumulate) {
11661                                 if (significant_bits < NV_MANT_DIG) {
11662                                     /* We are in the long "run" of xdigits,
11663                                      * accumulate the full four bits. */
11664                                     assert(shift >= 0);
11665                                     hexfp_uquad <<= shift;
11666                                     hexfp_uquad |= b;
11667                                     hexfp_frac_bits += shift;
11668                                 } else if (significant_bits - shift < NV_MANT_DIG) {
11669                                     /* We are at a hexdigit either at,
11670                                      * or straddling, the edge of mantissa.
11671                                      * We will try grabbing as many as
11672                                      * possible bits. */
11673                                     int tail =
11674                                       significant_bits - NV_MANT_DIG;
11675                                     if (tail <= 0)
11676                                        tail += shift;
11677                                     assert(tail >= 0);
11678                                     hexfp_uquad <<= tail;
11679                                     assert((shift - tail) >= 0);
11680                                     hexfp_uquad |= b >> (shift - tail);
11681                                     hexfp_frac_bits += tail;
11682
11683                                     /* Ignore the trailing zero bits
11684                                      * of the last non-zero xdigit.
11685                                      *
11686                                      * The assumption here is that if
11687                                      * one has input of e.g. the xdigit
11688                                      * eight (0x8), there is only one
11689                                      * bit being input, not the full
11690                                      * four bits.  Conversely, if one
11691                                      * specifies a zero xdigit, the
11692                                      * assumption is that one really
11693                                      * wants all those bits to be zero. */
11694                                     if (b) {
11695                                         if ((b & 0x1) == 0x0) {
11696                                             significant_bits--;
11697                                             if ((b & 0x2) == 0x0) {
11698                                                 significant_bits--;
11699                                                 if ((b & 0x4) == 0x0) {
11700                                                     significant_bits--;
11701                                                 }
11702                                             }
11703                                         }
11704                                     }
11705
11706                                     accumulate = FALSE;
11707                                 }
11708                             } else {
11709                                 /* Keep skipping the xdigits, and
11710                                  * accumulating the significant bits,
11711                                  * but do not shift the uquad
11712                                  * (which would catastrophically drop
11713                                  * high-order bits) or accumulate the
11714                                  * xdigits anymore. */
11715                             }
11716 #else /* HEXFP_NV */
11717                             if (accumulate) {
11718                                 nv_mult /= nvshift[shift];
11719                                 if (nv_mult > 0.0)
11720                                     hexfp_nv += b * nv_mult;
11721                                 else
11722                                     accumulate = FALSE;
11723                             }
11724 #endif
11725                         }
11726                         if (significant_bits >= NV_MANT_DIG)
11727                             accumulate = FALSE;
11728                     }
11729                 }
11730
11731                 if ((total_bits > 0 || significant_bits > 0) &&
11732                     isALPHA_FOLD_EQ(*h, 'p')) {
11733                     bool negexp = FALSE;
11734                     h++;
11735                     if (*h == '+')
11736                         h++;
11737                     else if (*h == '-') {
11738                         negexp = TRUE;
11739                         h++;
11740                     }
11741                     if (isDIGIT(*h)) {
11742                         I32 hexfp_exp = 0;
11743                         while (isDIGIT(*h) || *h == '_') {
11744                             if (isDIGIT(*h)) {
11745                                 hexfp_exp *= 10;
11746                                 hexfp_exp += *h - '0';
11747 #ifdef NV_MIN_EXP
11748                                 if (negexp
11749                                     && -hexfp_exp < NV_MIN_EXP - 1) {
11750                                     /* NOTE: this means that the exponent
11751                                      * underflow warning happens for
11752                                      * the IEEE 754 subnormals (denormals),
11753                                      * because DBL_MIN_EXP etc are the lowest
11754                                      * possible binary (or, rather, DBL_RADIX-base)
11755                                      * exponent for normals, not subnormals.
11756                                      *
11757                                      * This may or may not be a good thing. */
11758                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11759                                                    "Hexadecimal float: exponent underflow");
11760                                     break;
11761                                 }
11762 #endif
11763 #ifdef NV_MAX_EXP
11764                                 if (!negexp
11765                                     && hexfp_exp > NV_MAX_EXP - 1) {
11766                                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
11767                                                    "Hexadecimal float: exponent overflow");
11768                                     break;
11769                                 }
11770 #endif
11771                             }
11772                             h++;
11773                         }
11774                         if (negexp)
11775                             hexfp_exp = -hexfp_exp;
11776 #ifdef HEXFP_UQUAD
11777                         hexfp_exp -= hexfp_frac_bits;
11778 #endif
11779                         hexfp_mult = Perl_pow(2.0, hexfp_exp);
11780                         hexfp = TRUE;
11781                         goto decimal;
11782                     }
11783                 }
11784             }
11785
11786             if (!just_zero && !has_digs) {
11787                 /* 0x, 0o or 0b with no digits, treat it as an error.
11788                    Originally this backed up the parse before the b or
11789                    x, but that has the potential for silent changes in
11790                    behaviour, like for: "0x.3" and "0x+$foo".
11791                 */
11792                 const char *d = s;
11793                 char *oldbp = PL_bufptr;
11794                 if (*d) ++d; /* so the user sees the bad non-digit */
11795                 PL_bufptr = (char *)d; /* so yyerror reports the context */
11796                 yyerror(Perl_form(aTHX_ "No digits found for %s literal",
11797                                   bases[shift]));
11798                 PL_bufptr = oldbp;
11799             }
11800
11801             if (overflowed) {
11802                 if (n > 4294967295.0)
11803                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11804                                    "%s number > %s non-portable",
11805                                    Bases[shift],
11806                                    new_octal ? "0o37777777777" : maxima[shift]);
11807                 sv = newSVnv(n);
11808             }
11809             else {
11810 #if UVSIZE > 4
11811                 if (u > 0xffffffff)
11812                     Perl_ck_warner(aTHX_ packWARN(WARN_PORTABLE),
11813                                    "%s number > %s non-portable",
11814                                    Bases[shift],
11815                                    new_octal ? "0o37777777777" : maxima[shift]);
11816 #endif
11817                 sv = newSVuv(u);
11818             }
11819             if (just_zero && (PL_hints & HINT_NEW_INTEGER))
11820                 sv = new_constant(start, s - start, "integer",
11821                                   sv, NULL, NULL, 0, NULL);
11822             else if (PL_hints & HINT_NEW_BINARY)
11823                 sv = new_constant(start, s - start, "binary",
11824                                   sv, NULL, NULL, 0, NULL);
11825         }
11826         break;
11827
11828     /*
11829       handle decimal numbers.
11830       we're also sent here when we read a 0 as the first digit
11831     */
11832     case '1': case '2': case '3': case '4': case '5':
11833     case '6': case '7': case '8': case '9': case '.':
11834       decimal:
11835         d = PL_tokenbuf;
11836         e = PL_tokenbuf + sizeof PL_tokenbuf - 6; /* room for various punctuation */
11837         floatit = FALSE;
11838         if (hexfp) {
11839             floatit = TRUE;
11840             *d++ = '0';
11841             switch (shift) {
11842             case 4:
11843                 *d++ = 'x';
11844                 s = start + 2;
11845                 break;
11846             case 3:
11847                 if (new_octal) {
11848                     *d++ = 'o';
11849                     s = start + 2;
11850                     break;
11851                 }
11852                 s = start + 1;
11853                 break;
11854             case 1:
11855                 *d++ = 'b';
11856                 s = start + 2;
11857                 break;
11858             default:
11859                 NOT_REACHED; /* NOTREACHED */
11860             }
11861         }
11862
11863         /* read next group of digits and _ and copy into d */
11864         while (isDIGIT(*s)
11865                || *s == '_'
11866                || UNLIKELY(hexfp && isXDIGIT(*s)))
11867         {
11868             /* skip underscores, checking for misplaced ones
11869                if -w is on
11870             */
11871             if (*s == '_') {
11872                 if (lastub && s == lastub + 1)
11873                     WARN_ABOUT_UNDERSCORE();
11874                 lastub = s++;
11875             }
11876             else {
11877                 /* check for end of fixed-length buffer */
11878                 if (d >= e)
11879                     Perl_croak(aTHX_ "%s", number_too_long);
11880                 /* if we're ok, copy the character */
11881                 *d++ = *s++;
11882             }
11883         }
11884
11885         /* final misplaced underbar check */
11886         if (lastub && s == lastub + 1)
11887             WARN_ABOUT_UNDERSCORE();
11888
11889         /* read a decimal portion if there is one.  avoid
11890            3..5 being interpreted as the number 3. followed
11891            by .5
11892         */
11893         if (*s == '.' && s[1] != '.') {
11894             floatit = TRUE;
11895             *d++ = *s++;
11896
11897             if (*s == '_') {
11898                 WARN_ABOUT_UNDERSCORE();
11899                 lastub = s;
11900             }
11901
11902             /* copy, ignoring underbars, until we run out of digits.
11903             */
11904             for (; isDIGIT(*s)
11905                    || *s == '_'
11906                    || UNLIKELY(hexfp && isXDIGIT(*s));
11907                  s++)
11908             {
11909                 /* fixed length buffer check */
11910                 if (d >= e)
11911                     Perl_croak(aTHX_ "%s", number_too_long);
11912                 if (*s == '_') {
11913                    if (lastub && s == lastub + 1)
11914                         WARN_ABOUT_UNDERSCORE();
11915                    lastub = s;
11916                 }
11917                 else
11918                     *d++ = *s;
11919             }
11920             /* fractional part ending in underbar? */
11921             if (s[-1] == '_')
11922                 WARN_ABOUT_UNDERSCORE();
11923             if (*s == '.' && isDIGIT(s[1])) {
11924                 /* oops, it's really a v-string, but without the "v" */
11925                 s = start;
11926                 goto vstring;
11927             }
11928         }
11929
11930         /* read exponent part, if present */
11931         if ((isALPHA_FOLD_EQ(*s, 'e')
11932               || UNLIKELY(hexfp && isALPHA_FOLD_EQ(*s, 'p')))
11933             && memCHRs("+-0123456789_", s[1]))
11934         {
11935             int exp_digits = 0;
11936             const char *save_s = s;
11937             char * save_d = d;
11938
11939             /* regardless of whether user said 3E5 or 3e5, use lower 'e',
11940                ditto for p (hexfloats) */
11941             if ((isALPHA_FOLD_EQ(*s, 'e'))) {
11942                 /* At least some Mach atof()s don't grok 'E' */
11943                 *d++ = 'e';
11944             }
11945             else if (UNLIKELY(hexfp && (isALPHA_FOLD_EQ(*s, 'p')))) {
11946                 *d++ = 'p';
11947             }
11948
11949             s++;
11950
11951
11952             /* stray preinitial _ */
11953             if (*s == '_') {
11954                 WARN_ABOUT_UNDERSCORE();
11955                 lastub = s++;
11956             }
11957
11958             /* allow positive or negative exponent */
11959             if (*s == '+' || *s == '-')
11960                 *d++ = *s++;
11961
11962             /* stray initial _ */
11963             if (*s == '_') {
11964                 WARN_ABOUT_UNDERSCORE();
11965                 lastub = s++;
11966             }
11967
11968             /* read digits of exponent */
11969             while (isDIGIT(*s) || *s == '_') {
11970                 if (isDIGIT(*s)) {
11971                     ++exp_digits;
11972                     if (d >= e)
11973                         Perl_croak(aTHX_ "%s", number_too_long);
11974                     *d++ = *s++;
11975                 }
11976                 else {
11977                    if (((lastub && s == lastub + 1)
11978                         || (!isDIGIT(s[1]) && s[1] != '_')))
11979                         WARN_ABOUT_UNDERSCORE();
11980                    lastub = s++;
11981                 }
11982             }
11983
11984             if (!exp_digits) {
11985                 /* no exponent digits, the [eEpP] could be for something else,
11986                  * though in practice we don't get here for p since that's preparsed
11987                  * earlier, and results in only the 0xX being consumed, so behave similarly
11988                  * for decimal floats and consume only the D.DD, leaving the [eE] to the
11989                  * next token.
11990                  */
11991                 s = save_s;
11992                 d = save_d;
11993             }
11994             else {
11995                 floatit = TRUE;
11996             }
11997         }
11998
11999
12000         /*
12001            We try to do an integer conversion first if no characters
12002            indicating "float" have been found.
12003          */
12004
12005         if (!floatit) {
12006             UV uv;
12007             const int flags = grok_number (PL_tokenbuf, d - PL_tokenbuf, &uv);
12008
12009             if (flags == IS_NUMBER_IN_UV) {
12010               if (uv <= IV_MAX)
12011                 sv = newSViv(uv); /* Prefer IVs over UVs. */
12012               else
12013                 sv = newSVuv(uv);
12014             } else if (flags == (IS_NUMBER_IN_UV | IS_NUMBER_NEG)) {
12015               if (uv <= (UV) IV_MIN)
12016                 sv = newSViv(-(IV)uv);
12017               else
12018                 floatit = TRUE;
12019             } else
12020               floatit = TRUE;
12021         }
12022         if (floatit) {
12023             /* terminate the string */
12024             *d = '\0';
12025             if (UNLIKELY(hexfp)) {
12026 #  ifdef NV_MANT_DIG
12027                 if (significant_bits > NV_MANT_DIG)
12028                     Perl_ck_warner(aTHX_ packWARN(WARN_OVERFLOW),
12029                                    "Hexadecimal float: mantissa overflow");
12030 #  endif
12031 #ifdef HEXFP_UQUAD
12032                 nv = hexfp_uquad * hexfp_mult;
12033 #else /* HEXFP_NV */
12034                 nv = hexfp_nv * hexfp_mult;
12035 #endif
12036             } else {
12037                 nv = Atof(PL_tokenbuf);
12038             }
12039             sv = newSVnv(nv);
12040         }
12041
12042         if ( floatit
12043              ? (PL_hints & HINT_NEW_FLOAT) : (PL_hints & HINT_NEW_INTEGER) ) {
12044             const char *const key = floatit ? "float" : "integer";
12045             const STRLEN keylen = floatit ? 5 : 7;
12046             sv = S_new_constant(aTHX_ PL_tokenbuf, d - PL_tokenbuf,
12047                                 key, keylen, sv, NULL, NULL, 0, NULL);
12048         }
12049         break;
12050
12051     /* if it starts with a v, it could be a v-string */
12052     case 'v':
12053     vstring:
12054                 sv = newSV(5); /* preallocate storage space */
12055                 ENTER_with_name("scan_vstring");
12056                 SAVEFREESV(sv);
12057                 s = scan_vstring(s, PL_bufend, sv);
12058                 SvREFCNT_inc_simple_void_NN(sv);
12059                 LEAVE_with_name("scan_vstring");
12060         break;
12061     }
12062
12063     /* make the op for the constant and return */
12064
12065     if (sv)
12066         lvalp->opval = newSVOP(OP_CONST, 0, sv);
12067     else
12068         lvalp->opval = NULL;
12069
12070     return (char *)s;
12071 }
12072
12073 STATIC char *
12074 S_scan_formline(pTHX_ char *s)
12075 {
12076     SV * const stuff = newSVpvs("");
12077     bool needargs = FALSE;
12078     bool eofmt = FALSE;
12079
12080     PERL_ARGS_ASSERT_SCAN_FORMLINE;
12081
12082     while (!needargs) {
12083         char *eol;
12084         if (*s == '.') {
12085             char *t = s+1;
12086 #ifdef PERL_STRICT_CR
12087             while (SPACE_OR_TAB(*t))
12088                 t++;
12089 #else
12090             while (SPACE_OR_TAB(*t) || *t == '\r')
12091                 t++;
12092 #endif
12093             if (*t == '\n' || t == PL_bufend) {
12094                 eofmt = TRUE;
12095                 break;
12096             }
12097         }
12098         eol = (char *) memchr(s,'\n',PL_bufend-s);
12099         if (!eol++)
12100                 eol = PL_bufend;
12101         if (*s != '#') {
12102             char *t;
12103             for (t = s; t < eol; t++) {
12104                 if (*t == '~' && t[1] == '~' && SvCUR(stuff)) {
12105                     needargs = FALSE;
12106                     goto enough;        /* ~~ must be first line in formline */
12107                 }
12108                 if (*t == '@' || *t == '^')
12109                     needargs = TRUE;
12110             }
12111             if (eol > s) {
12112                 sv_catpvn(stuff, s, eol-s);
12113 #ifndef PERL_STRICT_CR
12114                 if (eol-s > 1 && eol[-2] == '\r' && eol[-1] == '\n') {
12115                     char *end = SvPVX(stuff) + SvCUR(stuff);
12116                     end[-2] = '\n';
12117                     end[-1] = '\0';
12118                     SvCUR_set(stuff, SvCUR(stuff) - 1);
12119                 }
12120 #endif
12121             }
12122             else
12123               break;
12124         }
12125         s = (char*)eol;
12126         if ((PL_rsfp || PL_parser->filtered)
12127          && PL_parser->form_lex_state == LEX_NORMAL) {
12128             bool got_some;
12129             PL_bufptr = PL_bufend;
12130             COPLINE_INC_WITH_HERELINES;
12131             got_some = lex_next_chunk(0);
12132             CopLINE_dec(PL_curcop);
12133             s = PL_bufptr;
12134             if (!got_some)
12135                 break;
12136         }
12137         incline(s, PL_bufend);
12138     }
12139   enough:
12140     if (!SvCUR(stuff) || needargs)
12141         PL_lex_state = PL_parser->form_lex_state;
12142     if (SvCUR(stuff)) {
12143         PL_expect = XSTATE;
12144         if (needargs) {
12145             const char *s2 = s;
12146             while (isSPACE(*s2) && *s2 != '\n')
12147                 s2++;
12148             if (*s2 == '{') {
12149                 PL_expect = XTERMBLOCK;
12150                 NEXTVAL_NEXTTOKE.ival = 0;
12151                 force_next(DO);
12152             }
12153             NEXTVAL_NEXTTOKE.ival = 0;
12154             force_next(FORMLBRACK);
12155         }
12156         if (!IN_BYTES) {
12157             if (UTF && is_utf8_string((U8*)SvPVX_const(stuff), SvCUR(stuff)))
12158                 SvUTF8_on(stuff);
12159         }
12160         NEXTVAL_NEXTTOKE.opval = newSVOP(OP_CONST, 0, stuff);
12161         force_next(THING);
12162     }
12163     else {
12164         SvREFCNT_dec(stuff);
12165         if (eofmt)
12166             PL_lex_formbrack = 0;
12167     }
12168     return s;
12169 }
12170
12171 I32
12172 Perl_start_subparse(pTHX_ I32 is_format, U32 flags)
12173 {
12174     const I32 oldsavestack_ix = PL_savestack_ix;
12175     CV* const outsidecv = PL_compcv;
12176
12177     SAVEI32(PL_subline);
12178     save_item(PL_subname);
12179     SAVESPTR(PL_compcv);
12180
12181     PL_compcv = MUTABLE_CV(newSV_type(is_format ? SVt_PVFM : SVt_PVCV));
12182     CvFLAGS(PL_compcv) |= flags;
12183
12184     PL_subline = CopLINE(PL_curcop);
12185     CvPADLIST(PL_compcv) = pad_new(padnew_SAVE|padnew_SAVESUB);
12186     CvOUTSIDE(PL_compcv) = MUTABLE_CV(SvREFCNT_inc_simple(outsidecv));
12187     CvOUTSIDE_SEQ(PL_compcv) = PL_cop_seqmax;
12188     if (outsidecv && CvPADLIST(outsidecv))
12189         CvPADLIST(PL_compcv)->xpadl_outid = CvPADLIST(outsidecv)->xpadl_id;
12190
12191     return oldsavestack_ix;
12192 }
12193
12194
12195 /* Do extra initialisation of a CV (typically one just created by
12196  * start_subparse()) if that CV is for a named sub
12197  */
12198
12199 void
12200 Perl_init_named_cv(pTHX_ CV *cv, OP *nameop)
12201 {
12202     PERL_ARGS_ASSERT_INIT_NAMED_CV;
12203
12204     if (nameop->op_type == OP_CONST) {
12205         const char *const name = SvPV_nolen_const(((SVOP*)nameop)->op_sv);
12206         if (   strEQ(name, "BEGIN")
12207             || strEQ(name, "END")
12208             || strEQ(name, "INIT")
12209             || strEQ(name, "CHECK")
12210             || strEQ(name, "UNITCHECK")
12211         )
12212           CvSPECIAL_on(cv);
12213     }
12214     else
12215     /* State subs inside anonymous subs need to be
12216      clonable themselves. */
12217     if (   CvANON(CvOUTSIDE(cv))
12218         || CvCLONE(CvOUTSIDE(cv))
12219         || !PadnameIsSTATE(PadlistNAMESARRAY(CvPADLIST(
12220                         CvOUTSIDE(cv)
12221                      ))[nameop->op_targ])
12222     )
12223       CvCLONE_on(cv);
12224 }
12225
12226
12227 static int
12228 S_yywarn(pTHX_ const char *const s, U32 flags)
12229 {
12230     PERL_ARGS_ASSERT_YYWARN;
12231
12232     PL_in_eval |= EVAL_WARNONLY;
12233     yyerror_pv(s, flags);
12234     return 0;
12235 }
12236
12237 void
12238 Perl_abort_execution(pTHX_ const char * const msg, const char * const name)
12239 {
12240     PERL_ARGS_ASSERT_ABORT_EXECUTION;
12241
12242     if (PL_minus_c)
12243         Perl_croak(aTHX_ "%s%s had compilation errors.\n", msg, name);
12244     else {
12245         Perl_croak(aTHX_
12246                 "%sExecution of %s aborted due to compilation errors.\n", msg, name);
12247     }
12248     NOT_REACHED; /* NOTREACHED */
12249 }
12250
12251 void
12252 Perl_yyquit(pTHX)
12253 {
12254     /* Called, after at least one error has been found, to abort the parse now,
12255      * instead of trying to forge ahead */
12256
12257     yyerror_pvn(NULL, 0, 0);
12258 }
12259
12260 int
12261 Perl_yyerror(pTHX_ const char *const s)
12262 {
12263     PERL_ARGS_ASSERT_YYERROR;
12264     return yyerror_pvn(s, strlen(s), 0);
12265 }
12266
12267 int
12268 Perl_yyerror_pv(pTHX_ const char *const s, U32 flags)
12269 {
12270     PERL_ARGS_ASSERT_YYERROR_PV;
12271     return yyerror_pvn(s, strlen(s), flags);
12272 }
12273
12274 int
12275 Perl_yyerror_pvn(pTHX_ const char *const s, STRLEN len, U32 flags)
12276 {
12277     const char *context = NULL;
12278     int contlen = -1;
12279     SV *msg;
12280     SV * const where_sv = newSVpvs_flags("", SVs_TEMP);
12281     int yychar  = PL_parser->yychar;
12282
12283     /* Output error message 's' with length 'len'.  'flags' are SV flags that
12284      * apply.  If the number of errors found is large enough, it abandons
12285      * parsing.  If 's' is NULL, there is no message, and it abandons
12286      * processing unconditionally */
12287
12288     if (s != NULL) {
12289         if (!yychar || (yychar == PERLY_SEMICOLON && !PL_rsfp))
12290             sv_catpvs(where_sv, "at EOF");
12291         else if (   PL_oldoldbufptr
12292                  && PL_bufptr > PL_oldoldbufptr
12293                  && PL_bufptr - PL_oldoldbufptr < 200
12294                  && PL_oldoldbufptr != PL_oldbufptr
12295                  && PL_oldbufptr != PL_bufptr)
12296         {
12297             /*
12298                     Only for NetWare:
12299                     The code below is removed for NetWare because it
12300                     abends/crashes on NetWare when the script has error such as
12301                     not having the closing quotes like:
12302                         if ($var eq "value)
12303                     Checking of white spaces is anyway done in NetWare code.
12304             */
12305 #ifndef NETWARE
12306             while (isSPACE(*PL_oldoldbufptr))
12307                 PL_oldoldbufptr++;
12308 #endif
12309             context = PL_oldoldbufptr;
12310             contlen = PL_bufptr - PL_oldoldbufptr;
12311         }
12312         else if (  PL_oldbufptr
12313                 && PL_bufptr > PL_oldbufptr
12314                 && PL_bufptr - PL_oldbufptr < 200
12315                 && PL_oldbufptr != PL_bufptr) {
12316             /*
12317                     Only for NetWare:
12318                     The code below is removed for NetWare because it
12319                     abends/crashes on NetWare when the script has error such as
12320                     not having the closing quotes like:
12321                         if ($var eq "value)
12322                     Checking of white spaces is anyway done in NetWare code.
12323             */
12324 #ifndef NETWARE
12325             while (isSPACE(*PL_oldbufptr))
12326                 PL_oldbufptr++;
12327 #endif
12328             context = PL_oldbufptr;
12329             contlen = PL_bufptr - PL_oldbufptr;
12330         }
12331         else if (yychar > 255)
12332             sv_catpvs(where_sv, "next token ???");
12333         else if (yychar == YYEMPTY) {
12334             if (PL_lex_state == LEX_NORMAL)
12335                 sv_catpvs(where_sv, "at end of line");
12336             else if (PL_lex_inpat)
12337                 sv_catpvs(where_sv, "within pattern");
12338             else
12339                 sv_catpvs(where_sv, "within string");
12340         }
12341         else {
12342             sv_catpvs(where_sv, "next char ");
12343             if (yychar < 32)
12344                 Perl_sv_catpvf(aTHX_ where_sv, "^%c", toCTRL(yychar));
12345             else if (isPRINT_LC(yychar)) {
12346                 const char string = yychar;
12347                 sv_catpvn(where_sv, &string, 1);
12348             }
12349             else
12350                 Perl_sv_catpvf(aTHX_ where_sv, "\\%03o", yychar & 255);
12351         }
12352         msg = newSVpvn_flags(s, len, (flags & SVf_UTF8) | SVs_TEMP);
12353         Perl_sv_catpvf(aTHX_ msg, " at %s line %" IVdf ", ",
12354             OutCopFILE(PL_curcop),
12355             (IV)(PL_parser->preambling == NOLINE
12356                    ? CopLINE(PL_curcop)
12357                    : PL_parser->preambling));
12358         if (context)
12359             Perl_sv_catpvf(aTHX_ msg, "near \"%" UTF8f "\"\n",
12360                                  UTF8fARG(UTF, contlen, context));
12361         else
12362             Perl_sv_catpvf(aTHX_ msg, "%" SVf "\n", SVfARG(where_sv));
12363         if (   PL_multi_start < PL_multi_end
12364             && (U32)(CopLINE(PL_curcop) - PL_multi_end) <= 1)
12365         {
12366             Perl_sv_catpvf(aTHX_ msg,
12367             "  (Might be a runaway multi-line %c%c string starting on"
12368             " line %" IVdf ")\n",
12369                     (int)PL_multi_open,(int)PL_multi_close,(IV)PL_multi_start);
12370             PL_multi_end = 0;
12371         }
12372         if (PL_in_eval & EVAL_WARNONLY) {
12373             PL_in_eval &= ~EVAL_WARNONLY;
12374             Perl_ck_warner_d(aTHX_ packWARN(WARN_SYNTAX), "%" SVf, SVfARG(msg));
12375         }
12376         else {
12377             qerror(msg);
12378         }
12379     }
12380     if (s == NULL || PL_error_count >= 10) {
12381         const char * msg = "";
12382         const char * const name = OutCopFILE(PL_curcop);
12383
12384         if (PL_in_eval) {
12385             SV * errsv = ERRSV;
12386             if (SvCUR(errsv)) {
12387                 msg = Perl_form(aTHX_ "%" SVf, SVfARG(errsv));
12388             }
12389         }
12390
12391         if (s == NULL) {
12392             abort_execution(msg, name);
12393         }
12394         else {
12395             Perl_croak(aTHX_ "%s%s has too many errors.\n", msg, name);
12396         }
12397     }
12398     PL_in_my = 0;
12399     PL_in_my_stash = NULL;
12400     return 0;
12401 }
12402
12403 STATIC char*
12404 S_swallow_bom(pTHX_ U8 *s)
12405 {
12406     const STRLEN slen = SvCUR(PL_linestr);
12407
12408     PERL_ARGS_ASSERT_SWALLOW_BOM;
12409
12410     switch (s[0]) {
12411     case 0xFF:
12412         if (s[1] == 0xFE) {
12413             /* UTF-16 little-endian? (or UTF-32LE?) */
12414             if (s[2] == 0 && s[3] == 0)  /* UTF-32 little-endian */
12415                 /* diag_listed_as: Unsupported script encoding %s */
12416                 Perl_croak(aTHX_ "Unsupported script encoding UTF-32LE");
12417 #ifndef PERL_NO_UTF16_FILTER
12418 #ifdef DEBUGGING
12419             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (BOM)\n");
12420 #endif
12421             s += 2;
12422             if (PL_bufend > (char*)s) {
12423                 s = add_utf16_textfilter(s, TRUE);
12424             }
12425 #else
12426             /* diag_listed_as: Unsupported script encoding %s */
12427             Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12428 #endif
12429         }
12430         break;
12431     case 0xFE:
12432         if (s[1] == 0xFF) {   /* UTF-16 big-endian? */
12433 #ifndef PERL_NO_UTF16_FILTER
12434 #ifdef DEBUGGING
12435             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (BOM)\n");
12436 #endif
12437             s += 2;
12438             if (PL_bufend > (char *)s) {
12439                 s = add_utf16_textfilter(s, FALSE);
12440             }
12441 #else
12442             /* diag_listed_as: Unsupported script encoding %s */
12443             Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12444 #endif
12445         }
12446         break;
12447     case BOM_UTF8_FIRST_BYTE: {
12448         if (memBEGINs(s+1, slen - 1, BOM_UTF8_TAIL)) {
12449 #ifdef DEBUGGING
12450             if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-8 script encoding (BOM)\n");
12451 #endif
12452             s += sizeof(BOM_UTF8) - 1;                     /* UTF-8 */
12453         }
12454         break;
12455     }
12456     case 0:
12457         if (slen > 3) {
12458              if (s[1] == 0) {
12459                   if (s[2] == 0xFE && s[3] == 0xFF) {
12460                        /* UTF-32 big-endian */
12461                        /* diag_listed_as: Unsupported script encoding %s */
12462                        Perl_croak(aTHX_ "Unsupported script encoding UTF-32BE");
12463                   }
12464              }
12465              else if (s[2] == 0 && s[3] != 0) {
12466                   /* Leading bytes
12467                    * 00 xx 00 xx
12468                    * are a good indicator of UTF-16BE. */
12469 #ifndef PERL_NO_UTF16_FILTER
12470 #ifdef DEBUGGING
12471                   if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16BE script encoding (no BOM)\n");
12472 #endif
12473                   s = add_utf16_textfilter(s, FALSE);
12474 #else
12475                   /* diag_listed_as: Unsupported script encoding %s */
12476                   Perl_croak(aTHX_ "Unsupported script encoding UTF-16BE");
12477 #endif
12478              }
12479         }
12480         break;
12481
12482     default:
12483          if (slen > 3 && s[1] == 0 && s[2] != 0 && s[3] == 0) {
12484                   /* Leading bytes
12485                    * xx 00 xx 00
12486                    * are a good indicator of UTF-16LE. */
12487 #ifndef PERL_NO_UTF16_FILTER
12488 #ifdef DEBUGGING
12489               if (DEBUG_p_TEST || DEBUG_T_TEST) PerlIO_printf(Perl_debug_log, "UTF-16LE script encoding (no BOM)\n");
12490 #endif
12491               s = add_utf16_textfilter(s, TRUE);
12492 #else
12493               /* diag_listed_as: Unsupported script encoding %s */
12494               Perl_croak(aTHX_ "Unsupported script encoding UTF-16LE");
12495 #endif
12496          }
12497     }
12498     return (char*)s;
12499 }
12500
12501
12502 #ifndef PERL_NO_UTF16_FILTER
12503 static I32
12504 S_utf16_textfilter(pTHX_ int idx, SV *sv, int maxlen)
12505 {
12506     SV *const filter = FILTER_DATA(idx);
12507     /* We re-use this each time round, throwing the contents away before we
12508        return.  */
12509     SV *const utf16_buffer = MUTABLE_SV(IoTOP_GV(filter));
12510     SV *const utf8_buffer = filter;
12511     IV status = IoPAGE(filter);
12512     const bool reverse = cBOOL(IoLINES(filter));
12513     I32 retval;
12514
12515     PERL_ARGS_ASSERT_UTF16_TEXTFILTER;
12516
12517     /* As we're automatically added, at the lowest level, and hence only called
12518        from this file, we can be sure that we're not called in block mode. Hence
12519        don't bother writing code to deal with block mode.  */
12520     if (maxlen) {
12521         Perl_croak(aTHX_ "panic: utf16_textfilter called in block mode (for %d characters)", maxlen);
12522     }
12523     if (status < 0) {
12524         Perl_croak(aTHX_ "panic: utf16_textfilter called after error (status=%" IVdf ")", status);
12525     }
12526     DEBUG_P(PerlIO_printf(Perl_debug_log,
12527                           "utf16_textfilter(%p,%ce): idx=%d maxlen=%d status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12528                           FPTR2DPTR(void *, S_utf16_textfilter),
12529                           reverse ? 'l' : 'b', idx, maxlen, status,
12530                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12531
12532     while (1) {
12533         STRLEN chars;
12534         STRLEN have;
12535         Size_t newlen;
12536         U8 *end;
12537         /* First, look in our buffer of existing UTF-8 data:  */
12538         char *nl = (char *)memchr(SvPVX(utf8_buffer), '\n', SvCUR(utf8_buffer));
12539
12540         if (nl) {
12541             ++nl;
12542         } else if (status == 0) {
12543             /* EOF */
12544             IoPAGE(filter) = 0;
12545             nl = SvEND(utf8_buffer);
12546         }
12547         if (nl) {
12548             STRLEN got = nl - SvPVX(utf8_buffer);
12549             /* Did we have anything to append?  */
12550             retval = got != 0;
12551             sv_catpvn(sv, SvPVX(utf8_buffer), got);
12552             /* Everything else in this code works just fine if SVp_POK isn't
12553                set.  This, however, needs it, and we need it to work, else
12554                we loop infinitely because the buffer is never consumed.  */
12555             sv_chop(utf8_buffer, nl);
12556             break;
12557         }
12558
12559         /* OK, not a complete line there, so need to read some more UTF-16.
12560            Read an extra octect if the buffer currently has an odd number. */
12561         while (1) {
12562             if (status <= 0)
12563                 break;
12564             if (SvCUR(utf16_buffer) >= 2) {
12565                 /* Location of the high octet of the last complete code point.
12566                    Gosh, UTF-16 is a pain. All the benefits of variable length,
12567                    *coupled* with all the benefits of partial reads and
12568                    endianness.  */
12569                 const U8 *const last_hi = (U8*)SvPVX(utf16_buffer)
12570                     + ((SvCUR(utf16_buffer) & ~1) - (reverse ? 1 : 2));
12571
12572                 if (*last_hi < 0xd8 || *last_hi > 0xdb) {
12573                     break;
12574                 }
12575
12576                 /* We have the first half of a surrogate. Read more.  */
12577                 DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter partial surrogate detected at %p\n", last_hi));
12578             }
12579
12580             status = FILTER_READ(idx + 1, utf16_buffer,
12581                                  160 + (SvCUR(utf16_buffer) & 1));
12582             DEBUG_P(PerlIO_printf(Perl_debug_log, "utf16_textfilter status=%" IVdf " SvCUR(sv)=%" UVuf "\n", status, (UV)SvCUR(utf16_buffer)));
12583             DEBUG_P({ sv_dump(utf16_buffer); sv_dump(utf8_buffer);});
12584             if (status < 0) {
12585                 /* Error */
12586                 IoPAGE(filter) = status;
12587                 return status;
12588             }
12589         }
12590
12591         /* 'chars' isn't quite the right name, as code points above 0xFFFF
12592          * require 4 bytes per char */
12593         chars = SvCUR(utf16_buffer) >> 1;
12594         have = SvCUR(utf8_buffer);
12595
12596         /* Assume the worst case size as noted by the functions: twice the
12597          * number of input bytes */
12598         SvGROW(utf8_buffer, have + chars * 4 + 1);
12599
12600         if (reverse) {
12601             end = utf16_to_utf8_reversed((U8*)SvPVX(utf16_buffer),
12602                                          (U8*)SvPVX_const(utf8_buffer) + have,
12603                                          chars * 2, &newlen);
12604         } else {
12605             end = utf16_to_utf8((U8*)SvPVX(utf16_buffer),
12606                                 (U8*)SvPVX_const(utf8_buffer) + have,
12607                                 chars * 2, &newlen);
12608         }
12609         SvCUR_set(utf8_buffer, have + newlen);
12610         *end = '\0';
12611
12612         /* No need to keep this SV "well-formed" with a '\0' after the end, as
12613            it's private to us, and utf16_to_utf8{,reversed} take a
12614            (pointer,length) pair, rather than a NUL-terminated string.  */
12615         if(SvCUR(utf16_buffer) & 1) {
12616             *SvPVX(utf16_buffer) = SvEND(utf16_buffer)[-1];
12617             SvCUR_set(utf16_buffer, 1);
12618         } else {
12619             SvCUR_set(utf16_buffer, 0);
12620         }
12621     }
12622     DEBUG_P(PerlIO_printf(Perl_debug_log,
12623                           "utf16_textfilter: returns, status=%" IVdf " utf16=%" UVuf " utf8=%" UVuf "\n",
12624                           status,
12625                           (UV)SvCUR(utf16_buffer), (UV)SvCUR(utf8_buffer)));
12626     DEBUG_P({ sv_dump(utf8_buffer); sv_dump(sv);});
12627     return retval;
12628 }
12629
12630 static U8 *
12631 S_add_utf16_textfilter(pTHX_ U8 *const s, bool reversed)
12632 {
12633     SV *filter = filter_add(S_utf16_textfilter, NULL);
12634
12635     PERL_ARGS_ASSERT_ADD_UTF16_TEXTFILTER;
12636
12637     IoTOP_GV(filter) = MUTABLE_GV(newSVpvn((char *)s, PL_bufend - (char*)s));
12638     SvPVCLEAR(filter);
12639     IoLINES(filter) = reversed;
12640     IoPAGE(filter) = 1; /* Not EOF */
12641
12642     /* Sadly, we have to return a valid pointer, come what may, so we have to
12643        ignore any error return from this.  */
12644     SvCUR_set(PL_linestr, 0);
12645     if (FILTER_READ(0, PL_linestr, 0)) {
12646         SvUTF8_on(PL_linestr);
12647     } else {
12648         SvUTF8_on(PL_linestr);
12649     }
12650     PL_bufend = SvEND(PL_linestr);
12651     return (U8*)SvPVX(PL_linestr);
12652 }
12653 #endif
12654
12655 /*
12656 Returns a pointer to the next character after the parsed
12657 vstring, as well as updating the passed in sv.
12658
12659 Function must be called like
12660
12661         sv = sv_2mortal(newSV(5));
12662         s = scan_vstring(s,e,sv);
12663
12664 where s and e are the start and end of the string.
12665 The sv should already be large enough to store the vstring
12666 passed in, for performance reasons.
12667
12668 This function may croak if fatal warnings are enabled in the
12669 calling scope, hence the sv_2mortal in the example (to prevent
12670 a leak).  Make sure to do SvREFCNT_inc afterwards if you use
12671 sv_2mortal.
12672
12673 */
12674
12675 char *
12676 Perl_scan_vstring(pTHX_ const char *s, const char *const e, SV *sv)
12677 {
12678     const char *pos = s;
12679     const char *start = s;
12680
12681     PERL_ARGS_ASSERT_SCAN_VSTRING;
12682
12683     if (*pos == 'v') pos++;  /* get past 'v' */
12684     while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12685         pos++;
12686     if ( *pos != '.') {
12687         /* this may not be a v-string if followed by => */
12688         const char *next = pos;
12689         while (next < e && isSPACE(*next))
12690             ++next;
12691         if ((e - next) >= 2 && *next == '=' && next[1] == '>' ) {
12692             /* return string not v-string */
12693             sv_setpvn(sv,(char *)s,pos-s);
12694             return (char *)pos;
12695         }
12696     }
12697
12698     if (!isALPHA(*pos)) {
12699         U8 tmpbuf[UTF8_MAXBYTES+1];
12700
12701         if (*s == 'v')
12702             s++;  /* get past 'v' */
12703
12704         SvPVCLEAR(sv);
12705
12706         for (;;) {
12707             /* this is atoi() that tolerates underscores */
12708             U8 *tmpend;
12709             UV rev = 0;
12710             const char *end = pos;
12711             UV mult = 1;
12712             while (--end >= s) {
12713                 if (*end != '_') {
12714                     const UV orev = rev;
12715                     rev += (*end - '0') * mult;
12716                     mult *= 10;
12717                     if (orev > rev)
12718                         /* diag_listed_as: Integer overflow in %s number */
12719                         Perl_ck_warner_d(aTHX_ packWARN(WARN_OVERFLOW),
12720                                          "Integer overflow in decimal number");
12721                 }
12722             }
12723
12724             /* Append native character for the rev point */
12725             tmpend = uvchr_to_utf8(tmpbuf, rev);
12726             sv_catpvn(sv, (const char*)tmpbuf, tmpend - tmpbuf);
12727             if (!UVCHR_IS_INVARIANT(rev))
12728                  SvUTF8_on(sv);
12729             if (pos + 1 < e && *pos == '.' && isDIGIT(pos[1]))
12730                  s = ++pos;
12731             else {
12732                  s = pos;
12733                  break;
12734             }
12735             while (pos < e && (isDIGIT(*pos) || *pos == '_'))
12736                  pos++;
12737         }
12738         SvPOK_on(sv);
12739         sv_magic(sv,NULL,PERL_MAGIC_vstring,(const char*)start, pos-start);
12740         SvRMAGICAL_on(sv);
12741     }
12742     return (char *)s;
12743 }
12744
12745 int
12746 Perl_keyword_plugin_standard(pTHX_
12747         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
12748 {
12749     PERL_ARGS_ASSERT_KEYWORD_PLUGIN_STANDARD;
12750     PERL_UNUSED_CONTEXT;
12751     PERL_UNUSED_ARG(keyword_ptr);
12752     PERL_UNUSED_ARG(keyword_len);
12753     PERL_UNUSED_ARG(op_ptr);
12754     return KEYWORD_PLUGIN_DECLINE;
12755 }
12756
12757 /*
12758 =for apidoc wrap_keyword_plugin
12759
12760 Puts a C function into the chain of keyword plugins.  This is the
12761 preferred way to manipulate the L</PL_keyword_plugin> variable.
12762 C<new_plugin> is a pointer to the C function that is to be added to the
12763 keyword plugin chain, and C<old_plugin_p> points to the storage location
12764 where a pointer to the next function in the chain will be stored.  The
12765 value of C<new_plugin> is written into the L</PL_keyword_plugin> variable,
12766 while the value previously stored there is written to C<*old_plugin_p>.
12767
12768 L</PL_keyword_plugin> is global to an entire process, and a module wishing
12769 to hook keyword parsing may find itself invoked more than once per
12770 process, typically in different threads.  To handle that situation, this
12771 function is idempotent.  The location C<*old_plugin_p> must initially
12772 (once per process) contain a null pointer.  A C variable of static
12773 duration (declared at file scope, typically also marked C<static> to give
12774 it internal linkage) will be implicitly initialised appropriately, if it
12775 does not have an explicit initialiser.  This function will only actually
12776 modify the plugin chain if it finds C<*old_plugin_p> to be null.  This
12777 function is also thread safe on the small scale.  It uses appropriate
12778 locking to avoid race conditions in accessing L</PL_keyword_plugin>.
12779
12780 When this function is called, the function referenced by C<new_plugin>
12781 must be ready to be called, except for C<*old_plugin_p> being unfilled.
12782 In a threading situation, C<new_plugin> may be called immediately, even
12783 before this function has returned.  C<*old_plugin_p> will always be
12784 appropriately set before C<new_plugin> is called.  If C<new_plugin>
12785 decides not to do anything special with the identifier that it is given
12786 (which is the usual case for most calls to a keyword plugin), it must
12787 chain the plugin function referenced by C<*old_plugin_p>.
12788
12789 Taken all together, XS code to install a keyword plugin should typically
12790 look something like this:
12791
12792     static Perl_keyword_plugin_t next_keyword_plugin;
12793     static OP *my_keyword_plugin(pTHX_
12794         char *keyword_ptr, STRLEN keyword_len, OP **op_ptr)
12795     {
12796         if (memEQs(keyword_ptr, keyword_len,
12797                    "my_new_keyword")) {
12798             ...
12799         } else {
12800             return next_keyword_plugin(aTHX_
12801                 keyword_ptr, keyword_len, op_ptr);
12802         }
12803     }
12804     BOOT:
12805         wrap_keyword_plugin(my_keyword_plugin,
12806                             &next_keyword_plugin);
12807
12808 Direct access to L</PL_keyword_plugin> should be avoided.
12809
12810 =cut
12811 */
12812
12813 void
12814 Perl_wrap_keyword_plugin(pTHX_
12815     Perl_keyword_plugin_t new_plugin, Perl_keyword_plugin_t *old_plugin_p)
12816 {
12817
12818     PERL_UNUSED_CONTEXT;
12819     PERL_ARGS_ASSERT_WRAP_KEYWORD_PLUGIN;
12820     if (*old_plugin_p) return;
12821     KEYWORD_PLUGIN_MUTEX_LOCK;
12822     if (!*old_plugin_p) {
12823         *old_plugin_p = PL_keyword_plugin;
12824         PL_keyword_plugin = new_plugin;
12825     }
12826     KEYWORD_PLUGIN_MUTEX_UNLOCK;
12827 }
12828
12829 #define parse_recdescent(g,p) S_parse_recdescent(aTHX_ g,p)
12830 static void
12831 S_parse_recdescent(pTHX_ int gramtype, I32 fakeeof)
12832 {
12833     SAVEI32(PL_lex_brackets);
12834     if (PL_lex_brackets > 100)
12835         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
12836     PL_lex_brackstack[PL_lex_brackets++] = XFAKEEOF;
12837     SAVEI32(PL_lex_allbrackets);
12838     PL_lex_allbrackets = 0;
12839     SAVEI8(PL_lex_fakeeof);
12840     PL_lex_fakeeof = (U8)fakeeof;
12841     if(yyparse(gramtype) && !PL_parser->error_count)
12842         qerror(Perl_mess(aTHX_ "Parse error"));
12843 }
12844
12845 #define parse_recdescent_for_op(g,p) S_parse_recdescent_for_op(aTHX_ g,p)
12846 static OP *
12847 S_parse_recdescent_for_op(pTHX_ int gramtype, I32 fakeeof)
12848 {
12849     OP *o;
12850     ENTER;
12851     SAVEVPTR(PL_eval_root);
12852     PL_eval_root = NULL;
12853     parse_recdescent(gramtype, fakeeof);
12854     o = PL_eval_root;
12855     LEAVE;
12856     return o;
12857 }
12858
12859 #define parse_expr(p,f) S_parse_expr(aTHX_ p,f)
12860 static OP *
12861 S_parse_expr(pTHX_ I32 fakeeof, U32 flags)
12862 {
12863     OP *exprop;
12864     if (flags & ~PARSE_OPTIONAL)
12865         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_expr");
12866     exprop = parse_recdescent_for_op(GRAMEXPR, fakeeof);
12867     if (!exprop && !(flags & PARSE_OPTIONAL)) {
12868         if (!PL_parser->error_count)
12869             qerror(Perl_mess(aTHX_ "Parse error"));
12870         exprop = newOP(OP_NULL, 0);
12871     }
12872     return exprop;
12873 }
12874
12875 /*
12876 =for apidoc parse_arithexpr
12877
12878 Parse a Perl arithmetic expression.  This may contain operators of precedence
12879 down to the bit shift operators.  The expression must be followed (and thus
12880 terminated) either by a comparison or lower-precedence operator or by
12881 something that would normally terminate an expression such as semicolon.
12882 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12883 otherwise it is mandatory.  It is up to the caller to ensure that the
12884 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12885 the source of the code to be parsed and the lexical context for the
12886 expression.
12887
12888 The op tree representing the expression is returned.  If an optional
12889 expression is absent, a null pointer is returned, otherwise the pointer
12890 will be non-null.
12891
12892 If an error occurs in parsing or compilation, in most cases a valid op
12893 tree is returned anyway.  The error is reflected in the parser state,
12894 normally resulting in a single exception at the top level of parsing
12895 which covers all the compilation errors that occurred.  Some compilation
12896 errors, however, will throw an exception immediately.
12897
12898 =for apidoc Amnh||PARSE_OPTIONAL
12899
12900 =cut
12901
12902 */
12903
12904 OP *
12905 Perl_parse_arithexpr(pTHX_ U32 flags)
12906 {
12907     return parse_expr(LEX_FAKEEOF_COMPARE, flags);
12908 }
12909
12910 /*
12911 =for apidoc parse_termexpr
12912
12913 Parse a Perl term expression.  This may contain operators of precedence
12914 down to the assignment operators.  The expression must be followed (and thus
12915 terminated) either by a comma or lower-precedence operator or by
12916 something that would normally terminate an expression such as semicolon.
12917 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12918 otherwise it is mandatory.  It is up to the caller to ensure that the
12919 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12920 the source of the code to be parsed and the lexical context for the
12921 expression.
12922
12923 The op tree representing the expression is returned.  If an optional
12924 expression is absent, a null pointer is returned, otherwise the pointer
12925 will be non-null.
12926
12927 If an error occurs in parsing or compilation, in most cases a valid op
12928 tree is returned anyway.  The error is reflected in the parser state,
12929 normally resulting in a single exception at the top level of parsing
12930 which covers all the compilation errors that occurred.  Some compilation
12931 errors, however, will throw an exception immediately.
12932
12933 =cut
12934 */
12935
12936 OP *
12937 Perl_parse_termexpr(pTHX_ U32 flags)
12938 {
12939     return parse_expr(LEX_FAKEEOF_COMMA, flags);
12940 }
12941
12942 /*
12943 =for apidoc parse_listexpr
12944
12945 Parse a Perl list expression.  This may contain operators of precedence
12946 down to the comma operator.  The expression must be followed (and thus
12947 terminated) either by a low-precedence logic operator such as C<or> or by
12948 something that would normally terminate an expression such as semicolon.
12949 If C<flags> has the C<PARSE_OPTIONAL> bit set, then the expression is optional,
12950 otherwise it is mandatory.  It is up to the caller to ensure that the
12951 dynamic parser state (L</PL_parser> et al) is correctly set to reflect
12952 the source of the code to be parsed and the lexical context for the
12953 expression.
12954
12955 The op tree representing the expression is returned.  If an optional
12956 expression is absent, a null pointer is returned, otherwise the pointer
12957 will be non-null.
12958
12959 If an error occurs in parsing or compilation, in most cases a valid op
12960 tree is returned anyway.  The error is reflected in the parser state,
12961 normally resulting in a single exception at the top level of parsing
12962 which covers all the compilation errors that occurred.  Some compilation
12963 errors, however, will throw an exception immediately.
12964
12965 =cut
12966 */
12967
12968 OP *
12969 Perl_parse_listexpr(pTHX_ U32 flags)
12970 {
12971     return parse_expr(LEX_FAKEEOF_LOWLOGIC, flags);
12972 }
12973
12974 /*
12975 =for apidoc parse_fullexpr
12976
12977 Parse a single complete Perl expression.  This allows the full
12978 expression grammar, including the lowest-precedence operators such
12979 as C<or>.  The expression must be followed (and thus terminated) by a
12980 token that an expression would normally be terminated by: end-of-file,
12981 closing bracketing punctuation, semicolon, or one of the keywords that
12982 signals a postfix expression-statement modifier.  If C<flags> has the
12983 C<PARSE_OPTIONAL> bit set, then the expression is optional, otherwise it is
12984 mandatory.  It is up to the caller to ensure that the dynamic parser
12985 state (L</PL_parser> et al) is correctly set to reflect the source of
12986 the code to be parsed and the lexical context for the expression.
12987
12988 The op tree representing the expression is returned.  If an optional
12989 expression is absent, a null pointer is returned, otherwise the pointer
12990 will be non-null.
12991
12992 If an error occurs in parsing or compilation, in most cases a valid op
12993 tree is returned anyway.  The error is reflected in the parser state,
12994 normally resulting in a single exception at the top level of parsing
12995 which covers all the compilation errors that occurred.  Some compilation
12996 errors, however, will throw an exception immediately.
12997
12998 =cut
12999 */
13000
13001 OP *
13002 Perl_parse_fullexpr(pTHX_ U32 flags)
13003 {
13004     return parse_expr(LEX_FAKEEOF_NONEXPR, flags);
13005 }
13006
13007 /*
13008 =for apidoc parse_block
13009
13010 Parse a single complete Perl code block.  This consists of an opening
13011 brace, a sequence of statements, and a closing brace.  The block
13012 constitutes a lexical scope, so C<my> variables and various compile-time
13013 effects can be contained within it.  It is up to the caller to ensure
13014 that the dynamic parser state (L</PL_parser> et al) is correctly set to
13015 reflect the source of the code to be parsed and the lexical context for
13016 the statement.
13017
13018 The op tree representing the code block is returned.  This is always a
13019 real op, never a null pointer.  It will normally be a C<lineseq> list,
13020 including C<nextstate> or equivalent ops.  No ops to construct any kind
13021 of runtime scope are included by virtue of it being a block.
13022
13023 If an error occurs in parsing or compilation, in most cases a valid op
13024 tree (most likely null) is returned anyway.  The error is reflected in
13025 the parser state, normally resulting in a single exception at the top
13026 level of parsing which covers all the compilation errors that occurred.
13027 Some compilation errors, however, will throw an exception immediately.
13028
13029 The C<flags> parameter is reserved for future use, and must always
13030 be zero.
13031
13032 =cut
13033 */
13034
13035 OP *
13036 Perl_parse_block(pTHX_ U32 flags)
13037 {
13038     if (flags)
13039         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_block");
13040     return parse_recdescent_for_op(GRAMBLOCK, LEX_FAKEEOF_NEVER);
13041 }
13042
13043 /*
13044 =for apidoc parse_barestmt
13045
13046 Parse a single unadorned Perl statement.  This may be a normal imperative
13047 statement or a declaration that has compile-time effect.  It does not
13048 include any label or other affixture.  It is up to the caller to ensure
13049 that the dynamic parser state (L</PL_parser> et al) is correctly set to
13050 reflect the source of the code to be parsed and the lexical context for
13051 the statement.
13052
13053 The op tree representing the statement is returned.  This may be a
13054 null pointer if the statement is null, for example if it was actually
13055 a subroutine definition (which has compile-time side effects).  If not
13056 null, it will be ops directly implementing the statement, suitable to
13057 pass to L</newSTATEOP>.  It will not normally include a C<nextstate> or
13058 equivalent op (except for those embedded in a scope contained entirely
13059 within the statement).
13060
13061 If an error occurs in parsing or compilation, in most cases a valid op
13062 tree (most likely null) is returned anyway.  The error is reflected in
13063 the parser state, normally resulting in a single exception at the top
13064 level of parsing which covers all the compilation errors that occurred.
13065 Some compilation errors, however, will throw an exception immediately.
13066
13067 The C<flags> parameter is reserved for future use, and must always
13068 be zero.
13069
13070 =cut
13071 */
13072
13073 OP *
13074 Perl_parse_barestmt(pTHX_ U32 flags)
13075 {
13076     if (flags)
13077         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_barestmt");
13078     return parse_recdescent_for_op(GRAMBARESTMT, LEX_FAKEEOF_NEVER);
13079 }
13080
13081 /*
13082 =for apidoc parse_label
13083
13084 Parse a single label, possibly optional, of the type that may prefix a
13085 Perl statement.  It is up to the caller to ensure that the dynamic parser
13086 state (L</PL_parser> et al) is correctly set to reflect the source of
13087 the code to be parsed.  If C<flags> has the C<PARSE_OPTIONAL> bit set, then the
13088 label is optional, otherwise it is mandatory.
13089
13090 The name of the label is returned in the form of a fresh scalar.  If an
13091 optional label is absent, a null pointer is returned.
13092
13093 If an error occurs in parsing, which can only occur if the label is
13094 mandatory, a valid label is returned anyway.  The error is reflected in
13095 the parser state, normally resulting in a single exception at the top
13096 level of parsing which covers all the compilation errors that occurred.
13097
13098 =cut
13099 */
13100
13101 SV *
13102 Perl_parse_label(pTHX_ U32 flags)
13103 {
13104     if (flags & ~PARSE_OPTIONAL)
13105         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_label");
13106     if (PL_nexttoke) {
13107         PL_parser->yychar = yylex();
13108         if (PL_parser->yychar == LABEL) {
13109             SV * const labelsv = cSVOPx(pl_yylval.opval)->op_sv;
13110             PL_parser->yychar = YYEMPTY;
13111             cSVOPx(pl_yylval.opval)->op_sv = NULL;
13112             op_free(pl_yylval.opval);
13113             return labelsv;
13114         } else {
13115             yyunlex();
13116             goto no_label;
13117         }
13118     } else {
13119         char *s, *t;
13120         STRLEN wlen, bufptr_pos;
13121         lex_read_space(0);
13122         t = s = PL_bufptr;
13123         if (!isIDFIRST_lazy_if_safe(s, PL_bufend, UTF))
13124             goto no_label;
13125         t = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, FALSE, &wlen);
13126         if (word_takes_any_delimiter(s, wlen))
13127             goto no_label;
13128         bufptr_pos = s - SvPVX(PL_linestr);
13129         PL_bufptr = t;
13130         lex_read_space(LEX_KEEP_PREVIOUS);
13131         t = PL_bufptr;
13132         s = SvPVX(PL_linestr) + bufptr_pos;
13133         if (t[0] == ':' && t[1] != ':') {
13134             PL_oldoldbufptr = PL_oldbufptr;
13135             PL_oldbufptr = s;
13136             PL_bufptr = t+1;
13137             return newSVpvn_flags(s, wlen, UTF ? SVf_UTF8 : 0);
13138         } else {
13139             PL_bufptr = s;
13140             no_label:
13141             if (flags & PARSE_OPTIONAL) {
13142                 return NULL;
13143             } else {
13144                 qerror(Perl_mess(aTHX_ "Parse error"));
13145                 return newSVpvs("x");
13146             }
13147         }
13148     }
13149 }
13150
13151 /*
13152 =for apidoc parse_fullstmt
13153
13154 Parse a single complete Perl statement.  This may be a normal imperative
13155 statement or a declaration that has compile-time effect, and may include
13156 optional labels.  It is up to the caller to ensure that the dynamic
13157 parser state (L</PL_parser> et al) is correctly set to reflect the source
13158 of the code to be parsed and the lexical context for the statement.
13159
13160 The op tree representing the statement is returned.  This may be a
13161 null pointer if the statement is null, for example if it was actually
13162 a subroutine definition (which has compile-time side effects).  If not
13163 null, it will be the result of a L</newSTATEOP> call, normally including
13164 a C<nextstate> or equivalent op.
13165
13166 If an error occurs in parsing or compilation, in most cases a valid op
13167 tree (most likely null) is returned anyway.  The error is reflected in
13168 the parser state, normally resulting in a single exception at the top
13169 level of parsing which covers all the compilation errors that occurred.
13170 Some compilation errors, however, will throw an exception immediately.
13171
13172 The C<flags> parameter is reserved for future use, and must always
13173 be zero.
13174
13175 =cut
13176 */
13177
13178 OP *
13179 Perl_parse_fullstmt(pTHX_ U32 flags)
13180 {
13181     if (flags)
13182         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_fullstmt");
13183     return parse_recdescent_for_op(GRAMFULLSTMT, LEX_FAKEEOF_NEVER);
13184 }
13185
13186 /*
13187 =for apidoc parse_stmtseq
13188
13189 Parse a sequence of zero or more Perl statements.  These may be normal
13190 imperative statements, including optional labels, or declarations
13191 that have compile-time effect, or any mixture thereof.  The statement
13192 sequence ends when a closing brace or end-of-file is encountered in a
13193 place where a new statement could have validly started.  It is up to
13194 the caller to ensure that the dynamic parser state (L</PL_parser> et al)
13195 is correctly set to reflect the source of the code to be parsed and the
13196 lexical context for the statements.
13197
13198 The op tree representing the statement sequence is returned.  This may
13199 be a null pointer if the statements were all null, for example if there
13200 were no statements or if there were only subroutine definitions (which
13201 have compile-time side effects).  If not null, it will be a C<lineseq>
13202 list, normally including C<nextstate> or equivalent ops.
13203
13204 If an error occurs in parsing or compilation, in most cases a valid op
13205 tree is returned anyway.  The error is reflected in the parser state,
13206 normally resulting in a single exception at the top level of parsing
13207 which covers all the compilation errors that occurred.  Some compilation
13208 errors, however, will throw an exception immediately.
13209
13210 The C<flags> parameter is reserved for future use, and must always
13211 be zero.
13212
13213 =cut
13214 */
13215
13216 OP *
13217 Perl_parse_stmtseq(pTHX_ U32 flags)
13218 {
13219     OP *stmtseqop;
13220     I32 c;
13221     if (flags)
13222         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_stmtseq");
13223     stmtseqop = parse_recdescent_for_op(GRAMSTMTSEQ, LEX_FAKEEOF_CLOSING);
13224     c = lex_peek_unichar(0);
13225     if (c != -1 && c != /*{*/'}')
13226         qerror(Perl_mess(aTHX_ "Parse error"));
13227     return stmtseqop;
13228 }
13229
13230 /*
13231 =for apidoc parse_subsignature
13232
13233 Parse a subroutine signature declaration. This is the contents of the
13234 parentheses following a named or anonymous subroutine declaration when the
13235 C<signatures> feature is enabled. Note that this function neither expects
13236 nor consumes the opening and closing parentheses around the signature; it
13237 is the caller's job to handle these.
13238
13239 This function must only be called during parsing of a subroutine; after
13240 L</start_subparse> has been called. It might allocate lexical variables on
13241 the pad for the current subroutine.
13242
13243 The op tree to unpack the arguments from the stack at runtime is returned.
13244 This op tree should appear at the beginning of the compiled function. The
13245 caller may wish to use L</op_append_list> to build their function body
13246 after it, or splice it together with the body before calling L</newATTRSUB>.
13247
13248 The C<flags> parameter is reserved for future use, and must always
13249 be zero.
13250
13251 =cut
13252 */
13253
13254 OP *
13255 Perl_parse_subsignature(pTHX_ U32 flags)
13256 {
13257     if (flags)
13258         Perl_croak(aTHX_ "Parsing code internal error (%s)", "parse_subsignature");
13259     return parse_recdescent_for_op(GRAMSUBSIGNATURE, LEX_FAKEEOF_NONEXPR);
13260 }
13261
13262 /*
13263  * ex: set ts=8 sts=4 sw=4 et:
13264  */