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