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
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.
12 * 'It all comes from here, the stench and the peril.' --Frodo
14 * [p.719 of _The Lord of the Rings_, IV/ix: "Shelob's Lair"]
18 * This file is the lexer for Perl. It's closely linked to the
21 * The main routine is yylex(), which returns the next token.
25 =head1 Lexer interface
26 This is the lower layer of the Perl parser, managing characters and tokens.
28 =for apidoc AmU|yy_parser *|PL_parser
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.
39 #define PERL_IN_TOKE_C
41 #include "dquote_inline.h"
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)
46 #define pl_yylval (PL_parser->yylval)
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)
87 # define PL_nexttoke (PL_parser->nexttoke)
88 # define PL_nexttype (PL_parser->nexttype)
89 # define PL_nextval (PL_parser->nextval)
91 static const char* const ident_too_long = "Identifier too long";
93 # define NEXTVAL_NEXTTOKE PL_nextval[PL_nexttoke]
95 #define XENUMMASK 0x3f
97 #define XFAKEBRACK 0x80
99 #ifdef USE_UTF8_SCRIPTS
100 # define UTF cBOOL(!IN_BYTES)
102 # define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8)))
105 /* The maximum number of characters preceding the unrecognized one to display */
106 #define UNRECOGNIZED_PRECEDE_COUNT 10
108 /* In variables named $^X, these are the legal values for X.
109 * 1999-02-27 mjd-perl-patch@plover.com */
110 #define isCONTROLVAR(x) (isUPPER(x) || strchr("[\\]^_?", (x)))
112 #define SPACE_OR_TAB(c) isBLANK_A(c)
114 #define HEXFP_PEEK(s) \
116 (isXDIGIT(s[1]) || isALPHA_FOLD_EQ(s[1], 'p'))) || \
117 isALPHA_FOLD_EQ(s[0], 'p'))
119 /* LEX_* are values for PL_lex_state, the state of the lexer.
120 * They are arranged oddly so that the guard on the switch statement
121 * can get by with a single comparison (if the compiler is smart enough).
123 * These values refer to the various states within a sublex parse,
124 * i.e. within a double quotish string
127 /* #define LEX_NOTPARSING 11 is done in perl.h. */
129 #define LEX_NORMAL 10 /* normal code (ie not within "...") */
130 #define LEX_INTERPNORMAL 9 /* code within a string, eg "$foo[$x+1]" */
131 #define LEX_INTERPCASEMOD 8 /* expecting a \U, \Q or \E etc */
132 #define LEX_INTERPPUSH 7 /* starting a new sublex parse level */
133 #define LEX_INTERPSTART 6 /* expecting the start of a $var */
135 /* at end of code, eg "$x" followed by: */
136 #define LEX_INTERPEND 5 /* ... eg not one of [, { or -> */
137 #define LEX_INTERPENDMAYBE 4 /* ... eg one of [, { or -> */
139 #define LEX_INTERPCONCAT 3 /* expecting anything, eg at start of
140 string or after \E, $foo, etc */
141 #define LEX_INTERPCONST 2 /* NOT USED */
142 #define LEX_FORMLINE 1 /* expecting a format line */
146 static const char* const lex_state_names[] = {
161 #include "keywords.h"
163 /* CLINE is a macro that ensures PL_copline has a sane value */
165 #define CLINE (PL_copline = (CopLINE(PL_curcop) < PL_copline ? CopLINE(PL_curcop) : PL_copline))
168 * Convenience functions to return different tokens and prime the
169 * lexer for the next token. They all take an argument.
171 * TOKEN : generic token (used for '(', DOLSHARP, etc)
172 * OPERATOR : generic operator
173 * AOPERATOR : assignment operator
174 * PREBLOCK : beginning the block after an if, while, foreach, ...
175 * PRETERMBLOCK : beginning a non-code-defining {} block (eg, hash ref)
176 * PREREF : *EXPR where EXPR is not a simple identifier
177 * TERM : expression term
178 * POSTDEREF : postfix dereference (->$* ->@[...] etc.)
179 * LOOPX : loop exiting command (goto, last, dump, etc)
180 * FTST : file test operator
181 * FUN0 : zero-argument function
182 * FUN0OP : zero-argument function, with its op created in this file
183 * FUN1 : not used, except for not, which isn't a UNIOP
184 * BOop : bitwise or or xor
186 * BCop : bitwise complement
187 * SHop : shift operator
188 * PWop : power operator
189 * PMop : pattern-matching operator
190 * Aop : addition-level operator
191 * AopNOASSIGN : addition-level operator that is never part of .=
192 * Mop : multiplication-level operator
193 * Eop : equality-testing operator
194 * Rop : relational operator <= != gt
196 * Also see LOP and lop() below.
199 #ifdef DEBUGGING /* Serve -DT. */
200 # define REPORT(retval) tokereport((I32)retval, &pl_yylval)
202 # define REPORT(retval) (retval)
205 #define TOKEN(retval) return ( PL_bufptr = s, REPORT(retval))
206 #define OPERATOR(retval) return (PL_expect = XTERM, PL_bufptr = s, REPORT(retval))
207 #define AOPERATOR(retval) return ao((PL_expect = XTERM, PL_bufptr = s, retval))
208 #define PREBLOCK(retval) return (PL_expect = XBLOCK,PL_bufptr = s, REPORT(retval))
209 #define PRETERMBLOCK(retval) return (PL_expect = XTERMBLOCK,PL_bufptr = s, REPORT(retval))
210 #define PREREF(retval) return (PL_expect = XREF,PL_bufptr = s, REPORT(retval))
211 #define TERM(retval) return (CLINE, PL_expect = XOPERATOR, PL_bufptr = s, REPORT(retval))
212 #define POSTDEREF(f) return (PL_bufptr = s, S_postderef(aTHX_ REPORT(f),s[1]))
213 #define LOOPX(f) return (PL_bufptr = force_word(s,BAREWORD,TRUE,FALSE), \
215 PL_expect = PL_nexttoke ? XOPERATOR : XTERM, \
217 #define FTST(f) return (pl_yylval.ival=f, PL_expect=XTERMORDORDOR, PL_bufptr=s, REPORT((int)UNIOP))
218 #define FUN0(f) return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0))
219 #define FUN0OP(f) return (pl_yylval.opval=f, CLINE, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC0OP))
220 #define FUN1(f) return (pl_yylval.ival=f, PL_expect=XOPERATOR, PL_bufptr=s, REPORT((int)FUNC1))
221 #define BOop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITOROP))
222 #define BAop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)BITANDOP))
223 #define BCop(f) return pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr = s, \
225 #define SHop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)SHIFTOP))
226 #define PWop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)POWOP))
227 #define PMop(f) return(pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)MATCHOP))
228 #define Aop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)ADDOP))
229 #define AopNOASSIGN(f) return (pl_yylval.ival=f, PL_bufptr=s, REPORT((int)ADDOP))
230 #define Mop(f) return ao((pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, (int)MULOP))
231 #define Eop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)EQOP))
232 #define Rop(f) return (pl_yylval.ival=f, PL_expect=XTERM, PL_bufptr=s, REPORT((int)RELOP))
234 /* This bit of chicanery makes a unary function followed by
235 * a parenthesis into a function with one argument, highest precedence.
236 * The UNIDOR macro is for unary functions that can be followed by the //
237 * operator (such as C<shift // 0>).
239 #define UNI3(f,x,have_x) { \
240 pl_yylval.ival = f; \
241 if (have_x) PL_expect = x; \
243 PL_last_uni = PL_oldbufptr; \
244 PL_last_lop_op = (f) < 0 ? -(f) : (f); \
246 return REPORT( (int)FUNC1 ); \
248 return REPORT( *s=='(' ? (int)FUNC1 : (int)UNIOP ); \
250 #define UNI(f) UNI3(f,XTERM,1)
251 #define UNIDOR(f) UNI3(f,XTERMORDORDOR,1)
252 #define UNIPROTO(f,optional) { \
253 if (optional) PL_last_uni = PL_oldbufptr; \
257 #define UNIBRACK(f) UNI3(f,0,0)
259 /* grandfather return to old style */
262 if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC) \
263 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC; \
264 pl_yylval.ival = (f); \
270 #define COPLINE_INC_WITH_HERELINES \
272 CopLINE_inc(PL_curcop); \
273 if (PL_parser->herelines) \
274 CopLINE(PL_curcop) += PL_parser->herelines, \
275 PL_parser->herelines = 0; \
277 /* Called after scan_str to update CopLINE(PL_curcop), but only when there
278 * is no sublex_push to follow. */
279 #define COPLINE_SET_FROM_MULTI_END \
281 CopLINE_set(PL_curcop, PL_multi_end); \
282 if (PL_multi_end != PL_multi_start) \
283 PL_parser->herelines = 0; \
289 /* how to interpret the pl_yylval associated with the token */
293 TOKENTYPE_OPNUM, /* pl_yylval.ival contains an opcode number */
298 static struct debug_tokens {
300 enum token_type type;
302 } const debug_tokens[] =
304 { ADDOP, TOKENTYPE_OPNUM, "ADDOP" },
305 { ANDAND, TOKENTYPE_NONE, "ANDAND" },
306 { ANDOP, TOKENTYPE_NONE, "ANDOP" },
307 { ANONSUB, TOKENTYPE_IVAL, "ANONSUB" },
308 { ARROW, TOKENTYPE_NONE, "ARROW" },
309 { ASSIGNOP, TOKENTYPE_OPNUM, "ASSIGNOP" },
310 { BITANDOP, TOKENTYPE_OPNUM, "BITANDOP" },
311 { BITOROP, TOKENTYPE_OPNUM, "BITOROP" },
312 { COLONATTR, TOKENTYPE_NONE, "COLONATTR" },
313 { CONTINUE, TOKENTYPE_NONE, "CONTINUE" },
314 { DEFAULT, TOKENTYPE_NONE, "DEFAULT" },
315 { DO, TOKENTYPE_NONE, "DO" },
316 { DOLSHARP, TOKENTYPE_NONE, "DOLSHARP" },
317 { DORDOR, TOKENTYPE_NONE, "DORDOR" },
318 { DOROP, TOKENTYPE_OPNUM, "DOROP" },
319 { DOTDOT, TOKENTYPE_IVAL, "DOTDOT" },
320 { ELSE, TOKENTYPE_NONE, "ELSE" },
321 { ELSIF, TOKENTYPE_IVAL, "ELSIF" },
322 { EQOP, TOKENTYPE_OPNUM, "EQOP" },
323 { FOR, TOKENTYPE_IVAL, "FOR" },
324 { FORMAT, TOKENTYPE_NONE, "FORMAT" },
325 { FORMLBRACK, TOKENTYPE_NONE, "FORMLBRACK" },
326 { FORMRBRACK, TOKENTYPE_NONE, "FORMRBRACK" },
327 { FUNC, TOKENTYPE_OPNUM, "FUNC" },
328 { FUNC0, TOKENTYPE_OPNUM, "FUNC0" },
329 { FUNC0OP, TOKENTYPE_OPVAL, "FUNC0OP" },
330 { FUNC0SUB, TOKENTYPE_OPVAL, "FUNC0SUB" },
331 { FUNC1, TOKENTYPE_OPNUM, "FUNC1" },
332 { FUNCMETH, TOKENTYPE_OPVAL, "FUNCMETH" },
333 { GIVEN, TOKENTYPE_IVAL, "GIVEN" },
334 { HASHBRACK, TOKENTYPE_NONE, "HASHBRACK" },
335 { IF, TOKENTYPE_IVAL, "IF" },
336 { LABEL, TOKENTYPE_PVAL, "LABEL" },
337 { LOCAL, TOKENTYPE_IVAL, "LOCAL" },
338 { LOOPEX, TOKENTYPE_OPNUM, "LOOPEX" },
339 { LSTOP, TOKENTYPE_OPNUM, "LSTOP" },
340 { LSTOPSUB, TOKENTYPE_OPVAL, "LSTOPSUB" },
341 { MATCHOP, TOKENTYPE_OPNUM, "MATCHOP" },
342 { METHOD, TOKENTYPE_OPVAL, "METHOD" },
343 { MULOP, TOKENTYPE_OPNUM, "MULOP" },
344 { MY, TOKENTYPE_IVAL, "MY" },
345 { NOAMP, TOKENTYPE_NONE, "NOAMP" },
346 { NOTOP, TOKENTYPE_NONE, "NOTOP" },
347 { OROP, TOKENTYPE_IVAL, "OROP" },
348 { OROR, TOKENTYPE_NONE, "OROR" },
349 { PACKAGE, TOKENTYPE_NONE, "PACKAGE" },
350 { PLUGEXPR, TOKENTYPE_OPVAL, "PLUGEXPR" },
351 { PLUGSTMT, TOKENTYPE_OPVAL, "PLUGSTMT" },
352 { PMFUNC, TOKENTYPE_OPVAL, "PMFUNC" },
353 { POSTJOIN, TOKENTYPE_NONE, "POSTJOIN" },
354 { POSTDEC, TOKENTYPE_NONE, "POSTDEC" },
355 { POSTINC, TOKENTYPE_NONE, "POSTINC" },
356 { POWOP, TOKENTYPE_OPNUM, "POWOP" },
357 { PREDEC, TOKENTYPE_NONE, "PREDEC" },
358 { PREINC, TOKENTYPE_NONE, "PREINC" },
359 { PRIVATEREF, TOKENTYPE_OPVAL, "PRIVATEREF" },
360 { QWLIST, TOKENTYPE_OPVAL, "QWLIST" },
361 { REFGEN, TOKENTYPE_NONE, "REFGEN" },
362 { RELOP, TOKENTYPE_OPNUM, "RELOP" },
363 { REQUIRE, TOKENTYPE_NONE, "REQUIRE" },
364 { SHIFTOP, TOKENTYPE_OPNUM, "SHIFTOP" },
365 { SUB, TOKENTYPE_NONE, "SUB" },
366 { THING, TOKENTYPE_OPVAL, "THING" },
367 { UMINUS, TOKENTYPE_NONE, "UMINUS" },
368 { UNIOP, TOKENTYPE_OPNUM, "UNIOP" },
369 { UNIOPSUB, TOKENTYPE_OPVAL, "UNIOPSUB" },
370 { UNLESS, TOKENTYPE_IVAL, "UNLESS" },
371 { UNTIL, TOKENTYPE_IVAL, "UNTIL" },
372 { USE, TOKENTYPE_IVAL, "USE" },
373 { WHEN, TOKENTYPE_IVAL, "WHEN" },
374 { WHILE, TOKENTYPE_IVAL, "WHILE" },
375 { BAREWORD, TOKENTYPE_OPVAL, "BAREWORD" },
376 { YADAYADA, TOKENTYPE_IVAL, "YADAYADA" },
377 { 0, TOKENTYPE_NONE, NULL }
380 /* dump the returned token in rv, plus any optional arg in pl_yylval */
383 S_tokereport(pTHX_ I32 rv, const YYSTYPE* lvalp)
385 PERL_ARGS_ASSERT_TOKEREPORT;
388 const char *name = NULL;
389 enum token_type type = TOKENTYPE_NONE;
390 const struct debug_tokens *p;
391 SV* const report = newSVpvs("<== ");
393 for (p = debug_tokens; p->token; p++) {
394 if (p->token == (int)rv) {
401 Perl_sv_catpv(aTHX_ report, name);
402 else if (isGRAPH(rv))
404 Perl_sv_catpvf(aTHX_ report, "'%c'", (char)rv);
406 sv_catpvs(report, " (pending identifier)");
409 sv_catpvs(report, "EOF");
411 Perl_sv_catpvf(aTHX_ report, "?? %"IVdf, (IV)rv);
416 Perl_sv_catpvf(aTHX_ report, "(ival=%"IVdf")", (IV)lvalp->ival);
418 case TOKENTYPE_OPNUM:
419 Perl_sv_catpvf(aTHX_ report, "(ival=op_%s)",
420 PL_op_name[lvalp->ival]);
423 Perl_sv_catpvf(aTHX_ report, "(pval=\"%s\")", lvalp->pval);
425 case TOKENTYPE_OPVAL:
427 Perl_sv_catpvf(aTHX_ report, "(opval=op_%s)",
428 PL_op_name[lvalp->opval->op_type]);
429 if (lvalp->opval->op_type == OP_CONST) {
430 Perl_sv_catpvf(aTHX_ report, " %s",
431 SvPEEK(cSVOPx_sv(lvalp->opval)));
436 sv_catpvs(report, "(opval=null)");
439 PerlIO_printf(Perl_debug_log, "### %s\n\n", SvPV_nolen_const(report));
445 /* print the buffer with suitable escapes */
448 S_printbuf(pTHX_ const char *const fmt, const char *const s)
450 SV* const tmp = newSVpvs("");
452 PERL_ARGS_ASSERT_PRINTBUF;
454 GCC_DIAG_IGNORE(-Wformat-nonliteral); /* fmt checked by caller */
455 PerlIO_printf(Perl_debug_log, fmt, pv_display(tmp, s, strlen(s), 0, 60));
463 S_deprecate_commaless_var_list(pTHX) {
465 deprecate("comma-less variable list");
466 return REPORT(','); /* grandfather non-comma-format format */
472 * This subroutine looks for an '=' next to the operator that has just been
473 * parsed and turns it into an ASSIGNOP if it finds one.
477 S_ao(pTHX_ int toketype)
479 if (*PL_bufptr == '=') {
481 if (toketype == ANDAND)
482 pl_yylval.ival = OP_ANDASSIGN;
483 else if (toketype == OROR)
484 pl_yylval.ival = OP_ORASSIGN;
485 else if (toketype == DORDOR)
486 pl_yylval.ival = OP_DORASSIGN;
489 return REPORT(toketype);
494 * When Perl expects an operator and finds something else, no_op
495 * prints the warning. It always prints "<something> found where
496 * operator expected. It prints "Missing semicolon on previous line?"
497 * if the surprise occurs at the start of the line. "do you need to
498 * predeclare ..." is printed out for code like "sub bar; foo bar $x"
499 * where the compiler doesn't know if foo is a method call or a function.
500 * It prints "Missing operator before end of line" if there's nothing
501 * after the missing operator, or "... before <...>" if there is something
502 * after the missing operator.
504 * PL_bufptr is expected to point to the start of the thing that was found,
505 * and s after the next token or partial token.
509 S_no_op(pTHX_ const char *const what, char *s)
511 char * const oldbp = PL_bufptr;
512 const bool is_first = (PL_oldbufptr == PL_linestart);
514 PERL_ARGS_ASSERT_NO_OP;
520 yywarn(Perl_form(aTHX_ "%s found where operator expected", what), UTF ? SVf_UTF8 : 0);
521 if (ckWARN_d(WARN_SYNTAX)) {
523 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
524 "\t(Missing semicolon on previous line?)\n");
525 else if (PL_oldoldbufptr && isIDFIRST_lazy_if(PL_oldoldbufptr,UTF)) {
527 for (t = PL_oldoldbufptr; (isWORDCHAR_lazy_if(t,UTF) || *t == ':');
528 t += UTF ? UTF8SKIP(t) : 1)
530 if (t < PL_bufptr && isSPACE(*t))
531 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
532 "\t(Do you need to predeclare %"UTF8f"?)\n",
533 UTF8fARG(UTF, t - PL_oldoldbufptr, PL_oldoldbufptr));
537 Perl_warner(aTHX_ packWARN(WARN_SYNTAX),
538 "\t(Missing operator before %"UTF8f"?)\n",
539 UTF8fARG(UTF, s - oldbp, oldbp));
547 * Complain about missing quote/regexp/heredoc terminator.
548 * If it's called with NULL then it cauterizes the line buffer.
549 * If we're in a delimited string and the delimiter is a control
550 * character, it's reformatted into a two-char sequence like ^C.
555 S_missingterm(pTHX_ char *s)
557 char tmpbuf[UTF8_MAXBYTES + 1];
562 char * const nl = strrchr(s,'\n');
567 else if (PL_multi_close < 32) {
569 tmpbuf[1] = (char)toCTRL(PL_multi_close);
574 if (LIKELY(PL_multi_close < 256)) {
575 *tmpbuf = (char)PL_multi_close;
580 *uvchr_to_utf8((U8 *)tmpbuf, PL_multi_close) = 0;
584 q = strchr(s,'"') ? '\'' : '"';
585 sv = sv_2mortal(newSVpv(s,0));
588 Perl_croak(aTHX_ "Can't find string terminator %c%"SVf
589 "%c anywhere before EOF",q,SVfARG(sv),q);
595 * Check whether the named feature is enabled.
598 Perl_feature_is_enabled(pTHX_ const char *const name, STRLEN namelen)
600 char he_name[8 + MAX_FEATURE_LEN] = "feature_";
602 PERL_ARGS_ASSERT_FEATURE_IS_ENABLED;
604 assert(CURRENT_FEATURE_BUNDLE == FEATURE_BUNDLE_CUSTOM);
606 if (namelen > MAX_FEATURE_LEN)
608 memcpy(&he_name[8], name, namelen);
610 return cBOOL(cop_hints_fetch_pvn(PL_curcop, he_name, 8 + namelen, 0,
611 REFCOUNTED_HE_EXISTS));
615 * experimental text filters for win32 carriage-returns, utf16-to-utf8 and
616 * utf16-to-utf8-reversed.
619 #ifdef PERL_CR_FILTER
623 const char *s = SvPVX_const(sv);
624 const char * const e = s + SvCUR(sv);
626 PERL_ARGS_ASSERT_STRIP_RETURN;
628 /* outer loop optimized to do nothing if there are no CR-LFs */
630 if (*s++ == '\r' && *s == '\n') {
631 /* hit a CR-LF, need to copy the rest */
635 if (*s == '\r' && s[1] == '\n')
646 S_cr_textfilter(pTHX_ int idx, SV *sv, int maxlen)
648 const I32 count = FILTER_READ(idx+1, sv, maxlen);
649 if (count > 0 && !maxlen)
656 =for apidoc Amx|void|lex_start|SV *line|PerlIO *rsfp|U32 flags
658 Creates and initialises a new lexer/parser state object, supplying
659 a context in which to lex and parse from a new source of Perl code.
660 A pointer to the new state object is placed in L</PL_parser>. An entry
661 is made on the save stack so that upon unwinding the new state object
662 will be destroyed and the former value of L</PL_parser> will be restored.
663 Nothing else need be done to clean up the parsing context.
665 The code to be parsed comes from C<line> and C<rsfp>. C<line>, if
666 non-null, provides a string (in SV form) containing code to be parsed.
667 A copy of the string is made, so subsequent modification of C<line>
668 does not affect parsing. C<rsfp>, if non-null, provides an input stream
669 from which code will be read to be parsed. If both are non-null, the
670 code in C<line> comes first and must consist of complete lines of input,
671 and C<rsfp> supplies the remainder of the source.
673 The C<flags> parameter is reserved for future use. Currently it is only
674 used by perl internally, so extensions should always pass zero.
679 /* LEX_START_SAME_FILTER indicates that this is not a new file, so it
680 can share filters with the current parser.
681 LEX_START_DONT_CLOSE indicates that the file handle wasn't opened by the
682 caller, hence isn't owned by the parser, so shouldn't be closed on parser
683 destruction. This is used to handle the case of defaulting to reading the
684 script from the standard input because no filename was given on the command
685 line (without getting confused by situation where STDIN has been closed, so
686 the script handle is opened on fd 0) */
689 Perl_lex_start(pTHX_ SV *line, PerlIO *rsfp, U32 flags)
691 const char *s = NULL;
692 yy_parser *parser, *oparser;
693 if (flags && flags & ~LEX_START_FLAGS)
694 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_start");
696 /* create and initialise a parser */
698 Newxz(parser, 1, yy_parser);
699 parser->old_parser = oparser = PL_parser;
702 parser->stack = NULL;
704 parser->stack_size = 0;
706 /* on scope exit, free this parser and restore any outer one */
708 parser->saved_curcop = PL_curcop;
710 /* initialise lexer state */
712 parser->nexttoke = 0;
713 parser->error_count = oparser ? oparser->error_count : 0;
714 parser->copline = parser->preambling = NOLINE;
715 parser->lex_state = LEX_NORMAL;
716 parser->expect = XSTATE;
718 parser->rsfp_filters =
719 !(flags & LEX_START_SAME_FILTER) || !oparser
721 : MUTABLE_AV(SvREFCNT_inc(
722 oparser->rsfp_filters
723 ? oparser->rsfp_filters
724 : (oparser->rsfp_filters = newAV())
727 Newx(parser->lex_brackstack, 120, char);
728 Newx(parser->lex_casestack, 12, char);
729 *parser->lex_casestack = '\0';
730 Newxz(parser->lex_shared, 1, LEXSHARED);
734 s = SvPV_const(line, len);
735 parser->linestr = flags & LEX_START_COPIED
736 ? SvREFCNT_inc_simple_NN(line)
737 : newSVpvn_flags(s, len, SvUTF8(line));
739 sv_catpvs(parser->linestr, "\n;");
741 parser->linestr = newSVpvn("\n;", rsfp ? 1 : 2);
743 parser->oldoldbufptr =
746 parser->linestart = SvPVX(parser->linestr);
747 parser->bufend = parser->bufptr + SvCUR(parser->linestr);
748 parser->last_lop = parser->last_uni = NULL;
750 STATIC_ASSERT_STMT(FITS_IN_8_BITS(LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
751 |LEX_DONT_CLOSE_RSFP));
752 parser->lex_flags = (U8) (flags & (LEX_IGNORE_UTF8_HINTS|LEX_EVALBYTES
753 |LEX_DONT_CLOSE_RSFP));
755 parser->in_pod = parser->filtered = 0;
759 /* delete a parser object */
762 Perl_parser_free(pTHX_ const yy_parser *parser)
764 PERL_ARGS_ASSERT_PARSER_FREE;
766 PL_curcop = parser->saved_curcop;
767 SvREFCNT_dec(parser->linestr);
769 if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
770 PerlIO_clearerr(parser->rsfp);
771 else if (parser->rsfp && (!parser->old_parser
772 || (parser->old_parser && parser->rsfp != parser->old_parser->rsfp)))
773 PerlIO_close(parser->rsfp);
774 SvREFCNT_dec(parser->rsfp_filters);
775 SvREFCNT_dec(parser->lex_stuff);
776 SvREFCNT_dec(parser->lex_sub_repl);
778 Safefree(parser->lex_brackstack);
779 Safefree(parser->lex_casestack);
780 Safefree(parser->lex_shared);
781 PL_parser = parser->old_parser;
786 Perl_parser_free_nexttoke_ops(pTHX_ yy_parser *parser, OPSLAB *slab)
788 I32 nexttoke = parser->nexttoke;
789 PERL_ARGS_ASSERT_PARSER_FREE_NEXTTOKE_OPS;
791 if (S_is_opval_token(parser->nexttype[nexttoke] & 0xffff)
792 && parser->nextval[nexttoke].opval
793 && parser->nextval[nexttoke].opval->op_slabbed
794 && OpSLAB(parser->nextval[nexttoke].opval) == slab) {
795 op_free(parser->nextval[nexttoke].opval);
796 parser->nextval[nexttoke].opval = NULL;
803 =for apidoc AmxU|SV *|PL_parser-E<gt>linestr
805 Buffer scalar containing the chunk currently under consideration of the
806 text currently being lexed. This is always a plain string scalar (for
807 which C<SvPOK> is true). It is not intended to be used as a scalar by
808 normal scalar means; instead refer to the buffer directly by the pointer
809 variables described below.
811 The lexer maintains various C<char*> pointers to things in the
812 C<PL_parser-E<gt>linestr> buffer. If C<PL_parser-E<gt>linestr> is ever
813 reallocated, all of these pointers must be updated. Don't attempt to
814 do this manually, but rather use L</lex_grow_linestr> if you need to
815 reallocate the buffer.
817 The content of the text chunk in the buffer is commonly exactly one
818 complete line of input, up to and including a newline terminator,
819 but there are situations where it is otherwise. The octets of the
820 buffer may be intended to be interpreted as either UTF-8 or Latin-1.
821 The function L</lex_bufutf8> tells you which. Do not use the C<SvUTF8>
822 flag on this scalar, which may disagree with it.
824 For direct examination of the buffer, the variable
825 L</PL_parser-E<gt>bufend> points to the end of the buffer. The current
826 lexing position is pointed to by L</PL_parser-E<gt>bufptr>. Direct use
827 of these pointers is usually preferable to examination of the scalar
828 through normal scalar means.
830 =for apidoc AmxU|char *|PL_parser-E<gt>bufend
832 Direct pointer to the end of the chunk of text currently being lexed, the
833 end of the lexer buffer. This is equal to C<SvPVX(PL_parser-E<gt>linestr)
834 + SvCUR(PL_parser-E<gt>linestr)>. A C<NUL> character (zero octet) is
835 always located at the end of the buffer, and does not count as part of
836 the buffer's contents.
838 =for apidoc AmxU|char *|PL_parser-E<gt>bufptr
840 Points to the current position of lexing inside the lexer buffer.
841 Characters around this point may be freely examined, within
842 the range delimited by C<SvPVX(L</PL_parser-E<gt>linestr>)> and
843 L</PL_parser-E<gt>bufend>. The octets of the buffer may be intended to be
844 interpreted as either UTF-8 or Latin-1, as indicated by L</lex_bufutf8>.
846 Lexing code (whether in the Perl core or not) moves this pointer past
847 the characters that it consumes. It is also expected to perform some
848 bookkeeping whenever a newline character is consumed. This movement
849 can be more conveniently performed by the function L</lex_read_to>,
850 which handles newlines appropriately.
852 Interpretation of the buffer's octets can be abstracted out by
853 using the slightly higher-level functions L</lex_peek_unichar> and
854 L</lex_read_unichar>.
856 =for apidoc AmxU|char *|PL_parser-E<gt>linestart
858 Points to the start of the current line inside the lexer buffer.
859 This is useful for indicating at which column an error occurred, and
860 not much else. This must be updated by any lexing code that consumes
861 a newline; the function L</lex_read_to> handles this detail.
867 =for apidoc Amx|bool|lex_bufutf8
869 Indicates whether the octets in the lexer buffer
870 (L</PL_parser-E<gt>linestr>) should be interpreted as the UTF-8 encoding
871 of Unicode characters. If not, they should be interpreted as Latin-1
872 characters. This is analogous to the C<SvUTF8> flag for scalars.
874 In UTF-8 mode, it is not guaranteed that the lexer buffer actually
875 contains valid UTF-8. Lexing code must be robust in the face of invalid
878 The actual C<SvUTF8> flag of the L</PL_parser-E<gt>linestr> scalar
879 is significant, but not the whole story regarding the input character
880 encoding. Normally, when a file is being read, the scalar contains octets
881 and its C<SvUTF8> flag is off, but the octets should be interpreted as
882 UTF-8 if the C<use utf8> pragma is in effect. During a string eval,
883 however, the scalar may have the C<SvUTF8> flag on, and in this case its
884 octets should be interpreted as UTF-8 unless the C<use bytes> pragma
885 is in effect. This logic may change in the future; use this function
886 instead of implementing the logic yourself.
892 Perl_lex_bufutf8(pTHX)
898 =for apidoc Amx|char *|lex_grow_linestr|STRLEN len
900 Reallocates the lexer buffer (L</PL_parser-E<gt>linestr>) to accommodate
901 at least C<len> octets (including terminating C<NUL>). Returns a
902 pointer to the reallocated buffer. This is necessary before making
903 any direct modification of the buffer that would increase its length.
904 L</lex_stuff_pvn> provides a more convenient way to insert text into
907 Do not use C<SvGROW> or C<sv_grow> directly on C<PL_parser-E<gt>linestr>;
908 this function updates all of the lexer's variables that point directly
915 Perl_lex_grow_linestr(pTHX_ STRLEN len)
919 STRLEN bufend_pos, bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
920 STRLEN linestart_pos, last_uni_pos, last_lop_pos, re_eval_start_pos;
921 linestr = PL_parser->linestr;
922 buf = SvPVX(linestr);
923 if (len <= SvLEN(linestr))
925 bufend_pos = PL_parser->bufend - buf;
926 bufptr_pos = PL_parser->bufptr - buf;
927 oldbufptr_pos = PL_parser->oldbufptr - buf;
928 oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
929 linestart_pos = PL_parser->linestart - buf;
930 last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
931 last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
932 re_eval_start_pos = PL_parser->lex_shared->re_eval_start ?
933 PL_parser->lex_shared->re_eval_start - buf : 0;
935 buf = sv_grow(linestr, len);
937 PL_parser->bufend = buf + bufend_pos;
938 PL_parser->bufptr = buf + bufptr_pos;
939 PL_parser->oldbufptr = buf + oldbufptr_pos;
940 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
941 PL_parser->linestart = buf + linestart_pos;
942 if (PL_parser->last_uni)
943 PL_parser->last_uni = buf + last_uni_pos;
944 if (PL_parser->last_lop)
945 PL_parser->last_lop = buf + last_lop_pos;
946 if (PL_parser->lex_shared->re_eval_start)
947 PL_parser->lex_shared->re_eval_start = buf + re_eval_start_pos;
952 =for apidoc Amx|void|lex_stuff_pvn|const char *pv|STRLEN len|U32 flags
954 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
955 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
956 reallocating the buffer if necessary. This means that lexing code that
957 runs later will see the characters as if they had appeared in the input.
958 It is not recommended to do this as part of normal parsing, and most
959 uses of this facility run the risk of the inserted characters being
960 interpreted in an unintended manner.
962 The string to be inserted is represented by C<len> octets starting
963 at C<pv>. These octets are interpreted as either UTF-8 or Latin-1,
964 according to whether the C<LEX_STUFF_UTF8> flag is set in C<flags>.
965 The characters are recoded for the lexer buffer, according to how the
966 buffer is currently being interpreted (L</lex_bufutf8>). If a string
967 to be inserted is available as a Perl scalar, the L</lex_stuff_sv>
968 function is more convenient.
974 Perl_lex_stuff_pvn(pTHX_ const char *pv, STRLEN len, U32 flags)
978 PERL_ARGS_ASSERT_LEX_STUFF_PVN;
979 if (flags & ~(LEX_STUFF_UTF8))
980 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_pvn");
982 if (flags & LEX_STUFF_UTF8) {
985 STRLEN highhalf = 0; /* Count of variants */
986 const char *p, *e = pv+len;
987 for (p = pv; p != e; p++) {
988 if (! UTF8_IS_INVARIANT(*p)) {
994 lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len+highhalf);
995 bufptr = PL_parser->bufptr;
996 Move(bufptr, bufptr+len+highhalf, PL_parser->bufend+1-bufptr, char);
997 SvCUR_set(PL_parser->linestr,
998 SvCUR(PL_parser->linestr) + len+highhalf);
999 PL_parser->bufend += len+highhalf;
1000 for (p = pv; p != e; p++) {
1002 if (! UTF8_IS_INVARIANT(c)) {
1003 *bufptr++ = UTF8_TWO_BYTE_HI(c);
1004 *bufptr++ = UTF8_TWO_BYTE_LO(c);
1006 *bufptr++ = (char)c;
1011 if (flags & LEX_STUFF_UTF8) {
1012 STRLEN highhalf = 0;
1013 const char *p, *e = pv+len;
1014 for (p = pv; p != e; p++) {
1016 if (UTF8_IS_ABOVE_LATIN1(c)) {
1017 Perl_croak(aTHX_ "Lexing code attempted to stuff "
1018 "non-Latin-1 character into Latin-1 input");
1019 } else if (UTF8_IS_NEXT_CHAR_DOWNGRADEABLE(p, e)) {
1022 } else if (! UTF8_IS_INVARIANT(c)) {
1023 /* malformed UTF-8 */
1025 SAVESPTR(PL_warnhook);
1026 PL_warnhook = PERL_WARNHOOK_FATAL;
1027 utf8n_to_uvchr((U8*)p, e-p, NULL, 0);
1033 lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len-highhalf);
1034 bufptr = PL_parser->bufptr;
1035 Move(bufptr, bufptr+len-highhalf, PL_parser->bufend+1-bufptr, char);
1036 SvCUR_set(PL_parser->linestr,
1037 SvCUR(PL_parser->linestr) + len-highhalf);
1038 PL_parser->bufend += len-highhalf;
1041 if (UTF8_IS_INVARIANT(*p)) {
1047 *bufptr++ = EIGHT_BIT_UTF8_TO_NATIVE(*p, *(p+1));
1053 lex_grow_linestr(SvCUR(PL_parser->linestr)+1+len);
1054 bufptr = PL_parser->bufptr;
1055 Move(bufptr, bufptr+len, PL_parser->bufend+1-bufptr, char);
1056 SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) + len);
1057 PL_parser->bufend += len;
1058 Copy(pv, bufptr, len, char);
1064 =for apidoc Amx|void|lex_stuff_pv|const char *pv|U32 flags
1066 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1067 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1068 reallocating the buffer if necessary. This means that lexing code that
1069 runs later will see the characters as if they had appeared in the input.
1070 It is not recommended to do this as part of normal parsing, and most
1071 uses of this facility run the risk of the inserted characters being
1072 interpreted in an unintended manner.
1074 The string to be inserted is represented by octets starting at C<pv>
1075 and continuing to the first nul. These octets are interpreted as either
1076 UTF-8 or Latin-1, according to whether the C<LEX_STUFF_UTF8> flag is set
1077 in C<flags>. The characters are recoded for the lexer buffer, according
1078 to how the buffer is currently being interpreted (L</lex_bufutf8>).
1079 If it is not convenient to nul-terminate a string to be inserted, the
1080 L</lex_stuff_pvn> function is more appropriate.
1086 Perl_lex_stuff_pv(pTHX_ const char *pv, U32 flags)
1088 PERL_ARGS_ASSERT_LEX_STUFF_PV;
1089 lex_stuff_pvn(pv, strlen(pv), flags);
1093 =for apidoc Amx|void|lex_stuff_sv|SV *sv|U32 flags
1095 Insert characters into the lexer buffer (L</PL_parser-E<gt>linestr>),
1096 immediately after the current lexing point (L</PL_parser-E<gt>bufptr>),
1097 reallocating the buffer if necessary. This means that lexing code that
1098 runs later will see the characters as if they had appeared in the input.
1099 It is not recommended to do this as part of normal parsing, and most
1100 uses of this facility run the risk of the inserted characters being
1101 interpreted in an unintended manner.
1103 The string to be inserted is the string value of C<sv>. The characters
1104 are recoded for the lexer buffer, according to how the buffer is currently
1105 being interpreted (L</lex_bufutf8>). If a string to be inserted is
1106 not already a Perl scalar, the L</lex_stuff_pvn> function avoids the
1107 need to construct a scalar.
1113 Perl_lex_stuff_sv(pTHX_ SV *sv, U32 flags)
1117 PERL_ARGS_ASSERT_LEX_STUFF_SV;
1119 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_stuff_sv");
1121 lex_stuff_pvn(pv, len, flags | (SvUTF8(sv) ? LEX_STUFF_UTF8 : 0));
1125 =for apidoc Amx|void|lex_unstuff|char *ptr
1127 Discards text about to be lexed, from L</PL_parser-E<gt>bufptr> up to
1128 C<ptr>. Text following C<ptr> will be moved, and the buffer shortened.
1129 This hides the discarded text from any lexing code that runs later,
1130 as if the text had never appeared.
1132 This is not the normal way to consume lexed text. For that, use
1139 Perl_lex_unstuff(pTHX_ char *ptr)
1143 PERL_ARGS_ASSERT_LEX_UNSTUFF;
1144 buf = PL_parser->bufptr;
1146 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1149 bufend = PL_parser->bufend;
1151 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_unstuff");
1152 unstuff_len = ptr - buf;
1153 Move(ptr, buf, bufend+1-ptr, char);
1154 SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - unstuff_len);
1155 PL_parser->bufend = bufend - unstuff_len;
1159 =for apidoc Amx|void|lex_read_to|char *ptr
1161 Consume text in the lexer buffer, from L</PL_parser-E<gt>bufptr> up
1162 to C<ptr>. This advances L</PL_parser-E<gt>bufptr> to match C<ptr>,
1163 performing the correct bookkeeping whenever a newline character is passed.
1164 This is the normal way to consume lexed text.
1166 Interpretation of the buffer's octets can be abstracted out by
1167 using the slightly higher-level functions L</lex_peek_unichar> and
1168 L</lex_read_unichar>.
1174 Perl_lex_read_to(pTHX_ char *ptr)
1177 PERL_ARGS_ASSERT_LEX_READ_TO;
1178 s = PL_parser->bufptr;
1179 if (ptr < s || ptr > PL_parser->bufend)
1180 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_to");
1181 for (; s != ptr; s++)
1183 COPLINE_INC_WITH_HERELINES;
1184 PL_parser->linestart = s+1;
1186 PL_parser->bufptr = ptr;
1190 =for apidoc Amx|void|lex_discard_to|char *ptr
1192 Discards the first part of the L</PL_parser-E<gt>linestr> buffer,
1193 up to C<ptr>. The remaining content of the buffer will be moved, and
1194 all pointers into the buffer updated appropriately. C<ptr> must not
1195 be later in the buffer than the position of L</PL_parser-E<gt>bufptr>:
1196 it is not permitted to discard text that has yet to be lexed.
1198 Normally it is not necessarily to do this directly, because it suffices to
1199 use the implicit discarding behaviour of L</lex_next_chunk> and things
1200 based on it. However, if a token stretches across multiple lines,
1201 and the lexing code has kept multiple lines of text in the buffer for
1202 that purpose, then after completion of the token it would be wise to
1203 explicitly discard the now-unneeded earlier lines, to avoid future
1204 multi-line tokens growing the buffer without bound.
1210 Perl_lex_discard_to(pTHX_ char *ptr)
1214 PERL_ARGS_ASSERT_LEX_DISCARD_TO;
1215 buf = SvPVX(PL_parser->linestr);
1217 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1220 if (ptr > PL_parser->bufptr)
1221 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_discard_to");
1222 discard_len = ptr - buf;
1223 if (PL_parser->oldbufptr < ptr)
1224 PL_parser->oldbufptr = ptr;
1225 if (PL_parser->oldoldbufptr < ptr)
1226 PL_parser->oldoldbufptr = ptr;
1227 if (PL_parser->last_uni && PL_parser->last_uni < ptr)
1228 PL_parser->last_uni = NULL;
1229 if (PL_parser->last_lop && PL_parser->last_lop < ptr)
1230 PL_parser->last_lop = NULL;
1231 Move(ptr, buf, PL_parser->bufend+1-ptr, char);
1232 SvCUR_set(PL_parser->linestr, SvCUR(PL_parser->linestr) - discard_len);
1233 PL_parser->bufend -= discard_len;
1234 PL_parser->bufptr -= discard_len;
1235 PL_parser->oldbufptr -= discard_len;
1236 PL_parser->oldoldbufptr -= discard_len;
1237 if (PL_parser->last_uni)
1238 PL_parser->last_uni -= discard_len;
1239 if (PL_parser->last_lop)
1240 PL_parser->last_lop -= discard_len;
1244 =for apidoc Amx|bool|lex_next_chunk|U32 flags
1246 Reads in the next chunk of text to be lexed, appending it to
1247 L</PL_parser-E<gt>linestr>. This should be called when lexing code has
1248 looked to the end of the current chunk and wants to know more. It is
1249 usual, but not necessary, for lexing to have consumed the entirety of
1250 the current chunk at this time.
1252 If L</PL_parser-E<gt>bufptr> is pointing to the very end of the current
1253 chunk (i.e., the current chunk has been entirely consumed), normally the
1254 current chunk will be discarded at the same time that the new chunk is
1255 read in. If C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, the current chunk
1256 will not be discarded. If the current chunk has not been entirely
1257 consumed, then it will not be discarded regardless of the flag.
1259 Returns true if some new text was added to the buffer, or false if the
1260 buffer has reached the end of the input text.
1265 #define LEX_FAKE_EOF 0x80000000
1266 #define LEX_NO_TERM 0x40000000 /* here-doc */
1269 Perl_lex_next_chunk(pTHX_ U32 flags)
1273 STRLEN old_bufend_pos, new_bufend_pos;
1274 STRLEN bufptr_pos, oldbufptr_pos, oldoldbufptr_pos;
1275 STRLEN linestart_pos, last_uni_pos, last_lop_pos;
1276 bool got_some_for_debugger = 0;
1278 if (flags & ~(LEX_KEEP_PREVIOUS|LEX_FAKE_EOF|LEX_NO_TERM))
1279 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_next_chunk");
1280 if (!(flags & LEX_NO_TERM) && PL_lex_inwhat)
1282 linestr = PL_parser->linestr;
1283 buf = SvPVX(linestr);
1284 if (!(flags & LEX_KEEP_PREVIOUS)
1285 && PL_parser->bufptr == PL_parser->bufend)
1287 old_bufend_pos = bufptr_pos = oldbufptr_pos = oldoldbufptr_pos = 0;
1289 if (PL_parser->last_uni != PL_parser->bufend)
1290 PL_parser->last_uni = NULL;
1291 if (PL_parser->last_lop != PL_parser->bufend)
1292 PL_parser->last_lop = NULL;
1293 last_uni_pos = last_lop_pos = 0;
1297 old_bufend_pos = PL_parser->bufend - buf;
1298 bufptr_pos = PL_parser->bufptr - buf;
1299 oldbufptr_pos = PL_parser->oldbufptr - buf;
1300 oldoldbufptr_pos = PL_parser->oldoldbufptr - buf;
1301 linestart_pos = PL_parser->linestart - buf;
1302 last_uni_pos = PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
1303 last_lop_pos = PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
1305 if (flags & LEX_FAKE_EOF) {
1307 } else if (!PL_parser->rsfp && !PL_parser->filtered) {
1309 } else if (filter_gets(linestr, old_bufend_pos)) {
1311 got_some_for_debugger = 1;
1312 } else if (flags & LEX_NO_TERM) {
1315 if (!SvPOK(linestr)) /* can get undefined by filter_gets */
1316 sv_setpvs(linestr, "");
1318 /* End of real input. Close filehandle (unless it was STDIN),
1319 * then add implicit termination.
1321 if (PL_parser->lex_flags & LEX_DONT_CLOSE_RSFP)
1322 PerlIO_clearerr(PL_parser->rsfp);
1323 else if (PL_parser->rsfp)
1324 (void)PerlIO_close(PL_parser->rsfp);
1325 PL_parser->rsfp = NULL;
1326 PL_parser->in_pod = PL_parser->filtered = 0;
1327 if (!PL_in_eval && PL_minus_p) {
1329 /*{*/";}continue{print or die qq(-p destination: $!\\n);}");
1330 PL_minus_n = PL_minus_p = 0;
1331 } else if (!PL_in_eval && PL_minus_n) {
1332 sv_catpvs(linestr, /*{*/";}");
1335 sv_catpvs(linestr, ";");
1338 buf = SvPVX(linestr);
1339 new_bufend_pos = SvCUR(linestr);
1340 PL_parser->bufend = buf + new_bufend_pos;
1341 PL_parser->bufptr = buf + bufptr_pos;
1342 PL_parser->oldbufptr = buf + oldbufptr_pos;
1343 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
1344 PL_parser->linestart = buf + linestart_pos;
1345 if (PL_parser->last_uni)
1346 PL_parser->last_uni = buf + last_uni_pos;
1347 if (PL_parser->last_lop)
1348 PL_parser->last_lop = buf + last_lop_pos;
1349 if (PL_parser->preambling != NOLINE) {
1350 CopLINE_set(PL_curcop, PL_parser->preambling + 1);
1351 PL_parser->preambling = NOLINE;
1353 if ( got_some_for_debugger
1354 && PERLDB_LINE_OR_SAVESRC
1355 && PL_curstash != PL_debstash)
1357 /* debugger active and we're not compiling the debugger code,
1358 * so store the line into the debugger's array of lines
1360 update_debugger_info(NULL, buf+old_bufend_pos,
1361 new_bufend_pos-old_bufend_pos);
1367 =for apidoc Amx|I32|lex_peek_unichar|U32 flags
1369 Looks ahead one (Unicode) character in the text currently being lexed.
1370 Returns the codepoint (unsigned integer value) of the next character,
1371 or -1 if lexing has reached the end of the input text. To consume the
1372 peeked character, use L</lex_read_unichar>.
1374 If the next character is in (or extends into) the next chunk of input
1375 text, the next chunk will be read in. Normally the current chunk will be
1376 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1377 bit set, then the current chunk will not be discarded.
1379 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1380 is encountered, an exception is generated.
1386 Perl_lex_peek_unichar(pTHX_ U32 flags)
1390 if (flags & ~(LEX_KEEP_PREVIOUS))
1391 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_peek_unichar");
1392 s = PL_parser->bufptr;
1393 bufend = PL_parser->bufend;
1399 if (!lex_next_chunk(flags))
1401 s = PL_parser->bufptr;
1402 bufend = PL_parser->bufend;
1405 if (UTF8_IS_INVARIANT(head))
1407 if (UTF8_IS_START(head)) {
1408 len = UTF8SKIP(&head);
1409 while ((STRLEN)(bufend-s) < len) {
1410 if (!lex_next_chunk(flags | LEX_KEEP_PREVIOUS))
1412 s = PL_parser->bufptr;
1413 bufend = PL_parser->bufend;
1416 unichar = utf8n_to_uvchr((U8*)s, bufend-s, &retlen, UTF8_CHECK_ONLY);
1417 if (retlen == (STRLEN)-1) {
1418 /* malformed UTF-8 */
1420 SAVESPTR(PL_warnhook);
1421 PL_warnhook = PERL_WARNHOOK_FATAL;
1422 utf8n_to_uvchr((U8*)s, bufend-s, NULL, 0);
1428 if (!lex_next_chunk(flags))
1430 s = PL_parser->bufptr;
1437 =for apidoc Amx|I32|lex_read_unichar|U32 flags
1439 Reads the next (Unicode) character in the text currently being lexed.
1440 Returns the codepoint (unsigned integer value) of the character read,
1441 and moves L</PL_parser-E<gt>bufptr> past the character, or returns -1
1442 if lexing has reached the end of the input text. To non-destructively
1443 examine the next character, use L</lex_peek_unichar> instead.
1445 If the next character is in (or extends into) the next chunk of input
1446 text, the next chunk will be read in. Normally the current chunk will be
1447 discarded at the same time, but if C<flags> has the C<LEX_KEEP_PREVIOUS>
1448 bit set, then the current chunk will not be discarded.
1450 If the input is being interpreted as UTF-8 and a UTF-8 encoding error
1451 is encountered, an exception is generated.
1457 Perl_lex_read_unichar(pTHX_ U32 flags)
1460 if (flags & ~(LEX_KEEP_PREVIOUS))
1461 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_unichar");
1462 c = lex_peek_unichar(flags);
1465 COPLINE_INC_WITH_HERELINES;
1467 PL_parser->bufptr += UTF8SKIP(PL_parser->bufptr);
1469 ++(PL_parser->bufptr);
1475 =for apidoc Amx|void|lex_read_space|U32 flags
1477 Reads optional spaces, in Perl style, in the text currently being
1478 lexed. The spaces may include ordinary whitespace characters and
1479 Perl-style comments. C<#line> directives are processed if encountered.
1480 L</PL_parser-E<gt>bufptr> is moved past the spaces, so that it points
1481 at a non-space character (or the end of the input text).
1483 If spaces extend into the next chunk of input text, the next chunk will
1484 be read in. Normally the current chunk will be discarded at the same
1485 time, but if C<flags> has the C<LEX_KEEP_PREVIOUS> bit set, then the current
1486 chunk will not be discarded.
1491 #define LEX_NO_INCLINE 0x40000000
1492 #define LEX_NO_NEXT_CHUNK 0x80000000
1495 Perl_lex_read_space(pTHX_ U32 flags)
1498 const bool can_incline = !(flags & LEX_NO_INCLINE);
1499 bool need_incline = 0;
1500 if (flags & ~(LEX_KEEP_PREVIOUS|LEX_NO_NEXT_CHUNK|LEX_NO_INCLINE))
1501 Perl_croak(aTHX_ "Lexing code internal error (%s)", "lex_read_space");
1502 s = PL_parser->bufptr;
1503 bufend = PL_parser->bufend;
1509 } while (!(c == '\n' || (c == 0 && s == bufend)));
1510 } else if (c == '\n') {
1513 PL_parser->linestart = s;
1519 } else if (isSPACE(c)) {
1521 } else if (c == 0 && s == bufend) {
1524 if (flags & LEX_NO_NEXT_CHUNK)
1526 PL_parser->bufptr = s;
1527 l = CopLINE(PL_curcop);
1528 CopLINE(PL_curcop) += PL_parser->herelines + 1;
1529 got_more = lex_next_chunk(flags);
1530 CopLINE_set(PL_curcop, l);
1531 s = PL_parser->bufptr;
1532 bufend = PL_parser->bufend;
1535 if (can_incline && need_incline && PL_parser->rsfp) {
1545 PL_parser->bufptr = s;
1550 =for apidoc EXMp|bool|validate_proto|SV *name|SV *proto|bool warn
1552 This function performs syntax checking on a prototype, C<proto>.
1553 If C<warn> is true, any illegal characters or mismatched brackets
1554 will trigger illegalproto warnings, declaring that they were
1555 detected in the prototype for C<name>.
1557 The return value is C<true> if this is a valid prototype, and
1558 C<false> if it is not, regardless of whether C<warn> was C<true> or
1561 Note that C<NULL> is a valid C<proto> and will always return C<true>.
1568 Perl_validate_proto(pTHX_ SV *name, SV *proto, bool warn)
1570 STRLEN len, origlen;
1571 char *p = proto ? SvPV(proto, len) : NULL;
1572 bool bad_proto = FALSE;
1573 bool in_brackets = FALSE;
1574 bool after_slash = FALSE;
1575 char greedy_proto = ' ';
1576 bool proto_after_greedy_proto = FALSE;
1577 bool must_be_last = FALSE;
1578 bool underscore = FALSE;
1579 bool bad_proto_after_underscore = FALSE;
1581 PERL_ARGS_ASSERT_VALIDATE_PROTO;
1587 for (; len--; p++) {
1590 proto_after_greedy_proto = TRUE;
1592 if (!strchr(";@%", *p))
1593 bad_proto_after_underscore = TRUE;
1596 if (!strchr("$@%*;[]&\\_+", *p) || *p == '\0') {
1603 in_brackets = FALSE;
1604 else if ((*p == '@' || *p == '%')
1608 must_be_last = TRUE;
1617 after_slash = FALSE;
1622 SV *tmpsv = newSVpvs_flags("", SVs_TEMP);
1625 ? sv_uni_display(tmpsv, newSVpvn_flags(p, origlen, SVs_TEMP | SVf_UTF8),
1626 origlen, UNI_DISPLAY_ISPRINT)
1627 : pv_pretty(tmpsv, p, origlen, 60, NULL, NULL, PERL_PV_ESCAPE_NONASCII);
1629 if (proto_after_greedy_proto)
1630 Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1631 "Prototype after '%c' for %"SVf" : %s",
1632 greedy_proto, SVfARG(name), p);
1634 Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1635 "Missing ']' in prototype for %"SVf" : %s",
1638 Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1639 "Illegal character in prototype for %"SVf" : %s",
1641 if (bad_proto_after_underscore)
1642 Perl_warner(aTHX_ packWARN(WARN_ILLEGALPROTO),
1643 "Illegal character after '_' in prototype for %"SVf" : %s",
1647 return (! (proto_after_greedy_proto || bad_proto) );
1652 * This subroutine has nothing to do with tilting, whether at windmills
1653 * or pinball tables. Its name is short for "increment line". It
1654 * increments the current line number in CopLINE(PL_curcop) and checks
1655 * to see whether the line starts with a comment of the form
1656 * # line 500 "foo.pm"
1657 * If so, it sets the current line number and file to the values in the comment.
1661 S_incline(pTHX_ const char *s)
1669 PERL_ARGS_ASSERT_INCLINE;
1671 COPLINE_INC_WITH_HERELINES;
1672 if (!PL_rsfp && !PL_parser->filtered && PL_lex_state == LEX_NORMAL
1673 && s+1 == PL_bufend && *s == ';') {
1674 /* fake newline in string eval */
1675 CopLINE_dec(PL_curcop);
1680 while (SPACE_OR_TAB(*s))
1682 if (strnEQ(s, "line", 4))
1686 if (SPACE_OR_TAB(*s))
1690 while (SPACE_OR_TAB(*s))
1698 if (!SPACE_OR_TAB(*s) && *s != '\r' && *s != '\n' && *s != '\0')
1700 while (SPACE_OR_TAB(*s))
1702 if (*s == '"' && (t = strchr(s+1, '"'))) {
1708 while (*t && !isSPACE(*t))
1712 while (SPACE_OR_TAB(*e) || *e == '\r' || *e == '\f')
1714 if (*e != '\n' && *e != '\0')
1715 return; /* false alarm */
1717 if (!grok_atoUV(n, &uv, &e))
1719 line_num = ((line_t)uv) - 1;
1722 const STRLEN len = t - s;
1724 if (!PL_rsfp && !PL_parser->filtered) {
1725 /* must copy *{"::_<(eval N)[oldfilename:L]"}
1726 * to *{"::_<newfilename"} */
1727 /* However, the long form of evals is only turned on by the
1728 debugger - usually they're "(eval %lu)" */
1729 GV * const cfgv = CopFILEGV(PL_curcop);
1732 STRLEN tmplen2 = len;
1736 if (tmplen2 + 2 <= sizeof smallbuf)
1739 Newx(tmpbuf2, tmplen2 + 2, char);
1744 memcpy(tmpbuf2 + 2, s, tmplen2);
1747 gv2 = *(GV**)hv_fetch(PL_defstash, tmpbuf2, tmplen2, TRUE);
1749 gv_init(gv2, PL_defstash, tmpbuf2, tmplen2, FALSE);
1750 /* adjust ${"::_<newfilename"} to store the new file name */
1751 GvSV(gv2) = newSVpvn(tmpbuf2 + 2, tmplen2 - 2);
1752 /* The line number may differ. If that is the case,
1753 alias the saved lines that are in the array.
1754 Otherwise alias the whole array. */
1755 if (CopLINE(PL_curcop) == line_num) {
1756 GvHV(gv2) = MUTABLE_HV(SvREFCNT_inc(GvHV(cfgv)));
1757 GvAV(gv2) = MUTABLE_AV(SvREFCNT_inc(GvAV(cfgv)));
1759 else if (GvAV(cfgv)) {
1760 AV * const av = GvAV(cfgv);
1761 const I32 start = CopLINE(PL_curcop)+1;
1762 I32 items = AvFILLp(av) - start;
1764 AV * const av2 = GvAVn(gv2);
1765 SV **svp = AvARRAY(av) + start;
1766 I32 l = (I32)line_num+1;
1768 av_store(av2, l++, SvREFCNT_inc(*svp++));
1773 if (tmpbuf2 != smallbuf) Safefree(tmpbuf2);
1776 CopFILE_free(PL_curcop);
1777 CopFILE_setn(PL_curcop, s, len);
1779 CopLINE_set(PL_curcop, line_num);
1783 S_update_debugger_info(pTHX_ SV *orig_sv, const char *const buf, STRLEN len)
1785 AV *av = CopFILEAVx(PL_curcop);
1788 if (PL_parser->preambling == NOLINE) sv = newSV_type(SVt_PVMG);
1790 sv = *av_fetch(av, 0, 1);
1791 SvUPGRADE(sv, SVt_PVMG);
1793 if (!SvPOK(sv)) sv_setpvs(sv,"");
1795 sv_catsv(sv, orig_sv);
1797 sv_catpvn(sv, buf, len);
1802 if (PL_parser->preambling == NOLINE)
1803 av_store(av, CopLINE(PL_curcop), sv);
1809 * Called to gobble the appropriate amount and type of whitespace.
1810 * Skips comments as well.
1811 * Returns the next character after the whitespace that is skipped.
1814 * Same thing, but look ahead without incrementing line numbers or
1815 * adjusting PL_linestart.
1818 #define skipspace(s) skipspace_flags(s, 0)
1819 #define peekspace(s) skipspace_flags(s, LEX_NO_INCLINE)
1822 S_skipspace_flags(pTHX_ char *s, U32 flags)
1824 PERL_ARGS_ASSERT_SKIPSPACE_FLAGS;
1825 if (PL_lex_formbrack && PL_lex_brackets <= PL_lex_formbrack) {
1826 while (s < PL_bufend && (SPACE_OR_TAB(*s) || !*s))
1829 STRLEN bufptr_pos = PL_bufptr - SvPVX(PL_linestr);
1831 lex_read_space(flags | LEX_KEEP_PREVIOUS |
1832 (PL_lex_inwhat || PL_lex_state == LEX_FORMLINE ?
1833 LEX_NO_NEXT_CHUNK : 0));
1835 PL_bufptr = SvPVX(PL_linestr) + bufptr_pos;
1836 if (PL_linestart > PL_bufptr)
1837 PL_bufptr = PL_linestart;
1845 * Check the unary operators to ensure there's no ambiguity in how they're
1846 * used. An ambiguous piece of code would be:
1848 * This doesn't mean rand() + 5. Because rand() is a unary operator,
1849 * the +5 is its argument.
1858 if (PL_oldoldbufptr != PL_last_uni)
1860 while (isSPACE(*PL_last_uni))
1863 while (isWORDCHAR_lazy_if(s,UTF) || *s == '-')
1864 s += UTF ? UTF8SKIP(s) : 1;
1865 if ((t = strchr(s, '(')) && t < PL_bufptr)
1868 Perl_ck_warner_d(aTHX_ packWARN(WARN_AMBIGUOUS),
1869 "Warning: Use of \"%"UTF8f"\" without parentheses is ambiguous",
1870 UTF8fARG(UTF, (int)(s - PL_last_uni), PL_last_uni));
1874 * LOP : macro to build a list operator. Its behaviour has been replaced
1875 * with a subroutine, S_lop() for which LOP is just another name.
1878 #define LOP(f,x) return lop(f,x,s)
1882 * Build a list operator (or something that might be one). The rules:
1883 * - if we have a next token, then it's a list operator (no parens) for
1884 * which the next token has already been parsed; e.g.,
1887 * - if the next thing is an opening paren, then it's a function
1888 * - else it's a list operator
1892 S_lop(pTHX_ I32 f, int x, char *s)
1894 PERL_ARGS_ASSERT_LOP;
1899 PL_last_lop = PL_oldbufptr;
1900 PL_last_lop_op = (OPCODE)f;
1905 return REPORT(FUNC);
1908 return REPORT(FUNC);
1911 if (!PL_lex_allbrackets && PL_lex_fakeeof > LEX_FAKEEOF_LOWLOGIC)
1912 PL_lex_fakeeof = LEX_FAKEEOF_LOWLOGIC;
1913 return REPORT(LSTOP);
1919 * When the lexer realizes it knows the next token (for instance,
1920 * it is reordering tokens for the parser) then it can call S_force_next
1921 * to know what token to return the next time the lexer is called. Caller
1922 * will need to set PL_nextval[] and possibly PL_expect to ensure
1923 * the lexer handles the token correctly.
1927 S_force_next(pTHX_ I32 type)
1931 PerlIO_printf(Perl_debug_log, "### forced token:\n");
1932 tokereport(type, &NEXTVAL_NEXTTOKE);
1935 assert(PL_nexttoke < C_ARRAY_LENGTH(PL_nexttype));
1936 PL_nexttype[PL_nexttoke] = type;
1943 * This subroutine handles postfix deref syntax after the arrow has already
1944 * been emitted. @* $* etc. are emitted as two separate token right here.
1945 * @[ @{ %[ %{ *{ are emitted also as two tokens, but this function emits
1946 * only the first, leaving yylex to find the next.
1950 S_postderef(pTHX_ int const funny, char const next)
1952 assert(funny == DOLSHARP || strchr("$@%&*", funny));
1954 PL_expect = XOPERATOR;
1955 if (PL_lex_state == LEX_INTERPNORMAL && !PL_lex_brackets) {
1956 assert('@' == funny || '$' == funny || DOLSHARP == funny);
1957 PL_lex_state = LEX_INTERPEND;
1959 force_next(POSTJOIN);
1965 if ('@' == funny && PL_lex_state == LEX_INTERPNORMAL
1966 && !PL_lex_brackets)
1968 PL_expect = XOPERATOR;
1977 int yyc = PL_parser->yychar;
1978 if (yyc != YYEMPTY) {
1980 NEXTVAL_NEXTTOKE = PL_parser->yylval;
1981 if (yyc == '{'/*}*/ || yyc == HASHBRACK || yyc == '['/*]*/) {
1982 PL_lex_allbrackets--;
1984 yyc |= (3<<24) | (PL_lex_brackstack[PL_lex_brackets] << 16);
1985 } else if (yyc == '('/*)*/) {
1986 PL_lex_allbrackets--;
1991 PL_parser->yychar = YYEMPTY;
1996 S_newSV_maybe_utf8(pTHX_ const char *const start, STRLEN len)
1998 SV * const sv = newSVpvn_utf8(start, len,
2001 && !is_utf8_invariant_string((const U8*)start, len)
2002 && is_utf8_string((const U8*)start, len));
2008 * When the lexer knows the next thing is a word (for instance, it has
2009 * just seen -> and it knows that the next char is a word char, then
2010 * it calls S_force_word to stick the next word into the PL_nexttoke/val
2014 * char *start : buffer position (must be within PL_linestr)
2015 * int token : PL_next* will be this type of bare word
2016 * (e.g., METHOD,BAREWORD)
2017 * int check_keyword : if true, Perl checks to make sure the word isn't
2018 * a keyword (do this if the word is a label, e.g. goto FOO)
2019 * int allow_pack : if true, : characters will also be allowed (require,
2020 * use, etc. do this)
2024 S_force_word(pTHX_ char *start, int token, int check_keyword, int allow_pack)
2029 PERL_ARGS_ASSERT_FORCE_WORD;
2031 start = skipspace(start);
2033 if (isIDFIRST_lazy_if(s,UTF)
2034 || (allow_pack && *s == ':' && s[1] == ':') )
2036 s = scan_word(s, PL_tokenbuf, sizeof PL_tokenbuf, allow_pack, &len);
2037 if (check_keyword) {
2038 char *s2 = PL_tokenbuf;
2040 if (allow_pack && len > 6 && strnEQ(s2, "CORE::", 6))
2042 if (keyword(s2, len2, 0))
2045 if (token == METHOD) {
2050 PL_expect = XOPERATOR;
2053 NEXTVAL_NEXTTOKE.opval
2054 = (OP*)newSVOP(OP_CONST,0,
2055 S_newSV_maybe_utf8(aTHX_ PL_tokenbuf, len));
2056 NEXTVAL_NEXTTOKE.opval->op_private |= OPpCONST_BARE;
2064 * Called when the lexer wants $foo *foo &foo etc, but the program
2065 * text only contains the "foo" portion. The first argument is a pointer
2066 * to the "foo", and the second argument is the type symbol to prefix.
2067 * Forces the next token to be a "BAREWORD".
2068 * Creates the symbol if it didn't already exist (via gv_fetchpv()).
2072 S_force_ident(pTHX_ const char *s, int kind)
2074 PERL_ARGS_ASSERT_FORCE_IDENT;
2077 const STRLEN len = s[1] ? strlen(s) : 1; /* s = "\"" see yylex */
2078 OP* const o = (OP*)newSVOP(OP_CONST, 0, newSVpvn_flags(s, len,
2079 UTF ? SVf_UTF8 : 0));
2080 NEXTVAL_NEXTTOKE.opval = o;
2081 force_next(BAREWORD);
2083 o->op_private = OPpCONST_ENTERED;
2084 /* XXX see note in pp_entereval() for why we forgo typo
2085 warnings if the symbol must be introduced in an eval.
2087 gv_fetchpvn_flags(s, len,
2088 (PL_in_eval ? GV_ADDMULTI
2089 : GV_ADD) | ( UTF ? SVf_UTF8 : 0 ),
2090 kind == '$' ? SVt_PV :
2091 kind == '@' ? SVt_PVAV :
2092 kind == '%' ? SVt_PVHV :
2100 S_force_ident_maybe_lex(pTHX_ char pit)
2102 NEXTVAL_NEXTTOKE.ival = pit;
2107 Perl_str_to_version(pTHX_ SV *sv)
2112 const char *start = SvPV_const(sv,len);
2113 const char * const end = start + len;
2114 const bool utf = SvUTF8(sv) ? TRUE : FALSE;
2116 PERL_ARGS_ASSERT_STR_TO_VERSION;
2118 while (start < end) {
2122 n = utf8n_to_uvchr((U8*)start, len, &skip, 0);
2127 retval += ((NV)n)/nshift;
2136 * Forces the next token to be a version number.
2137 * If the next token appears to be an invalid version number, (e.g. "v2b"),
2138 * and if "guessing" is TRUE, then no new token is created (and the caller
2139 * must use an alternative parsing method).
2143 S_force_version(pTHX_ char *s, int guessing)
2148 PERL_ARGS_ASSERT_FORCE_VERSION;
2156 while (isDIGIT(*d) || *d == '_' || *d == '.')
2158 if (*d == ';' || isSPACE(*d) || *d == '{' || *d == '}' || !*d) {
2160 s = scan_num(s, &pl_yylval);
2161 version = pl_yylval.opval;
2162 ver = cSVOPx(version)->op_sv;
2163 if (SvPOK(ver) && !SvNIOK(ver)) {
2164 SvUPGRADE(ver, SVt_PVNV);
2165 SvNV_set(ver, str_to_version(ver));
2166 SvNOK_on(ver); /* hint that it is a version */
2169 else if (guessing) {
2174 /* NOTE: The parser sees the package name and the VERSION swapped */
2175 NEXTVAL_NEXTTOKE.opval = version;
2176 force_next(BAREWORD);
2182 * S_force_strict_version
2183 * Forces the next token to be a version number using strict syntax rules.
2187 S_force_strict_version(pTHX_ char *s)
2190 const char *errstr = NULL;
2192 PERL_ARGS_ASSERT_FORCE_STRICT_VERSION;
2194 while (isSPACE(*s)) /* leading whitespace */
2197 if (is_STRICT_VERSION(s,&errstr)) {
2199 s = (char *)scan_version(s, ver, 0);
2200 version = newSVOP(OP_CONST, 0, ver);
2202 else if ((*s != ';' && *s != '{' && *s != '}' )
2203 && (s = skipspace(s), (*s != ';' && *s != '{' && *s != '}' )))
2207 yyerror(errstr); /* version required */
2211 /* NOTE: The parser sees the package name and the VERSION swapped */
2212 NEXTVAL_NEXTTOKE.opval = version;
2213 force_next(BAREWORD);
2220 * Tokenize a quoted string passed in as an SV. It finds the next
2221 * chunk, up to end of string or a backslash. It may make a new
2222 * SV containing that chunk (if HINT_NEW_STRING is on). It also
2227 S_tokeq(pTHX_ SV *sv)
2234 PERL_ARGS_ASSERT_TOKEQ;
2238 assert (!SvIsCOW(sv));
2239 if (SvTYPE(sv) >= SVt_PVIV && SvIVX(sv) == -1) /* <<'heredoc' */
2243 /* This is relying on the SV being "well formed" with a trailing '\0' */
2244 while (s < send && !(*s == '\\' && s[1] == '\\'))
2249 if ( PL_hints & HINT_NEW_STRING ) {
2250 pv = newSVpvn_flags(SvPVX_const(pv), SvCUR(sv),
2251 SVs_TEMP | SvUTF8(sv));
2255 if (s + 1 < send && (s[1] == '\\'))
2256 s++; /* all that, just for this */
2261 SvCUR_set(sv, d - SvPVX_const(sv));
2263 if ( PL_hints & HINT_NEW_STRING )
2264 return new_constant(NULL, 0, "q", sv, pv, "q", 1);
2269 * Now come three functions related to double-quote context,
2270 * S_sublex_start, S_sublex_push, and S_sublex_done. They're used when
2271 * converting things like "\u\Lgnat" into ucfirst(lc("gnat")). They
2272 * interact with PL_lex_state, and create fake ( ... ) argument lists
2273 * to handle functions and concatenation.
2277 * stringify ( const[foo] concat lcfirst ( const[bar] ) )
2282 * Assumes that pl_yylval.ival is the op we're creating (e.g. OP_LCFIRST).
2284 * Pattern matching will set PL_lex_op to the pattern-matching op to
2285 * make (we return THING if pl_yylval.ival is OP_NULL, PMFUNC otherwise).
2287 * OP_CONST and OP_READLINE are easy--just make the new op and return.
2289 * Everything else becomes a FUNC.
2291 * Sets PL_lex_state to LEX_INTERPPUSH unless (ival was OP_NULL or we
2292 * had an OP_CONST or OP_READLINE). This just sets us up for a
2293 * call to S_sublex_push().
2297 S_sublex_start(pTHX)
2299 const I32 op_type = pl_yylval.ival;
2301 if (op_type == OP_NULL) {
2302 pl_yylval.opval = PL_lex_op;
2306 if (op_type == OP_CONST) {
2307 SV *sv = PL_lex_stuff;
2308 PL_lex_stuff = NULL;
2311 if (SvTYPE(sv) == SVt_PVIV) {
2312 /* Overloaded constants, nothing fancy: Convert to SVt_PV: */
2314 const char * const p = SvPV_const(sv, len);
2315 SV * const nsv = newSVpvn_flags(p, len, SvUTF8(sv));
2319 pl_yylval.opval = (OP*)newSVOP(op_type, 0, sv);
2323 PL_parser->lex_super_state = PL_lex_state;
2324 PL_parser->lex_sub_inwhat = (U16)op_type;
2325 PL_parser->lex_sub_op = PL_lex_op;
2326 PL_lex_state = LEX_INTERPPUSH;
2330 pl_yylval.opval = PL_lex_op;
2340 * Create a new scope to save the lexing state. The scope will be
2341 * ended in S_sublex_done. Returns a '(', starting the function arguments
2342 * to the uc, lc, etc. found before.
2343 * Sets PL_lex_state to LEX_INTERPCONCAT.
2350 const bool is_heredoc = PL_multi_close == '<';
2353 PL_lex_state = PL_parser->lex_super_state;
2354 SAVEI8(PL_lex_dojoin);
2355 SAVEI32(PL_lex_brackets);
2356 SAVEI32(PL_lex_allbrackets);
2357 SAVEI32(PL_lex_formbrack);
2358 SAVEI8(PL_lex_fakeeof);
2359 SAVEI32(PL_lex_casemods);
2360 SAVEI32(PL_lex_starts);
2361 SAVEI8(PL_lex_state);
2362 SAVESPTR(PL_lex_repl);
2363 SAVEVPTR(PL_lex_inpat);
2364 SAVEI16(PL_lex_inwhat);
2367 SAVECOPLINE(PL_curcop);
2368 SAVEI32(PL_multi_end);
2369 SAVEI32(PL_parser->herelines);
2370 PL_parser->herelines = 0;
2372 SAVEIV(PL_multi_close);
2373 SAVEPPTR(PL_bufptr);
2374 SAVEPPTR(PL_bufend);
2375 SAVEPPTR(PL_oldbufptr);
2376 SAVEPPTR(PL_oldoldbufptr);
2377 SAVEPPTR(PL_last_lop);
2378 SAVEPPTR(PL_last_uni);
2379 SAVEPPTR(PL_linestart);
2380 SAVESPTR(PL_linestr);
2381 SAVEGENERICPV(PL_lex_brackstack);
2382 SAVEGENERICPV(PL_lex_casestack);
2383 SAVEGENERICPV(PL_parser->lex_shared);
2384 SAVEBOOL(PL_parser->lex_re_reparsing);
2385 SAVEI32(PL_copline);
2387 /* The here-doc parser needs to be able to peek into outer lexing
2388 scopes to find the body of the here-doc. So we put PL_linestr and
2389 PL_bufptr into lex_shared, to ‘share’ those values.
2391 PL_parser->lex_shared->ls_linestr = PL_linestr;
2392 PL_parser->lex_shared->ls_bufptr = PL_bufptr;
2394 PL_linestr = PL_lex_stuff;
2395 PL_lex_repl = PL_parser->lex_sub_repl;
2396 PL_lex_stuff = NULL;
2397 PL_parser->lex_sub_repl = NULL;
2399 /* Arrange for PL_lex_stuff to be freed on scope exit, in case it gets
2400 set for an inner quote-like operator and then an error causes scope-
2401 popping. We must not have a PL_lex_stuff value left dangling, as
2402 that breaks assumptions elsewhere. See bug #123617. */
2403 SAVEGENERICSV(PL_lex_stuff);
2404 SAVEGENERICSV(PL_parser->lex_sub_repl);
2406 PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart
2407 = SvPVX(PL_linestr);
2408 PL_bufend += SvCUR(PL_linestr);
2409 PL_last_lop = PL_last_uni = NULL;
2410 SAVEFREESV(PL_linestr);
2411 if (PL_lex_repl) SAVEFREESV(PL_lex_repl);
2413 PL_lex_dojoin = FALSE;
2414 PL_lex_brackets = PL_lex_formbrack = 0;
2415 PL_lex_allbrackets = 0;
2416 PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2417 Newx(PL_lex_brackstack, 120, char);
2418 Newx(PL_lex_casestack, 12, char);
2419 PL_lex_casemods = 0;
2420 *PL_lex_casestack = '\0';
2422 PL_lex_state = LEX_INTERPCONCAT;
2424 CopLINE_set(PL_curcop, (line_t)PL_multi_start);
2425 PL_copline = NOLINE;
2427 Newxz(shared, 1, LEXSHARED);
2428 shared->ls_prev = PL_parser->lex_shared;
2429 PL_parser->lex_shared = shared;
2431 PL_lex_inwhat = PL_parser->lex_sub_inwhat;
2432 if (PL_lex_inwhat == OP_TRANSR) PL_lex_inwhat = OP_TRANS;
2433 if (PL_lex_inwhat == OP_MATCH || PL_lex_inwhat == OP_QR || PL_lex_inwhat == OP_SUBST)
2434 PL_lex_inpat = PL_parser->lex_sub_op;
2436 PL_lex_inpat = NULL;
2438 PL_parser->lex_re_reparsing = cBOOL(PL_in_eval & EVAL_RE_REPARSING);
2439 PL_in_eval &= ~EVAL_RE_REPARSING;
2446 * Restores lexer state after a S_sublex_push.
2452 if (!PL_lex_starts++) {
2453 SV * const sv = newSVpvs("");
2454 if (SvUTF8(PL_linestr))
2456 PL_expect = XOPERATOR;
2457 pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
2461 if (PL_lex_casemods) { /* oops, we've got some unbalanced parens */
2462 PL_lex_state = LEX_INTERPCASEMOD;
2466 /* Is there a right-hand side to take care of? (s//RHS/ or tr//RHS/) */
2467 assert(PL_lex_inwhat != OP_TRANSR);
2469 assert (PL_lex_inwhat == OP_SUBST || PL_lex_inwhat == OP_TRANS);
2470 PL_linestr = PL_lex_repl;
2472 PL_bufend = PL_bufptr = PL_oldbufptr = PL_oldoldbufptr = PL_linestart = SvPVX(PL_linestr);
2473 PL_bufend += SvCUR(PL_linestr);
2474 PL_last_lop = PL_last_uni = NULL;
2475 PL_lex_dojoin = FALSE;
2476 PL_lex_brackets = 0;
2477 PL_lex_allbrackets = 0;
2478 PL_lex_fakeeof = LEX_FAKEEOF_NEVER;
2479 PL_lex_casemods = 0;
2480 *PL_lex_casestack = '\0';
2482 if (SvEVALED(PL_lex_repl)) {
2483 PL_lex_state = LEX_INTERPNORMAL;
2485 /* we don't clear PL_lex_repl here, so that we can check later
2486 whether this is an evalled subst; that means we rely on the
2487 logic to ensure sublex_done() is called again only via the
2488 branch (in yylex()) that clears PL_lex_repl, else we'll loop */
2491 PL_lex_state = LEX_INTERPCONCAT;
2494 if (SvTYPE(PL_linestr) >= SVt_PVNV) {
2495 CopLINE(PL_curcop) +=
2496 ((XPVNV*)SvANY(PL_linestr))->xnv_u.xnv_lines
2497 + PL_parser->herelines;
2498 PL_parser->herelines = 0;
2503 const line_t l = CopLINE(PL_curcop);
2505 if (PL_multi_close == '<')
2506 PL_parser->herelines += l - PL_multi_end;
2507 PL_bufend = SvPVX(PL_linestr);
2508 PL_bufend += SvCUR(PL_linestr);
2509 PL_expect = XOPERATOR;
2514 PERL_STATIC_INLINE SV*
2515 S_get_and_check_backslash_N_name(pTHX_ const char* s, const char* const e)
2517 /* <s> points to first character of interior of \N{}, <e> to one beyond the
2518 * interior, hence to the "}". Finds what the name resolves to, returning
2519 * an SV* containing it; NULL if no valid one found */
2521 SV* res = newSVpvn_flags(s, e - s, UTF ? SVf_UTF8 : 0);
2528 const U8* first_bad_char_loc;
2529 const char* backslash_ptr = s - 3; /* Points to the <\> of \N{... */
2531 PERL_ARGS_ASSERT_GET_AND_CHECK_BACKSLASH_N_NAME;
2534 Perl_ck_warner_d(aTHX_ packWARN(WARN_DEPRECATED),
2535 "Unknown charname '' is deprecated");
2539 if (UTF && ! is_utf8_string_loc((U8 *) backslash_ptr,
2541 &first_bad_char_loc))
2543 /* If warnings are on, this will print a more detailed analysis of what
2544 * is wrong than the error message below */
2545 utf8n_to_uvchr(first_bad_char_loc,
2546 e - ((char *) first_bad_char_loc),
2549 /* We deliberately don't try to print the malformed character, which
2550 * might not print very well; it also may be just the first of many
2551 * malformations, so don't print what comes after it */
2552 yyerror_pv(Perl_form(aTHX_
2553 "Malformed UTF-8 character immediately after '%.*s'",
2554 (int) (first_bad_char_loc - (U8 *) backslash_ptr), backslash_ptr),
2559 res = new_constant( NULL, 0, "charnames", res, NULL, backslash_ptr,
2560 /* include the <}> */
2561 e - backslash_ptr + 1);
2563 SvREFCNT_dec_NN(res);
2567 /* See if the charnames handler is the Perl core's, and if so, we can skip
2568 * the validation needed for a user-supplied one, as Perl's does its own
2570 table = GvHV(PL_hintgv); /* ^H */
2571 cvp = hv_fetchs(table, "charnames", FALSE);
2572 if (cvp && (cv = *cvp) && SvROK(cv) && (rv = SvRV(cv),
2573 SvTYPE(rv) == SVt_PVCV) && ((stash = CvSTASH(rv)) != NULL))
2575 const char * const name = HvNAME(stash);
2576 if (HvNAMELEN(stash) == sizeof("_charnames")-1
2577 && strEQ(name, "_charnames")) {
2582 /* Here, it isn't Perl's charname handler. We can't rely on a
2583 * user-supplied handler to validate the input name. For non-ut8 input,
2584 * look to see that the first character is legal. Then loop through the
2585 * rest checking that each is a continuation */
2587 /* This code makes the reasonable assumption that the only Latin1-range
2588 * characters that begin a character name alias are alphabetic, otherwise
2589 * would have to create a isCHARNAME_BEGIN macro */
2592 if (! isALPHAU(*s)) {
2597 if (! isCHARNAME_CONT(*s)) {
2600 if (*s == ' ' && *(s-1) == ' ') {
2607 /* Similarly for utf8. For invariants can check directly; for other
2608 * Latin1, can calculate their code point and check; otherwise use a
2610 if (UTF8_IS_INVARIANT(*s)) {
2611 if (! isALPHAU(*s)) {
2615 } else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2616 if (! isALPHAU(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1)))) {
2622 if (! PL_utf8_charname_begin) {
2623 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2624 PL_utf8_charname_begin = _core_swash_init("utf8",
2625 "_Perl_Charname_Begin",
2627 1, 0, NULL, &flags);
2629 if (! swash_fetch(PL_utf8_charname_begin, (U8 *) s, TRUE)) {
2636 if (UTF8_IS_INVARIANT(*s)) {
2637 if (! isCHARNAME_CONT(*s)) {
2640 if (*s == ' ' && *(s-1) == ' ') {
2645 else if (UTF8_IS_DOWNGRADEABLE_START(*s)) {
2646 if (! isCHARNAME_CONT(EIGHT_BIT_UTF8_TO_NATIVE(*s, *(s+1))))
2653 if (! PL_utf8_charname_continue) {
2654 U8 flags = _CORE_SWASH_INIT_ACCEPT_INVLIST;
2655 PL_utf8_charname_continue = _core_swash_init("utf8",
2656 "_Perl_Charname_Continue",
2658 1, 0, NULL, &flags);
2660 if (! swash_fetch(PL_utf8_charname_continue, (U8 *) s, TRUE)) {
2667 if (*(s-1) == ' ') {
2670 "charnames alias definitions may not contain trailing "
2671 "white-space; marked by <-- HERE in %.*s<-- HERE %.*s",
2672 (int)(s - backslash_ptr + 1), backslash_ptr,
2673 (int)(e - s + 1), s + 1
2675 UTF ? SVf_UTF8 : 0);
2679 if (SvUTF8(res)) { /* Don't accept malformed input */
2680 const U8* first_bad_char_loc;
2682 const char* const str = SvPV_const(res, len);
2683 if (! is_utf8_string_loc((U8 *) str, len, &first_bad_char_loc)) {
2684 /* If warnings are on, this will print a more detailed analysis of
2685 * what is wrong than the error message below */
2686 utf8n_to_uvchr(first_bad_char_loc,
2687 (char *) first_bad_char_loc - str,
2690 /* We deliberately don't try to print the malformed character,
2691 * which might not print very well; it also may be just the first
2692 * of many malformations, so don't print what comes after it */
2695 "Malformed UTF-8 returned by %.*s immediately after '%.*s'",
2696 (int) (e - backslash_ptr + 1), backslash_ptr,
2697 (int) ((char *) first_bad_char_loc - str), str
2708 /* The final %.*s makes sure that should the trailing NUL be missing
2709 * that this print won't run off the end of the string */
2712 "Invalid character in \\N{...}; marked by <-- HERE in %.*s<-- HERE %.*s",
2713 (int)(s - backslash_ptr + 1), backslash_ptr,
2714 (int)(e - s + 1), s + 1
2716 UTF ? SVf_UTF8 : 0);
2723 "charnames alias definitions may not contain a sequence of "
2724 "multiple spaces; marked by <-- HERE in %.*s<-- HERE %.*s",
2725 (int)(s - backslash_ptr + 1), backslash_ptr,
2726 (int)(e - s + 1), s + 1
2728 UTF ? SVf_UTF8 : 0);
2735 Extracts the next constant part of a pattern, double-quoted string,
2736 or transliteration. This is terrifying code.
2738 For example, in parsing the double-quoted string "ab\x63$d", it would
2739 stop at the '$' and return an OP_CONST containing 'abc'.
2741 It looks at PL_lex_inwhat and PL_lex_inpat to find out whether it's
2742 processing a pattern (PL_lex_inpat is true), a transliteration
2743 (PL_lex_inwhat == OP_TRANS is true), or a double-quoted string.
2745 Returns a pointer to the character scanned up to. If this is
2746 advanced from the start pointer supplied (i.e. if anything was
2747 successfully parsed), will leave an OP_CONST for the substring scanned
2748 in pl_yylval. Caller must intuit reason for not parsing further
2749 by looking at the next characters herself.
2753 \N{FOO} => \N{U+hex_for_character_FOO}
2754 (if FOO expands to multiple characters, expands to \N{U+xx.XX.yy ...})
2757 all other \-char, including \N and \N{ apart from \N{ABC}
2760 @ and $ where it appears to be a var, but not for $ as tail anchor
2764 In transliterations:
2765 characters are VERY literal, except for - not at the start or end
2766 of the string, which indicates a range. If the range is in bytes,
2767 scan_const expands the range to the full set of intermediate
2768 characters. If the range is in utf8, the hyphen is replaced with
2769 a certain range mark which will be handled by pmtrans() in op.c.
2771 In double-quoted strings:
2773 double-quoted style: \r and \n
2774 constants: \x31, etc.
2775 deprecated backrefs: \1 (in substitution replacements)
2776 case and quoting: \U \Q \E
2779 scan_const does *not* construct ops to handle interpolated strings.
2780 It stops processing as soon as it finds an embedded $ or @ variable
2781 and leaves it to the caller to work out what's going on.
2783 embedded arrays (whether in pattern or not) could be:
2784 @foo, @::foo, @'foo, @{foo}, @$foo, @+, @-.
2786 $ in double-quoted strings must be the symbol of an embedded scalar.
2788 $ in pattern could be $foo or could be tail anchor. Assumption:
2789 it's a tail anchor if $ is the last thing in the string, or if it's
2790 followed by one of "()| \r\n\t"
2792 \1 (backreferences) are turned into $1 in substitutions
2794 The structure of the code is
2795 while (there's a character to process) {
2796 handle transliteration ranges
2797 skip regexp comments /(?#comment)/ and codes /(?{code})/
2798 skip #-initiated comments in //x patterns
2799 check for embedded arrays
2800 check for embedded scalars
2802 deprecate \1 in substitution replacements
2803 handle string-changing backslashes \l \U \Q \E, etc.
2804 switch (what was escaped) {
2805 handle \- in a transliteration (becomes a literal -)
2806 if a pattern and not \N{, go treat as regular character
2807 handle \132 (octal characters)
2808 handle \x15 and \x{1234} (hex characters)
2809 handle \N{name} (named characters, also \N{3,5} in a pattern)
2810 handle \cV (control characters)
2811 handle printf-style backslashes (\f, \r, \n, etc)
2814 } (end if backslash)
2815 handle regular character
2816 } (end while character to read)
2821 S_scan_const(pTHX_ char *start)
2823 char *send = PL_bufend; /* end of the constant */
2824 SV *sv = newSV(send - start); /* sv for the constant. See note below
2826 char *s = start; /* start of the constant */
2827 char *d = SvPVX(sv); /* destination for copies */
2828 bool dorange = FALSE; /* are we in a translit range? */
2829 bool didrange = FALSE; /* did we just finish a range? */
2830 bool in_charclass = FALSE; /* within /[...]/ */
2831 bool has_utf8 = FALSE; /* Output constant is UTF8 */
2832 bool this_utf8 = cBOOL(UTF); /* Is the source string assumed to be
2833 UTF8? But, this can show as true
2834 when the source isn't utf8, as for
2835 example when it is entirely composed
2837 SV *res; /* result from charnames */
2838 STRLEN offset_to_max; /* The offset in the output to where the range
2839 high-end character is temporarily placed */
2841 /* Note on sizing: The scanned constant is placed into sv, which is
2842 * initialized by newSV() assuming one byte of output for every byte of
2843 * input. This routine expects newSV() to allocate an extra byte for a
2844 * trailing NUL, which this routine will append if it gets to the end of
2845 * the input. There may be more bytes of input than output (eg., \N{LATIN
2846 * CAPITAL LETTER A}), or more output than input if the constant ends up
2847 * recoded to utf8, but each time a construct is found that might increase
2848 * the needed size, SvGROW() is called. Its size parameter each time is
2849 * based on the best guess estimate at the time, namely the length used so
2850 * far, plus the length the current construct will occupy, plus room for
2851 * the trailing NUL, plus one byte for every input byte still unscanned */
2853 UV uv = UV_MAX; /* Initialize to weird value to try to catch any uses
2856 int backslash_N = 0; /* ? was the character from \N{} */
2857 int non_portable_endpoint = 0; /* ? In a range is an endpoint
2858 platform-specific like \x65 */
2861 PERL_ARGS_ASSERT_SCAN_CONST;
2863 assert(PL_lex_inwhat != OP_TRANSR);
2864 if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
2865 /* If we are doing a trans and we know we want UTF8 set expectation */
2866 has_utf8 = PL_parser->lex_sub_op->op_private & (OPpTRANS_FROM_UTF|OPpTRANS_TO_UTF);
2867 this_utf8 = PL_parser->lex_sub_op->op_private & (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
2870 /* Protect sv from errors and fatal warnings. */
2871 ENTER_with_name("scan_const");
2875 || dorange /* Handle tr/// range at right edge of input */
2878 /* get transliterations out of the way (they're most literal) */
2879 if (PL_lex_inwhat == OP_TRANS) {
2881 /* But there isn't any special handling necessary unless there is a
2882 * range, so for most cases we just drop down and handle the value
2883 * as any other. There are two exceptions.
2885 * 1. A minus sign indicates that we are actually going to have
2886 * a range. In this case, skip the '-', set a flag, then drop
2887 * down to handle what should be the end range value.
2888 * 2. After we've handled that value, the next time through, that
2889 * flag is set and we fix up the range.
2891 * Ranges entirely within Latin1 are expanded out entirely, in
2892 * order to avoid the significant overhead of making a swash.
2893 * Ranges that extend above Latin1 have to have a swash, so there
2894 * is no advantage to abbreviate them here, so they are stored here
2895 * as Min, ILLEGAL_UTF8_BYTE, Max. The illegal byte signifies a
2896 * hyphen without any possible ambiguity. On EBCDIC machines, if
2897 * the range is expressed as Unicode, the Latin1 portion is
2898 * expanded out even if the entire range extends above Latin1.
2899 * This is because each code point in it has to be processed here
2900 * individually to get its native translation */
2904 /* Here, we don't think we're in a range. If we've processed
2905 * at least one character, then see if this next one is a '-',
2906 * indicating the previous one was the start of a range. But
2907 * don't bother if we're too close to the end for the minus to
2909 if (*s != '-' || s >= send - 1 || s == start) {
2911 /* A regular character. Process like any other, but first
2912 * clear any flags */
2916 non_portable_endpoint = 0;
2919 /* Drops down to generic code to process current byte */
2922 if (didrange) { /* Something like y/A-C-Z// */
2923 Perl_croak(aTHX_ "Ambiguous range in transliteration operator");
2928 s++; /* Skip past the minus */
2930 /* d now points to where the end-range character will be
2931 * placed. Save it so won't have to go finding it later,
2932 * and drop down to get that character. (Actually we
2933 * instead save the offset, to handle the case where a
2934 * realloc in the meantime could change the actual
2935 * pointer). We'll finish processing the range the next
2936 * time through the loop */
2937 offset_to_max = d - SvPVX_const(sv);
2939 } /* End of not a range */
2941 /* Here we have parsed a range. Now must handle it. At this
2943 * 'sv' is a SV* that contains the output string we are
2944 * constructing. The final two characters in that string
2945 * are the range start and range end, in order.
2946 * 'd' points to just beyond the range end in the 'sv' string,
2947 * where we would next place something
2948 * 'offset_to_max' is the offset in 'sv' at which the character
2949 * before 'd' begins.
2951 const char * max_ptr = SvPVX_const(sv) + offset_to_max;
2952 const char * min_ptr;
2954 IV range_max; /* last character in range */
2957 #ifndef EBCDIC /* Not meaningful except in EBCDIC, so initialize to false */
2958 const bool convert_unicode = FALSE;
2959 const IV real_range_max = 0;
2961 bool convert_unicode;
2962 IV real_range_max = 0;
2965 /* Get the range-ends code point values. */
2967 /* We know the utf8 is valid, because we just constructed
2968 * it ourselves in previous loop iterations */
2969 min_ptr = (char*) utf8_hop( (U8*) max_ptr, -1);
2970 range_min = valid_utf8_to_uvchr( (U8*) min_ptr, NULL);
2971 range_max = valid_utf8_to_uvchr( (U8*) max_ptr, NULL);
2974 min_ptr = max_ptr - 1;
2975 range_min = * (U8*) min_ptr;
2976 range_max = * (U8*) max_ptr;
2980 /* On EBCDIC platforms, we may have to deal with portable
2981 * ranges. These happen if at least one range endpoint is a
2982 * Unicode value (\N{...}), or if the range is a subset of
2983 * [A-Z] or [a-z], and both ends are literal characters,
2984 * like 'A', and not like \x{C1} */
2985 if ((convert_unicode
2986 = cBOOL(backslash_N) /* \N{} forces Unicode, hence
2988 || ( ! non_portable_endpoint
2989 && (( isLOWER_A(range_min) && isLOWER_A(range_max))
2990 || (isUPPER_A(range_min) && isUPPER_A(range_max))))
2993 /* Special handling is needed for these portable ranges.
2994 * They are defined to all be in Unicode terms, which
2995 * include all Unicode code points between the end points.
2996 * Convert to Unicode to get the Unicode range. Later we
2997 * will convert each code point in the range back to
2999 range_min = NATIVE_TO_UNI(range_min);
3000 range_max = NATIVE_TO_UNI(range_max);
3004 if (range_min > range_max) {
3005 if (convert_unicode) {
3006 /* Need to convert back to native for meaningful
3007 * messages for this platform */
3008 range_min = UNI_TO_NATIVE(range_min);
3009 range_max = UNI_TO_NATIVE(range_max);
3012 /* Use the characters themselves for the error message if
3013 * ASCII printables; otherwise some visible representation
3015 if (isPRINT_A(range_min) && isPRINT_A(range_max)) {
3017 "Invalid range \"%c-%c\" in transliteration operator",
3018 (char)range_min, (char)range_max);
3020 else if (convert_unicode) {
3021 /* diag_listed_as: Invalid range "%s" in transliteration operator */
3023 "Invalid range \"\\N{U+%04"UVXf"}-\\N{U+%04"UVXf"}\""
3024 " in transliteration operator",
3025 range_min, range_max);
3028 /* diag_listed_as: Invalid range "%s" in transliteration operator */
3030 "Invalid range \"\\x{%04"UVXf"}-\\x{%04"UVXf"}\""
3031 " in transliteration operator",
3032 range_min, range_max);
3038 /* We try to avoid creating a swash. If the upper end of
3039 * this range is below 256, this range won't force a swash;
3040 * otherwise it does force a swash, and as long as we have
3041 * to have one, we might as well not expand things out.
3042 * But if it's EBCDIC, we may have to look at each
3043 * character below 256 if we have to convert to/from
3047 && (range_min > 255 || ! convert_unicode)
3050 /* Move the high character one byte to the right; then
3051 * insert between it and the range begin, an illegal
3052 * byte which serves to indicate this is a range (using
3053 * a '-' could be ambiguous). */
3055 while (e-- > max_ptr) {
3058 *(e + 1) = (char) ILLEGAL_UTF8_BYTE;
3062 /* Here, we're going to expand out the range. For EBCDIC
3063 * the range can extend above 255 (not so in ASCII), so
3064 * for EBCDIC, split it into the parts above and below
3067 if (range_max > 255) {
3068 real_range_max = range_max;
3074 /* Here we need to expand out the string to contain each
3075 * character in the range. Grow the output to handle this */
3077 save_offset = min_ptr - SvPVX_const(sv);
3079 /* The base growth is the number of code points in the range */
3080 grow = range_max - range_min + 1;
3083 /* But if the output is UTF-8, some of those characters may
3084 * need two bytes (since the maximum range value here is
3085 * 255, the max bytes per character is two). On ASCII
3086 * platforms, it's not much trouble to get an accurate
3087 * count of what's needed. But on EBCDIC, the ones that
3088 * need 2 bytes are scattered around, so just use a worst
3089 * case value instead of calculating for that platform. */
3093 /* Only those above 127 require 2 bytes. This may be
3094 * everything in the range, or not */
3095 if (range_min > 127) {
3098 else if (range_max > 127) {
3099 grow += range_max - 127;
3104 /* Subtract 3 for the bytes that were already accounted for
3105 * (min, max, and the hyphen) */
3106 d = save_offset + SvGROW(sv, SvLEN(sv) + grow - 3);
3108 /* Here, we expand out the range. On ASCII platforms, the
3109 * compiler should optimize out the 'convert_unicode==TRUE'
3110 * portion of this */
3111 if (convert_unicode) {
3114 /* Recall that the min and max are now in Unicode terms, so
3115 * we have to convert each character to its native
3118 for (i = range_min; i <= range_max; i++) {
3119 append_utf8_from_native_byte(LATIN1_TO_NATIVE((U8) i),
3124 for (i = range_min; i <= range_max; i++) {
3125 *d++ = (char)LATIN1_TO_NATIVE((U8) i);
3132 /* Here, no conversions are necessary, which means that the
3133 * first character in the range is already in 'd' and
3134 * valid, so we can skip overwriting it */
3137 for (i = range_min + 1; i <= range_max; i++) {
3138 append_utf8_from_native_byte((U8) i, (U8 **) &d);
3143 for (i = range_min + 1; i <= range_max; i++) {
3149 /* (Compilers should optimize this out for non-EBCDIC). If the
3150 * original range extended above 255, add in that portion */
3151 if (real_range_max) {
3152 *d++ = (char) UTF8_TWO_BYTE_HI(0x100);
3153 *d++ = (char) UTF8_TWO_BYTE_LO(0x100);
3154 if (real_range_max > 0x101)
3155 *d++ = (char) ILLEGAL_UTF8_BYTE;
3156 if (real_range_max > 0x100)
3157 d = (char*)uvchr_to_utf8((U8*)d, real_range_max);
3161 /* mark the range as done, and continue */
3165 non_portable_endpoint = 0;
3169 } /* End of is a range */
3170 } /* End of transliteration. Joins main code after these else's */
3171 else if (*s == '[' && PL_lex_inpat && !in_charclass) {
3174 while (s1 >= start && *s1-- == '\\')
3177 in_charclass = TRUE;
3180 else if (*s == ']' && PL_lex_inpat && in_charclass) {
3183 while (s1 >= start && *s1-- == '\\')
3186 in_charclass = FALSE;
3189 /* skip for regexp comments /(?#comment)/, except for the last
3190 * char, which will be done separately.
3191 * Stop on (?{..}) and friends */
3193 else if (*s == '(' && PL_lex_inpat && s[1] == '?' && !in_charclass) {
3195 while (s+1 < send && *s != ')')
3198 else if (!PL_lex_casemods
3199 && ( s[2] == '{' /* This should match regcomp.c */
3200 || (s[2] == '?' && s[3] == '{')))
3206 /* likewise skip #-initiated comments in //x patterns */
3210 && ((PMOP*)PL_lex_inpat)->op_pmflags & RXf_PMf_EXTENDED)
3212 while (s+1 < send && *s != '\n')
3216 /* no further processing of single-quoted regex */
3217 else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'')
3218 goto default_action;
3220 /* check for embedded arrays
3221 (@foo, @::foo, @'foo, @{foo}, @$foo, @+, @-)
3223 else if (*s == '@' && s[1]) {
3224 if (UTF ? isIDFIRST_utf8((U8*)s+1) : isWORDCHAR_A(s[1]))
3226 if (strchr(":'{$", s[1]))
3228 if (!PL_lex_inpat && (s[1] == '+' || s[1] == '-'))
3229 break; /* in regexp, neither @+ nor @- are interpolated */
3232 /* check for embedded scalars. only stop if we're sure it's a
3235 else if (*s == '$') {
3236 if (!PL_lex_inpat) /* not a regexp, so $ must be var */
3238 if (s + 1 < send && !strchr("()| \r\n\t", s[1])) {
3240 Perl_ck_warner(aTHX_ packWARN(WARN_AMBIGUOUS),
3241 "Possible unintended interpolation of $\\ in regex");
3243 break; /* in regexp, $ might be tail anchor */
3247 /* End of else if chain - OP_TRANS rejoin rest */
3250 if (*s == '\\' && s+1 < send) {
3251 char* e; /* Can be used for ending '}', etc. */
3255 /* warn on \1 - \9 in substitution replacements, but note that \11
3256 * is an octal; and \19 is \1 followed by '9' */
3257 if (PL_lex_inwhat == OP_SUBST
3263 /* diag_listed_as: \%d better written as $%d */
3264 Perl_ck_warner(aTHX_ packWARN(WARN_SYNTAX), "\\%c better written as $%c", *s, *s);
3269 /* string-change backslash escapes */
3270 if (PL_lex_inwhat != OP_TRANS && *s && strchr("lLuUEQF", *s)) {
3274 /* In a pattern, process \N, but skip any other backslash escapes.
3275 * This is because we don't want to translate an escape sequence
3276 * into a meta symbol and have the regex compiler use the meta
3277 * symbol meaning, e.g. \x{2E} would be confused with a dot. But
3278 * in spite of this, we do have to process \N here while the proper
3279 * charnames handler is in scope. See bugs #56444 and #62056.
3281 * There is a complication because \N in a pattern may also stand
3282 * for 'match a non-nl', and not mean a charname, in which case its
3283 * processing should be deferred to the regex compiler. To be a
3284 * charname it must be followed immediately by a '{', and not look
3285 * like \N followed by a curly quantifier, i.e., not something like
3286 * \N{3,}. regcurly returns a boolean indicating if it is a legal
3288 else if (PL_lex_inpat
3291 || regcurly(s + 1)))
3294 goto default_action;
3300 if ((isALPHANUMERIC(*s)))
3301 Perl_ck_warner(aTHX_ packWARN(WARN_MISC),
3302 "Unrecognized escape \\%c passed through",
3304 /* default action is to copy the quoted character */
3305 goto default_action;
3308 /* eg. \132 indicates the octal constant 0132 */
3309 case '0': case '1': case '2': case '3':
3310 case '4': case '5': case '6': case '7':
3312 I32 flags = PERL_SCAN_SILENT_ILLDIGIT;
3314 uv = grok_oct(s, &len, &flags, NULL);
3316 if (len < 3 && s < send && isDIGIT(*s)
3317 && ckWARN(WARN_MISC))
3319 Perl_warner(aTHX_ packWARN(WARN_MISC),
3320 "%s", form_short_octal_warning(s, len));
3323 goto NUM_ESCAPE_INSERT;
3325 /* eg. \o{24} indicates the octal constant \024 */
3330 bool valid = grok_bslash_o(&s, &uv, &error,
3331 TRUE, /* Output warning */
3332 FALSE, /* Not strict */
3333 TRUE, /* Output warnings for
3340 goto NUM_ESCAPE_INSERT;
3343 /* eg. \x24 indicates the hex constant 0x24 */
3348 bool valid = grok_bslash_x(&s, &uv, &error,
3349 TRUE, /* Output warning */
3350 FALSE, /* Not strict */
3351 TRUE, /* Output warnings for
3361 /* Insert oct or hex escaped character. */
3363 /* Here uv is the ordinal of the next character being added */
3364 if (UVCHR_IS_INVARIANT(uv)) {
3368 if (!has_utf8 && uv > 255) {
3369 /* Might need to recode whatever we have accumulated so
3370 * far if it contains any chars variant in utf8 or
3373 SvCUR_set(sv, d - SvPVX_const(sv));
3376 /* See Note on sizing above. */
3377 sv_utf8_upgrade_flags_grow(
3379 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE
3380 /* Above-latin1 in string
3381 * implies no encoding */
3382 |SV_UTF8_NO_ENCODING,
3383 UVCHR_SKIP(uv) + (STRLEN)(send - s) + 1);
3384 d = SvPVX(sv) + SvCUR(sv);
3389 /* Usually, there will already be enough room in 'sv'
3390 * since such escapes are likely longer than any UTF-8
3391 * sequence they can end up as. This isn't the case on
3392 * EBCDIC where \x{40000000} contains 12 bytes, and the
3393 * UTF-8 for it contains 14. And, we have to allow for
3394 * a trailing NUL. It probably can't happen on ASCII
3395 * platforms, but be safe */
3396 const STRLEN needed = d - SvPVX(sv) + UVCHR_SKIP(uv)
3398 if (UNLIKELY(needed > SvLEN(sv))) {
3399 SvCUR_set(sv, d - SvPVX_const(sv));
3400 d = sv_grow(sv, needed) + SvCUR(sv);
3403 d = (char*)uvchr_to_utf8((U8*)d, uv);
3404 if (PL_lex_inwhat == OP_TRANS
3405 && PL_parser->lex_sub_op)
3407 PL_parser->lex_sub_op->op_private |=
3408 (PL_lex_repl ? OPpTRANS_FROM_UTF
3417 non_portable_endpoint++;
3422 /* In a non-pattern \N must be like \N{U+0041}, or it can be a
3423 * named character, like \N{LATIN SMALL LETTER A}, or a named
3424 * sequence, like \N{LATIN CAPITAL LETTER A WITH MACRON AND
3425 * GRAVE} (except y/// can't handle the latter, croaking). For
3426 * convenience all three forms are referred to as "named
3427 * characters" below.
3429 * For patterns, \N also can mean to match a non-newline. Code
3430 * before this 'switch' statement should already have handled
3431 * this situation, and hence this code only has to deal with
3432 * the named character cases.
3434 * For non-patterns, the named characters are converted to
3435 * their string equivalents. In patterns, named characters are
3436 * not converted to their ultimate forms for the same reasons
3437 * that other escapes aren't. Instead, they are converted to
3438 * the \N{U+...} form to get the value from the charnames that
3439 * is in effect right now, while preserving the fact that it
3440 * was a named character, so that the regex compiler knows
3443 * The structure of this section of code (besides checking for
3444 * errors and upgrading to utf8) is:
3445 * If the named character is of the form \N{U+...}, pass it
3446 * through if a pattern; otherwise convert the code point
3448 * Otherwise must be some \N{NAME}: convert to
3449 * \N{U+c1.c2...} if a pattern; otherwise convert to utf8
3451 * Transliteration is an exception. The conversion to utf8 is
3452 * only done if the code point requires it to be representable.
3454 * Here, 's' points to the 'N'; the test below is guaranteed to
3455 * succeed if we are being called on a pattern, as we already
3456 * know from a test above that the next character is a '{'. A
3457 * non-pattern \N must mean 'named character', which requires
3461 yyerror("Missing braces on \\N{}");
3466 /* If there is no matching '}', it is an error. */
3467 if (! (e = strchr(s, '}'))) {
3468 if (! PL_lex_inpat) {
3469 yyerror("Missing right brace on \\N{}");
3471 yyerror("Missing right brace on \\N{} or unescaped left brace after \\N");
3476 /* Here it looks like a named character */
3478 if (*s == 'U' && s[1] == '+') { /* \N{U+...} */
3479 s += 2; /* Skip to next char after the 'U+' */
3482 /* In patterns, we can have \N{U+xxxx.yyyy.zzzz...} */
3483 /* Check the syntax. */
3486 if (!isXDIGIT(*s)) {
3489 "Invalid hexadecimal number in \\N{U+...}"
3497 else if ((*s == '.' || *s == '_')
3503 /* Pass everything through unchanged.
3504 * +1 is for the '}' */
3505 Copy(orig_s, d, e - orig_s + 1, char);
3506 d += e - orig_s + 1;
3508 else { /* Not a pattern: convert the hex to string */
3509 I32 flags = PERL_SCAN_ALLOW_UNDERSCORES
3510 | PERL_SCAN_SILENT_ILLDIGIT
3511 | PERL_SCAN_DISALLOW_PREFIX;
3513 uv = grok_hex(s, &len, &flags, NULL);
3514 if (len == 0 || (len != (STRLEN)(e - s)))
3517 /* For non-tr///, if the destination is not in utf8,
3518 * unconditionally recode it to be so. This is
3519 * because \N{} implies Unicode semantics, and scalars
3520 * have to be in utf8 to guarantee those semantics.
3521 * tr/// doesn't care about Unicode rules, so no need
3522 * there to upgrade to UTF-8 for small enough code
3524 if (! has_utf8 && ( uv > 0xFF
3525 || PL_lex_inwhat != OP_TRANS))
3527 SvCUR_set(sv, d - SvPVX_const(sv));
3530 /* See Note on sizing above. */
3531 sv_utf8_upgrade_flags_grow(
3533 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3534 UVCHR_SKIP(uv) + (STRLEN)(send - e) + 1);
3535 d = SvPVX(sv) + SvCUR(sv);
3539 /* Add the (Unicode) code point to the output. */
3540 if (! has_utf8 || OFFUNI_IS_INVARIANT(uv)) {
3541 *d++ = (char) LATIN1_TO_NATIVE(uv);
3544 d = (char*) uvoffuni_to_utf8_flags((U8*)d, uv, 0);
3548 else /* Here is \N{NAME} but not \N{U+...}. */
3549 if ((res = get_and_check_backslash_N_name(s, e)))
3552 const char *str = SvPV_const(res, len);
3555 if (! len) { /* The name resolved to an empty string */
3556 Copy("\\N{}", d, 4, char);
3560 /* In order to not lose information for the regex
3561 * compiler, pass the result in the specially made
3562 * syntax: \N{U+c1.c2.c3...}, where c1 etc. are
3563 * the code points in hex of each character
3564 * returned by charnames */
3566 const char *str_end = str + len;
3567 const STRLEN off = d - SvPVX_const(sv);
3569 if (! SvUTF8(res)) {
3570 /* For the non-UTF-8 case, we can determine the
3571 * exact length needed without having to parse
3572 * through the string. Each character takes up
3573 * 2 hex digits plus either a trailing dot or
3575 const char initial_text[] = "\\N{U+";
3576 const STRLEN initial_len = sizeof(initial_text)
3578 d = off + SvGROW(sv, off
3581 /* +1 for trailing NUL */
3584 + (STRLEN)(send - e));
3585 Copy(initial_text, d, initial_len, char);
3587 while (str < str_end) {
3590 my_snprintf(hex_string,
3594 /* The regex compiler is
3595 * expecting Unicode, not
3597 NATIVE_TO_LATIN1(*str));
3598 PERL_MY_SNPRINTF_POST_GUARD(len,
3599 sizeof(hex_string));
3600 Copy(hex_string, d, 3, char);
3604 d--; /* Below, we will overwrite the final
3605 dot with a right brace */
3608 STRLEN char_length; /* cur char's byte length */
3610 /* and the number of bytes after this is
3611 * translated into hex digits */
3612 STRLEN output_length;
3614 /* 2 hex per byte; 2 chars for '\N'; 2 chars
3615 * for max('U+', '.'); and 1 for NUL */
3616 char hex_string[2 * UTF8_MAXBYTES + 5];
3618 /* Get the first character of the result. */
3619 U32 uv = utf8n_to_uvchr((U8 *) str,
3623 /* Convert first code point to Unicode hex,
3624 * including the boiler plate before it. */
3626 my_snprintf(hex_string, sizeof(hex_string),
3628 (unsigned int) NATIVE_TO_UNI(uv));
3630 /* Make sure there is enough space to hold it */
3631 d = off + SvGROW(sv, off
3633 + (STRLEN)(send - e)
3634 + 2); /* '}' + NUL */
3636 Copy(hex_string, d, output_length, char);
3639 /* For each subsequent character, append dot and
3640 * its Unicode code point in hex */
3641 while ((str += char_length) < str_end) {
3642 const STRLEN off = d - SvPVX_const(sv);
3643 U32 uv = utf8n_to_uvchr((U8 *) str,
3648 my_snprintf(hex_string,
3651 (unsigned int) NATIVE_TO_UNI(uv));
3653 d = off + SvGROW(sv, off
3655 + (STRLEN)(send - e)
3656 + 2); /* '}' + NUL */
3657 Copy(hex_string, d, output_length, char);
3662 *d++ = '}'; /* Done. Add the trailing brace */
3665 else { /* Here, not in a pattern. Convert the name to a
3668 if (PL_lex_inwhat == OP_TRANS) {
3669 str = SvPV_const(res, len);
3670 if (len > ((SvUTF8(res))
3674 yyerror(Perl_form(aTHX_
3675 "%.*s must not be a named sequence"
3676 " in transliteration operator",
3677 /* +1 to include the "}" */
3678 (int) (e + 1 - start), start));
3679 goto end_backslash_N;
3682 else if (! SvUTF8(res)) {
3683 /* Make sure \N{} return is UTF-8. This is because
3684 * \N{} implies Unicode semantics, and scalars have
3685 * to be in utf8 to guarantee those semantics; but
3686 * not needed in tr/// */
3687 sv_utf8_upgrade_flags(res, SV_UTF8_NO_ENCODING);
3688 str = SvPV_const(res, len);
3691 /* Upgrade destination to be utf8 if this new
3693 if (! has_utf8 && SvUTF8(res)) {
3694 SvCUR_set(sv, d - SvPVX_const(sv));
3697 /* See Note on sizing above. */
3698 sv_utf8_upgrade_flags_grow(sv,
3699 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3700 len + (STRLEN)(send - s) + 1);
3701 d = SvPVX(sv) + SvCUR(sv);
3703 } else if (len > (STRLEN)(e - s + 4)) { /* I _guess_ 4 is \N{} --jhi */
3705 /* See Note on sizing above. (NOTE: SvCUR() is not
3706 * set correctly here). */
3707 const STRLEN off = d - SvPVX_const(sv);
3708 d = off + SvGROW(sv, off + len + (STRLEN)(send - s) + 1);
3710 Copy(str, d, len, char);
3716 } /* End \N{NAME} */
3720 backslash_N++; /* \N{} is defined to be Unicode */
3722 s = e + 1; /* Point to just after the '}' */
3725 /* \c is a control character */
3729 *d++ = grok_bslash_c(*s++, 1);
3732 yyerror("Missing control char name in \\c");
3735 non_portable_endpoint++;
3739 /* printf-style backslashes, formfeeds, newlines, etc */
3765 } /* end if (backslash) */
3768 /* If we started with encoded form, or already know we want it,
3769 then encode the next character */
3770 if (! NATIVE_BYTE_IS_INVARIANT((U8)(*s)) && (this_utf8 || has_utf8)) {
3773 /* One might think that it is wasted effort in the case of the
3774 * source being utf8 (this_utf8 == TRUE) to take the next character
3775 * in the source, convert it to an unsigned value, and then convert
3776 * it back again. But the source has not been validated here. The
3777 * routine that does the conversion checks for errors like
3780 const UV nextuv = (this_utf8)
3781 ? utf8n_to_uvchr((U8*)s, send - s, &len, 0)
3783 const STRLEN need = UVCHR_SKIP(nextuv);
3785 SvCUR_set(sv, d - SvPVX_const(sv));
3788 /* See Note on sizing above. */
3789 sv_utf8_upgrade_flags_grow(sv,
3790 SV_GMAGIC|SV_FORCE_UTF8_UPGRADE,
3791 need + (STRLEN)(send - s) + 1);
3792 d = SvPVX(sv) + SvCUR(sv);
3794 } else if (need > len) {
3795 /* encoded value larger than old, may need extra space (NOTE:
3796 * SvCUR() is not set correctly here). See Note on sizing
3798 const STRLEN off = d - SvPVX_const(sv);
3799 d = SvGROW(sv, off + need + (STRLEN)(send - s) + 1) + off;
3803 d = (char*)uvchr_to_utf8((U8*)d, nextuv);
3808 } /* while loop to process each character */
3810 /* terminate the string and set up the sv */
3812 SvCUR_set(sv, d - SvPVX_const(sv));
3813 if (SvCUR(sv) >= SvLEN(sv))
3814 Perl_croak(aTHX_ "panic: constant overflowed allocated space, %"UVuf
3815 " >= %"UVuf, (UV)SvCUR(sv), (UV)SvLEN(sv));
3820 if (PL_lex_inwhat == OP_TRANS && PL_parser->lex_sub_op) {
3821 PL_parser->lex_sub_op->op_private |=
3822 (PL_lex_repl ? OPpTRANS_FROM_UTF : OPpTRANS_TO_UTF);
3826 /* shrink the sv if we allocated more than we used */
3827 if (SvCUR(sv) + 5 < SvLEN(sv)) {
3828 SvPV_shrink_to_cur(sv);
3831 /* return the substring (via pl_yylval) only if we parsed anything */
3834 for (; s2 < s; s2++) {
3836 COPLINE_INC_WITH_HERELINES;
3838 SvREFCNT_inc_simple_void_NN(sv);
3839 if ( (PL_hints & ( PL_lex_inpat ? HINT_NEW_RE : HINT_NEW_STRING ))
3840 && ! PL_parser->lex_re_reparsing)
3842 const char *const key = PL_lex_inpat ? "qr" : "q";
3843 const STRLEN keylen = PL_lex_inpat ? 2 : 1;
3847 if (PL_lex_inwhat == OP_TRANS) {
3850 } else if (PL_lex_inwhat == OP_SUBST && !PL_lex_inpat) {
3853 } else if (PL_lex_inpat && SvIVX(PL_linestr) == '\'') {
3861 sv = S_new_constant(aTHX_ start, s - start, key, keylen, sv, NULL,
3864 pl_yylval.opval = (OP*)newSVOP(OP_CONST, 0, sv);
3866 LEAVE_with_name("scan_const");
3871 * Returns TRUE if there's more to the expression (e.g., a subscript),
3874 * It deals with "$foo[3]" and /$foo[3]/ and /$foo[0123456789$]+/
3876 * ->[ and ->{ return TRUE
3877 * ->$* ->$#* ->@* ->@[ ->@{ return TRUE if postderef_qq is enabled
3878 * { and [ outside a pattern are always subscripts, so return TRUE
3879 * if we're outside a pattern and it's not { or [, then return FALSE
3880 * if we're in a pattern and the first char is a {
3881 * {4,5} (any digits around the comma) returns FALSE
3882 * if we're in a pattern and the first char is a [
3884 * [SOMETHING] has a funky algorithm to decide whether it's a
3885 * character class or not. It has to deal with things like
3886 * /$foo[-3]/ and /$foo[$bar]/ as well as /$foo[$\d]+/
3887 * anything else returns TRUE
3890 /* This is the one truly awful dwimmer necessary to conflate C and sed. */
3893 S_intuit_more(pTHX_ char *s)
3895 PERL_ARGS_ASSERT_INTUIT_MORE;
3897 if (PL_lex_brackets)
3899 if (*s == '-' && s[1] == '>' && (s[2] == '[' || s[2] == '{'))
3901 if (*s == '-' && s[1] == '>'
3902 && FEATURE_POSTDEREF_QQ_IS_ENABLED
3903 && ( (s[2] == '$' && (s[3] == '*' || (s[3] == '#' && s[4] == '*')))
3904 ||(s[2] == '@' && strchr("*[{",s[3])) ))
3906 if (*s != '{' && *s != '[')
3911 /* In a pattern, so maybe we have {n,m}. */
3919 /* On the other hand, maybe we have a character class */
3922 if (*s == ']' || *s == '^')
3925 /* this is terrifying, and it works */
3928 const char * const send = strchr(s,']');
3929 unsigned char un_char, last_un_char;
3930 char tmpbuf[sizeof PL_tokenbuf * 4];
3932 if (!send) /* has to be an expression */
3934 weight = 2; /* let's weigh the evidence */
3938 else if (isDIGIT(*s)) {
3940 if (isDIGIT(s[1]) && s[2] == ']')
3946 Zero(seen,256,char);
3948 for (; s < send; s++) {
3949 last_un_char = un_char;
3950 un_char = (unsigned char)*s;
3955 weight -= seen[un_char] * 10;
3956 if (isWORDCHAR_lazy_if(s+1,UTF)) {
3958 char *tmp = PL_bufend;
3959 PL_bufend = (char*)send;
3960 scan_ident(s, tmpbuf, sizeof tmpbuf, FALSE);
3962 len = (int)strlen(tmpbuf);
3963 if (len > 1 && gv_fetchpvn_flags(tmpbuf, len,
3964 UTF ? SVf_UTF8 : 0, SVt_PV))
3971 && strchr("[#!%*<>()-=",s[1]))
3973 if (/*{*/ strchr("])} =",s[2]))
3982 if (strchr("wds]",s[1]))
3984 else if (seen[(U8)'\''] || seen[(U8)'"'])
3986 else if (strchr("rnftbxcav",s[1]))
3988 else if (isDIGIT(s[1])) {
3990 while (s[1] && isDIGIT(s[1]))
4000 if (strchr("aA01! ",last_un_char))
4002 if (strchr("zZ79~",s[1]))
4004 if (last_un_char == 255 && (isDIGIT(s[1]) || s[1] == '$'))
4005 weight -= 5; /* cope with negative subscript */
4008 if (!isWORDCHAR(last_un_char)
4009 && !(last_un_char == '$' || last_un_char == '@'
4010 || last_un_char == '&')
4011 && isALPHA(*s) && s[1] && isALPHA(s[1])) {
4015 if (keyword(d, s - d, 0))
4018 if (un_char == last_un_char + 1)
4020 weight -= seen[un_char];
4025 if (weight >= 0) /* probably a character class */
4035 * Does all the checking to disambiguate
4037 * between foo(bar) and bar->foo. Returns 0 if not a method, otherwise
4038 * FUNCMETH (bar->foo(args)) or METHOD (bar->foo args).
4040 * First argument is the stuff after the first token, e.g. "bar".
4042 * Not a method if foo is a filehandle.
4043 * Not a method if foo is a subroutine prototyped to take a filehandle.
4044 * Not a method if it's really "Foo $bar"
4045 * Method if it's "foo $bar"
4046 * Not a method if it's really "print foo $bar"
4047 * Method if it's really "foo package::" (interpreted as package->foo)
4048 * Not a method if bar is known to be a subroutine ("sub bar; foo bar")
4049 * Not a method if bar is a filehandle or package, but is quoted with
4054 S_intuit_method(pTHX_ char *start, SV *ioname, CV *cv)
4056 char *s = start + (*start == '$');
4057 char tmpbuf[sizeof PL_tokenbuf];
4060 /* Mustn't actually add anything to a symbol table.
4061 But also don't want to "initialise" any placeholder
4062 constants that might already be there into full
4063 blown PVGVs with attached PVCV. */
4065 ioname ? gv_fetchsv(ioname, GV_NOADD_NOINIT, SVt_PVCV) : NULL;
4067 PERL_ARGS_ASSERT_INTUIT_METHOD;
4069 if (gv && SvTYPE(gv) == SVt_PVGV && GvIO(gv))
4071 if (cv && SvPOK(cv)) {
4072 const char *proto = CvPROTO(cv);
4074 while (*proto && (isSPACE(*proto) || *proto == ';'))
4081 if (*start == '$') {
4082 if (cv || PL_last_lop_op == OP_PRINT || PL_last_lop_op == OP_SAY
4083 || isUPPER(*PL_tokenbuf))
4088 return *s == '(' ? FUNCMETH : METHOD;
4091 s = scan_word(s, tmpbuf, sizeof tmpbuf, TRUE, &len);
4092 /* start is the beginning of the possible filehandle/object,
4093 * and s is the end of it
4094 * tmpbuf is a copy of it (but with single quotes as double colons)
4097 if (!keyword(tmpbuf, len, 0)) {
4098 if (len > 2 && tmpbuf[len - 2] == ':' && tmpbuf[len - 1] == ':') {
4103 indirgv = gv_fetchpvn_flags(tmpbuf, len,
4104 GV_NOADD_NOINIT|( UTF ? SVf_UTF8 : 0 ),
4106 if (indirgv && SvTYPE(indirgv) != SVt_NULL
4107 && (!isGV(indirgv) || GvCVu(indirgv)))
4109 /* filehandle or package name makes it a method */
4110 if (!cv || GvIO(indirgv) || gv_stashpvn(tmpbuf, len, UTF ? SVf_UTF8 : 0)) {
4112 if ((PL_bufend - s) >= 2 && *s == '=' && *(s+1) == '>')
4113 return 0; /* no assumptions -- "=>" quotes bareword */
4115 NEXTVAL_NEXTTOKE.opval = (OP*)newSVOP(OP_CONST, 0,
4116 S_newSV_maybe_utf8(aTHX_ tmpbuf, len));
4117 NEXTVAL_NEXTTOKE.opval->op_private = OPpCONST_BARE;
4119 force_next(BAREWORD);
4121 return *s == '(' ? FUNCMETH : METHOD;
4127 /* Encoded script support. filter_add() effectively inserts a
4128 * 'pre-processing' function into the current source input stream.
4129 * Note that the filter function only applies to the current source file
4130 * (e.g., it will not affect files 'require'd or 'use'd by this one).
4132 * The datasv parameter (which may be NULL) can be used to pass
4133 * private data to this instance of the filter. The filter function
4134 * can recover the SV using the FILTER_DATA macro and use it to
4135 * store private buffers and state information.
4137 * The supplied datasv parameter is upgraded to a PVIO type
4138 * and the IoDIRP/IoANY field is used to store the function pointer,
4139 * and IOf_FAKE_DIRP is enabled on datasv to mark this as such.
4140 * Note that IoTOP_NAME, IoFMT_NAME, IoBOTTOM_NAME, if set for
4141 * private use must be set using malloc'd pointers.
4145 Perl_filter_add(pTHX_ filter_t funcp, SV *datasv)
4153 if (PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS)
4154 Perl_croak(aTHX_ "Source filters apply only to byte streams");
4156 if (!PL_rsfp_filters)
4157 PL_rsfp_filters = newAV();
4160 SvUPGRADE(datasv, SVt_PVIO);
4161 IoANY(datasv) = FPTR2DPTR(void *, funcp); /* stash funcp into spare field */
4162 IoFLAGS(datasv) |= IOf_FAKE_DIRP;
4163 DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_add func %p (%s)\n",
4164 FPTR2DPTR(void *, IoANY(datasv)),
4165 SvPV_nolen(datasv)));
4166 av_unshift(PL_rsfp_filters, 1);
4167 av_store(PL_rsfp_filters, 0, datasv) ;
4169 !PL_parser->filtered
4170 && PL_parser->lex_flags & LEX_EVALBYTES
4171 && PL_bufptr < PL_bufend
4173 const char *s = PL_bufptr;
4174 while (s < PL_bufend) {
4176 SV *linestr = PL_parser->linestr;
4177 char *buf = SvPVX(linestr);
4178 STRLEN const bufptr_pos = PL_parser->bufptr - buf;
4179 STRLEN const oldbufptr_pos = PL_parser->oldbufptr - buf;
4180 STRLEN const oldoldbufptr_pos=PL_parser->oldoldbufptr-buf;
4181 STRLEN const linestart_pos = PL_parser->linestart - buf;
4182 STRLEN const last_uni_pos =
4183 PL_parser->last_uni ? PL_parser->last_uni - buf : 0;
4184 STRLEN const last_lop_pos =
4185 PL_parser->last_lop ? PL_parser->last_lop - buf : 0;
4186 av_push(PL_rsfp_filters, linestr);
4187 PL_parser->linestr =
4188 newSVpvn(SvPVX(linestr), ++s-SvPVX(linestr));
4189 buf = SvPVX(PL_parser->linestr);
4190 PL_parser->bufend = buf + SvCUR(PL_parser->linestr);
4191 PL_parser->bufptr = buf + bufptr_pos;
4192 PL_parser->oldbufptr = buf + oldbufptr_pos;
4193 PL_parser->oldoldbufptr = buf + oldoldbufptr_pos;
4194 PL_parser->linestart = buf + linestart_pos;
4195 if (PL_parser->last_uni)
4196 PL_parser->last_uni = buf + last_uni_pos;
4197 if (PL_parser->last_lop)
4198 PL_parser->last_lop = buf + last_lop_pos;
4199 SvLEN(linestr) = SvCUR(linestr);
4200 SvCUR(linestr) = s-SvPVX(linestr);
4201 PL_parser->filtered = 1;
4211 /* Delete most recently added instance of this filter function. */
4213 Perl_filter_del(pTHX_ filter_t funcp)
4217 PERL_ARGS_ASSERT_FILTER_DEL;
4220 DEBUG_P(PerlIO_printf(Perl_debug_log, "filter_del func %p",
4221 FPTR2DPTR(void*, funcp)));
4223 if (!PL_parser || !PL_rsfp_filters || AvFILLp(PL_rsfp_filters)<0)
4225 /* if filter is on top of stack (usual case) just pop it off */
4226 datasv = FILTER_DATA(AvFILLp(PL_rsfp_filters));
4227 if (IoANY(datasv) == FPTR2DPTR(void *, funcp)) {
4228 sv_free(av_pop(PL_rsfp_filters));
4232 /* we need to search for the correct entry and clear it */
4233 Perl_die(aTHX_ "filter_del can only delete in reverse order (currently)");
4237 /* Invoke the idxth filter function for the current rsfp. */
4238 /* maxlen 0 = read one text line */
4240 Perl_filter_read(pTHX_ int idx, SV *buf_sv, int maxlen)
4244 /* This API is bad. It should have been using unsigned int for maxlen.
4245 Not sure if we want to change the API, but if not we should sanity
4246 check the value here. */
4247 unsigned int correct_length = maxlen < 0 ? PERL_INT_MAX : maxlen;
4249 PERL_ARGS_ASSERT_FILTER_READ;
4251 if (!PL_parser || !PL_rsfp_filters)
4253 if (idx > AvFILLp(PL_rsfp_filters)) { /* Any more filters? */
4254 /* Provide a default input filter to make life easy. */
4255 /* Note that we append to the line. This is handy. */
4256 DEBUG_P(PerlIO_printf(Perl_debug_log,
4257 "filter_read %d: from rsfp\n", idx));
4258 if (correct_length) {
4261 const int old_len = SvCUR(buf_sv);
4263 /* ensure buf_sv is large enough */
4264 SvGROW(buf_sv, (STRLEN)(old_len + correct_length + 1)) ;
4265 if ((len = PerlIO_read(PL_rsfp, SvPVX(buf_sv) + old_len,
4266 correct_length)) <= 0) {
4267 if (PerlIO_error(PL_rsfp))
4268 return -1; /* error */
4270 return 0 ; /* end of file */
4272 SvCUR_set(buf_sv, old_len + len) ;
4273 SvPVX(buf_sv)[old_len + len] = '\0';
4276 if (sv_gets(buf_sv, PL_rsfp, SvCUR(buf_sv)) == NULL) {
4277 if (PerlIO_error(PL_rsfp))
4278 return -1; /* error */
4280 return 0 ; /* end of file */
4283 return SvCUR(buf_sv);
4285 /* Skip this filter slot if filter has been deleted */
4286 if ( (datasv = FILTER_DATA(idx)) == &PL_sv_undef) {
4287 DEBUG_P(PerlIO_printf(Perl_debug_log,
4288 "filter_read %d: skipped (filter deleted)\n",
4290 return FILTER_READ(idx+1, buf_sv, correct_length); /* recurse */
4292 if (SvTYPE(datasv) != SVt_PVIO) {
4293 if (correct_length) {
4295 const STRLEN remainder = SvLEN(datasv) - SvCUR(datasv);
4296 if (!remainder) return 0; /* eof */
4297 if (correct_length > remainder) correct_length = remainder;
4298 sv_catpvn(buf_sv, SvEND(datasv), correct_length);
4299 SvCUR_set(datasv, SvCUR(datasv) + correct_length);
4302 const char *s = SvEND(datasv);
4303 const char *send = SvPVX(datasv) + SvLEN(datasv);
4311 if (s == send) return 0; /* eof */
4312 sv_catpvn(buf_sv, SvEND(datasv), s-SvEND(datasv));