This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
disallow nested declarations [perl #125587] [perl #121058]
[perl5.git] / toke.c
1 /*    toke.c
2  *
3  *    Copyright (C) 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000,
4  *    2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 by Larry Wall and others
5  *
6  *    You may distribute under the terms of either the GNU General Public
7  *    License or the Artistic License, as specified in the README file.
8  *
9  */
10
11 /*
12  *  'It all comes from here, the stench and the peril.'    --Frodo
13  *
14  *     [p.719 of _The Lord of the Rings_, IV/ix: "Shelob's Lair"]
15  */
16
17 /*
18  * This file is the lexer for Perl.  It's closely linked to the
19  * parser, perly.y.
20  *
21  * The main routine is yylex(), which returns the next token.
22  */
23
24 /*
25 =head1 Lexer interface
26 This is the lower layer of the Perl parser, managing characters and tokens.
27
28 =for apidoc AmU|yy_parser *|PL_parser
29
30 Pointer to a structure encapsulating the state of the parsing operation
31 currently in progress.  The pointer can be locally changed to perform
32 a nested parse without interfering with the state of an outer parse.
33 Individual members of C<PL_parser> have their own documentation.
34
35 =cut
36 */
37
38 #include "EXTERN.h"
39 #define PERL_IN_TOKE_C
40 #include "perl.h"
41 #include "dquote_inline.h"
42
43 #define new_constant(a,b,c,d,e,f,g)     \
44         S_new_constant(aTHX_ a,b,STR_WITH_LEN(c),d,e,f, g)
45
46 #define pl_yylval       (PL_parser->yylval)
47
48 /* XXX temporary backwards compatibility */
49 #define PL_lex_brackets         (PL_parser->lex_brackets)
50 #define PL_lex_allbrackets      (PL_parser->lex_allbrackets)
51 #define PL_lex_fakeeof          (PL_parser->lex_fakeeof)
52 #define PL_lex_brackstack       (PL_parser->lex_brackstack)
53 #define PL_lex_casemods         (PL_parser->lex_casemods)
54 #define PL_lex_casestack        (PL_parser->lex_casestack)
55 #define PL_lex_defer            (PL_parser->lex_defer)
56 #define PL_lex_dojoin           (PL_parser->lex_dojoin)
57 #define PL_lex_formbrack        (PL_parser->lex_formbrack)
58 #define PL_lex_inpat            (PL_parser->lex_inpat)
59 #define PL_lex_inwhat           (PL_parser->lex_inwhat)
60 #define PL_lex_op               (PL_parser->lex_op)
61 #define PL_lex_repl             (PL_parser->lex_repl)
62 #define PL_lex_starts           (PL_parser->lex_starts)
63 #define PL_lex_stuff            (PL_parser->lex_stuff)
64 #define PL_multi_start          (PL_parser->multi_start)
65 #define PL_multi_open           (PL_parser->multi_open)
66 #define PL_multi_close          (PL_parser->multi_close)
67 #define PL_preambled            (PL_parser->preambled)
68 #define PL_sublex_info          (PL_parser->sublex_info)
69 #define PL_linestr              (PL_parser->linestr)
70 #define PL_expect               (PL_parser->expect)
71 #define PL_copline              (PL_parser->copline)
72 #define PL_bufptr               (PL_parser->bufptr)
73 #define PL_oldbufptr            (PL_parser->oldbufptr)
74 #define PL_oldoldbufptr         (PL_parser->oldoldbufptr)
75 #define PL_linestart            (PL_parser->linestart)
76 #define PL_bufend               (PL_parser->bufend)
77 #define PL_last_uni             (PL_parser->last_uni)
78 #define PL_last_lop             (PL_parser->last_lop)
79 #define PL_last_lop_op          (PL_parser->last_lop_op)
80 #define PL_lex_state            (PL_parser->lex_state)
81 #define PL_rsfp                 (PL_parser->rsfp)
82 #define PL_rsfp_filters         (PL_parser->rsfp_filters)
83 #define PL_in_my                (PL_parser->in_my)
84 #define PL_in_my_stash          (PL_parser->in_my_stash)
85 #define PL_tokenbuf             (PL_parser->tokenbuf)
86 #define PL_multi_end            (PL_parser->multi_end)
87 #define PL_error_count          (PL_parser->error_count)
88
89 #  define PL_nexttoke           (PL_parser->nexttoke)
90 #  define PL_nexttype           (PL_parser->nexttype)
91 #  define PL_nextval            (PL_parser->nextval)
92
93 static const char* const ident_too_long = "Identifier too long";
94
95 #  define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
96
97 #define XENUMMASK  0x3f
98 #define XFAKEEOF   0x40
99 #define XFAKEBRACK 0x80
100
101 #ifdef USE_UTF8_SCRIPTS
102 #   define UTF cBOOL(!IN_BYTES)
103 #else
104 #   define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
105 #endif
106
107 /* The maximum number of characters preceding the unrecognized one to display */
108 #define UNRECOGNIZED_PRECEDE_COUNT 10
109
110 /* In variables named $^X, these are the legal values for X.
111  * 1999-02-27 mjd-perl-patch@plover.com */
112 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
113
114 #define SPACE_OR_TAB(c) isBLANK_A(c)
115
116 #define HEXFP_PEEK(s)     \
117     (((s[0] == '.') && \
118       (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
119      isALPHA_FOLD_EQ(s[0], 'p'))
120
121 /* LEX_* are values for PL_lex_state, the state of the lexer.
122  * They are arranged oddly so that the guard on the switch statement
123  * can get by with a single comparison (if the compiler is smart enough).
124  *
125  * These values refer to the various states within a sublex parse,
126  * i.e. within a double quotish string
127  */
128
129 /* #define LEX_NOTPARSING               11 is done in perl.h. */
130
131 #define LEX_NORMAL              10 /* normal code (ie not within "...")     */
132 #define LEX_INTERPNORMAL         9 /* code within a string, eg "$foo[$x+1]" */
133 #define LEX_INTERPCASEMOD        8 /* expecting a \U, \Q or \E etc          */
134 #define LEX_INTERPPUSH           7 /* starting a new sublex parse level     */
135 #define LEX_INTERPSTART          6 /* expecting the start of a $var         */
136
137                                    /* at end of code, eg "$x" followed by:  */
138 #define LEX_INTERPEND            5 /* ... eg not one of [, { or ->          */
139 #define LEX_INTERPENDMAYBE       4 /* ... eg one of [, { or ->              */
140
141 #define LEX_INTERPCONCAT         3 /* expecting anything, eg at start of
142                                         string or after \E, $foo, etc       */
143 #define LEX_INTERPCONST          2 /* NOT USED */
144 #define LEX_FORMLINE             1 /* expecting a format line               */
145 #define LEX_KNOWNEXT             0 /* next token known; just return it      */
146
147
148 #ifdef DEBUGGING
149 static const char* const lex_state_names[] = {
150     "KNOWNEXT",
151     "FORMLINE",
152     "INTERPCONST",
153     "INTERPCONCAT",
154     "INTERPENDMAYBE",
155     "INTERPEND",
156     "INTERPSTART",
157     "INTERPPUSH",
158     "INTERPCASEMOD",
159     "INTERPNORMAL",
160     "NORMAL"
161 };
162 #endif
163
164 #include "keywords.h"
165
166 /* CLINE is a macro that ensures PL_copline has a sane value */
167
168 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
169
170 /*
171  * Convenience functions to return different tokens and prime the
172  * lexer for the next token.  They all take an argument.
173  *
174  * TOKEN        : generic token (used for '(', DOLSHARP, etc)
175  * OPERATOR     : generic operator
176  * AOPERATOR    : assignment operator
177  * PREBLOCK     : beginning the block after an if, while, foreach, ...
178  * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
179  * PREREF       : *EXPR where EXPR is not a simple identifier
180  * TERM         : expression term
181  * POSTDEREF    : postfix dereference (->$* ->@[...] etc.)
182  * LOOPX        : loop exiting command (goto, last, dump, etc)
183  * FTST         : file test operator
184  * FUN0         : zero-argument function
185  * FUN0OP       : zero-argument function, with its op created in this file
186  * FUN1         : not used, except for not, which isn't a UNIOP
187  * BOop         : bitwise or or xor
188  * BAop         : bitwise and
189  * BCop         : bitwise complement
190  * SHop         : shift operator
191  * PWop         : power operator
192  * PMop         : pattern-matching operator
193  * Aop          : addition-level operator
194  * AopNOASSIGN  : addition-level operator that is never part of .=
195  * Mop          : multiplication-level operator
196  * Eop          : equality-testing operator
197  * Rop          : relational operator <= != gt
198  *
199  * Also see LOP and lop() below.
200  */
201
202 #ifdef DEBUGGING /* Serve -DT. */
203 #   define REPORT(retval) tokereport((I32)retval, &pl_yylval)
204 #else
205 #   define REPORT(retval) (retval)
206 #endif
207
208 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
209 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
210 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
211 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
212 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
213 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
214 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
215 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
216 #define LOOPX(f) return (PL_bufptr = force_word(s,WORD,TRUE,FALSE), \
217                          pl_yylval.ival=f, \
218                          PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
219                          REPORT((int)LOOPEX))
220 #define FTST(f)  return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
221 #define FUN0(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
222 #define FUN0OP(f)  return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
223 #define FUN1(f)  return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
224 #define BOop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
225 #define BAop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
226 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
227                        REPORT('~')
228 #define SHop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
229 #define PWop(f)  return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
230 #define PMop(f)  return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
231 #define Aop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
232 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
233 #define Mop(f)   return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
234 #define Eop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
235 #define Rop(f)   return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
236
237 /* This bit of chicanery makes a unary function followed by
238  * a parenthesis into a function with one argument, highest precedence.
239  * The UNIDOR macro is for unary functions that can be followed by the //
240  * operator (such as C<shift // 0>).
241  */
242 #define UNI3(f,x,have_x) { \
243         pl_yylval.ival = f; \
244         if (have_x) PL_expect = x; \
245         PL_bufptr = s; \
246         PL_last_uni = PL_oldbufptr; \
247         PL_last_lop_op = f; \
248         if (*s == '(') \
249             return REPORT( (int)FUNC1 ); \
250         s = skipspace(s); \
251         return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
252         }
253 #define UNI(f)    UNI3(f,XTERM,1)
254 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
255 #define UNIPROTO(f,optional) { \
256         if (optional) PL_last_uni = PL_oldbufptr; \
257         OPERATOR(f); \
258         }
259
260 #define UNIBRACK(f) UNI3(f,0,0)
261
262 /* grandfather return to old style */
263 #define OLDLOP(f) \
264         do { \
265             if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
266                 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
267             pl_yylval.ival = (f); \
268             PL_expect = XTERM; \
269             PL_bufptr = s; \
270             return (int)LSTOP; \
271         } while(0)
272
273 #define COPLINE_INC_WITH_HERELINES                  \
274     STMT_START {                                     \
275         CopLINE_inc(PL_curcop);                       \
276         if (PL_parser->herelines)                      \
277             CopLINE(PL_curcop) += PL_parser->herelines, \
278             PL_parser->herelines = 0;                    \
279     } STMT_END
280 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
281  * is no sublex_push to follow. */
282 #define COPLINE_SET_FROM_MULTI_END            \
283     STMT_START {                               \
284         CopLINE_set(PL_curcop, PL_multi_end);   \
285         if (PL_multi_end != PL_multi_start)      \
286             PL_parser->herelines = 0;             \
287     } STMT_END
288
289
290 #ifdef DEBUGGING
291
292 /* how to interpret the pl_yylval associated with the token */
293 enum token_type {
294     TOKENTYPE_NONE,
295     TOKENTYPE_IVAL,
296     TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
297     TOKENTYPE_PVAL,
298     TOKENTYPE_OPVAL
299 };
300
301 static struct debug_tokens {
302     const int token;
303     enum token_type type;
304     const char *name;
305 } const debug_tokens[] =
306 {
307     { ADDOP,            TOKENTYPE_OPNUM,        "ADDOP" },
308     { ANDAND,           TOKENTYPE_NONE,         "ANDAND" },
309     { ANDOP,            TOKENTYPE_NONE,         "ANDOP" },
310     { ANONSUB,          TOKENTYPE_IVAL,         "ANONSUB" },
311     { ARROW,            TOKENTYPE_NONE,         "ARROW" },
312     { ASSIGNOP,         TOKENTYPE_OPNUM,        "ASSIGNOP" },
313     { BITANDOP,         TOKENTYPE_OPNUM,        "BITANDOP" },
314     { BITOROP,          TOKENTYPE_OPNUM,        "BITOROP" },
315     { COLONATTR,        TOKENTYPE_NONE,         "COLONATTR" },
316     { CONTINUE,         TOKENTYPE_NONE,         "CONTINUE" },
317     { DEFAULT,          TOKENTYPE_NONE,         "DEFAULT" },
318     { DO,               TOKENTYPE_NONE,         "DO" },
319     { DOLSHARP,         TOKENTYPE_NONE,         "DOLSHARP" },
320     { DORDOR,           TOKENTYPE_NONE,         "DORDOR" },
321     { DOROP,            TOKENTYPE_OPNUM,        "DOROP" },
322     { DOTDOT,           TOKENTYPE_IVAL,         "DOTDOT" },
323     { ELSE,             TOKENTYPE_NONE,         "ELSE" },
324     { ELSIF,            TOKENTYPE_IVAL,         "ELSIF" },
325     { EQOP,             TOKENTYPE_OPNUM,        "EQOP" },
326     { FOR,              TOKENTYPE_IVAL,         "FOR" },
327     { FORMAT,           TOKENTYPE_NONE,         "FORMAT" },
328     { FORMLBRACK,       TOKENTYPE_NONE,         "FORMLBRACK" },
329     { FORMRBRACK,       TOKENTYPE_NONE,         "FORMRBRACK" },
330     { FUNC,             TOKENTYPE_OPNUM,        "FUNC" },
331     { FUNC0,            TOKENTYPE_OPNUM,        "FUNC0" },
332     { FUNC0OP,          TOKENTYPE_OPVAL,        "FUNC0OP" },
333     { FUNC0SUB,         TOKENTYPE_OPVAL,        "FUNC0SUB" },
334     { FUNC1,            TOKENTYPE_OPNUM,        "FUNC1" },
335     { FUNCMETH,         TOKENTYPE_OPVAL,        "FUNCMETH" },
336     { GIVEN,            TOKENTYPE_IVAL,         "GIVEN" },
337     { HASHBRACK,        TOKENTYPE_NONE,         "HASHBRACK" },
338     { IF,               TOKENTYPE_IVAL,         "IF" },
339     { LABEL,            TOKENTYPE_PVAL,         "LABEL" },
340     { LOCAL,            TOKENTYPE_IVAL,         "LOCAL" },
341     { LOOPEX,           TOKENTYPE_OPNUM,        "LOOPEX" },
342     { LSTOP,            TOKENTYPE_OPNUM,        "LSTOP" },
343     { LSTOPSUB,         TOKENTYPE_OPVAL,        "LSTOPSUB" },
344     { MATCHOP,          TOKENTYPE_OPNUM,        "MATCHOP" },
345     { METHOD,           TOKENTYPE_OPVAL,        "METHOD" },
346     { MULOP,            TOKENTYPE_OPNUM,        "MULOP" },
347     { MY,               TOKENTYPE_IVAL,         "MY" },
348     { NOAMP,            TOKENTYPE_NONE,         "NOAMP" },
349     { NOTOP,            TOKENTYPE_NONE,         "NOTOP" },
350     { OROP,             TOKENTYPE_IVAL,         "OROP" },
351     { OROR,             TOKENTYPE_NONE,         "OROR" },
352     { PACKAGE,          TOKENTYPE_NONE,         "PACKAGE" },
353     { PLUGEXPR,         TOKENTYPE_OPVAL,        "PLUGEXPR" },
354     { PLUGSTMT,         TOKENTYPE_OPVAL,        "PLUGSTMT" },
355     { PMFUNC,           TOKENTYPE_OPVAL,        "PMFUNC" },
356     { POSTJOIN,         TOKENTYPE_NONE,         "POSTJOIN" },
357     { POSTDEC,          TOKENTYPE_NONE,         "POSTDEC" },
358     { POSTINC,          TOKENTYPE_NONE,         "POSTINC" },
359     { POWOP,            TOKENTYPE_OPNUM,        "POWOP" },
360     { PREDEC,           TOKENTYPE_NONE,         "PREDEC" },
361     { PREINC,           TOKENTYPE_NONE,         "PREINC" },
362     { PRIVATEREF,       TOKENTYPE_OPVAL,        "PRIVATEREF" },
363     { QWLIST,           TOKENTYPE_OPVAL,        "QWLIST" },
364     { REFGEN,           TOKENTYPE_NONE,         "REFGEN" },
365     { RELOP,            TOKENTYPE_OPNUM,        "RELOP" },
366     { REQUIRE,          TOKENTYPE_NONE,         "REQUIRE" },
367     { SHIFTOP,          TOKENTYPE_OPNUM,        "SHIFTOP" },
368     { SUB,              TOKENTYPE_NONE,         "SUB" },
369     { THING,            TOKENTYPE_OPVAL,        "THING" },
370     { UMINUS,           TOKENTYPE_NONE,         "UMINUS" },
371     { UNIOP,            TOKENTYPE_OPNUM,        "UNIOP" },
372     { UNIOPSUB,         TOKENTYPE_OPVAL,        "UNIOPSUB" },
373     { UNLESS,           TOKENTYPE_IVAL,         "UNLESS" },
374     { UNTIL,            TOKENTYPE_IVAL,         "UNTIL" },
375     { USE,              TOKENTYPE_IVAL,         "USE" },
376     { WHEN,             TOKENTYPE_IVAL,         "WHEN" },
377     { WHILE,            TOKENTYPE_IVAL,         "WHILE" },
378     { WORD,             TOKENTYPE_OPVAL,        "WORD" },
379     { YADAYADA,         TOKENTYPE_IVAL,         "YADAYADA" },
380     { 0,                TOKENTYPE_NONE,         NULL }
381 };
382
383 /* dump the returned token in rv, plus any optional arg in pl_yylval */
384
385 STATIC int
386 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
387 {
388     PERL_ARGS_ASSERT_TOKEREPORT;
389
390     if (DEBUG_T_TEST) {
391         const char *name = NULL;
392         enum token_type type = TOKENTYPE_NONE;
393         const struct debug_tokens *p;
394         SV* const report = newSVpvs("<== ");
395
396         for (p = debug_tokens; p->token; p++) {
397             if (p->token == (int)rv) {
398                 name = p->name;
399                 type = p->type;
400                 break;
401             }
402         }
403         if (name)
404             Perl_sv_catpv(aTHX_ report, name);
405         else if (isGRAPH(rv))
406         {
407             Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
408             if ((char)rv == 'p')
409                 sv_catpvs(report, " (pending identifier)");
410         }
411         else if (!rv)
412             sv_catpvs(report, "EOF");
413         else
414             Perl_sv_catpvf(aTHX_ report, "?? %"IVdf, (IV)rv);
415         switch (type) {
416         case TOKENTYPE_NONE:
417             break;
418         case TOKENTYPE_IVAL:
419             Perl_sv_catpvf(aTHX_ report, "(ival=%"IVdf")", (IV)lvalp->ival);
420             break;
421         case TOKENTYPE_OPNUM:
422             Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
423                                     PL_op_name[lvalp->ival]);
424             break;
425         case TOKENTYPE_PVAL:
426             Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
427             break;
428         case TOKENTYPE_OPVAL:
429             if (lvalp->opval) {
430                 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
431                                     PL_op_name[lvalp->opval->op_type]);
432                 if (lvalp->opval->op_type == OP_CONST) {
433                     Perl_sv_catpvf(aTHX_ report, " %s",
434                         SvPEEK(cSVOPx_sv(lvalp->opval)));
435                 }
436
437             }
438             else
439                 sv_catpvs(report, "(opval=null)");
440             break;
441         }
442         PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
443     };
444     return (int)rv;
445 }
446
447
448 /* print the buffer with suitable escapes */
449
450 STATIC void
451 S_printbuf(pTHX_ const char *const fmt, const char *const s)
452 {
453     SV* const tmp = newSVpvs("");
454
455     PERL_ARGS_ASSERT_PRINTBUF;
456
457     GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
458     PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
459     GCC_DIAG_RESTORE;
460     SvREFCNT_dec(tmp);
461 }
462
463 #endif
464
465 static int
466 S_deprecate_commaless_var_list(pTHX) {
467     PL_expect = XTERM;
468     deprecate("comma-less variable list");
469     return REPORT(','); /* grandfather non-comma-format format */
470 }
471
472 /*
473  * S_ao
474  *
475  * This subroutine looks for an '=' next to the operator that has just been
476  * parsed and turns it into an ASSIGNOP if it finds one.
477  */
478
479 STATIC int
480 S_ao(pTHX_ int toketype)
481 {
482     if (*PL_bufptr == '=') {
483         PL_bufptr++;
484         if (toketype == ANDAND)
485             pl_yylval.ival = OP_ANDASSIGN;
486         else if (toketype == OROR)
487             pl_yylval.ival = OP_ORASSIGN;
488         else if (toketype == DORDOR)
489             pl_yylval.ival = OP_DORASSIGN;
490         toketype = ASSIGNOP;
491     }
492     return REPORT(toketype);
493 }
494
495 /*
496  * S_no_op
497  * When Perl expects an operator and finds something else, no_op
498  * prints the warning.  It always prints "<something> found where
499  * operator expected.  It prints "Missing semicolon on previous line?"
500  * if the surprise occurs at the start of the line.  "do you need to
501  * predeclare ..." is printed out for code like "sub bar; foo bar $x"
502  * where the compiler doesn't know if foo is a method call or a function.
503  * It prints "Missing operator before end of line" if there's nothing
504  * after the missing operator, or "... before <...>" if there is something
505  * after the missing operator.
506  *
507  * PL_bufptr is expected to point to the start of the thing that was found,
508  * and s after the next token or partial token.
509  */
510
511 STATIC void
512 S_no_op(pTHX_ const char *const what, char *s)
513 {
514     char * const oldbp = PL_bufptr;
515     const bool is_first = (PL_oldbufptr == PL_linestart);
516
517     PERL_ARGS_ASSERT_NO_OP;
518
519     if (!s)
520         s = oldbp;
521     else
522         PL_bufptr = s;
523     yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
524     if (ckWARN_d(WARN_SYNTAX)) {
525         if (is_first)
526             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
527                     "\t(Missing semicolon on previous line?)\n");
528         else if (PL_oldoldbufptr && isIDFIRST_lazy_if(PL_oldoldbufptr,UTF)) {
529             const char *t;
530             for (t = PL_oldoldbufptr; (isWORDCHAR_lazy_if(t,UTF) || *t == ':');
531                                                             t += UTF ? UTF8SKIP(t) : 1)
532                 NOOP;
533             if (t < PL_bufptr && isSPACE(*t))
534                 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
535                         "\t(Do you need to predeclare %"UTF8f"?)\n",
536                       UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
537         }
538         else {
539             assert(s >= oldbp);
540             Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
541                     "\t(Missing operator before %"UTF8f"?)\n",
542                      UTF8fARG(UTF, s - oldbp, oldbp));
543         }
544     }
545     PL_bufptr = oldbp;
546 }
547
548 /*
549  * S_missingterm
550  * Complain about missing quote/regexp/heredoc terminator.
551  * If it's called with NULL then it cauterizes the line buffer.
552  * If we're in a delimited string and the delimiter is a control
553  * character, it's reformatted into a two-char sequence like ^C.
554  * This is fatal.
555  */
556
557 STATIC void
558 S_missingterm(pTHX_ char *s)
559 {
560     char tmpbuf[3];
561     char q;
562     if (s) {
563         char * const nl = strrchr(s,'\n');
564         if (nl)
565             *nl = '\0';
566     }
567     else if ((U8) PL_multi_close < 32) {
568         *tmpbuf = '^';
569         tmpbuf[1] = (char)toCTRL(PL_multi_close);
570         tmpbuf[2] = '\0';
571         s = tmpbuf;
572     }
573     else {
574         *tmpbuf = (char)PL_multi_close;
575         tmpbuf[1] = '\0';
576         s = tmpbuf;
577     }
578     q = strchr(s,'"') ? '\'' : '"';
579     Perl_croak(aTHX_ "Can't find string terminator %c%s%c anywhere before EOF",q,s,q);
580 }
581
582 #include "feature.h"
583
584 /*
585  * Check whether the named feature is enabled.
586  */
587 bool
588 Perl_feature_is_enabled(pTHX_ const char *const name, STRLEN namelen)
589 {
590     char he_name[8 + MAX_FEATURE_LEN] = "feature_";
591
592     PERL_ARGS_ASSERT_FEATURE_IS_ENABLED;
593
594     assert(CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM);
595
596     if (namelen > MAX_FEATURE_LEN)
597         return FALSE;
598     memcpy(&he_name[8], name, namelen);
599
600     return cBOOL(cop_hints_fetch_pvn(PL_curcop, he_name, 8 + namelen, 0,
601                                      REFCOUNTED_HE_EXISTS));
602 }
603
604 /*
605  * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
606  * utf16-to-utf8-reversed.
607  */
608
609 #ifdef PERL_CR_FILTER
610 static void
611 strip_return(SV *sv)
612 {
613     const char *s = SvPVX_const(sv);
614     const char * const e = s + SvCUR(sv);
615
616     PERL_ARGS_ASSERT_STRIP_RETURN;
617
618     /* outer loop optimized to do nothing if there are no CR-LFs */
619     while (s < e) {
620         if (*s++ == '\r' && *s == '\n') {
621             /* hit a CR-LF, need to copy the rest */
622             char *d = s - 1;
623             *d++ = *s++;
624             while (s < e) {
625                 if (*s == '\r' && s[1] == '\n')
626                     s++;
627                 *d++ = *s++;
628             }
629             SvCUR(sv) -= s - d;
630             return;
631         }
632     }
633 }
634
635 STATIC I32
636 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
637 {
638     const I32 count = FILTER_READ(idx+1, sv, maxlen);
639     if (count > 0 && !maxlen)
640         strip_return(sv);
641     return count;
642 }
643 #endif
644
645 /*
646 =for apidoc Amx|void|lex_start|SV *line|PerlIO *rsfp|U32 flags
647
648 Creates and initialises a new lexer/parser state object, supplying
649 a context in which to lex and parse from a new source of Perl code.
650 A pointer to the new state object is placed in L</PL_parser>.  An entry
651 is made on the save stack so that upon unwinding the new state object
652 will be destroyed and the former value of L</PL_parser> will be restored.
653 Nothing else need be done to clean up the parsing context.
654
655 The code to be parsed comes from C<line> and C<rsfp>.  C<line>, if
656 non-null, provides a string (in SV form) containing code to be parsed.
657 A copy of the string is made, so subsequent modification of C<line>
658 does not affect parsing.  C<rsfp>, if non-null, provides an input stream
659 from which code will be read to be parsed.  If both are non-null, the
660 code in C<line> comes first and must consist of complete lines of input,
661 and C<rsfp> supplies the remainder of the source.
662
663 The C<flags> parameter is reserved for future use.  Currently it is only
664 used by perl internally, so extensions should always pass zero.
665
666 =cut
667 */
668
669 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
670    can share filters with the current parser.
671    LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
672    caller, hence isn't owned by the parser, so shouldn't be closed on parser
673    destruction. This is used to handle the case of defaulting to reading the
674    script from the standard input because no filename was given on the command
675    line (without getting confused by situation where STDIN has been closed, so
676    the script handle is opened on fd 0)  */
677
678 void
679 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
680 {
681     const char *s = NULL;
682     yy_parser *parser, *oparser;
683     if (flags && flags & ~LEX_START_FLAGS)
684         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
685
686     /* create and initialise a parser */
687
688     Newxz(parser, 1, yy_parser);
689     parser->old_parser = oparser = PL_parser;
690     PL_parser = parser;
691
692     parser->stack = NULL;
693     parser->ps = NULL;
694     parser->stack_size = 0;
695
696     /* on scope exit, free this parser and restore any outer one */
697     SAVEPARSER(parser);
698     parser->saved_curcop = PL_curcop;
699
700     /* initialise lexer state */
701
702     parser->nexttoke = 0;
703     parser->error_count = oparser ? oparser->error_count : 0;
704     parser->copline = parser->preambling = NOLINE;
705     parser->lex_state = LEX_NORMAL;
706     parser->expect = XSTATE;
707     parser->rsfp = rsfp;
708     parser->rsfp_filters =
709       !(flags & LEX_START_SAME_FILTER) || !oparser
710         ? NULL
711         : MUTABLE_AV(SvREFCNT_inc(
712             oparser->rsfp_filters
713              ? oparser->rsfp_filters
714              : (oparser->rsfp_filters = newAV())
715           ));
716
717     Newx(parser->lex_brackstack, 120, char);
718     Newx(parser->lex_casestack, 12, char);
719     *parser->lex_casestack = '\0';
720     Newxz(parser->lex_shared, 1, LEXSHARED);
721
722     if (line) {
723         STRLEN len;
724         s = SvPV_const(line, len);
725         parser->linestr = flags & LEX_START_COPIED
726                             ? SvREFCNT_inc_simple_NN(line)
727                             : newSVpvn_flags(s, len, SvUTF8(line));
728         sv_catpvn(parser->linestr, "\n;", rsfp ? 1 : 2);
729     } else {
730         parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
731     }
732     parser->oldoldbufptr =
733         parser->oldbufptr =
734         parser->bufptr =
735         parser->linestart = SvPVX(parser->linestr);
736     parser->bufend = parser->bufptr + SvCUR(parser->linestr);
737     parser->last_lop = parser->last_uni = NULL;
738
739     STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
740                                                         |LEX_DONT_CLOSE_RSFP));
741     parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
742                                                         |LEX_DONT_CLOSE_RSFP));
743
744     parser->in_pod = parser->filtered = 0;
745 }
746
747
748 /* delete a parser object */
749
750 void
751 Perl_parser_free(pTHX_  const yy_parser *parser)
752 {
753     PERL_ARGS_ASSERT_PARSER_FREE;
754
755     PL_curcop = parser->saved_curcop;
756     SvREFCNT_dec(parser->linestr);
757
758     if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
759         PerlIO_clearerr(parser->rsfp);
760     else if (parser->rsfp && (!parser->old_parser
761           || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
762         PerlIO_close(parser->rsfp);
763     SvREFCNT_dec(parser->rsfp_filters);
764     SvREFCNT_dec(parser->lex_stuff);
765     SvREFCNT_dec(parser->sublex_info.repl);
766
767     Safefree(parser->lex_brackstack);
768     Safefree(parser->lex_casestack);
769     Safefree(parser->lex_shared);
770     PL_parser = parser->old_parser;
771     Safefree(parser);
772 }
773
774 void
775 Perl_parser_free_nexttoke_ops(pTHX_  yy_parser *parser, OPSLAB *slab)
776 {
777     I32 nexttoke = parser->nexttoke;
778     PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
779     while (nexttoke--) {
780         if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
781          && parser->nextval[nexttoke].opval
782          && parser->nextval[nexttoke].opval->op_slabbed
783          && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
784             op_free(parser->nextval[nexttoke].opval);
785             parser->nextval[nexttoke].opval = NULL;
786         }
787     }
788 }
789
790
791 /*
792 =for apidoc AmxU|SV *|PL_parser-E<gt>linestr
793
794 Buffer scalar containing the chunk currently under consideration of the
795 text currently being lexed.  This is always a plain string scalar (for
796 which C<SvPOK> is true).  It is not intended to be used as a scalar by
797 normal scalar means; instead refer to the buffer directly by the pointer
798 variables described below.
799
800 The lexer maintains various C<char*> pointers to things in the
801 C<PL_parser-E<gt>linestr> buffer.  If C<PL_parser-E<gt>linestr> is ever
802 reallocated, all of these pointers must be updated.  Don't attempt to
803 do this manually, but rather use L</lex_grow_linestr> if you need to
804 reallocate the buffer.
805
806 The content of the text chunk in the buffer is commonly exactly one
807 complete line of input, up to and including a newline terminator,
808 but there are situations where it is otherwise.  The octets of the
809 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
810 The function L</lex_bufutf8> tells you which.  Do not use the C<SvUTF8>
811 flag on this scalar, which may disagree with it.
812
813 For direct examination of the buffer, the variable
814 L</PL_parser-E<gt>bufend> points to the end of the buffer.  The current
815 lexing position is pointed to by L</PL_parser-E<gt>bufptr>.  Direct use
816 of these pointers is usually preferable to examination of the scalar
817 through normal scalar means.
818
819 =for apidoc AmxU|char *|PL_parser-E<gt>bufend
820
821 Direct pointer to the end of the chunk of text currently being lexed, the
822 end of the lexer buffer.  This is equal to C<SvPVX(PL_parser-E<gt>linestr)
823 + SvCUR(PL_parser-E<gt>linestr)>.  A C<NUL> character (zero octet) is
824 always located at the end of the buffer, and does not count as part of
825 the buffer's contents.
826
827 =for apidoc AmxU|char *|PL_parser-E<gt>bufptr
828
829 Points to the current position of lexing inside the lexer buffer.
830 Characters around this point may be freely examined, within
831 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
832 L</PL_parser-E<gt>bufend>.  The octets of the buffer may be intended to be
833 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
834
835 Lexing code (whether in the Perl core or not) moves this pointer past
836 the characters that it consumes.  It is also expected to perform some
837 bookkeeping whenever a newline character is consumed.  This movement
838 can be more conveniently performed by the function L</lex_read_to>,
839 which handles newlines appropriately.
840
841 Interpretation of the buffer's octets can be abstracted out by
842 using the slightly higher-level functions L</lex_peek_unichar> and
843 L</lex_read_unichar>.
844
845 =for apidoc AmxU|char *|PL_parser-E<gt>linestart
846
847 Points to the start of the current line inside the lexer buffer.
848 This is useful for indicating at which column an error occurred, and
849 not much else.  This must be updated by any lexing code that consumes
850 a newline; the function L</lex_read_to> handles this detail.
851
852 =cut
853 */
854
855 /*
856 =for apidoc Amx|bool|lex_bufutf8
857
858 Indicates whether the octets in the lexer buffer
859 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
860 of Unicode characters.  If not, they should be interpreted as Latin-1
861 characters.  This is analogous to the C<SvUTF8> flag for scalars.
862
863 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
864 contains valid UTF-8.  Lexing code must be robust in the face of invalid
865 encoding.
866
867 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
868 is significant, but not the whole story regarding the input character
869 encoding.  Normally, when a file is being read, the scalar contains octets
870 and its C<SvUTF8> flag is off, but the octets should be interpreted as
871 UTF-8 if the C<use utf8> pragma is in effect.  During a string eval,
872 however, the scalar may have the C<SvUTF8> flag on, and in this case its
873 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
874 is in effect.  This logic may change in the future; use this function
875 instead of implementing the logic yourself.
876
877 =cut
878 */
879
880 bool
881 Perl_lex_bufutf8(pTHX)
882 {
883     return UTF;
884 }
885
886 /*
887 =for apidoc Amx|char *|lex_grow_linestr|STRLEN len
888
889 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
890 at least C<len> octets (including terminating C<NUL>).  Returns a
891 pointer to the reallocated buffer.  This is necessary before making
892 any direct modification of the buffer that would increase its length.
893 L</lex_stuff_pvn> provides a more convenient way to insert text into
894 the buffer.
895
896 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
897 this function updates all of the lexer's variables that point directly
898 into the buffer.
899
900 =cut
901 */
902
903 char *
904 Perl_lex_grow_linestr(pTHX_ STRLEN len)
905 {
906     SV *linestr;
907     char *buf;
908     STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
909     STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
910     linestr = PL_parser->linestr;
911     buf = SvPVX(linestr);
912     if (len <= SvLEN(linestr))
913         return buf;
914     bufend_pos = PL_parser->bufend - buf;
915     bufptr_pos = PL_parser->bufptr - buf;
916     oldbufptr_pos = PL_parser->oldbufptr - buf;
917     oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
918     linestart_pos = PL_parser->linestart - buf;
919     last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
920     last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
921     re_eval_start_pos = PL_parser->lex_shared->re_eval_start ?
922                             PL_parser->lex_shared->re_eval_start - buf : 0;
923
924     buf = sv_grow(linestr, len);
925
926     PL_parser->bufend = buf + bufend_pos;
927     PL_parser->bufptr = buf + bufptr_pos;
928     PL_parser->oldbufptr = buf + oldbufptr_pos;
929     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
930     PL_parser->linestart = buf + linestart_pos;
931     if (PL_parser->last_uni)
932         PL_parser->last_uni = buf + last_uni_pos;
933     if (PL_parser->last_lop)
934         PL_parser->last_lop = buf + last_lop_pos;
935     if (PL_parser->lex_shared->re_eval_start)
936         PL_parser->lex_shared->re_eval_start  = buf + re_eval_start_pos;
937     return buf;
938 }
939
940 /*
941 =for apidoc Amx|void|lex_stuff_pvn|const char *pv|STRLEN len|U32 flags
942
943 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
944 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
945 reallocating the buffer if necessary.  This means that lexing code that
946 runs later will see the characters as if they had appeared in the input.
947 It is not recommended to do this as part of normal parsing, and most
948 uses of this facility run the risk of the inserted characters being
949 interpreted in an unintended manner.
950
951 The string to be inserted is represented by C<len> octets starting
952 at C<pv>.  These octets are interpreted as either UTF-8 or Latin-1,
953 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
954 The characters are recoded for the lexer buffer, according to how the
955 buffer is currently being interpreted (L</lex_bufutf8>).  If a string
956 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
957 function is more convenient.
958
959 =cut
960 */
961
962 void
963 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
964 {
965     dVAR;
966     char *bufptr;
967     PERL_ARGS_ASSERT_LEX_STUFF_PVN;
968     if (flags & ~(LEX_STUFF_UTF8))
969         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
970     if (UTF) {
971         if (flags & LEX_STUFF_UTF8) {
972             goto plain_copy;
973         } else {
974             STRLEN highhalf = 0;    /* Count of variants */
975             const char *p, *e = pv+len;
976             for (p = pv; p != e; p++) {
977                 if (! UTF8_IS_INVARIANT(*p)) {
978                     highhalf++;
979                 }
980             }
981             if (!highhalf)
982                 goto plain_copy;
983             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
984             bufptr = PL_parser->bufptr;
985             Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
986             SvCUR_set(PL_parser->linestr,
987                 SvCUR(PL_parser->linestr) + len+highhalf);
988             PL_parser->bufend += len+highhalf;
989             for (p = pv; p != e; p++) {
990                 U8 c = (U8)*p;
991                 if (! UTF8_IS_INVARIANT(c)) {
992                     *bufptr++ = UTF8_TWO_BYTE_HI(c);
993                     *bufptr++ = UTF8_TWO_BYTE_LO(c);
994                 } else {
995                     *bufptr++ = (char)c;
996                 }
997             }
998         }
999     } else {
1000         if (flags & LEX_STUFF_UTF8) {
1001             STRLEN highhalf = 0;
1002             const char *p, *e = pv+len;
1003             for (p = pv; p != e; p++) {
1004                 U8 c = (U8)*p;
1005                 if (UTF8_IS_ABOVE_LATIN1(c)) {
1006                     Perl_croak(aTHX_ "Lexing code attempted to stuff "
1007                                 "non-Latin-1 character into Latin-1 input");
1008                 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1009                     p++;
1010                     highhalf++;
1011                 } else if (! UTF8_IS_INVARIANT(c)) {
1012                     /* malformed UTF-8 */
1013                     ENTER;
1014                     SAVESPTR(PL_warnhook);
1015                     PL_warnhook = PERL_WARNHOOK_FATAL;
1016                     utf8n_to_uvchr((U8*)p, e-p, NULL, 0);
1017                     LEAVE;
1018                 }
1019             }
1020             if (!highhalf)
1021                 goto plain_copy;
1022             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1023             bufptr = PL_parser->bufptr;
1024             Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1025             SvCUR_set(PL_parser->linestr,
1026                 SvCUR(PL_parser->linestr) + len-highhalf);
1027             PL_parser->bufend += len-highhalf;
1028             p = pv;
1029             while (p < e) {
1030                 if (UTF8_IS_INVARIANT(*p)) {
1031                     *bufptr++ = *p;
1032                     p++;
1033                 }
1034                 else {
1035                     assert(p < e -1 );
1036                     *bufptr++ = TWO_BYTE_UTF8_TO_NATIVE(*p, *(p+1));
1037                     p += 2;
1038                 }
1039             }
1040         } else {
1041           plain_copy:
1042             lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1043             bufptr = PL_parser->bufptr;
1044             Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1045             SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1046             PL_parser->bufend += len;
1047             Copy(pv, bufptr, len, char);
1048         }
1049     }
1050 }
1051
1052 /*
1053 =for apidoc Amx|void|lex_stuff_pv|const char *pv|U32 flags
1054
1055 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1056 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1057 reallocating the buffer if necessary.  This means that lexing code that
1058 runs later will see the characters as if they had appeared in the input.
1059 It is not recommended to do this as part of normal parsing, and most
1060 uses of this facility run the risk of the inserted characters being
1061 interpreted in an unintended manner.
1062
1063 The string to be inserted is represented by octets starting at C<pv>
1064 and continuing to the first nul.  These octets are interpreted as either
1065 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1066 in C<flags>.  The characters are recoded for the lexer buffer, according
1067 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1068 If it is not convenient to nul-terminate a string to be inserted, the
1069 L</lex_stuff_pvn> function is more appropriate.
1070
1071 =cut
1072 */
1073
1074 void
1075 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1076 {
1077     PERL_ARGS_ASSERT_LEX_STUFF_PV;
1078     lex_stuff_pvn(pv, strlen(pv), flags);
1079 }
1080
1081 /*
1082 =for apidoc Amx|void|lex_stuff_sv|SV *sv|U32 flags
1083
1084 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1085 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1086 reallocating the buffer if necessary.  This means that lexing code that
1087 runs later will see the characters as if they had appeared in the input.
1088 It is not recommended to do this as part of normal parsing, and most
1089 uses of this facility run the risk of the inserted characters being
1090 interpreted in an unintended manner.
1091
1092 The string to be inserted is the string value of C<sv>.  The characters
1093 are recoded for the lexer buffer, according to how the buffer is currently
1094 being interpreted (L</lex_bufutf8>).  If a string to be inserted is
1095 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1096 need to construct a scalar.
1097
1098 =cut
1099 */
1100
1101 void
1102 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1103 {
1104     char *pv;
1105     STRLEN len;
1106     PERL_ARGS_ASSERT_LEX_STUFF_SV;
1107     if (flags)
1108         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1109     pv = SvPV(sv, len);
1110     lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1111 }
1112
1113 /*
1114 =for apidoc Amx|void|lex_unstuff|char *ptr
1115
1116 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1117 C<ptr>.  Text following C<ptr> will be moved, and the buffer shortened.
1118 This hides the discarded text from any lexing code that runs later,
1119 as if the text had never appeared.
1120
1121 This is not the normal way to consume lexed text.  For that, use
1122 L</lex_read_to>.
1123
1124 =cut
1125 */
1126
1127 void
1128 Perl_lex_unstuff(pTHX_ char *ptr)
1129 {
1130     char *buf, *bufend;
1131     STRLEN unstuff_len;
1132     PERL_ARGS_ASSERT_LEX_UNSTUFF;
1133     buf = PL_parser->bufptr;
1134     if (ptr < buf)
1135         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1136     if (ptr == buf)
1137         return;
1138     bufend = PL_parser->bufend;
1139     if (ptr > bufend)
1140         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1141     unstuff_len = ptr - buf;
1142     Move(ptr, buf, bufend+1-ptr, char);
1143     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1144     PL_parser->bufend = bufend - unstuff_len;
1145 }
1146
1147 /*
1148 =for apidoc Amx|void|lex_read_to|char *ptr
1149
1150 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1151 to C<ptr>.  This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1152 performing the correct bookkeeping whenever a newline character is passed.
1153 This is the normal way to consume lexed text.
1154
1155 Interpretation of the buffer's octets can be abstracted out by
1156 using the slightly higher-level functions L</lex_peek_unichar> and
1157 L</lex_read_unichar>.
1158
1159 =cut
1160 */
1161
1162 void
1163 Perl_lex_read_to(pTHX_ char *ptr)
1164 {
1165     char *s;
1166     PERL_ARGS_ASSERT_LEX_READ_TO;
1167     s = PL_parser->bufptr;
1168     if (ptr < s || ptr > PL_parser->bufend)
1169         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1170     for (; s != ptr; s++)
1171         if (*s == '\n') {
1172             COPLINE_INC_WITH_HERELINES;
1173             PL_parser->linestart = s+1;
1174         }
1175     PL_parser->bufptr = ptr;
1176 }
1177
1178 /*
1179 =for apidoc Amx|void|lex_discard_to|char *ptr
1180
1181 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1182 up to C<ptr>.  The remaining content of the buffer will be moved, and
1183 all pointers into the buffer updated appropriately.  C<ptr> must not
1184 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1185 it is not permitted to discard text that has yet to be lexed.
1186
1187 Normally it is not necessarily to do this directly, because it suffices to
1188 use the implicit discarding behaviour of L</lex_next_chunk> and things
1189 based on it.  However, if a token stretches across multiple lines,
1190 and the lexing code has kept multiple lines of text in the buffer for
1191 that purpose, then after completion of the token it would be wise to
1192 explicitly discard the now-unneeded earlier lines, to avoid future
1193 multi-line tokens growing the buffer without bound.
1194
1195 =cut
1196 */
1197
1198 void
1199 Perl_lex_discard_to(pTHX_ char *ptr)
1200 {
1201     char *buf;
1202     STRLEN discard_len;
1203     PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1204     buf = SvPVX(PL_parser->linestr);
1205     if (ptr < buf)
1206         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1207     if (ptr == buf)
1208         return;
1209     if (ptr > PL_parser->bufptr)
1210         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1211     discard_len = ptr - buf;
1212     if (PL_parser->oldbufptr < ptr)
1213         PL_parser->oldbufptr = ptr;
1214     if (PL_parser->oldoldbufptr < ptr)
1215         PL_parser->oldoldbufptr = ptr;
1216     if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1217         PL_parser->last_uni = NULL;
1218     if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1219         PL_parser->last_lop = NULL;
1220     Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1221     SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1222     PL_parser->bufend -= discard_len;
1223     PL_parser->bufptr -= discard_len;
1224     PL_parser->oldbufptr -= discard_len;
1225     PL_parser->oldoldbufptr -= discard_len;
1226     if (PL_parser->last_uni)
1227         PL_parser->last_uni -= discard_len;
1228     if (PL_parser->last_lop)
1229         PL_parser->last_lop -= discard_len;
1230 }
1231
1232 /*
1233 =for apidoc Amx|bool|lex_next_chunk|U32 flags
1234
1235 Reads in the next chunk of text to be lexed, appending it to
1236 L</PL_parser-E<gt>linestr>.  This should be called when lexing code has
1237 looked to the end of the current chunk and wants to know more.  It is
1238 usual, but not necessary, for lexing to have consumed the entirety of
1239 the current chunk at this time.
1240
1241 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1242 chunk (i.e., the current chunk has been entirely consumed), normally the
1243 current chunk will be discarded at the same time that the new chunk is
1244 read in.  If C<flags> includes C<LEX_KEEP_PREVIOUS>, the current chunk
1245 will not be discarded.  If the current chunk has not been entirely
1246 consumed, then it will not be discarded regardless of the flag.
1247
1248 Returns true if some new text was added to the buffer, or false if the
1249 buffer has reached the end of the input text.
1250
1251 =cut
1252 */
1253
1254 #define LEX_FAKE_EOF 0x80000000
1255 #define LEX_NO_TERM  0x40000000 /* here-doc */
1256
1257 bool
1258 Perl_lex_next_chunk(pTHX_ U32 flags)
1259 {
1260     SV *linestr;
1261     char *buf;
1262     STRLEN old_bufend_pos, new_bufend_pos;
1263     STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1264     STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1265     bool got_some_for_debugger = 0;
1266     bool got_some;
1267     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1268         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1269     if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1270         return FALSE;
1271     linestr = PL_parser->linestr;
1272     buf = SvPVX(linestr);
1273     if (!(flags & LEX_KEEP_PREVIOUS)
1274           && PL_parser->bufptr == PL_parser->bufend)
1275     {
1276         old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1277         linestart_pos = 0;
1278         if (PL_parser->last_uni != PL_parser->bufend)
1279             PL_parser->last_uni = NULL;
1280         if (PL_parser->last_lop != PL_parser->bufend)
1281             PL_parser->last_lop = NULL;
1282         last_uni_pos = last_lop_pos = 0;
1283         *buf = 0;
1284         SvCUR(linestr) = 0;
1285     } else {
1286         old_bufend_pos = PL_parser->bufend - buf;
1287         bufptr_pos = PL_parser->bufptr - buf;
1288         oldbufptr_pos = PL_parser->oldbufptr - buf;
1289         oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1290         linestart_pos = PL_parser->linestart - buf;
1291         last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1292         last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1293     }
1294     if (flags & LEX_FAKE_EOF) {
1295         goto eof;
1296     } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1297         got_some = 0;
1298     } else if (filter_gets(linestr, old_bufend_pos)) {
1299         got_some = 1;
1300         got_some_for_debugger = 1;
1301     } else if (flags & LEX_NO_TERM) {
1302         got_some = 0;
1303     } else {
1304         if (!SvPOK(linestr))   /* can get undefined by filter_gets */
1305             sv_setpvs(linestr, "");
1306         eof:
1307         /* End of real input.  Close filehandle (unless it was STDIN),
1308          * then add implicit termination.
1309          */
1310         if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1311             PerlIO_clearerr(PL_parser->rsfp);
1312         else if (PL_parser->rsfp)
1313             (void)PerlIO_close(PL_parser->rsfp);
1314         PL_parser->rsfp = NULL;
1315         PL_parser->in_pod = PL_parser->filtered = 0;
1316         if (!PL_in_eval && PL_minus_p) {
1317             sv_catpvs(linestr,
1318                 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1319             PL_minus_n = PL_minus_p = 0;
1320         } else if (!PL_in_eval && PL_minus_n) {
1321             sv_catpvs(linestr, /*{*/";}");
1322             PL_minus_n = 0;
1323         } else
1324             sv_catpvs(linestr, ";");
1325         got_some = 1;
1326     }
1327     buf = SvPVX(linestr);
1328     new_bufend_pos = SvCUR(linestr);
1329     PL_parser->bufend = buf + new_bufend_pos;
1330     PL_parser->bufptr = buf + bufptr_pos;
1331     PL_parser->oldbufptr = buf + oldbufptr_pos;
1332     PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1333     PL_parser->linestart = buf + linestart_pos;
1334     if (PL_parser->last_uni)
1335         PL_parser->last_uni = buf + last_uni_pos;
1336     if (PL_parser->last_lop)
1337         PL_parser->last_lop = buf + last_lop_pos;
1338     if (PL_parser->preambling != NOLINE) {
1339         CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1340         PL_parser->preambling = NOLINE;
1341     }
1342     if (   got_some_for_debugger
1343         && PERLDB_LINE_OR_SAVESRC
1344         && PL_curstash != PL_debstash)
1345     {
1346         /* debugger active and we're not compiling the debugger code,
1347          * so store the line into the debugger's array of lines
1348          */
1349         update_debugger_info(NULL, buf+old_bufend_pos,
1350             new_bufend_pos-old_bufend_pos);
1351     }
1352     return got_some;
1353 }
1354
1355 /*
1356 =for apidoc Amx|I32|lex_peek_unichar|U32 flags
1357
1358 Looks ahead one (Unicode) character in the text currently being lexed.
1359 Returns the codepoint (unsigned integer value) of the next character,
1360 or -1 if lexing has reached the end of the input text.  To consume the
1361 peeked character, use L</lex_read_unichar>.
1362
1363 If the next character is in (or extends into) the next chunk of input
1364 text, the next chunk will be read in.  Normally the current chunk will be
1365 discarded at the same time, but if C<flags> includes C<LEX_KEEP_PREVIOUS>
1366 then the current chunk will not be discarded.
1367
1368 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1369 is encountered, an exception is generated.
1370
1371 =cut
1372 */
1373
1374 I32
1375 Perl_lex_peek_unichar(pTHX_ U32 flags)
1376 {
1377     dVAR;
1378     char *s, *bufend;
1379     if (flags & ~(LEX_KEEP_PREVIOUS))
1380         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1381     s = PL_parser->bufptr;
1382     bufend = PL_parser->bufend;
1383     if (UTF) {
1384         U8 head;
1385         I32 unichar;
1386         STRLEN len, retlen;
1387         if (s == bufend) {
1388             if (!lex_next_chunk(flags))
1389                 return -1;
1390             s = PL_parser->bufptr;
1391             bufend = PL_parser->bufend;
1392         }
1393         head = (U8)*s;
1394         if (UTF8_IS_INVARIANT(head))
1395             return head;
1396         if (UTF8_IS_START(head)) {
1397             len = UTF8SKIP(&head);
1398             while ((STRLEN)(bufend-s) < len) {
1399                 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1400                     break;
1401                 s = PL_parser->bufptr;
1402                 bufend = PL_parser->bufend;
1403             }
1404         }
1405         unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1406         if (retlen == (STRLEN)-1) {
1407             /* malformed UTF-8 */
1408             ENTER;
1409             SAVESPTR(PL_warnhook);
1410             PL_warnhook = PERL_WARNHOOK_FATAL;
1411             utf8n_to_uvchr((U8*)s, bufend-s, NULL, 0);
1412             LEAVE;
1413         }
1414         return unichar;
1415     } else {
1416         if (s == bufend) {
1417             if (!lex_next_chunk(flags))
1418                 return -1;
1419             s = PL_parser->bufptr;
1420         }
1421         return (U8)*s;
1422     }
1423 }
1424
1425 /*
1426 =for apidoc Amx|I32|lex_read_unichar|U32 flags
1427
1428 Reads the next (Unicode) character in the text currently being lexed.
1429 Returns the codepoint (unsigned integer value) of the character read,
1430 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1431 if lexing has reached the end of the input text.  To non-destructively
1432 examine the next character, use L</lex_peek_unichar> instead.
1433
1434 If the next character is in (or extends into) the next chunk of input
1435 text, the next chunk will be read in.  Normally the current chunk will be
1436 discarded at the same time, but if C<flags> includes C<LEX_KEEP_PREVIOUS>
1437 then the current chunk will not be discarded.
1438
1439 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1440 is encountered, an exception is generated.
1441
1442 =cut
1443 */
1444
1445 I32
1446 Perl_lex_read_unichar(pTHX_ U32 flags)
1447 {
1448     I32 c;
1449     if (flags & ~(LEX_KEEP_PREVIOUS))
1450         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1451     c = lex_peek_unichar(flags);
1452     if (c != -1) {
1453         if (c == '\n')
1454             COPLINE_INC_WITH_HERELINES;
1455         if (UTF)
1456             PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1457         else
1458             ++(PL_parser->bufptr);
1459     }
1460     return c;
1461 }
1462
1463 /*
1464 =for apidoc Amx|void|lex_read_space|U32 flags
1465
1466 Reads optional spaces, in Perl style, in the text currently being
1467 lexed.  The spaces may include ordinary whitespace characters and
1468 Perl-style comments.  C<#line> directives are processed if encountered.
1469 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1470 at a non-space character (or the end of the input text).
1471
1472 If spaces extend into the next chunk of input text, the next chunk will
1473 be read in.  Normally the current chunk will be discarded at the same
1474 time, but if C<flags> includes C<LEX_KEEP_PREVIOUS> then the current
1475 chunk will not be discarded.
1476
1477 =cut
1478 */
1479
1480 #define LEX_NO_INCLINE    0x40000000
1481 #define LEX_NO_NEXT_CHUNK 0x80000000
1482
1483 void
1484 Perl_lex_read_space(pTHX_ U32 flags)
1485 {
1486     char *s, *bufend;
1487     const bool can_incline = !(flags & LEX_NO_INCLINE);
1488     bool need_incline = 0;
1489     if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1490         Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1491     s = PL_parser->bufptr;
1492     bufend = PL_parser->bufend;
1493     while (1) {
1494         char c = *s;
1495         if (c == '#') {
1496             do {
1497                 c = *++s;
1498             } while (!(c == '\n' || (c == 0 && s == bufend)));
1499         } else if (c == '\n') {
1500             s++;
1501             if (can_incline) {
1502                 PL_parser->linestart = s;
1503                 if (s == bufend)
1504                     need_incline = 1;
1505                 else
1506                     incline(s);
1507             }
1508         } else if (isSPACE(c)) {
1509             s++;
1510         } else if (c == 0 && s == bufend) {
1511             bool got_more;
1512             line_t l;
1513             if (flags & LEX_NO_NEXT_CHUNK)
1514                 break;
1515             PL_parser->bufptr = s;
1516             l = CopLINE(PL_curcop);
1517             CopLINE(PL_curcop) += PL_parser->herelines + 1;
1518             got_more = lex_next_chunk(flags);
1519             CopLINE_set(PL_curcop, l);
1520             s = PL_parser->bufptr;
1521             bufend = PL_parser->bufend;
1522             if (!got_more)
1523                 break;
1524             if (can_incline && need_incline && PL_parser->rsfp) {
1525                 incline(s);
1526                 need_incline = 0;
1527             }
1528         } else if (!c) {
1529             s++;
1530         } else {
1531             break;
1532         }
1533     }
1534     PL_parser->bufptr = s;
1535 }
1536
1537 /*
1538
1539 =for apidoc EXMp|bool|validate_proto|SV *name|SV *proto|bool warn
1540
1541 This function performs syntax checking on a prototype, C<proto>.
1542 If C<warn> is true, any illegal characters or mismatched brackets
1543 will trigger illegalproto warnings, declaring that they were
1544 detected in the prototype for C<name>.
1545
1546 The return value is C<true> if this is a valid prototype, and
1547 C<false> if it is not, regardless of whether C<warn> was C<true> or
1548 C<false>.
1549
1550 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1551
1552 =cut
1553
1554  */
1555
1556 bool
1557 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn)
1558 {
1559     STRLEN len, origlen;
1560     char *p = proto ? SvPV(proto, len) : NULL;
1561     bool bad_proto = FALSE;
1562     bool in_brackets = FALSE;
1563     bool after_slash = FALSE;
1564     char greedy_proto = ' ';
1565     bool proto_after_greedy_proto = FALSE;
1566     bool must_be_last = FALSE;
1567     bool underscore = FALSE;
1568     bool bad_proto_after_underscore = FALSE;
1569
1570     PERL_ARGS_ASSERT_VALIDATE_PROTO;
1571
1572     if (!proto)
1573         return TRUE;
1574
1575     origlen = len;
1576     for (; len--; p++) {
1577         if (!isSPACE(*p)) {
1578             if (must_be_last)
1579                 proto_after_greedy_proto = TRUE;
1580             if (underscore) {
1581                 if (!strchr(";@%", *p))
1582                     bad_proto_after_underscore = TRUE;
1583                 underscore = FALSE;
1584             }
1585             if (!strchr("$@%*;[]&\\_+", *p) || *p == '\0') {
1586                 bad_proto = TRUE;
1587             }
1588             else {
1589                 if (*p == '[')
1590                     in_brackets = TRUE;
1591                 else if (*p == ']')
1592                     in_brackets = FALSE;
1593                 else if ((*p == '@' || *p == '%')
1594                          && !after_slash
1595                          && !in_brackets )
1596                 {
1597                     must_be_last = TRUE;
1598                     greedy_proto = *p;
1599                 }
1600                 else if (*p == '_')
1601                     underscore = TRUE;
1602             }
1603             if (*p == '\\')
1604                 after_slash = TRUE;
1605             else
1606                 after_slash = FALSE;
1607         }
1608     }
1609
1610     if (warn) {
1611         SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1612         p -= origlen;
1613         p = SvUTF8(proto)
1614             ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1615                              origlen, UNI_DISPLAY_ISPRINT)
1616             : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1617
1618         if (proto_after_greedy_proto)
1619             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1620                         "Prototype after '%c' for %"SVf" : %s",
1621                         greedy_proto, SVfARG(name), p);
1622         if (in_brackets)
1623             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1624                         "Missing ']' in prototype for %"SVf" : %s",
1625                         SVfARG(name), p);
1626         if (bad_proto)
1627             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1628                         "Illegal character in prototype for %"SVf" : %s",
1629                         SVfARG(name), p);
1630         if (bad_proto_after_underscore)
1631             Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1632                         "Illegal character after '_' in prototype for %"SVf" : %s",
1633                         SVfARG(name), p);
1634     }
1635
1636     return (! (proto_after_greedy_proto || bad_proto) );
1637 }
1638
1639 /*
1640  * S_incline
1641  * This subroutine has nothing to do with tilting, whether at windmills
1642  * or pinball tables.  Its name is short for "increment line".  It
1643  * increments the current line number in CopLINE(PL_curcop) and checks
1644  * to see whether the line starts with a comment of the form
1645  *    # line 500 "foo.pm"
1646  * If so, it sets the current line number and file to the values in the comment.
1647  */
1648
1649 STATIC void
1650 S_incline(pTHX_ const char *s)
1651 {
1652     const char *t;
1653     const char *n;
1654     const char *e;
1655     line_t line_num;
1656     UV uv;
1657
1658     PERL_ARGS_ASSERT_INCLINE;
1659
1660     COPLINE_INC_WITH_HERELINES;
1661     if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1662      && s+1 == PL_bufend && *s == ';') {
1663         /* fake newline in string eval */
1664         CopLINE_dec(PL_curcop);
1665         return;
1666     }
1667     if (*s++ != '#')
1668         return;
1669     while (SPACE_OR_TAB(*s))
1670         s++;
1671     if (strnEQ(s, "line", 4))
1672         s += 4;
1673     else
1674         return;
1675     if (SPACE_OR_TAB(*s))
1676         s++;
1677     else
1678         return;
1679     while (SPACE_OR_TAB(*s))
1680         s++;
1681     if (!isDIGIT(*s))
1682         return;
1683
1684     n = s;
1685     while (isDIGIT(*s))
1686         s++;
1687     if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1688         return;
1689     while (SPACE_OR_TAB(*s))
1690         s++;
1691     if (*s == '"' && (t = strchr(s+1, '"'))) {
1692         s++;
1693         e = t + 1;
1694     }
1695     else {
1696         t = s;
1697         while (!isSPACE(*t))
1698             t++;
1699         e = t;
1700     }
1701     while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1702         e++;
1703     if (*e != '\n' && *e != '\0')
1704         return;         /* false alarm */
1705
1706     if (!grok_atoUV(n, &uv, &e))
1707         return;
1708     line_num = ((line_t)uv) - 1;
1709
1710     if (t - s > 0) {
1711         const STRLEN len = t - s;
1712
1713         if (!PL_rsfp && !PL_parser->filtered) {
1714             /* must copy *{"::_<(eval N)[oldfilename:L]"}
1715              * to *{"::_<newfilename"} */
1716             /* However, the long form of evals is only turned on by the
1717                debugger - usually they're "(eval %lu)" */
1718             GV * const cfgv = CopFILEGV(PL_curcop);
1719             if (cfgv) {
1720                 char smallbuf[128];
1721                 STRLEN tmplen2 = len;
1722                 char *tmpbuf2;
1723                 GV *gv2;
1724
1725                 if (tmplen2 + 2 <= sizeof smallbuf)
1726                     tmpbuf2 = smallbuf;
1727                 else
1728                     Newx(tmpbuf2, tmplen2 + 2, char);
1729
1730                 tmpbuf2[0] = '_';
1731                 tmpbuf2[1] = '<';
1732
1733                 memcpy(tmpbuf2 + 2, s, tmplen2);
1734                 tmplen2 += 2;
1735
1736                 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1737                 if (!isGV(gv2)) {
1738                     gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1739                     /* adjust ${"::_<newfilename"} to store the new file name */
1740                     GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1741                     /* The line number may differ. If that is the case,
1742                        alias the saved lines that are in the array.
1743                        Otherwise alias the whole array. */
1744                     if (CopLINE(PL_curcop) == line_num) {
1745                         GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1746                         GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1747                     }
1748                     else if (GvAV(cfgv)) {
1749                         AV * const av = GvAV(cfgv);
1750                         const I32 start = CopLINE(PL_curcop)+1;
1751                         I32 items = AvFILLp(av) - start;
1752                         if (items > 0) {
1753                             AV * const av2 = GvAVn(gv2);
1754                             SV **svp = AvARRAY(av) + start;
1755                             I32 l = (I32)line_num+1;
1756                             while (items--)
1757                                 av_store(av2, l++, SvREFCNT_inc(*svp++));
1758                         }
1759                     }
1760                 }
1761
1762                 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1763             }
1764         }
1765         CopFILE_free(PL_curcop);
1766         CopFILE_setn(PL_curcop, s, len);
1767     }
1768     CopLINE_set(PL_curcop, line_num);
1769 }
1770
1771 #define skipspace(s) skipspace_flags(s, 0)
1772
1773
1774 STATIC void
1775 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1776 {
1777     AV *av = CopFILEAVx(PL_curcop);
1778     if (av) {
1779         SV * sv;
1780         if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1781         else {
1782             sv = *av_fetch(av, 0, 1);
1783             SvUPGRADE(sv, SVt_PVMG);
1784         }
1785         if (!SvPOK(sv)) sv_setpvs(sv,"");
1786         if (orig_sv)
1787             sv_catsv(sv, orig_sv);
1788         else
1789             sv_catpvn(sv, buf, len);
1790         if (!SvIOK(sv)) {
1791             (void)SvIOK_on(sv);
1792             SvIV_set(sv, 0);
1793         }
1794         if (PL_parser->preambling == NOLINE)
1795             av_store(av, CopLINE(PL_curcop), sv);
1796     }
1797 }
1798
1799 /*
1800  * S_skipspace
1801  * Called to gobble the appropriate amount and type of whitespace.
1802  * Skips comments as well.
1803  */
1804
1805 STATIC char *
1806 S_skipspace_flags(pTHX_ char *s, U32 flags)
1807 {
1808     PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1809     if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1810         while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1811             s++;
1812     } else {
1813         STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1814         PL_bufptr = s;
1815         lex_read_space(flags | LEX_KEEP_PREVIOUS |
1816                 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1817                     LEX_NO_NEXT_CHUNK : 0));
1818         s = PL_bufptr;
1819         PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1820         if (PL_linestart > PL_bufptr)
1821             PL_bufptr = PL_linestart;
1822         return s;
1823     }
1824     return s;
1825 }
1826
1827 /*
1828  * S_check_uni
1829  * Check the unary operators to ensure there's no ambiguity in how they're
1830  * used.  An ambiguous piece of code would be:
1831  *     rand + 5
1832  * This doesn't mean rand() + 5.  Because rand() is a unary operator,
1833  * the +5 is its argument.
1834  */
1835
1836 STATIC void
1837 S_check_uni(pTHX)
1838 {
1839     const char *s;
1840     const char *t;
1841
1842     if (PL_oldoldbufptr != PL_last_uni)
1843         return;
1844     while (isSPACE(*PL_last_uni))
1845         PL_last_uni++;
1846     s = PL_last_uni;
1847     while (isWORDCHAR_lazy_if(s,UTF) || *s == '-')
1848         s += UTF ? UTF8SKIP(s) : 1;
1849     if ((t = strchr(s, '(')) && t < PL_bufptr)
1850         return;
1851
1852     Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1853                      "Warning: Use of \"%"UTF8f"\" without parentheses is ambiguous",
1854                      UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1855 }
1856
1857 /*
1858  * LOP : macro to build a list operator.  Its behaviour has been replaced
1859  * with a subroutine, S_lop() for which LOP is just another name.
1860  */
1861
1862 #define LOP(f,x) return lop(f,x,s)
1863
1864 /*
1865  * S_lop
1866  * Build a list operator (or something that might be one).  The rules:
1867  *  - if we have a next token, then it's a list operator (no parens) for
1868  *    which the next token has already been parsed; e.g.,
1869  *       sort foo @args
1870  *       sort foo (@args)
1871  *  - if the next thing is an opening paren, then it's a function
1872  *  - else it's a list operator
1873  */
1874
1875 STATIC I32
1876 S_lop(pTHX_ I32 f, int x, char *s)
1877 {
1878     PERL_ARGS_ASSERT_LOP;
1879
1880     pl_yylval.ival = f;
1881     CLINE;
1882     PL_bufptr = s;
1883     PL_last_lop = PL_oldbufptr;
1884     PL_last_lop_op = (OPCODE)f;
1885     if (PL_nexttoke)
1886         goto lstop;
1887     PL_expect = x;
1888     if (*s == '(')
1889         return REPORT(FUNC);
1890     s = skipspace(s);
1891     if (*s == '(')
1892         return REPORT(FUNC);
1893     else {
1894         lstop:
1895         if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1896             PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1897         return REPORT(LSTOP);
1898     }
1899 }
1900
1901 /*
1902  * S_force_next
1903  * When the lexer realizes it knows the next token (for instance,
1904  * it is reordering tokens for the parser) then it can call S_force_next
1905  * to know what token to return the next time the lexer is called.  Caller
1906  * will need to set PL_nextval[] and possibly PL_expect to ensure
1907  * the lexer handles the token correctly.
1908  */
1909
1910 STATIC void
1911 S_force_next(pTHX_ I32 type)
1912 {
1913 #ifdef DEBUGGING
1914     if (DEBUG_T_TEST) {
1915         PerlIO_printf(Perl_debug_log, "### forced token:\n");
1916         tokereport(type, &NEXTVAL_NEXTTOKE);
1917     }
1918 #endif
1919     assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
1920     PL_nexttype[PL_nexttoke] = type;
1921     PL_nexttoke++;
1922     if (PL_lex_state != LEX_KNOWNEXT) {
1923         PL_lex_defer = PL_lex_state;
1924         PL_lex_state = LEX_KNOWNEXT;
1925     }
1926 }
1927
1928 /*
1929  * S_postderef
1930  *
1931  * This subroutine handles postfix deref syntax after the arrow has already
1932  * been emitted.  @* $* etc. are emitted as two separate token right here.
1933  * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
1934  * only the first, leaving yylex to find the next.
1935  */
1936
1937 static int
1938 S_postderef(pTHX_ int const funny, char const next)
1939 {
1940     assert(funny == DOLSHARP || strchr("$@%&*", funny));
1941     assert(strchr("*[{", next));
1942     if (next == '*') {
1943         PL_expect = XOPERATOR;
1944         if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
1945             assert('@' == funny || '$' == funny || DOLSHARP == funny);
1946             PL_lex_state = LEX_INTERPEND;
1947             force_next(POSTJOIN);
1948         }
1949         force_next(next);
1950         PL_bufptr+=2;
1951     }
1952     else {
1953         if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
1954          && !PL_lex_brackets)
1955             PL_lex_dojoin = 2;
1956         PL_expect = XOPERATOR;
1957         PL_bufptr++;
1958     }
1959     return funny;
1960 }
1961
1962 void
1963 Perl_yyunlex(pTHX)
1964 {
1965     int yyc = PL_parser->yychar;
1966     if (yyc != YYEMPTY) {
1967         if (yyc) {
1968             NEXTVAL_NEXTTOKE = PL_parser->yylval;
1969             if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
1970                 PL_lex_allbrackets--;
1971                 PL_lex_brackets--;
1972                 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
1973             } else if (yyc == '('/*)*/) {
1974                 PL_lex_allbrackets--;
1975                 yyc |= (2<<24);
1976             }
1977             force_next(yyc);
1978         }
1979         PL_parser->yychar = YYEMPTY;
1980     }
1981 }
1982
1983 STATIC SV *
1984 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
1985 {
1986     SV * const sv = newSVpvn_utf8(start, len,
1987                                   !IN_BYTES
1988                                   && UTF
1989                                   && !is_invariant_string((const U8*)start, len)
1990                                   && is_utf8_string((const U8*)start, len));
1991     return sv;
1992 }
1993
1994 /*
1995  * S_force_word
1996  * When the lexer knows the next thing is a word (for instance, it has
1997  * just seen -> and it knows that the next char is a word char, then
1998  * it calls S_force_word to stick the next word into the PL_nexttoke/val
1999  * lookahead.
2000  *
2001  * Arguments:
2002  *   char *start : buffer position (must be within PL_linestr)
2003  *   int token   : PL_next* will be this type of bare word (e.g., METHOD,WORD)
2004  *   int check_keyword : if true, Perl checks to make sure the word isn't
2005  *       a keyword (do this if the word is a label, e.g. goto FOO)
2006  *   int allow_pack : if true, : characters will also be allowed (require,
2007  *       use, etc. do this)
2008  */
2009
2010 STATIC char *
2011 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2012 {
2013     char *s;
2014     STRLEN len;
2015
2016     PERL_ARGS_ASSERT_FORCE_WORD;
2017
2018     start = skipspace(start);
2019     s = start;
2020     if (isIDFIRST_lazy_if(s,UTF)
2021         || (allow_pack && *s == ':') )
2022     {
2023         s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2024         if (check_keyword) {
2025           char *s2 = PL_tokenbuf;
2026           STRLEN len2 = len;
2027           if (allow_pack && len > 6 && strnEQ(s2, "CORE::", 6))
2028             s2 += 6, len2 -= 6;
2029           if (keyword(s2, len2, 0))
2030             return start;
2031         }
2032         if (token == METHOD) {
2033             s = skipspace(s);
2034             if (*s == '(')
2035                 PL_expect = XTERM;
2036             else {
2037                 PL_expect = XOPERATOR;
2038             }
2039         }
2040         NEXTVAL_NEXTTOKE.opval
2041             = (OP*)newSVOP(OP_CONST,0,
2042                            S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2043         NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2044         force_next(token);
2045     }
2046     return s;
2047 }
2048
2049 /*
2050  * S_force_ident
2051  * Called when the lexer wants $foo *foo &foo etc, but the program
2052  * text only contains the "foo" portion.  The first argument is a pointer
2053  * to the "foo", and the second argument is the type symbol to prefix.
2054  * Forces the next token to be a "WORD".
2055  * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2056  */
2057
2058 STATIC void
2059 S_force_ident(pTHX_ const char *s, int kind)
2060 {
2061     PERL_ARGS_ASSERT_FORCE_IDENT;
2062
2063     if (s[0]) {
2064         const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2065         OP* const o = (OP*)newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2066                                                                 UTF ? SVf_UTF8 : 0));
2067         NEXTVAL_NEXTTOKE.opval = o;
2068         force_next(WORD);
2069         if (kind) {
2070             o->op_private = OPpCONST_ENTERED;
2071             /* XXX see note in pp_entereval() for why we forgo typo
2072                warnings if the symbol must be introduced in an eval.
2073                GSAR 96-10-12 */
2074             gv_fetchpvn_flags(s, len,
2075                               (PL_in_eval ? GV_ADDMULTI
2076                               : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2077                               kind == '$' ? SVt_PV :
2078                               kind == '@' ? SVt_PVAV :
2079                               kind == '%' ? SVt_PVHV :
2080                               SVt_PVGV
2081                               );
2082         }
2083     }
2084 }
2085
2086 static void
2087 S_force_ident_maybe_lex(pTHX_ char pit)
2088 {
2089     NEXTVAL_NEXTTOKE.ival = pit;
2090     force_next('p');
2091 }
2092
2093 NV
2094 Perl_str_to_version(pTHX_ SV *sv)
2095 {
2096     NV retval = 0.0;
2097     NV nshift = 1.0;
2098     STRLEN len;
2099     const char *start = SvPV_const(sv,len);
2100     const char * const end = start + len;
2101     const bool utf = SvUTF8(sv) ? TRUE : FALSE;
2102
2103     PERL_ARGS_ASSERT_STR_TO_VERSION;
2104
2105     while (start < end) {
2106         STRLEN skip;
2107         UV n;
2108         if (utf)
2109             n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2110         else {
2111             n = *(U8*)start;
2112             skip = 1;
2113         }
2114         retval += ((NV)n)/nshift;
2115         start += skip;
2116         nshift *= 1000;
2117     }
2118     return retval;
2119 }
2120
2121 /*
2122  * S_force_version
2123  * Forces the next token to be a version number.
2124  * If the next token appears to be an invalid version number, (e.g. "v2b"),
2125  * and if "guessing" is TRUE, then no new token is created (and the caller
2126  * must use an alternative parsing method).
2127  */
2128
2129 STATIC char *
2130 S_force_version(pTHX_ char *s, int guessing)
2131 {
2132     OP *version = NULL;
2133     char *d;
2134
2135     PERL_ARGS_ASSERT_FORCE_VERSION;
2136
2137     s = skipspace(s);
2138
2139     d = s;
2140     if (*d == 'v')
2141         d++;
2142     if (isDIGIT(*d)) {
2143         while (isDIGIT(*d) || *d == '_' || *d == '.')
2144             d++;
2145         if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2146             SV *ver;
2147             s = scan_num(s, &pl_yylval);
2148             version = pl_yylval.opval;
2149             ver = cSVOPx(version)->op_sv;
2150             if (SvPOK(ver) && !SvNIOK(ver)) {
2151                 SvUPGRADE(ver, SVt_PVNV);
2152                 SvNV_set(ver, str_to_version(ver));
2153                 SvNOK_on(ver);          /* hint that it is a version */
2154             }
2155         }
2156         else if (guessing) {
2157             return s;
2158         }
2159     }
2160
2161     /* NOTE: The parser sees the package name and the VERSION swapped */
2162     NEXTVAL_NEXTTOKE.opval = version;
2163     force_next(WORD);
2164
2165     return s;
2166 }
2167
2168 /*
2169  * S_force_strict_version
2170  * Forces the next token to be a version number using strict syntax rules.
2171  */
2172
2173 STATIC char *
2174 S_force_strict_version(pTHX_ char *s)
2175 {
2176     OP *version = NULL;
2177     const char *errstr = NULL;
2178
2179     PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2180
2181     while (isSPACE(*s)) /* leading whitespace */
2182         s++;
2183
2184     if (is_STRICT_VERSION(s,&errstr)) {
2185         SV *ver = newSV(0);
2186         s = (char *)scan_version(s, ver, 0);
2187         version = newSVOP(OP_CONST, 0, ver);
2188     }
2189     else if ((*s != ';' && *s != '{' && *s != '}' )
2190              && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2191     {
2192         PL_bufptr = s;
2193         if (errstr)
2194             yyerror(errstr); /* version required */
2195         return s;
2196     }
2197
2198     /* NOTE: The parser sees the package name and the VERSION swapped */
2199     NEXTVAL_NEXTTOKE.opval = version;
2200     force_next(WORD);
2201
2202     return s;
2203 }
2204
2205 /*
2206  * S_tokeq
2207  * Tokenize a quoted string passed in as an SV.  It finds the next
2208  * chunk, up to end of string or a backslash.  It may make a new
2209  * SV containing that chunk (if HINT_NEW_STRING is on).  It also
2210  * turns \\ into \.
2211  */
2212
2213 STATIC SV *
2214 S_tokeq(pTHX_ SV *sv)
2215 {
2216     char *s;
2217     char *send;
2218     char *d;
2219     SV *pv = sv;
2220
2221     PERL_ARGS_ASSERT_TOKEQ;
2222
2223     assert (SvPOK(sv));
2224     assert (SvLEN(sv));
2225     assert (!SvIsCOW(sv));
2226     if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2227         goto finish;
2228     s = SvPVX(sv);
2229     send = SvEND(sv);
2230     /* This is relying on the SV being "well formed" with a trailing '\0'  */
2231     while (s < send && !(*s == '\\' && s[1] == '\\'))
2232         s++;
2233     if (s == send)
2234         goto finish;
2235     d = s;
2236     if ( PL_hints & HINT_NEW_STRING ) {
2237         pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2238                             SVs_TEMP | SvUTF8(sv));
2239     }
2240     while (s < send) {
2241         if (*s == '\\') {
2242             if (s + 1 < send && (s[1] == '\\'))
2243                 s++;            /* all that, just for this */
2244         }
2245         *d++ = *s++;
2246     }
2247     *d = '\0';
2248     SvCUR_set(sv, d - SvPVX_const(sv));
2249   finish:
2250     if ( PL_hints & HINT_NEW_STRING )
2251        return new_constant(NULL, 0, "q", sv, pv, "q", 1);
2252     return sv;
2253 }
2254
2255 /*
2256  * Now come three functions related to double-quote context,
2257  * S_sublex_start, S_sublex_push, and S_sublex_done.  They're used when
2258  * converting things like "\u\Lgnat" into ucfirst(lc("gnat")).  They
2259  * interact with PL_lex_state, and create fake ( ... ) argument lists
2260  * to handle functions and concatenation.
2261  * For example,
2262  *   "foo\lbar"
2263  * is tokenised as
2264  *    stringify ( const[foo] concat lcfirst ( const[bar] ) )
2265  */
2266
2267 /*
2268  * S_sublex_start
2269  * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2270  *
2271  * Pattern matching will set PL_lex_op to the pattern-matching op to
2272  * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2273  *
2274  * OP_CONST and OP_READLINE are easy--just make the new op and return.
2275  *
2276  * Everything else becomes a FUNC.
2277  *
2278  * Sets PL_lex_state to LEX_INTERPPUSH unless (ival was OP_NULL or we
2279  * had an OP_CONST or OP_READLINE).  This just sets us up for a
2280  * call to S_sublex_push().
2281  */
2282
2283 STATIC I32
2284 S_sublex_start(pTHX)
2285 {
2286     const I32 op_type = pl_yylval.ival;
2287
2288     if (op_type == OP_NULL) {
2289         pl_yylval.opval = PL_lex_op;
2290         PL_lex_op = NULL;
2291         return THING;
2292     }
2293     if (op_type == OP_CONST) {
2294         SV *sv = PL_lex_stuff;
2295         PL_lex_stuff = NULL;
2296         sv = tokeq(sv);
2297
2298         if (SvTYPE(sv) == SVt_PVIV) {
2299             /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2300             STRLEN len;
2301             const char * const p = SvPV_const(sv, len);
2302             SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2303             SvREFCNT_dec(sv);
2304             sv = nsv;
2305         }
2306         pl_yylval.opval = (OP*)newSVOP(op_type, 0, sv);
2307         return THING;
2308     }
2309
2310     PL_sublex_info.super_state = PL_lex_state;
2311     PL_sublex_info.sub_inwhat = (U16)op_type;
2312     PL_sublex_info.sub_op = PL_lex_op;
2313     PL_lex_state = LEX_INTERPPUSH;
2314
2315     PL_expect = XTERM;
2316     if (PL_lex_op) {
2317         pl_yylval.opval = PL_lex_op;
2318         PL_lex_op = NULL;
2319         return PMFUNC;
2320     }
2321     else
2322         return FUNC;
2323 }
2324
2325 /*
2326  * S_sublex_push
2327  * Create a new scope to save the lexing state.  The scope will be
2328  * ended in S_sublex_done.  Returns a '(', starting the function arguments
2329  * to the uc, lc, etc. found before.
2330  * Sets PL_lex_state to LEX_INTERPCONCAT.
2331  */
2332
2333 STATIC I32
2334 S_sublex_push(pTHX)
2335 {
2336     LEXSHARED *shared;
2337     const bool is_heredoc = PL_multi_close == '<';
2338     ENTER;
2339
2340     PL_lex_state = PL_sublex_info.super_state;
2341     SAVEI8(PL_lex_dojoin);
2342     SAVEI32(PL_lex_brackets);
2343     SAVEI32(PL_lex_allbrackets);
2344     SAVEI32(PL_lex_formbrack);
2345     SAVEI8(PL_lex_fakeeof);
2346     SAVEI32(PL_lex_casemods);
2347     SAVEI32(PL_lex_starts);
2348     SAVEI8(PL_lex_state);
2349     SAVEI8(PL_lex_defer);
2350     SAVESPTR(PL_lex_repl);
2351     SAVEVPTR(PL_lex_inpat);
2352     SAVEI16(PL_lex_inwhat);
2353     if (is_heredoc)
2354     {
2355         SAVECOPLINE(PL_curcop);
2356         SAVEI32(PL_multi_end);
2357         SAVEI32(PL_parser->herelines);
2358         PL_parser->herelines = 0;
2359     }
2360     SAVEI8(PL_multi_close);
2361     SAVEPPTR(PL_bufptr);
2362     SAVEPPTR(PL_bufend);
2363     SAVEPPTR(PL_oldbufptr);
2364     SAVEPPTR(PL_oldoldbufptr);
2365     SAVEPPTR(PL_last_lop);
2366     SAVEPPTR(PL_last_uni);
2367     SAVEPPTR(PL_linestart);
2368     SAVESPTR(PL_linestr);
2369     SAVEGENERICPV(PL_lex_brackstack);
2370     SAVEGENERICPV(PL_lex_casestack);
2371     SAVEGENERICPV(PL_parser->lex_shared);
2372     SAVEBOOL(PL_parser->lex_re_reparsing);
2373     SAVEI32(PL_copline);
2374
2375     /* The here-doc parser needs to be able to peek into outer lexing
2376        scopes to find the body of the here-doc.  So we put PL_linestr and
2377        PL_bufptr into lex_shared, to â€˜share’ those values.
2378      */
2379     PL_parser->lex_shared->ls_linestr = PL_linestr;
2380     PL_parser->lex_shared->ls_bufptr  = PL_bufptr;
2381
2382     PL_linestr = PL_lex_stuff;
2383     PL_lex_repl = PL_sublex_info.repl;
2384     PL_lex_stuff = NULL;
2385     PL_sublex_info.repl = NULL;
2386
2387     /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2388        set for an inner quote-like operator and then an error causes scope-
2389        popping.  We must not have a PL_lex_stuff value left dangling, as
2390        that breaks assumptions elsewhere.  See bug #123617.  */
2391     SAVEGENERICSV(PL_lex_stuff);
2392     SAVEGENERICSV(PL_sublex_info.repl);
2393
2394     PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2395         = SvPVX(PL_linestr);
2396     PL_bufend += SvCUR(PL_linestr);
2397     PL_last_lop = PL_last_uni = NULL;
2398     SAVEFREESV(PL_linestr);
2399     if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2400
2401     PL_lex_dojoin = FALSE;
2402     PL_lex_brackets = PL_lex_formbrack = 0;
2403     PL_lex_allbrackets = 0;
2404     PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2405     Newx(PL_lex_brackstack, 120, char);
2406     Newx(PL_lex_casestack, 12, char);
2407     PL_lex_casemods = 0;
2408     *PL_lex_casestack = '\0';
2409     PL_lex_starts = 0;
2410     PL_lex_state = LEX_INTERPCONCAT;
2411     if (is_heredoc)
2412         CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2413     PL_copline = NOLINE;
2414     
2415     Newxz(shared, 1, LEXSHARED);
2416     shared->ls_prev = PL_parser->lex_shared;
2417     PL_parser->lex_shared = shared;
2418
2419     PL_lex_inwhat = PL_sublex_info.sub_inwhat;
2420     if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2421     if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2422         PL_lex_inpat = PL_sublex_info.sub_op;
2423     else
2424         PL_lex_inpat = NULL;
2425
2426     PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2427     PL_in_eval &= ~EVAL_RE_REPARSING;
2428
2429     return '(';
2430 }
2431
2432 /*
2433  * S_sublex_done
2434  * Restores lexer state after a S_sublex_push.
2435  */
2436
2437 STATIC I32
2438 S_sublex_done(pTHX)
2439 {
2440     if (!PL_lex_starts++) {
2441         SV * const sv = newSVpvs("");
2442         if (SvUTF8(PL_linestr))
2443             SvUTF8_on(sv);
2444         PL_expect = XOPERATOR;
2445         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
2446         return THING;
2447     }
2448
2449     if (PL_lex_casemods) {              /* oops, we've got some unbalanced parens */
2450         PL_lex_state = LEX_INTERPCASEMOD;
2451         return yylex();
2452     }
2453
2454     /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2455     assert(PL_lex_inwhat != OP_TRANSR);
2456     if (PL_lex_repl) {
2457         assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2458         PL_linestr = PL_lex_repl;
2459         PL_lex_inpat = 0;
2460         PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2461         PL_bufend += SvCUR(PL_linestr);
2462         PL_last_lop = PL_last_uni = NULL;
2463         PL_lex_dojoin = FALSE;
2464         PL_lex_brackets = 0;
2465         PL_lex_allbrackets = 0;
2466         PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2467         PL_lex_casemods = 0;
2468         *PL_lex_casestack = '\0';
2469         PL_lex_starts = 0;
2470         if (SvEVALED(PL_lex_repl)) {
2471             PL_lex_state = LEX_INTERPNORMAL;
2472             PL_lex_starts++;
2473             /*  we don't clear PL_lex_repl here, so that we can check later
2474                 whether this is an evalled subst; that means we rely on the
2475                 logic to ensure sublex_done() is called again only via the
2476                 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2477         }
2478         else {
2479             PL_lex_state = LEX_INTERPCONCAT;
2480             PL_lex_repl = NULL;
2481         }
2482         if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2483             CopLINE(PL_curcop) +=
2484                 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xpad_cop_seq.xlow
2485                  + PL_parser->herelines;
2486             PL_parser->herelines = 0;
2487         }
2488         return '/';
2489     }
2490     else {
2491         const line_t l = CopLINE(PL_curcop);
2492         LEAVE;
2493         if (PL_multi_close == '<')
2494             PL_parser->herelines += l - PL_multi_end;
2495         PL_bufend = SvPVX(PL_linestr);
2496         PL_bufend += SvCUR(PL_linestr);
2497         PL_expect = XOPERATOR;
2498         return ')';
2499     }
2500 }
2501
2502 PERL_STATIC_INLINE SV*
2503 S_get_and_check_backslash_N_name(pTHX_ const char* s, const char* const e)
2504 {
2505     /* <s> points to first character of interior of \N{}, <e> to one beyond the
2506      * interior, hence to the "}".  Finds what the name resolves to, returning
2507      * an SV* containing it; NULL if no valid one found */
2508
2509     SV* res = newSVpvn_flags(s, e - s, UTF ? SVf_UTF8 : 0);
2510
2511     HV * table;
2512     SV **cvp;
2513     SV *cv;
2514     SV *rv;
2515     HV *stash;
2516     const U8* first_bad_char_loc;
2517     const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2518
2519     PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2520
2521     if (!SvCUR(res))
2522         return res;
2523
2524     if (UTF && ! is_utf8_string_loc((U8 *) backslash_ptr,
2525                                      e - backslash_ptr,
2526                                      &first_bad_char_loc))
2527     {
2528         /* If warnings are on, this will print a more detailed analysis of what
2529          * is wrong than the error message below */
2530         utf8n_to_uvchr(first_bad_char_loc,
2531                        e - ((char *) first_bad_char_loc),
2532                        NULL, 0);
2533
2534         /* We deliberately don't try to print the malformed character, which
2535          * might not print very well; it also may be just the first of many
2536          * malformations, so don't print what comes after it */
2537         yyerror_pv(Perl_form(aTHX_
2538             "Malformed UTF-8 character immediately after '%.*s'",
2539             (int) (first_bad_char_loc - (U8 *) backslash_ptr), backslash_ptr),
2540                    SVf_UTF8);
2541         return NULL;
2542     }
2543
2544     res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2545                         /* include the <}> */
2546                         e - backslash_ptr + 1);
2547     if (! SvPOK(res)) {
2548         SvREFCNT_dec_NN(res);
2549         return NULL;
2550     }
2551
2552     /* See if the charnames handler is the Perl core's, and if so, we can skip
2553      * the validation needed for a user-supplied one, as Perl's does its own
2554      * validation. */
2555     table = GvHV(PL_hintgv);             /* ^H */
2556     cvp = hv_fetchs(table, "charnames", FALSE);
2557     if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2558         SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2559     {
2560         const char * const name = HvNAME(stash);
2561         if (HvNAMELEN(stash) == sizeof("_charnames")-1
2562          && strEQ(name, "_charnames")) {
2563            return res;
2564        }
2565     }
2566
2567     /* Here, it isn't Perl's charname handler.  We can't rely on a
2568      * user-supplied handler to validate the input name.  For non-ut8 input,
2569      * look to see that the first character is legal.  Then loop through the
2570      * rest checking that each is a continuation */
2571
2572     /* This code makes the reasonable assumption that the only Latin1-range
2573      * characters that begin a character name alias are alphabetic, otherwise
2574      * would have to create a isCHARNAME_BEGIN macro */
2575
2576     if (! UTF) {
2577         if (! isALPHAU(*s)) {
2578             goto bad_charname;
2579         }
2580         s++;
2581         while (s < e) {
2582             if (! isCHARNAME_CONT(*s)) {
2583                 goto bad_charname;
2584             }
2585             if (*s == ' ' && *(s-1) == ' ') {
2586                 goto multi_spaces;
2587             }
2588             if ((U8) *s == NBSP_NATIVE && ckWARN_d(WARN_DEPRECATED)) {
2589                 Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
2590                            "NO-BREAK SPACE in a charnames "
2591                            "alias definition is deprecated");
2592             }
2593             s++;
2594         }
2595     }
2596     else {
2597         /* Similarly for utf8.  For invariants can check directly; for other
2598          * Latin1, can calculate their code point and check; otherwise  use a
2599          * swash */
2600         if (UTF8_IS_INVARIANT(*s)) {
2601             if (! isALPHAU(*s)) {
2602                 goto bad_charname;
2603             }
2604             s++;
2605         } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2606             if (! isALPHAU(TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1)))) {
2607                 goto bad_charname;
2608             }
2609             s += 2;
2610         }
2611         else {
2612             if (! PL_utf8_charname_begin) {
2613                 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2614                 PL_utf8_charname_begin = _core_swash_init("utf8",
2615                                                         "_Perl_Charname_Begin",
2616                                                         &PL_sv_undef,
2617                                                         1, 0, NULL, &flags);
2618             }
2619             if (! swash_fetch(PL_utf8_charname_begin, (U8 *) s, TRUE)) {
2620                 goto bad_charname;
2621             }
2622             s += UTF8SKIP(s);
2623         }
2624
2625         while (s < e) {
2626             if (UTF8_IS_INVARIANT(*s)) {
2627                 if (! isCHARNAME_CONT(*s)) {
2628                     goto bad_charname;
2629                 }
2630                 if (*s == ' ' && *(s-1) == ' ') {
2631                     goto multi_spaces;
2632                 }
2633                 s++;
2634             }
2635             else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2636                 if (! isCHARNAME_CONT(TWO_BYTE_UTF8_TO_NATIVE(*s, *(s+1))))
2637                 {
2638                     goto bad_charname;
2639                 }
2640                 if (*s == *NBSP_UTF8
2641                     && *(s+1) == *(NBSP_UTF8+1)
2642                     && ckWARN_d(WARN_DEPRECATED))
2643                 {
2644                     Perl_warner(aTHX_ packWARN(WARN_DEPRECATED),
2645                                 "NO-BREAK SPACE in a charnames "
2646                                 "alias definition is deprecated");
2647                 }
2648                 s += 2;
2649             }
2650             else {
2651                 if (! PL_utf8_charname_continue) {
2652                     U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2653                     PL_utf8_charname_continue = _core_swash_init("utf8",
2654                                                 "_Perl_Charname_Continue",
2655                                                 &PL_sv_undef,
2656                                                 1, 0, NULL, &flags);
2657                 }
2658                 if (! swash_fetch(PL_utf8_charname_continue, (U8 *) s, TRUE)) {
2659                     goto bad_charname;
2660                 }
2661                 s += UTF8SKIP(s);
2662             }
2663         }
2664     }
2665     if (*(s-1) == ' ') {
2666         yyerror_pv(
2667             Perl_form(aTHX_
2668             "charnames alias definitions may not contain trailing "
2669             "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2670             (int)(s - backslash_ptr + 1), backslash_ptr,
2671             (int)(e - s + 1), s + 1
2672             ),
2673         UTF ? SVf_UTF8 : 0);
2674         return NULL;
2675     }
2676
2677     if (SvUTF8(res)) { /* Don't accept malformed input */
2678         const U8* first_bad_char_loc;
2679         STRLEN len;
2680         const char* const str = SvPV_const(res, len);
2681         if (! is_utf8_string_loc((U8 *) str, len, &first_bad_char_loc)) {
2682             /* If warnings are on, this will print a more detailed analysis of
2683              * what is wrong than the error message below */
2684             utf8n_to_uvchr(first_bad_char_loc,
2685                            (char *) first_bad_char_loc - str,
2686                            NULL, 0);
2687
2688             /* We deliberately don't try to print the malformed character,
2689              * which might not print very well; it also may be just the first
2690              * of many malformations, so don't print what comes after it */
2691             yyerror_pv(
2692               Perl_form(aTHX_
2693                 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2694                  (int) (e - backslash_ptr + 1), backslash_ptr,
2695                  (int) ((char *) first_bad_char_loc - str), str
2696               ),
2697               SVf_UTF8);
2698             return NULL;
2699         }
2700     }
2701
2702     return res;
2703
2704   bad_charname: {
2705
2706         /* The final %.*s makes sure that should the trailing NUL be missing
2707          * that this print won't run off the end of the string */
2708         yyerror_pv(
2709           Perl_form(aTHX_
2710             "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2711             (int)(s - backslash_ptr + 1), backslash_ptr,
2712             (int)(e - s + 1), s + 1
2713           ),
2714           UTF ? SVf_UTF8 : 0);
2715         return NULL;
2716     }
2717
2718   multi_spaces:
2719         yyerror_pv(
2720           Perl_form(aTHX_
2721             "charnames alias definitions may not contain a sequence of "
2722             "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2723             (int)(s - backslash_ptr + 1), backslash_ptr,
2724             (int)(e - s + 1), s + 1
2725           ),
2726           UTF ? SVf_UTF8 : 0);
2727         return NULL;
2728 }
2729
2730 /*
2731   scan_const
2732
2733   Extracts the next constant part of a pattern, double-quoted string,
2734   or transliteration.  This is terrifying code.
2735
2736   For example, in parsing the double-quoted string "ab\x63$d", it would
2737   stop at the '$' and return an OP_CONST containing 'abc'.
2738
2739   It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2740   processing a pattern (PL_lex_inpat is true), a transliteration
2741   (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2742
2743   Returns a pointer to the character scanned up to. If this is
2744   advanced from the start pointer supplied (i.e. if anything was
2745   successfully parsed), will leave an OP_CONST for the substring scanned
2746   in pl_yylval. Caller must intuit reason for not parsing further
2747   by looking at the next characters herself.
2748
2749   In patterns:
2750     expand:
2751       \N{FOO}  => \N{U+hex_for_character_FOO}
2752       (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2753
2754     pass through:
2755         all other \-char, including \N and \N{ apart from \N{ABC}
2756
2757     stops on:
2758         @ and $ where it appears to be a var, but not for $ as tail anchor
2759         \l \L \u \U \Q \E
2760         (?{  or  (??{
2761
2762   In transliterations:
2763     characters are VERY literal, except for - not at the start or end
2764     of the string, which indicates a range. If the range is in bytes,
2765     scan_const expands the range to the full set of intermediate
2766     characters. If the range is in utf8, the hyphen is replaced with
2767     a certain range mark which will be handled by pmtrans() in op.c.
2768
2769   In double-quoted strings:
2770     backslashes:
2771       double-quoted style: \r and \n
2772       constants: \x31, etc.
2773       deprecated backrefs: \1 (in substitution replacements)
2774       case and quoting: \U \Q \E
2775     stops on @ and $
2776
2777   scan_const does *not* construct ops to handle interpolated strings.
2778   It stops processing as soon as it finds an embedded $ or @ variable
2779   and leaves it to the caller to work out what's going on.
2780
2781   embedded arrays (whether in pattern or not) could be:
2782       @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2783
2784   $ in double-quoted strings must be the symbol of an embedded scalar.
2785
2786   $ in pattern could be $foo or could be tail anchor.  Assumption:
2787   it's a tail anchor if $ is the last thing in the string, or if it's
2788   followed by one of "()| \r\n\t"
2789
2790   \1 (backreferences) are turned into $1 in substitutions
2791
2792   The structure of the code is
2793       while (there's a character to process) {
2794           handle transliteration ranges
2795           skip regexp comments /(?#comment)/ and codes /(?{code})/
2796           skip #-initiated comments in //x patterns
2797           check for embedded arrays
2798           check for embedded scalars
2799           if (backslash) {
2800               deprecate \1 in substitution replacements
2801               handle string-changing backslashes \l \U \Q \E, etc.
2802               switch (what was escaped) {
2803                   handle \- in a transliteration (becomes a literal -)
2804                   if a pattern and not \N{, go treat as regular character
2805                   handle \132 (octal characters)
2806                   handle \x15 and \x{1234} (hex characters)
2807                   handle \N{name} (named characters, also \N{3,5} in a pattern)
2808                   handle \cV (control characters)
2809                   handle printf-style backslashes (\f, \r, \n, etc)
2810               } (end switch)
2811               continue
2812           } (end if backslash)
2813           handle regular character
2814     } (end while character to read)
2815                 
2816 */
2817
2818 STATIC char *
2819 S_scan_const(pTHX_ char *start)
2820 {
2821     char *send = PL_bufend;             /* end of the constant */
2822     SV *sv = newSV(send - start);       /* sv for the constant.  See note below
2823                                            on sizing. */
2824     char *s = start;                    /* start of the constant */
2825     char *d = SvPVX(sv);                /* destination for copies */
2826     bool dorange = FALSE;               /* are we in a translit range? */
2827     bool didrange = FALSE;              /* did we just finish a range? */
2828     bool in_charclass = FALSE;          /* within /[...]/ */
2829     bool has_utf8 = FALSE;              /* Output constant is UTF8 */
2830     bool  this_utf8 = cBOOL(UTF);       /* Is the source string assumed to be
2831                                            UTF8?  But, this can show as true
2832                                            when the source isn't utf8, as for
2833                                            example when it is entirely composed
2834                                            of hex constants */
2835     SV *res;                            /* result from charnames */
2836
2837     /* Note on sizing:  The scanned constant is placed into sv, which is
2838      * initialized by newSV() assuming one byte of output for every byte of
2839      * input.  This routine expects newSV() to allocate an extra byte for a
2840      * trailing NUL, which this routine will append if it gets to the end of
2841      * the input.  There may be more bytes of input than output (eg., \N{LATIN
2842      * CAPITAL LETTER A}), or more output than input if the constant ends up
2843      * recoded to utf8, but each time a construct is found that might increase
2844      * the needed size, SvGROW() is called.  Its size parameter each time is
2845      * based on the best guess estimate at the time, namely the length used so
2846      * far, plus the length the current construct will occupy, plus room for
2847      * the trailing NUL, plus one byte for every input byte still unscanned */ 
2848
2849     UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2850                        before set */
2851 #ifdef EBCDIC
2852     UV literal_endpoint = 0;
2853     bool native_range = TRUE; /* turned to FALSE if the first endpoint is Unicode. */
2854 #endif
2855
2856     PERL_ARGS_ASSERT_SCAN_CONST;
2857
2858     assert(PL_lex_inwhat != OP_TRANSR);
2859     if (PL_lex_inwhat == OP_TRANS && PL_sublex_info.sub_op) {
2860         /* If we are doing a trans and we know we want UTF8 set expectation */
2861         has_utf8   = PL_sublex_info.sub_op->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF);
2862         this_utf8  = PL_sublex_info.sub_op->op_private & (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
2863     }
2864
2865     /* Protect sv from errors and fatal warnings. */
2866     ENTER_with_name("scan_const");
2867     SAVEFREESV(sv);
2868
2869     while (s < send || dorange) {
2870
2871         /* get transliterations out of the way (they're most literal) */
2872         if (PL_lex_inwhat == OP_TRANS) {
2873             /* expand a range A-Z to the full set of characters.  AIE! */
2874             if (dorange) {
2875                 I32 i;                          /* current expanded character */
2876                 I32 min;                        /* first character in range */
2877                 I32 max;                        /* last character in range */
2878
2879 #ifdef EBCDIC
2880                 UV uvmax = 0;
2881 #endif
2882
2883                 if (has_utf8
2884 #ifdef EBCDIC
2885                     && !native_range
2886 #endif
2887                 ) {
2888                     char * const c = (char*)utf8_hop((U8*)d, -1);
2889                     char *e = d++;
2890                     while (e-- > c)
2891                         *(e + 1) = *e;
2892                     *c = (char) ILLEGAL_UTF8_BYTE;
2893                     /* mark the range as done, and continue */
2894                     dorange = FALSE;
2895                     didrange = TRUE;
2896                     continue;
2897                 }
2898
2899                 i = d - SvPVX_const(sv);                /* remember current offset */
2900 #ifdef EBCDIC
2901                 SvGROW(sv,
2902                        SvLEN(sv) + ((has_utf8)
2903                                     ?  (512 - UTF_CONTINUATION_MARK
2904                                         + UNISKIP(0x100))
2905                                     : 256));
2906                 /* How many two-byte within 0..255: 128 in UTF-8,
2907                  * 96 in UTF-8-mod. */
2908 #else
2909                 SvGROW(sv, SvLEN(sv) + 256);    /* never more than 256 chars in a range */
2910 #endif
2911                 d = SvPVX(sv) + i;              /* refresh d after realloc */
2912 #ifdef EBCDIC
2913                 if (has_utf8) {
2914                     int j;
2915                     for (j = 0; j <= 1; j++) {
2916                         char * const c = (char*)utf8_hop((U8*)d, -1);
2917                         const UV uv    = utf8n_to_uvchr((U8*)c, d - c, NULL, 0);
2918                         if (j)
2919                             min = (U8)uv;
2920                         else if (uv < 256)
2921                             max = (U8)uv;
2922                         else {
2923                             max = (U8)0xff; /* only to \xff */
2924                             uvmax = uv; /* \x{100} to uvmax */
2925                         }
2926                         d = c; /* eat endpoint chars */
2927                      }
2928                 }
2929                else {
2930 #endif
2931                    d -= 2;              /* eat the first char and the - */
2932                    min = (U8)*d;        /* first char in range */
2933                    max = (U8)d[1];      /* last char in range  */
2934 #ifdef EBCDIC
2935                }
2936 #endif
2937
2938                 if (min > max) {
2939                     Perl_croak(aTHX_
2940                                "Invalid range \"%c-%c\" in transliteration operator",
2941                                (char)min, (char)max);
2942                 }
2943
2944 #ifdef EBCDIC
2945                 /* Because of the discontinuities in EBCDIC A-Z and a-z, expand
2946                  * any subsets of these ranges into individual characters */
2947                 if (literal_endpoint == 2
2948                     && ((isLOWER_A(min) && isLOWER_A(max))
2949                      || (isUPPER_A(min) && isUPPER_A(max))))
2950                 {
2951                     for (i = min; i <= max; i++) {
2952                         if (isALPHA_A(i))
2953                             *d++ = i;
2954                     }
2955                 }
2956                 else
2957 #endif
2958                     for (i = min; i <= max; i++)
2959 #ifdef EBCDIC
2960                         if (has_utf8) {
2961                             append_utf8_from_native_byte(i, &d);
2962                         }
2963                         else
2964 #endif
2965                             *d++ = (char)i;
2966  
2967 #ifdef EBCDIC
2968                 if (uvmax) {
2969                     d = (char*)uvchr_to_utf8((U8*)d, 0x100);
2970                     if (uvmax > 0x101)
2971                         *d++ = (char) ILLEGAL_UTF8_BYTE;
2972                     if (uvmax > 0x100)
2973                         d = (char*)uvchr_to_utf8((U8*)d, uvmax);
2974                 }
2975 #endif
2976
2977                 /* mark the range as done, and continue */
2978                 dorange = FALSE;
2979                 didrange = TRUE;
2980 #ifdef EBCDIC
2981                 literal_endpoint = 0;
2982 #endif
2983                 continue;
2984             }
2985
2986             /* range begins (ignore - as first or last char) */
2987             else if (*s == '-' && s+1 < send  && s != start) {
2988                 if (didrange) {
2989                     Perl_croak(aTHX_ "Ambiguous range in transliteration operator");
2990                 }
2991                 if (has_utf8
2992 #ifdef EBCDIC
2993                     && !native_range
2994 #endif
2995                     ) {
2996                     *d++ = (char) ILLEGAL_UTF8_BYTE;    /* use illegal utf8 byte--see pmtrans */
2997                     s++;
2998                     continue;
2999                 }
3000                 dorange = TRUE;
3001                 s++;
3002             }
3003             else {
3004                 didrange = FALSE;
3005 #ifdef EBCDIC
3006                 literal_endpoint = 0;
3007                 native_range = TRUE;
3008 #endif
3009             }
3010         }
3011
3012         /* if we get to any of these else's, we're not doing a
3013          * transliteration. */
3014
3015         else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3016             char *s1 = s-1;
3017             int esc = 0;
3018             while (s1 >= start && *s1-- == '\\')
3019                 esc = !esc;
3020             if (!esc)
3021                 in_charclass = TRUE;
3022         }
3023
3024         else if (*s == ']' && PL_lex_inpat &&  in_charclass) {
3025             char *s1 = s-1;
3026             int esc = 0;
3027             while (s1 >= start && *s1-- == '\\')
3028                 esc = !esc;
3029             if (!esc)
3030                 in_charclass = FALSE;
3031         }
3032
3033         /* skip for regexp comments /(?#comment)/, except for the last
3034          * char, which will be done separately.
3035          * Stop on (?{..}) and friends */
3036
3037         else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3038             if (s[2] == '#') {
3039                 while (s+1 < send && *s != ')')
3040                     *d++ = *s++;
3041             }
3042             else if (!PL_lex_casemods
3043                      && (    s[2] == '{' /* This should match regcomp.c */
3044                          || (s[2] == '?' && s[3] == '{')))
3045             {
3046                 break;
3047             }
3048         }
3049
3050         /* likewise skip #-initiated comments in //x patterns */
3051         else if (*s == '#'
3052                  && PL_lex_inpat
3053                  && !in_charclass
3054                  && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3055         {
3056             while (s+1 < send && *s != '\n')
3057                 *d++ = *s++;
3058         }
3059
3060         /* no further processing of single-quoted regex */
3061         else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3062             goto default_action;
3063
3064         /* check for embedded arrays
3065            (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3066            */
3067         else if (*s == '@' && s[1]) {
3068             if (UTF ? isIDFIRST_utf8((U8*)s+1) : isWORDCHAR_A(s[1]))
3069                 break;
3070             if (strchr(":'{$", s[1]))
3071                 break;
3072             if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3073                 break; /* in regexp, neither @+ nor @- are interpolated */
3074         }
3075
3076         /* check for embedded scalars.  only stop if we're sure it's a
3077            variable.
3078         */
3079         else if (*s == '$') {
3080             if (!PL_lex_inpat)  /* not a regexp, so $ must be var */
3081                 break;
3082             if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
3083                 if (s[1] == '\\') {
3084                     Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3085                                    "Possible unintended interpolation of $\\ in regex");
3086                 }
3087                 break;          /* in regexp, $ might be tail anchor */
3088             }
3089         }
3090
3091         /* End of else if chain - OP_TRANS rejoin rest */
3092
3093         /* backslashes */
3094         if (*s == '\\' && s+1 < send) {
3095             char* e;    /* Can be used for ending '}', etc. */
3096
3097             s++;
3098
3099             /* warn on \1 - \9 in substitution replacements, but note that \11
3100              * is an octal; and \19 is \1 followed by '9' */
3101             if (PL_lex_inwhat == OP_SUBST
3102                 && !PL_lex_inpat
3103                 && isDIGIT(*s)
3104                 && *s != '0'
3105                 && !isDIGIT(s[1]))
3106             {
3107                 /* diag_listed_as: \%d better written as $%d */
3108                 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3109                 *--s = '$';
3110                 break;
3111             }
3112
3113             /* string-change backslash escapes */
3114             if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQF", *s)) {
3115                 --s;
3116                 break;
3117             }
3118             /* In a pattern, process \N, but skip any other backslash escapes.
3119              * This is because we don't want to translate an escape sequence
3120              * into a meta symbol and have the regex compiler use the meta
3121              * symbol meaning, e.g. \x{2E} would be confused with a dot.  But
3122              * in spite of this, we do have to process \N here while the proper
3123              * charnames handler is in scope.  See bugs #56444 and #62056.
3124              *
3125              * There is a complication because \N in a pattern may also stand
3126              * for 'match a non-nl', and not mean a charname, in which case its
3127              * processing should be deferred to the regex compiler.  To be a
3128              * charname it must be followed immediately by a '{', and not look
3129              * like \N followed by a curly quantifier, i.e., not something like
3130              * \N{3,}.  regcurly returns a boolean indicating if it is a legal
3131              * quantifier */
3132             else if (PL_lex_inpat
3133                     && (*s != 'N'
3134                         || s[1] != '{'
3135                         || regcurly(s + 1)))
3136             {
3137                 *d++ = '\\';
3138                 goto default_action;
3139             }
3140
3141             switch (*s) {
3142
3143             /* quoted - in transliterations */
3144             case '-':
3145                 if (PL_lex_inwhat == OP_TRANS) {
3146                     *d++ = *s++;
3147                     continue;
3148                 }
3149                 /* FALLTHROUGH */
3150             default:
3151                 {
3152                     if ((isALPHANUMERIC(*s)))
3153                         Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3154                                        "Unrecognized escape \\%c passed through",
3155                                        *s);
3156                     /* default action is to copy the quoted character */
3157                     goto default_action;
3158                 }
3159
3160             /* eg. \132 indicates the octal constant 0132 */
3161             case '0': case '1': case '2': case '3':
3162             case '4': case '5': case '6': case '7':
3163                 {
3164                     I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
3165                     STRLEN len = 3;
3166                     uv = grok_oct(s, &len, &flags, NULL);
3167                     s += len;
3168                     if (len < 3 && s < send && isDIGIT(*s)
3169                         && ckWARN(WARN_MISC))
3170                     {
3171                         Perl_warner(aTHX_ packWARN(WARN_MISC),
3172                                     "%s", form_short_octal_warning(s, len));
3173                     }
3174                 }
3175                 goto NUM_ESCAPE_INSERT;
3176
3177             /* eg. \o{24} indicates the octal constant \024 */
3178             case 'o':
3179                 {
3180                     const char* error;
3181
3182                     bool valid = grok_bslash_o(&s, &uv, &error,
3183                                                TRUE, /* Output warning */
3184                                                FALSE, /* Not strict */
3185                                                TRUE, /* Output warnings for
3186                                                          non-portables */
3187                                                UTF);
3188                     if (! valid) {
3189                         yyerror(error);
3190                         continue;
3191                     }
3192                     goto NUM_ESCAPE_INSERT;
3193                 }
3194
3195             /* eg. \x24 indicates the hex constant 0x24 */
3196             case 'x':
3197                 {
3198                     const char* error;
3199
3200                     bool valid = grok_bslash_x(&s, &uv, &error,
3201                                                TRUE, /* Output warning */
3202                                                FALSE, /* Not strict */
3203                                                TRUE,  /* Output warnings for
3204                                                          non-portables */
3205                                                UTF);
3206                     if (! valid) {
3207                         yyerror(error);
3208                         continue;
3209                     }
3210                 }
3211
3212               NUM_ESCAPE_INSERT:
3213                 /* Insert oct or hex escaped character.  There will always be
3214                  * enough room in sv since such escapes will be longer than any
3215                  * UTF-8 sequence they can end up as, except if they force us
3216                  * to recode the rest of the string into utf8 */
3217                 
3218                 /* Here uv is the ordinal of the next character being added */
3219                 if (!UVCHR_IS_INVARIANT(uv)) {
3220                     if (!has_utf8 && uv > 255) {
3221                         /* Might need to recode whatever we have accumulated so
3222                          * far if it contains any chars variant in utf8 or
3223                          * utf-ebcdic. */
3224                           
3225                         SvCUR_set(sv, d - SvPVX_const(sv));
3226                         SvPOK_on(sv);
3227                         *d = '\0';
3228                         /* See Note on sizing above.  */
3229                         sv_utf8_upgrade_flags_grow(
3230                                          sv,
3231                                          SV_GMAGIC|SV_FORCE_UTF8_UPGRADE
3232                                                   /* Above-latin1 in string
3233                                                    * implies no encoding */
3234                                                   |SV_UTF8_NO_ENCODING,
3235                                          UNISKIP(uv) + (STRLEN)(send - s) + 1);
3236                         d = SvPVX(sv) + SvCUR(sv);
3237                         has_utf8 = TRUE;
3238                     }
3239
3240                     if (has_utf8) {
3241                         d = (char*)uvchr_to_utf8((U8*)d, uv);
3242                         if (PL_lex_inwhat == OP_TRANS
3243                             && PL_sublex_info.sub_op)
3244                         {
3245                             PL_sublex_info.sub_op->op_private |=
3246                                 (PL_lex_repl ? OPpTRANS_FROM_UTF
3247                                              : OPpTRANS_TO_UTF);
3248                         }
3249 #ifdef EBCDIC
3250                         if (uv > 255 && !dorange)
3251                             native_range = FALSE;
3252 #endif
3253                     }
3254                     else {
3255                         *d++ = (char)uv;
3256                     }
3257                 }
3258                 else {
3259                     *d++ = (char) uv;
3260                 }
3261                 continue;
3262
3263             case 'N':
3264                 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3265                  * named character, like \N{LATIN SMALL LETTER A}, or a named
3266                  * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3267                  * GRAVE}.  For convenience all three forms are referred to as
3268                  * "named characters" below.
3269                  *
3270                  * For patterns, \N also can mean to match a non-newline.  Code
3271                  * before this 'switch' statement should already have handled
3272                  * this situation, and hence this code only has to deal with
3273                  * the named character cases.
3274                  *
3275                  * For non-patterns, the named characters are converted to
3276                  * their string equivalents.  In patterns, named characters are
3277                  * not converted to their ultimate forms for the same reasons
3278                  * that other escapes aren't.  Instead, they are converted to
3279                  * the \N{U+...} form to get the value from the charnames that
3280                  * is in effect right now, while preserving the fact that it
3281                  * was a named character, so that the regex compiler knows
3282                  * this.
3283                  *
3284                  * The structure of this section of code (besides checking for
3285                  * errors and upgrading to utf8) is:
3286                  *  If the named character is of the form \N{U+...}, pass it
3287                  *      through if a pattern; otherwise convert the code point
3288                  *      to utf8
3289                  *  Otherwise must be some \N{NAME}: convert to \N{U+c1.c2...}
3290                  *      if a pattern; otherwise convert to utf8
3291                  *
3292                  * Here, 's' points to the 'N'; the test below is guaranteed to
3293                  * succeed if we are being called on a pattern, as we already
3294                  * know from a test above that the next character is a '{'.  A
3295                  * non-pattern \N must mean 'named character', which requires
3296                  * braces */
3297                 s++;
3298                 if (*s != '{') {
3299                     yyerror("Missing braces on \\N{}"); 
3300                     continue;
3301                 }
3302                 s++;
3303
3304                 /* If there is no matching '}', it is an error. */
3305                 if (! (e = strchr(s, '}'))) {
3306                     if (! PL_lex_inpat) {
3307                         yyerror("Missing right brace on \\N{}");
3308                     } else {
3309                         yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3310                     }
3311                     continue;
3312                 }
3313
3314                 /* Here it looks like a named character */
3315
3316                 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3317                     s += 2;         /* Skip to next char after the 'U+' */
3318                     if (PL_lex_inpat) {
3319
3320                         /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3321                         /* Check the syntax.  */
3322                         const char *orig_s;
3323                         orig_s = s - 5;
3324                         if (!isXDIGIT(*s)) {
3325                           bad_NU:
3326                             yyerror(
3327                                 "Invalid hexadecimal number in \\N{U+...}"
3328                             );
3329                             s = e + 1;
3330                             continue;
3331                         }
3332                         while (++s < e) {
3333                             if (isXDIGIT(*s))
3334                                 continue;
3335                             else if ((*s == '.' || *s == '_')
3336                                   && isXDIGIT(s[1]))
3337                                 continue;
3338                             goto bad_NU;
3339                         }
3340
3341                         /* Pass everything through unchanged.
3342                          * +1 is for the '}' */
3343                         Copy(orig_s, d, e - orig_s + 1, char);
3344                         d += e - orig_s + 1;
3345                     }
3346                     else {  /* Not a pattern: convert the hex to string */
3347                         I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3348                                 | PERL_SCAN_SILENT_ILLDIGIT
3349                                 | PERL_SCAN_DISALLOW_PREFIX;
3350                         STRLEN len = e - s;
3351                         uv = grok_hex(s, &len, &flags, NULL);
3352                         if (len == 0 || (len != (STRLEN)(e - s)))
3353                             goto bad_NU;
3354
3355                          /* If the destination is not in utf8, unconditionally
3356                           * recode it to be so.  This is because \N{} implies
3357                           * Unicode semantics, and scalars have to be in utf8
3358                           * to guarantee those semantics */
3359                         if (! has_utf8) {
3360                             SvCUR_set(sv, d - SvPVX_const(sv));
3361                             SvPOK_on(sv);
3362                             *d = '\0';
3363                             /* See Note on sizing above.  */
3364                             sv_utf8_upgrade_flags_grow(
3365                                         sv,
3366                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3367                                         UNISKIP(uv) + (STRLEN)(send - e) + 1);
3368                             d = SvPVX(sv) + SvCUR(sv);
3369                             has_utf8 = TRUE;
3370                         }
3371
3372                         /* Add the (Unicode) code point to the output. */
3373                         if (UNI_IS_INVARIANT(uv)) {
3374                             *d++ = (char) LATIN1_TO_NATIVE(uv);
3375                         }
3376                         else {
3377                             d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv, 0);
3378                         }
3379                     }
3380                 }
3381                 else /* Here is \N{NAME} but not \N{U+...}. */
3382                      if ((res = get_and_check_backslash_N_name(s, e)))
3383                 {
3384                     STRLEN len;
3385                     const char *str = SvPV_const(res, len);
3386                     if (PL_lex_inpat) {
3387
3388                         if (! len) { /* The name resolved to an empty string */
3389                             Copy("\\N{}", d, 4, char);
3390                             d += 4;
3391                         }
3392                         else {
3393                             /* In order to not lose information for the regex
3394                             * compiler, pass the result in the specially made
3395                             * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3396                             * the code points in hex of each character
3397                             * returned by charnames */
3398
3399                             const char *str_end = str + len;
3400                             const STRLEN off = d - SvPVX_const(sv);
3401
3402                             if (! SvUTF8(res)) {
3403                                 /* For the non-UTF-8 case, we can determine the
3404                                  * exact length needed without having to parse
3405                                  * through the string.  Each character takes up
3406                                  * 2 hex digits plus either a trailing dot or
3407                                  * the "}" */
3408                                 const char initial_text[] = "\\N{U+";
3409                                 const STRLEN initial_len = sizeof(initial_text)
3410                                                            - 1;
3411                                 d = off + SvGROW(sv, off
3412                                                     + 3 * len
3413
3414                                                     /* +1 for trailing NUL */
3415                                                     + initial_len + 1
3416
3417                                                     + (STRLEN)(send - e));
3418                                 Copy(initial_text, d, initial_len, char);
3419                                 d += initial_len;
3420                                 while (str < str_end) {
3421                                     char hex_string[4];
3422                                     int len =
3423                                         my_snprintf(hex_string,
3424                                                   sizeof(hex_string),
3425                                                   "%02X.",
3426
3427                                                   /* The regex compiler is
3428                                                    * expecting Unicode, not
3429                                                    * native */
3430                                                   (U8) NATIVE_TO_LATIN1(*str));
3431                                     PERL_MY_SNPRINTF_POST_GUARD(len,
3432                                                            sizeof(hex_string));
3433                                     Copy(hex_string, d, 3, char);
3434                                     d += 3;
3435                                     str++;
3436                                 }
3437                                 d--;    /* Below, we will overwrite the final
3438                                            dot with a right brace */
3439                             }
3440                             else {
3441                                 STRLEN char_length; /* cur char's byte length */
3442
3443                                 /* and the number of bytes after this is
3444                                  * translated into hex digits */
3445                                 STRLEN output_length;
3446
3447                                 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3448                                  * for max('U+', '.'); and 1 for NUL */
3449                                 char hex_string[2 * UTF8_MAXBYTES + 5];
3450
3451                                 /* Get the first character of the result. */
3452                                 U32 uv = utf8n_to_uvchr((U8 *) str,
3453                                                         len,
3454                                                         &char_length,
3455                                                         UTF8_ALLOW_ANYUV);
3456                                 /* Convert first code point to Unicode hex,
3457                                  * including the boiler plate before it. */
3458                                 output_length =
3459                                     my_snprintf(hex_string, sizeof(hex_string),
3460                                              "\\N{U+%X",
3461                                              (unsigned int) NATIVE_TO_UNI(uv));
3462
3463                                 /* Make sure there is enough space to hold it */
3464                                 d = off + SvGROW(sv, off
3465                                                     + output_length
3466                                                     + (STRLEN)(send - e)
3467                                                     + 2);       /* '}' + NUL */
3468                                 /* And output it */
3469                                 Copy(hex_string, d, output_length, char);
3470                                 d += output_length;
3471
3472                                 /* For each subsequent character, append dot and
3473                                 * its Unicode code point in hex */
3474                                 while ((str += char_length) < str_end) {
3475                                     const STRLEN off = d - SvPVX_const(sv);
3476                                     U32 uv = utf8n_to_uvchr((U8 *) str,
3477                                                             str_end - str,
3478                                                             &char_length,
3479                                                             UTF8_ALLOW_ANYUV);
3480                                     output_length =
3481                                         my_snprintf(hex_string,
3482                                              sizeof(hex_string),
3483                                              ".%X",
3484                                              (unsigned int) NATIVE_TO_UNI(uv));
3485
3486                                     d = off + SvGROW(sv, off
3487                                                         + output_length
3488                                                         + (STRLEN)(send - e)
3489                                                         + 2);   /* '}' +  NUL */
3490                                     Copy(hex_string, d, output_length, char);
3491                                     d += output_length;
3492                                 }
3493                             }
3494
3495                             *d++ = '}'; /* Done.  Add the trailing brace */
3496                         }
3497                     }
3498                     else { /* Here, not in a pattern.  Convert the name to a
3499                             * string. */
3500
3501                          /* If destination is not in utf8, unconditionally
3502                           * recode it to be so.  This is because \N{} implies
3503                           * Unicode semantics, and scalars have to be in utf8
3504                           * to guarantee those semantics */
3505                         if (! has_utf8) {
3506                             SvCUR_set(sv, d - SvPVX_const(sv));
3507                             SvPOK_on(sv);
3508                             *d = '\0';
3509                             /* See Note on sizing above.  */
3510                             sv_utf8_upgrade_flags_grow(sv,
3511                                                 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3512                                                 len + (STRLEN)(send - s) + 1);
3513                             d = SvPVX(sv) + SvCUR(sv);
3514                             has_utf8 = TRUE;
3515                         } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3516
3517                             /* See Note on sizing above.  (NOTE: SvCUR() is not
3518                              * set correctly here). */
3519                             const STRLEN off = d - SvPVX_const(sv);
3520                             d = off + SvGROW(sv, off + len + (STRLEN)(send - s) + 1);
3521                         }
3522                         if (! SvUTF8(res)) {    /* Make sure \N{} return is UTF-8 */
3523                             sv_utf8_upgrade_flags(res, SV_UTF8_NO_ENCODING);
3524                             str = SvPV_const(res, len);
3525                         }
3526                         Copy(str, d, len, char);
3527                         d += len;
3528                     }
3529
3530                     SvREFCNT_dec(res);
3531
3532                 } /* End \N{NAME} */
3533 #ifdef EBCDIC
3534                 if (!dorange) 
3535                     native_range = FALSE; /* \N{} is defined to be Unicode */
3536 #endif
3537                 s = e + 1;  /* Point to just after the '}' */
3538                 continue;
3539
3540             /* \c is a control character */
3541             case 'c':
3542                 s++;
3543                 if (s < send) {
3544                     *d++ = grok_bslash_c(*s++, 1);
3545                 }
3546                 else {
3547                     yyerror("Missing control char name in \\c");
3548                 }
3549                 continue;
3550
3551             /* printf-style backslashes, formfeeds, newlines, etc */
3552             case 'b':
3553                 *d++ = '\b';
3554                 break;
3555             case 'n':
3556                 *d++ = '\n';
3557                 break;
3558             case 'r':
3559                 *d++ = '\r';
3560                 break;
3561             case 'f':
3562                 *d++ = '\f';
3563                 break;
3564             case 't':
3565                 *d++ = '\t';
3566                 break;
3567             case 'e':
3568                 *d++ = ESC_NATIVE;
3569                 break;
3570             case 'a':
3571                 *d++ = '\a';
3572                 break;
3573             } /* end switch */
3574
3575             s++;
3576             continue;
3577         } /* end if (backslash) */
3578 #ifdef EBCDIC
3579         else
3580             literal_endpoint++;
3581 #endif
3582
3583     default_action:
3584         /* If we started with encoded form, or already know we want it,
3585            then encode the next character */
3586         if (! NATIVE_BYTE_IS_INVARIANT((U8)(*s)) && (this_utf8 || has_utf8)) {
3587             STRLEN len  = 1;
3588
3589
3590             /* One might think that it is wasted effort in the case of the
3591              * source being utf8 (this_utf8 == TRUE) to take the next character
3592              * in the source, convert it to an unsigned value, and then convert
3593              * it back again.  But the source has not been validated here.  The
3594              * routine that does the conversion checks for errors like
3595              * malformed utf8 */
3596
3597             const UV nextuv   = (this_utf8)
3598                                 ? utf8n_to_uvchr((U8*)s, send - s, &len, 0)
3599                                 : (UV) ((U8) *s);
3600             const STRLEN need = UNISKIP(nextuv);
3601             if (!has_utf8) {
3602                 SvCUR_set(sv, d - SvPVX_const(sv));
3603                 SvPOK_on(sv);
3604                 *d = '\0';
3605                 /* See Note on sizing above.  */
3606                 sv_utf8_upgrade_flags_grow(sv,
3607                                         SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3608                                         need + (STRLEN)(send - s) + 1);
3609                 d = SvPVX(sv) + SvCUR(sv);
3610                 has_utf8 = TRUE;
3611             } else if (need > len) {
3612                 /* encoded value larger than old, may need extra space (NOTE:
3613                  * SvCUR() is not set correctly here).   See Note on sizing
3614                  * above.  */
3615                 const STRLEN off = d - SvPVX_const(sv);
3616                 d = SvGROW(sv, off + need + (STRLEN)(send - s) + 1) + off;
3617             }
3618             s += len;
3619
3620             d = (char*)uvchr_to_utf8((U8*)d, nextuv);
3621 #ifdef EBCDIC
3622             if (uv > 255 && !dorange)
3623                 native_range = FALSE;
3624 #endif
3625         }
3626         else {
3627             *d++ = *s++;
3628         }
3629     } /* while loop to process each character */
3630
3631     /* terminate the string and set up the sv */
3632     *d = '\0';
3633     SvCUR_set(sv, d - SvPVX_const(sv));
3634     if (SvCUR(sv) >= SvLEN(sv))
3635         Perl_croak(aTHX_ "panic: constant overflowed allocated space, %"UVuf
3636                    " >= %"UVuf, (UV)SvCUR(sv), (UV)SvLEN(sv));
3637
3638     SvPOK_on(sv);
3639     if (IN_ENCODING && !has_utf8) {
3640         sv_recode_to_utf8(sv, _get_encoding());
3641         if (SvUTF8(sv))
3642             has_utf8 = TRUE;
3643     }
3644     if (has_utf8) {
3645         SvUTF8_on(sv);
3646         if (PL_lex_inwhat == OP_TRANS && PL_sublex_info.sub_op) {
3647             PL_sublex_info.sub_op->op_private |=
3648                     (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
3649         }
3650     }
3651
3652     /* shrink the sv if we allocated more than we used */
3653     if (SvCUR(sv) + 5 < SvLEN(sv)) {
3654         SvPV_shrink_to_cur(sv);
3655     }
3656
3657     /* return the substring (via pl_yylval) only if we parsed anything */
3658     if (s > start) {
3659         char *s2 = start;
3660         for (; s2 < s; s2++) {
3661             if (*s2 == '\n')
3662                 COPLINE_INC_WITH_HERELINES;
3663         }
3664         SvREFCNT_inc_simple_void_NN(sv);
3665         if (   (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
3666             && ! PL_parser->lex_re_reparsing)
3667         {
3668             const char *const key = PL_lex_inpat ? "qr" : "q";
3669             const STRLEN keylen = PL_lex_inpat ? 2 : 1;
3670             const char *type;
3671             STRLEN typelen;
3672
3673             if (PL_lex_inwhat == OP_TRANS) {
3674                 type = "tr";
3675                 typelen = 2;
3676             } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
3677                 type = "s";
3678                 typelen = 1;
3679             } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
3680                 type = "q";
3681                 typelen = 1;
3682             } else  {
3683                 type = "qq";
3684                 typelen = 2;
3685             }
3686
3687             sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
3688                                 type, typelen);
3689         }
3690         pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
3691     }
3692     LEAVE_with_name("scan_const");
3693     return s;
3694 }
3695
3696 /* S_intuit_more
3697  * Returns TRUE if there's more to the expression (e.g., a subscript),
3698  * FALSE otherwise.
3699  *
3700  * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
3701  *
3702  * ->[ and ->{ return TRUE
3703  * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
3704  * { and [ outside a pattern are always subscripts, so return TRUE
3705  * if we're outside a pattern and it's not { or [, then return FALSE
3706  * if we're in a pattern and the first char is a {
3707  *   {4,5} (any digits around the comma) returns FALSE
3708  * if we're in a pattern and the first char is a [
3709  *   [] returns FALSE
3710  *   [SOMETHING] has a funky algorithm to decide whether it's a
3711  *      character class or not.  It has to deal with things like
3712  *      /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
3713  * anything else returns TRUE
3714  */
3715
3716 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
3717
3718 STATIC int
3719 S_intuit_more(pTHX_ char *s)
3720 {
3721     PERL_ARGS_ASSERT_INTUIT_MORE;
3722
3723     if (PL_lex_brackets)
3724         return TRUE;
3725     if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
3726         return TRUE;
3727     if (*s == '-' && s[1] == '>'
3728      && FEATURE_POSTDEREF_QQ_IS_ENABLED
3729      && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
3730         ||(s[2] == '@' && strchr("*[{",s[3])) ))
3731         return TRUE;
3732     if (*s != '{' && *s != '[')
3733         return FALSE;
3734     if (!PL_lex_inpat)
3735         return TRUE;
3736
3737     /* In a pattern, so maybe we have {n,m}. */
3738     if (*s == '{') {
3739         if (regcurly(s)) {
3740             return FALSE;
3741         }
3742         return TRUE;
3743     }
3744
3745     /* On the other hand, maybe we have a character class */
3746
3747     s++;
3748     if (*s == ']' || *s == '^')
3749         return FALSE;
3750     else {
3751         /* this is terrifying, and it works */
3752         int weight;
3753         char seen[256];
3754         const char * const send = strchr(s,']');
3755         unsigned char un_char, last_un_char;
3756         char tmpbuf[sizeof PL_tokenbuf * 4];
3757
3758         if (!send)              /* has to be an expression */
3759             return TRUE;
3760         weight = 2;             /* let's weigh the evidence */
3761
3762         if (*s == '$')
3763             weight -= 3;
3764         else if (isDIGIT(*s)) {
3765             if (s[1] != ']') {
3766                 if (isDIGIT(s[1]) && s[2] == ']')
3767                     weight -= 10;
3768             }
3769             else
3770                 weight -= 100;
3771         }
3772         Zero(seen,256,char);
3773         un_char = 255;
3774         for (; s < send; s++) {
3775             last_un_char = un_char;
3776             un_char = (unsigned char)*s;
3777             switch (*s) {
3778             case '@':
3779             case '&':
3780             case '$':
3781                 weight -= seen[un_char] * 10;
3782                 if (isWORDCHAR_lazy_if(s+1,UTF)) {
3783                     int len;
3784                     char *tmp = PL_bufend;
3785                     PL_bufend = (char*)send;
3786                     scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
3787                     PL_bufend = tmp;
3788                     len = (int)strlen(tmpbuf);
3789                     if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
3790                                                     UTF ? SVf_UTF8 : 0, SVt_PV))
3791                         weight -= 100;
3792                     else
3793                         weight -= 10;
3794                 }
3795                 else if (*s == '$'
3796                          && s[1]
3797                          && strchr("[#!%*<>()-=",s[1]))
3798                 {
3799                     if (/*{*/ strchr("])} =",s[2]))
3800                         weight -= 10;
3801                     else
3802                         weight -= 1;
3803                 }
3804                 break;
3805             case '\\':
3806                 un_char = 254;
3807                 if (s[1]) {
3808                     if (strchr("wds]",s[1]))
3809                         weight += 100;
3810                     else if (seen[(U8)'\''] || seen[(U8)'"'])
3811                         weight += 1;
3812                     else if (strchr("rnftbxcav",s[1]))
3813                         weight += 40;
3814                     else if (isDIGIT(s[1])) {
3815                         weight += 40;
3816                         while (s[1] && isDIGIT(s[1]))
3817                             s++;
3818                     }
3819                 }
3820                 else
3821                     weight += 100;
3822                 break;
3823             case '-':
3824                 if (s[1] == '\\')
3825                     weight += 50;
3826                 if (strchr("aA01! ",last_un_char))
3827                     weight += 30;
3828                 if (strchr("zZ79~",s[1]))
3829                     weight += 30;
3830                 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
3831                     weight -= 5;        /* cope with negative subscript */
3832                 break;
3833             default:
3834                 if (!isWORDCHAR(last_un_char)
3835                     && !(last_un_char == '$' || last_un_char == '@'
3836                          || last_un_char == '&')
3837                     && isALPHA(*s) && s[1] && isALPHA(s[1])) {
3838                     char *d = s;
3839                     while (isALPHA(*s))
3840                         s++;
3841                     if (keyword(d, s - d, 0))
3842                         weight -= 150;
3843                 }
3844                 if (un_char == last_un_char + 1)
3845                     weight += 5;
3846                 weight -= seen[un_char];
3847                 break;
3848             }
3849             seen[un_char]++;
3850         }
3851         if (weight >= 0)        /* probably a character class */
3852             return FALSE;
3853     }
3854
3855     return TRUE;
3856 }
3857
3858 /*
3859  * S_intuit_method
3860  *
3861  * Does all the checking to disambiguate
3862  *   foo bar
3863  * between foo(bar) and bar->foo.  Returns 0 if not a method, otherwise
3864  * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
3865  *
3866  * First argument is the stuff after the first token, e.g. "bar".
3867  *
3868  * Not a method if foo is a filehandle.
3869  * Not a method if foo is a subroutine prototyped to take a filehandle.
3870  * Not a method if it's really "Foo $bar"
3871  * Method if it's "foo $bar"
3872  * Not a method if it's really "print foo $bar"
3873  * Method if it's really "foo package::" (interpreted as package->foo)
3874  * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
3875  * Not a method if bar is a filehandle or package, but is quoted with
3876  *   =>
3877  */
3878
3879 STATIC int
3880 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
3881 {
3882     char *s = start + (*start == '$');
3883     char tmpbuf[sizeof PL_tokenbuf];
3884     STRLEN len;
3885     GV* indirgv;
3886         /* Mustn't actually add anything to a symbol table.
3887            But also don't want to "initialise" any placeholder
3888            constants that might already be there into full
3889            blown PVGVs with attached PVCV.  */
3890     GV * const gv =
3891         ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
3892
3893     PERL_ARGS_ASSERT_INTUIT_METHOD;
3894
3895     if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
3896             return 0;
3897     if (cv && SvPOK(cv)) {
3898         const char *proto = CvPROTO(cv);
3899         if (proto) {
3900             while (*proto && (isSPACE(*proto) || *proto == ';'))
3901                 proto++;
3902             if (*proto == '*')
3903                 return 0;
3904         }
3905     }
3906
3907     if (*start == '$') {
3908         if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
3909             || isUPPER(*PL_tokenbuf))
3910             return 0;
3911         s = skipspace(s);
3912         PL_bufptr = start;
3913         PL_expect = XREF;
3914         return *s == '(' ? FUNCMETH : METHOD;
3915     }
3916
3917     s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
3918     /* start is the beginning of the possible filehandle/object,
3919      * and s is the end of it
3920      * tmpbuf is a copy of it (but with single quotes as double colons)
3921      */
3922
3923     if (!keyword(tmpbuf, len, 0)) {
3924         if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
3925             len -= 2;
3926             tmpbuf[len] = '\0';
3927             goto bare_package;
3928         }
3929         indirgv = gv_fetchpvn_flags(tmpbuf, len, ( UTF ? SVf_UTF8 : 0 ), SVt_PVCV);
3930         if (indirgv && GvCVu(indirgv))
3931             return 0;
3932         /* filehandle or package name makes it a method */
3933         if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
3934             s = skipspace(s);
3935             if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
3936                 return 0;       /* no assumptions -- "=>" quotes bareword */
3937       bare_package:
3938             NEXTVAL_NEXTTOKE.opval = (OP*)newSVOP(OP_CONST, 0,
3939                                                   S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
3940             NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
3941             PL_expect = XTERM;
3942             force_next(WORD);
3943             PL_bufptr = s;
3944             return *s == '(' ? FUNCMETH : METHOD;
3945         }
3946     }
3947     return 0;
3948 }
3949
3950 /* Encoded script support. filter_add() effectively inserts a
3951  * 'pre-processing' function into the current source input stream.
3952  * Note that the filter function only applies to the current source file
3953  * (e.g., it will not affect files 'require'd or 'use'd by this one).
3954  *
3955  * The datasv parameter (which may be NULL) can be used to pass
3956  * private data to this instance of the filter. The filter function
3957  * can recover the SV using the FILTER_DATA macro and use it to
3958  * store private buffers and state information.
3959  *
3960  * The supplied datasv parameter is upgraded to a PVIO type
3961  * and the IoDIRP/IoANY field is used to store the function pointer,
3962  * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
3963  * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
3964  * private use must be set using malloc'd pointers.
3965  */
3966
3967 SV *
3968 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
3969 {
3970     if (!funcp)
3971         return NULL;
3972
3973     if (!PL_parser)
3974         return NULL;
3975
3976     if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
3977         Perl_croak(aTHX_ "Source filters apply only to byte streams");
3978
3979     if (!PL_rsfp_filters)
3980         PL_rsfp_filters = newAV();
3981     if (!datasv)
3982         datasv = newSV(0);
3983     SvUPGRADE(datasv, SVt_PVIO);
3984     IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
3985     IoFLAGS(datasv) |= IOf_FAKE_DIRP;
3986     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
3987                           FPTR2DPTR(void *, IoANY(datasv)),
3988                           SvPV_nolen(datasv)));
3989     av_unshift(PL_rsfp_filters, 1);
3990     av_store(PL_rsfp_filters, 0, datasv) ;
3991     if (
3992         !PL_parser->filtered
3993      && PL_parser->lex_flags & LEX_EVALBYTES
3994      && PL_bufptr < PL_bufend
3995     ) {
3996         const char *s = PL_bufptr;
3997         while (s < PL_bufend) {
3998             if (*s == '\n') {
3999                 SV *linestr = PL_parser->linestr;
4000                 char *buf = SvPVX(linestr);
4001                 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4002                 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4003                 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4004                 STRLEN const linestart_pos = PL_parser->linestart - buf;
4005                 STRLEN const last_uni_pos =
4006                     PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4007                 STRLEN const last_lop_pos =
4008                     PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4009                 av_push(PL_rsfp_filters, linestr);
4010                 PL_parser->linestr = 
4011                     newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4012                 buf = SvPVX(PL_parser->linestr);
4013                 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4014                 PL_parser->bufptr = buf + bufptr_pos;
4015                 PL_parser->oldbufptr = buf + oldbufptr_pos;
4016                 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4017                 PL_parser->linestart = buf + linestart_pos;
4018                 if (PL_parser->last_uni)
4019                     PL_parser->last_uni = buf + last_uni_pos;
4020                 if (PL_parser->last_lop)
4021                     PL_parser->last_lop = buf + last_lop_pos;
4022                 SvLEN(linestr) = SvCUR(linestr);
4023                 SvCUR(linestr) = s-SvPVX(linestr);
4024                 PL_parser->filtered = 1;
4025                 break;
4026             }
4027             s++;
4028         }
4029     }
4030     return(datasv);
4031 }
4032
4033
4034 /* Delete most recently added instance of this filter function. */
4035 void
4036 Perl_filter_del(pTHX_ filter_t funcp)
4037 {
4038     SV *datasv;
4039
4040     PERL_ARGS_ASSERT_FILTER_DEL;
4041
4042 #ifdef DEBUGGING
4043     DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4044                           FPTR2DPTR(void*, funcp)));
4045 #endif
4046     if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4047         return;
4048     /* if filter is on top of stack (usual case) just pop it off */
4049     datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4050     if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4051         sv_free(av_pop(PL_rsfp_filters));
4052
4053         return;
4054     }
4055     /* we need to search for the correct entry and clear it     */
4056     Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4057 }
4058
4059
4060 /* Invoke the idxth filter function for the current rsfp.        */
4061 /* maxlen 0 = read one text line */
4062 I32
4063 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4064 {
4065     filter_t funcp;
4066     SV *datasv = NULL;
4067     /* This API is bad. It should have been using unsigned int for maxlen.
4068        Not sure if we want to change the API, but if not we should sanity
4069        check the value here.  */
4070     unsigned int correct_length = maxlen < 0 ?  PERL_INT_MAX : maxlen;
4071
4072     PERL_ARGS_ASSERT_FILTER_READ;
4073
4074     if (!PL_parser || !PL_rsfp_filters)
4075         return -1;
4076     if (idx > AvFILLp(PL_rsfp_filters)) {       /* Any more filters?    */
4077         /* Provide a default input filter to make life easy.    */
4078         /* Note that we append to the line. This is handy.      */
4079         DEBUG_P(PerlIO_printf(Perl_debug_log,
4080                               "filter_read %d: from rsfp\n", idx));
4081         if (correct_length) {
4082             /* Want a block */
4083             int len ;
4084             const int old_len = SvCUR(buf_sv);
4085
4086             /* ensure buf_sv is large enough */
4087             SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4088             if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4089                                    correct_length)) <= 0) {
4090                 if (PerlIO_error(PL_rsfp))
4091                     return -1;          /* error */
4092                 else
4093                     return 0 ;          /* end of file */
4094             }
4095             SvCUR_set(buf_sv, old_len + len) ;
4096             SvPVX(buf_sv)[old_len + len] = '\0';
4097         } else {
4098             /* Want a line */
4099             if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4100                 if (PerlIO_error(PL_rsfp))
4101                     return -1;          /* error */
4102                 else
4103                     return 0 ;          /* end of file */
4104             }
4105         }
4106         return SvCUR(buf_sv);
4107     }
4108     /* Skip this filter slot if filter has been deleted */
4109     if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4110         DEBUG_P(PerlIO_printf(Perl_debug_log,
4111                               "filter_read %d: skipped (filter deleted)\n",
4112                               idx));
4113         return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4114     }
4115     if (SvTYPE(datasv) != SVt_PVIO) {
4116         if (correct_length) {
4117             /* Want a block */
4118             const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4119             if (!remainder) return 0; /* eof */
4120             if (correct_length > remainder) correct_length = remainder;
4121             sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4122             SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4123         } else {
4124             /* Want a line */
4125             const char *s = SvEND(datasv);
4126             const char *send = SvPVX(datasv) + SvLEN(datasv);
4127             while (s < send) {
4128                 if (*s == '\n') {
4129                     s++;
4130                     break;
4131                 }
4132                 s++;
4133             }
4134             if (s == send) return 0; /* eof */
4135             sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));
4136             SvCUR_set(datasv, s-SvPVX(datasv));
4137         }
4138         return SvCUR(buf_sv);
4139     }
4140     /* Get function pointer hidden within datasv        */
4141     funcp = DPTR2FPTR(filter_t, IoANY(datasv));
4142     DEBUG_P(PerlIO_printf(Perl_debug_log,
4143                           "filter_read %d: via function %p (%s)\n",
4144                           idx, (void*)datasv, SvPV_nolen_const(datasv)));
4145     /* Call function. The function is expected to       */
4146     /* call "FILTER_READ(idx+1, buf_sv)" first.         */
4147     /* Return: <0:error, =0:eof, >0:not eof             */
4148     return (*funcp)(aTHX_ idx, buf_sv, correct_length);
4149 }
4150
4151 STATIC char *
4152 S_filter_gets(pTHX_ SV *sv, STRLEN append)
4153 {
4154     PERL_ARGS_ASSERT_FILTER_GETS;
4155
4156 #ifdef PERL_CR_FILTER
4157     if (!PL_rsfp_filters) {
4158         filter_add(S_cr_textfilter,NULL);
4159     }
4160 #endif
4161     if (PL_rsfp_filters) {
4162         if (!append)
4163             SvCUR_set(sv, 0);   /* start with empty line        */
4164         if (FILTER_READ(0, sv, 0) > 0)
4165             return ( SvPVX(sv) ) ;
4166         else
4167             return NULL ;
4168     }
4169     else
4170         return (sv_gets(sv, PL_rsfp, append));
4171 }
4172
4173 STATIC HV *
4174 S_find_in_my_stash(pTHX_ const char *pkgname, STRLEN len)
4175 {
4176     GV *gv;
4177
4178     PERL_ARGS_ASSERT_FIND_IN_MY_STASH;
4179
4180     if (len == 11 && *pkgname == '_' && strEQ(pkgname, "__PACKAGE__"))
4181         return PL_curstash;
4182
4183     if (len > 2
4184         && (pkgname[len - 2] == ':' && pkgname[len - 1] == ':')
4185         && (gv = gv_fetchpvn_flags(pkgname,
4186                                    len,
4187                                    ( UTF ? SVf_UTF8 : 0 ), SVt_PVHV)))
4188     {
4189         return GvHV(gv);                        /* Foo:: */
4190     }
4191
4192     /* use constant CLASS => 'MyClass' */
4193     gv = gv_fetchpvn_flags(pkgname, len, UTF ? SVf_UTF8 : 0, SVt_PVCV);
4194     if (gv && GvCV(gv)) {
4195         SV * const sv = cv_const_sv(GvCV(gv));
4196         if (sv)
4197             return gv_stashsv(sv, 0);
4198     }
4199
4200     return gv_stashpvn(pkgname, len, UTF ? SVf_UTF8 : 0);
4201 }
4202
4203
4204 STATIC char *
4205 S_tokenize_use(pTHX_ int is_use, char *s) {
4206     PERL_ARGS_ASSERT_TOKENIZE_USE;
4207
4208     if (PL_expect != XSTATE)
4209         yyerror(Perl_form(aTHX_ "\"%s\" not allowed in expression",
4210                     is_use ? "use" : "no"));
4211     PL_expect = XTERM;
4212     s = skipspace(s);
4213     if (isDIGIT(*s) || (*s == 'v' && isDIGIT(s[1]))) {
4214         s = force_version(s, TRUE);
4215         if (*s == ';' || *s == '}'
4216                 || (s = skipspace(s), (*s == ';' || *s == '}'))) {
4217             NEXTVAL_NEXTTOKE.opval = NULL;
4218             force_next(WORD);
4219         }
4220         else if (*s == 'v') {
4221             s = force_word(s,WORD,FALSE,TRUE);
4222             s = force_version(s, FALSE);
4223         }
4224     }
4225     else {
4226         s = force_word(s,WORD,FALSE,TRUE);
4227         s = force_version(s, FALSE);
4228     }
4229     pl_yylval.ival = is_use;
4230     return s;
4231 }
4232 #ifdef DEBUGGING
4233     static const char* const exp_name[] =
4234         { "OPERATOR", "TERM", "REF", "STATE", "BLOCK", "ATTRBLOCK",
4235           "ATTRTERM", "TERMBLOCK", "XBLOCKTERM", "POSTDEREF",
4236           "TERMORDORDOR"
4237         };
4238 #endif
4239
4240 #define word_takes_any_delimeter(p,l) S_word_takes_any_delimeter(p,l)
4241 STATIC bool
4242 S_word_takes_any_delimeter(char *p, STRLEN len)
4243 {
4244     return (len == 1 && strchr("msyq", p[0]))
4245             || (len == 2
4246                 && ((p[0] == 't' && p[1] == 'r')
4247                     || (p[0] == 'q' && strchr("qwxr", p[1]))));
4248 }
4249
4250 static void
4251 S_check_scalar_slice(pTHX_ char *s)
4252 {
4253     s++;
4254     while (*s == ' ' || *s == '\t') s++;
4255     if (*s == 'q' && s[1] == 'w'
4256      && !isWORDCHAR_lazy_if(s+2,UTF))
4257         return;
4258     while (*s && (isWORDCHAR_lazy_if(s,UTF) || strchr(" \t$#+-'\"", *s)))
4259         s += UTF ? UTF8SKIP(s) : 1;
4260     if (*s == '}' || *s == ']')
4261         pl_yylval.ival = OPpSLICEWARNING;
4262 }
4263
4264 /*
4265   yylex
4266
4267   Works out what to call the token just pulled out of the input
4268   stream.  The yacc parser takes care of taking the ops we return and
4269   stitching them into a tree.
4270
4271   Returns:
4272     The type of the next token
4273
4274   Structure:
4275       Switch based on the current state:
4276           - if we already built the token before, use it
4277           - if we have a case modifier in a string, deal with that
4278           - handle other cases of interpolation inside a string
4279           - scan the next line if we are inside a format
4280       In the normal state switch on the next character:
4281           - default:
4282             if alphabetic, go to key lookup
4283             unrecoginized character - croak
4284           - 0/4/26: handle end-of-line or EOF
4285           - cases for whitespace
4286           - \n and #: handle comments and line numbers
4287           - various operators, brackets and sigils
4288           - numbers
4289           - quotes
4290           - 'v': vstrings (or go to key lookup)
4291           - 'x' repetition operator (or go to key lookup)
4292           - other ASCII alphanumerics (key lookup begins here):
4293               word before => ?
4294               keyword plugin
4295               scan built-in keyword (but do nothing with it yet)
4296               check for statement label
4297               check for lexical subs
4298                   goto just_a_word if there is one
4299               see whether built-in keyword is overridden
4300               switch on keyword number:
4301                   - default: just_a_word:
4302                       not a built-in keyword; handle bareword lookup
4303                       disambiguate between method and sub call
4304                       fall back to bareword
4305                   - cases for built-in keywords
4306 */
4307
4308
4309 int
4310 Perl_yylex(pTHX)
4311 {
4312     dVAR;
4313     char *s = PL_bufptr;
4314     char *d;
4315     STRLEN len;
4316     bool bof = FALSE;
4317     const bool saw_infix_sigil = cBOOL(PL_parser->saw_infix_sigil);
4318     U8 formbrack = 0;
4319     U32 fake_eof = 0;
4320
4321     /* orig_keyword, gvp, and gv are initialized here because
4322      * jump to the label just_a_word_zero can bypass their
4323      * initialization later. */
4324     I32 orig_keyword = 0;
4325     GV *gv = NULL;
4326     GV **gvp = NULL;
4327
4328     DEBUG_T( {
4329         SV* tmp = newSVpvs("");
4330         PerlIO_printf(Perl_debug_log, "### %"IVdf":LEX_%s/X%s %s\n",
4331             (IV)CopLINE(PL_curcop),
4332             lex_state_names[PL_lex_state],
4333             exp_name[PL_expect],
4334             pv_display(tmp, s, strlen(s), 0, 60));
4335         SvREFCNT_dec(tmp);
4336     } );
4337
4338     /* when we've already built the next token, just pull it out of the queue */
4339     if (PL_nexttoke) {
4340         PL_nexttoke--;
4341         pl_yylval = PL_nextval[PL_nexttoke];
4342         if (!PL_nexttoke) {
4343             PL_lex_state = PL_lex_defer;
4344             PL_lex_defer = LEX_NORMAL;
4345         }
4346         {
4347             I32 next_type;
4348             next_type = PL_nexttype[PL_nexttoke];
4349             if (next_type & (7<<24)) {
4350                 if (next_type & (1<<24)) {
4351                     if (PL_lex_brackets > 100)
4352                         Renew(PL_lex_brackstack, PL_lex_brackets + 10, char);
4353                     PL_lex_brackstack[PL_lex_brackets++] =
4354                         (char) ((next_type >> 16) & 0xff);
4355                 }
4356                 if (next_type & (2<<24))
4357                     PL_lex_allbrackets++;
4358                 if (next_type & (4<<24))
4359                     PL_lex_allbrackets--;
4360                 next_type &= 0xffff;
4361             }
4362             return REPORT(next_type == 'p' ? pending_ident() : next_type);
4363         }
4364     }
4365
4366     switch (PL_lex_state) {
4367     case LEX_NORMAL:
4368     case LEX_INTERPNORMAL:
4369         break;
4370
4371     /* interpolated case modifiers like \L \U, including \Q and \E.
4372        when we get here, PL_bufptr is at the \
4373     */
4374     case LEX_INTERPCASEMOD:
4375 #ifdef DEBUGGING
4376         if (PL_bufptr != PL_bufend && *PL_bufptr != '\\')
4377             Perl_croak(aTHX_
4378                        "panic: INTERPCASEMOD bufptr=%p, bufend=%p, *bufptr=%u",
4379                        PL_bufptr, PL_bufend, *PL_bufptr);
4380 #endif
4381         /* handle \E or end of string */
4382         if (PL_bufptr == PL_bufend || PL_bufptr[1] == 'E') {
4383             /* if at a \E */
4384             if (PL_lex_casemods) {
4385                 const char oldmod = PL_lex_casestack[--PL_lex_casemods];
4386                 PL_lex_casestack[PL_lex_casemods] = '\0';
4387
4388                 if (PL_bufptr != PL_bufend
4389                     && (oldmod == 'L' || oldmod == 'U' || oldmod == 'Q'
4390                         || oldmod == 'F')) {
4391                     PL_bufptr += 2;
4392                     PL_lex_state = LEX_INTERPCONCAT;
4393                 }
4394                 PL_lex_allbrackets--;
4395                 return REPORT(')');
4396