be C89 again (also avoid other compiler warnings)
[p5sagit/Function-Parameters.git] / Parameters.xs
1 /*
2 Copyright 2012 Lukas Mai.
3
4 This program is free software; you can redistribute it and/or modify it
5 under the terms of either: the GNU General Public License as published
6 by the Free Software Foundation; or the Artistic License.
7
8 See http://dev.perl.org/licenses/ for more information.
9  */
10
11 #ifdef __GNUC__
12  #if (__GNUC__ == 4 && __GNUC_MINOR__ >= 6) || __GNUC__ >= 5
13   #define PRAGMA_GCC_(X) _Pragma(#X)
14   #define PRAGMA_GCC(X) PRAGMA_GCC_(GCC X)
15  #endif
16 #endif
17
18 #ifndef PRAGMA_GCC
19  #define PRAGMA_GCC(X)
20 #endif
21
22 #ifdef DEVEL
23  #define WARNINGS_RESET PRAGMA_GCC(diagnostic pop)
24  #define WARNINGS_ENABLEW(X) PRAGMA_GCC(diagnostic warning #X)
25  #define WARNINGS_ENABLE \
26         WARNINGS_ENABLEW(-Wall) \
27         WARNINGS_ENABLEW(-Wextra) \
28         WARNINGS_ENABLEW(-Wundef) \
29         /* WARNINGS_ENABLEW(-Wshadow) :-( */ \
30         WARNINGS_ENABLEW(-Wbad-function-cast) \
31         WARNINGS_ENABLEW(-Wcast-align) \
32         WARNINGS_ENABLEW(-Wwrite-strings) \
33         /* WARNINGS_ENABLEW(-Wnested-externs) wtf? */ \
34         WARNINGS_ENABLEW(-Wstrict-prototypes) \
35         WARNINGS_ENABLEW(-Wmissing-prototypes) \
36         WARNINGS_ENABLEW(-Winline) \
37         WARNINGS_ENABLEW(-Wdisabled-optimization)
38
39 #else
40  #define WARNINGS_RESET
41  #define WARNINGS_ENABLE
42 #endif
43
44
45 #define PERL_NO_GET_CONTEXT
46 #include "EXTERN.h"
47 #include "perl.h"
48 #include "XSUB.h"
49
50 #include <string.h>
51
52
53 WARNINGS_ENABLE
54
55
56 #define HAVE_PERL_VERSION(R, V, S) \
57         (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S))))))
58
59 #if HAVE_PERL_VERSION(5, 16, 0)
60  #define IF_HAVE_PERL_5_16(YES, NO) YES
61 #else
62  #define IF_HAVE_PERL_5_16(YES, NO) NO
63 #endif
64
65 #if 0
66  #if HAVE_PERL_VERSION(5, 17, 6)
67   #error "internal error: missing definition of KEY_my (your perl is too new)"
68  #elif HAVE_PERL_VERSION(5, 15, 8)
69   #define S_KEY_my 134
70  #elif HAVE_PERL_VERSION(5, 15, 6)
71   #define S_KEY_my 133
72  #elif HAVE_PERL_VERSION(5, 15, 5)
73   #define S_KEY_my 132
74  #elif HAVE_PERL_VERSION(5, 13, 0)
75   #define S_KEY_my 131
76  #else
77   #error "internal error: missing definition of KEY_my (your perl is too old)"
78  #endif
79 #endif
80
81
82 #define MY_PKG "Function::Parameters"
83
84 #define HINTK_KEYWORDS MY_PKG "/keywords"
85 #define HINTK_FLAGS_   MY_PKG "/flags:"
86 #define HINTK_SHIFT_   MY_PKG "/shift:"
87 #define HINTK_ATTRS_   MY_PKG "/attrs:"
88
89 #define DEFSTRUCT(T) typedef struct T T; struct T
90
91 #define UV_BITS (sizeof (UV) * CHAR_BIT)
92
93 enum {
94         FLAG_NAME_OK      = 0x01,
95         FLAG_ANON_OK      = 0x02,
96         FLAG_DEFAULT_ARGS = 0x04,
97         FLAG_CHECK_NARGS  = 0x08,
98         FLAG_INVOCANT     = 0x10,
99         FLAG_NAMED_PARAMS = 0x20
100 };
101
102 DEFSTRUCT(KWSpec) {
103         unsigned flags;
104         SV *shift;
105         SV *attrs;
106 };
107
108 static int (*next_keyword_plugin)(pTHX_ char *, STRLEN, OP **);
109
110 DEFSTRUCT(Resource) {
111         Resource *next;
112         void *data;
113         void (*destroy)(pTHX_ void *);
114 };
115
116 typedef Resource *Sentinel[1];
117
118 static void sentinel_clear_void(pTHX_ void *p) {
119         Resource **pp = p;
120         while (*pp) {
121                 Resource *cur = *pp;
122                 cur->destroy(aTHX_ cur->data);
123                 cur->data = (void *)"no";
124                 cur->destroy = NULL;
125                 *pp = cur->next;
126                 Safefree(cur);
127         }
128 }
129
130 static void sentinel_register(Sentinel sen, void *data, void (*destroy)(pTHX_ void *)) {
131         Resource *cur;
132
133         Newx(cur, 1, Resource);
134         cur->data = data;
135         cur->destroy = destroy;
136         cur->next = *sen;
137         *sen = cur;
138 }
139
140 static void my_sv_refcnt_dec_void(pTHX_ void *p) {
141         SV *sv = p;
142         SvREFCNT_dec(sv);
143 }
144
145 static SV *sentinel_mortalize(Sentinel sen, SV *sv) {
146         sentinel_register(sen, sv, my_sv_refcnt_dec_void);
147         return sv;
148 }
149
150 static void my_safefree(void *p) {
151         Safefree(p);
152 }
153
154 #define SENTINEL_ALLOC(SEN, P, N, T) STMT_START { \
155         Newx(P, N, T); \
156         sentinel_register(SEN, P, my_safefree); \
157 } STMT_END
158
159 #define SENTINEL_MDUP(SEN, P, O, N, T) STMT_START { \
160         void *const _sentinel_mdup_tmp_ = (P); \
161         SENTINEL_ALLOC(SEN, P, N, T); \
162         memcpy(P, _sentinel_mdup_tmp_, O * sizeof (T)); \
163 } STMT_END
164
165 #define SENTINEL_REALLOC(SEN, P, N, T) STMT_START { \
166         assert((N) > 0); \
167         if (!(P)) { \
168                 SENTINEL_ALLOC(SEN, P, N, T); \
169         } else { \
170                 Resource **_sentinel_realloc_tmp_ = (SEN); \
171                 for (;;) { \
172                         assert(*_sentinel_realloc_tmp_ != NULL); \
173                         if ((*_sentinel_realloc_tmp_)->data == (P)) { \
174                                 Renew((*_sentinel_realloc_tmp_)->data, N, T); \
175                                 (P) = (*_sentinel_realloc_tmp_)->data; \
176                                 break; \
177                         } \
178                         _sentinel_realloc_tmp_ = &(*_sentinel_realloc_tmp_)->next; \
179                 } \
180         } \
181 } STMT_END
182
183 static int kw_flags(pTHX_ Sentinel sen, const char *kw_ptr, STRLEN kw_len, KWSpec *spec) {
184         HV *hints;
185         SV *sv, **psv;
186         const char *p, *kw_active;
187         STRLEN kw_active_len;
188
189         spec->flags = 0;
190         spec->shift = sentinel_mortalize(sen, newSVpvs(""));
191         spec->attrs = sentinel_mortalize(sen, newSVpvs(""));
192
193         if (!(hints = GvHV(PL_hintgv))) {
194                 return FALSE;
195         }
196         if (!(psv = hv_fetchs(hints, HINTK_KEYWORDS, 0))) {
197                 return FALSE;
198         }
199         sv = *psv;
200         kw_active = SvPV(sv, kw_active_len);
201         if (kw_active_len <= kw_len) {
202                 return FALSE;
203         }
204         for (
205                 p = kw_active;
206                 (p = strchr(p, *kw_ptr)) &&
207                 p < kw_active + kw_active_len - kw_len;
208                 p++
209         ) {
210                 if (
211                         (p == kw_active || p[-1] == ' ') &&
212                         p[kw_len] == ' ' &&
213                         memcmp(kw_ptr, p, kw_len) == 0
214                 ) {
215
216 #define FETCH_HINTK_INTO(NAME, PTR, LEN, X) STMT_START { \
217         const char *fk_ptr_; \
218         STRLEN fk_len_; \
219         SV *fk_sv_; \
220         fk_sv_ = sentinel_mortalize(sen, newSVpvs(HINTK_ ## NAME)); \
221         sv_catpvn(fk_sv_, PTR, LEN); \
222         fk_ptr_ = SvPV(fk_sv_, fk_len_); \
223         if (!((X) = hv_fetch(hints, fk_ptr_, fk_len_, 0))) { \
224                 croak("%s: internal error: $^H{'%.*s'} not set", MY_PKG, (int)fk_len_, fk_ptr_); \
225         } \
226 } STMT_END
227
228                         FETCH_HINTK_INTO(FLAGS_, kw_ptr, kw_len, psv);
229                         spec->flags = SvIV(*psv);
230
231                         FETCH_HINTK_INTO(SHIFT_, kw_ptr, kw_len, psv);
232                         SvSetSV(spec->shift, *psv);
233
234                         FETCH_HINTK_INTO(ATTRS_, kw_ptr, kw_len, psv);
235                         SvSetSV(spec->attrs, *psv);
236
237 #undef FETCH_HINTK_INTO
238                         return TRUE;
239                 }
240         }
241         return FALSE;
242 }
243
244
245 static void free_ptr_op(pTHX_ void *vp) {
246         OP **pp = vp;
247         op_free(*pp);
248         Safefree(pp);
249 }
250
251 #define sv_eq_pvs(SV, S) my_sv_eq_pvn(aTHX_ SV, "" S "", sizeof (S) - 1)
252
253 static int my_sv_eq_pvn(pTHX_ SV *sv, const char *p, STRLEN n) {
254         STRLEN sv_len;
255         const char *sv_p = SvPV(sv, sv_len);
256         return memcmp(sv_p, p, n) == 0;
257 }
258
259
260 #include "padop_on_crack.c.inc"
261
262
263 enum {
264         MY_ATTR_LVALUE = 0x01,
265         MY_ATTR_METHOD = 0x02,
266         MY_ATTR_SPECIAL = 0x04
267 };
268
269 static void my_sv_cat_c(pTHX_ SV *sv, U32 c) {
270         char ds[UTF8_MAXBYTES + 1], *d;
271         d = (char *)uvchr_to_utf8((U8 *)ds, c);
272         if (d - ds > 1) {
273                 sv_utf8_upgrade(sv);
274         }
275         sv_catpvn(sv, ds, d - ds);
276 }
277
278 static bool my_is_uni_xidfirst(pTHX_ UV c) {
279         U8 tmpbuf[UTF8_MAXBYTES + 1];
280         uvchr_to_utf8(tmpbuf, c);
281         return is_utf8_xidfirst(tmpbuf);
282 }
283
284 static bool my_is_uni_xidcont(pTHX_ UV c) {
285         U8 tmpbuf[UTF8_MAXBYTES + 1];
286         uvchr_to_utf8(tmpbuf, c);
287         return is_utf8_xidcont(tmpbuf);
288 }
289
290 static SV *my_scan_word(pTHX_ Sentinel sen, bool allow_package) {
291         bool at_start, at_substart;
292         I32 c;
293         SV *sv = sentinel_mortalize(sen, newSVpvs(""));
294         if (lex_bufutf8()) {
295                 SvUTF8_on(sv);
296         }
297
298         at_start = at_substart = TRUE;
299         c = lex_peek_unichar(0);
300
301         while (c != -1) {
302                 if (at_substart ? my_is_uni_xidfirst(aTHX_ c) : my_is_uni_xidcont(aTHX_ c)) {
303                         lex_read_unichar(0);
304                         my_sv_cat_c(aTHX_ sv, c);
305                         at_substart = FALSE;
306                         c = lex_peek_unichar(0);
307                 } else if (allow_package && !at_substart && c == '\'') {
308                         lex_read_unichar(0);
309                         c = lex_peek_unichar(0);
310                         if (!my_is_uni_xidfirst(aTHX_ c)) {
311                                 lex_stuff_pvs("'", 0);
312                                 break;
313                         }
314                         sv_catpvs(sv, "'");
315                         at_substart = TRUE;
316                 } else if (allow_package && (at_start || !at_substart) && c == ':') {
317                         lex_read_unichar(0);
318                         if (lex_peek_unichar(0) != ':') {
319                                 lex_stuff_pvs(":", 0);
320                                 break;
321                         }
322                         lex_read_unichar(0);
323                         c = lex_peek_unichar(0);
324                         if (!my_is_uni_xidfirst(aTHX_ c)) {
325                                 lex_stuff_pvs("::", 0);
326                                 break;
327                         }
328                         sv_catpvs(sv, "::");
329                         at_substart = TRUE;
330                 } else {
331                         break;
332                 }
333                 at_start = FALSE;
334         }
335
336         return SvCUR(sv) ? sv : NULL;
337 }
338
339 static SV *my_scan_parens_tail(pTHX_ Sentinel sen, bool keep_backslash) {
340         I32 c, nesting;
341         SV *sv;
342         line_t start;
343
344         start = CopLINE(PL_curcop);
345
346         sv = sentinel_mortalize(sen, newSVpvs(""));
347         if (lex_bufutf8()) {
348                 SvUTF8_on(sv);
349         }
350
351         nesting = 0;
352         for (;;) {
353                 c = lex_read_unichar(0);
354                 if (c == EOF) {
355                         CopLINE_set(PL_curcop, start);
356                         return NULL;
357                 }
358
359                 if (c == '\\') {
360                         c = lex_read_unichar(0);
361                         if (c == EOF) {
362                                 CopLINE_set(PL_curcop, start);
363                                 return NULL;
364                         }
365                         if (keep_backslash || (c != '(' && c != ')')) {
366                                 sv_catpvs(sv, "\\");
367                         }
368                 } else if (c == '(') {
369                         nesting++;
370                 } else if (c == ')') {
371                         if (!nesting) {
372                                 break;
373                         }
374                         nesting--;
375                 }
376
377                 my_sv_cat_c(aTHX_ sv, c);
378         }
379
380         return sv;
381 }
382
383 static void my_check_prototype(pTHX_ Sentinel sen, const SV *declarator, SV *proto) {
384         char *start, *r, *w, *end;
385         STRLEN len;
386
387         /* strip spaces */
388         start = SvPV(proto, len);
389         end = start + len;
390
391         for (w = r = start; r < end; r++) {
392                 if (!isSPACE(*r)) {
393                         *w++ = *r;
394                 }
395         }
396         *w = '\0';
397         SvCUR_set(proto, w - start);
398         end = w;
399         len = end - start;
400
401         if (!ckWARN(WARN_ILLEGALPROTO)) {
402                 return;
403         }
404
405         /* check for bad characters */
406         if (strspn(start, "$@%*;[]&\\_+") != len) {
407                 SV *dsv = sentinel_mortalize(sen, newSVpvs(""));
408                 warner(
409                         packWARN(WARN_ILLEGALPROTO),
410                         "Illegal character in prototype for %"SVf" : %s",
411                         SVfARG(declarator),
412                         SvUTF8(proto)
413                                 ? sv_uni_display(
414                                         dsv,
415                                         proto,
416                                         len,
417                                         UNI_DISPLAY_ISPRINT
418                                 )
419                                 : pv_pretty(dsv, start, len, 60, NULL, NULL,
420                                         PERL_PV_ESCAPE_NONASCII
421                                 )
422                 );
423                 return;
424         }
425
426         for (r = start; r < end; r++) {
427                 switch (*r) {
428                         default:
429                                 warner(
430                                         packWARN(WARN_ILLEGALPROTO),
431                                         "Illegal character in prototype for %"SVf" : %s",
432                                         SVfARG(declarator), r
433                                 );
434                                 return;
435
436                         case '_':
437                                 if (r[1] && !strchr(";@%", *r)) {
438                                         warner(
439                                                 packWARN(WARN_ILLEGALPROTO),
440                                                 "Illegal character after '_' in prototype for %"SVf" : %s",
441                                                 SVfARG(declarator), r
442                                         );
443                                         return;
444                                 }
445                                 break;
446
447                         case '@':
448                         case '%':
449                                 if (r[1]) {
450                                         warner(
451                                                 packWARN(WARN_ILLEGALPROTO),
452                                                 "prototype after '%c' for %"SVf": %s",
453                                                 *r, SVfARG(declarator), r + 1
454                                         );
455                                         return;
456                                 }
457                                 break;
458
459                         case '\\':
460                                 r++;
461                                 if (strchr("$@%&*", *r)) {
462                                         break;
463                                 }
464                                 if (*r == '[') {
465                                         r++;
466                                         for (; r < end && *r != ']'; r++) {
467                                                 if (!strchr("$@%&*", *r)) {
468                                                         break;
469                                                 }
470                                         }
471                                         if (*r == ']' && r[-1] != '[') {
472                                                 break;
473                                         }
474                                 }
475                                 warner(
476                                         packWARN(WARN_ILLEGALPROTO),
477                                         "Illegal character after '\\' in prototype for %"SVf" : %s",
478                                         SVfARG(declarator), r
479                                 );
480                                 return;
481
482                         case '$':
483                         case '*':
484                         case '&':
485                         case ';':
486                         case '+':
487                                 break;
488                 }
489         }
490 }
491
492
493 DEFSTRUCT(Param) {
494         SV *name;
495         PADOFFSET padoff;
496 };
497
498 DEFSTRUCT(ParamInit) {
499         Param param;
500         OP *init;
501 };
502
503 #define VEC(B) B ## _Vec
504
505 #define DEFVECTOR(B) DEFSTRUCT(VEC(B)) { \
506         B (*data); \
507         size_t used, size; \
508 }
509
510 DEFVECTOR(Param);
511 DEFVECTOR(ParamInit);
512
513 #define DEFVECTOR_INIT(N, B) static void N(VEC(B) *p) { \
514         p->used = 0; \
515         p->size = 23; \
516         Newx(p->data, p->size, B); \
517 } static void N(VEC(B) *)
518
519 DEFSTRUCT(ParamSpec) {
520         Param invocant;
521         VEC(Param) positional_required;
522         VEC(ParamInit) positional_optional;
523         VEC(Param) named_required;
524         VEC(ParamInit) named_optional;
525         Param slurpy;
526         PADOFFSET rest_hash;
527 };
528
529 DEFVECTOR_INIT(pv_init, Param);
530 DEFVECTOR_INIT(piv_init, ParamInit);
531
532 static void p_init(Param *p) {
533         p->name = NULL;
534         p->padoff = NOT_IN_PAD;
535 }
536
537 static void ps_init(ParamSpec *ps) {
538         p_init(&ps->invocant);
539         pv_init(&ps->positional_required);
540         piv_init(&ps->positional_optional);
541         pv_init(&ps->named_required);
542         piv_init(&ps->named_optional);
543         p_init(&ps->slurpy);
544         ps->rest_hash = NOT_IN_PAD;
545 }
546
547 #define DEFVECTOR_EXTEND(N, B) static B (*N(VEC(B) *p)) { \
548         assert(p->used <= p->size); \
549         if (p->used == p->size) { \
550                 const size_t n = p->size / 2 * 3 + 1; \
551                 Renew(p->data, n, B); \
552                 p->size = n; \
553         } \
554         return &p->data[p->used]; \
555 } static B (*N(VEC(B) *))
556
557 DEFVECTOR_EXTEND(pv_extend, Param);
558 DEFVECTOR_EXTEND(piv_extend, ParamInit);
559
560 #define DEFVECTOR_CLEAR(N, B, F) static void N(pTHX_ VEC(B) *p) { \
561         while (p->used) { \
562                 p->used--; \
563                 F(aTHX_ &p->data[p->used]); \
564         } \
565         Safefree(p->data); \
566         p->data = NULL; \
567         p->size = 0; \
568 } static void N(pTHX_ VEC(B) *)
569
570 static void p_clear(pTHX_ Param *p) {
571         p->name = NULL;
572         p->padoff = NOT_IN_PAD;
573 }
574
575 static void pi_clear(pTHX_ ParamInit *pi) {
576         p_clear(aTHX_ &pi->param);
577         if (pi->init) {
578                 op_free(pi->init);
579                 pi->init = NULL;
580         }
581 }
582
583 DEFVECTOR_CLEAR(pv_clear, Param, p_clear);
584 DEFVECTOR_CLEAR(piv_clear, ParamInit, pi_clear);
585
586 static void ps_clear(pTHX_ ParamSpec *ps) {
587         p_clear(aTHX_ &ps->invocant);
588
589         pv_clear(aTHX_ &ps->positional_required);
590         piv_clear(aTHX_ &ps->positional_optional);
591
592         pv_clear(aTHX_ &ps->named_required);
593         piv_clear(aTHX_ &ps->named_optional);
594
595         p_clear(aTHX_ &ps->slurpy);
596 }
597
598 static int ps_contains(pTHX_ const ParamSpec *ps, SV *sv) {
599         size_t i, lim;
600
601         if (ps->invocant.name && sv_eq(sv, ps->invocant.name)) {
602                 return 1;
603         }
604
605         for (i = 0, lim = ps->positional_required.used; i < lim; i++) {
606                 if (sv_eq(sv, ps->positional_required.data[i].name)) {
607                         return 1;
608                 }
609         }
610
611         for (i = 0, lim = ps->positional_optional.used; i < lim; i++) {
612                 if (sv_eq(sv, ps->positional_optional.data[i].param.name)) {
613                         return 1;
614                 }
615         }
616
617         for (i = 0, lim = ps->named_required.used; i < lim; i++) {
618                 if (sv_eq(sv, ps->named_required.data[i].name)) {
619                         return 1;
620                 }
621         }
622
623         for (i = 0, lim = ps->named_optional.used; i < lim; i++) {
624                 if (sv_eq(sv, ps->named_optional.data[i].param.name)) {
625                         return 1;
626                 }
627         }
628
629         return 0;
630 }
631
632 static void ps_free_void(pTHX_ void *p) {
633         ps_clear(aTHX_ p);
634         Safefree(p);
635 }
636
637 static int args_min(pTHX_ const ParamSpec *ps, const KWSpec *ks) {
638         int n = 0;
639         if (!ps) {
640                 return SvTRUE(ks->shift) ? 1 : 0;
641         }
642         if (ps->invocant.name) {
643                 n++;
644         }
645         n += ps->positional_required.used;
646         n += ps->named_required.used * 2;
647         return n;
648 }
649
650 static int args_max(const ParamSpec *ps) {
651         int n = 0;
652         if (!ps) {
653                 return -1;
654         }
655         if (ps->invocant.name) {
656                 n++;
657         }
658         n += ps->positional_required.used;
659         n += ps->positional_optional.used;
660         if (ps->named_required.used || ps->named_optional.used || ps->slurpy.name) {
661                 n = -1;
662         }
663         return n;
664 }
665
666 static size_t count_positional_params(const ParamSpec *ps) {
667         return ps->positional_required.used + ps->positional_optional.used;
668 }
669
670 static size_t count_named_params(const ParamSpec *ps) {
671         return ps->named_required.used + ps->named_optional.used;
672 }
673
674 enum {
675         PARAM_INVOCANT = 0x01,
676         PARAM_NAMED    = 0x02
677 };
678
679 /* *pinit must be NULL on entry.
680  * caller must free *pinit on error.
681  */
682 static PADOFFSET parse_param(
683         pTHX_
684         Sentinel sen,
685         const SV *declarator, const KWSpec *spec, ParamSpec *param_spec,
686         int *pflags, SV **pname, OP **pinit
687 ) {
688         I32 c;
689         char sigil;
690         SV *name;
691
692         assert(!*pinit);
693         *pflags = 0;
694
695         c = lex_peek_unichar(0);
696
697         if (c == ':') {
698                 lex_read_unichar(0);
699                 lex_read_space(0);
700
701                 *pflags |= PARAM_NAMED;
702
703                 c = lex_peek_unichar(0);
704         }
705
706         if (c == -1) {
707                 croak("In %"SVf": unterminated parameter list", SVfARG(declarator));
708         }
709         if (!(c == '$' || c == '@' || c == '%')) {
710                 croak("In %"SVf": unexpected '%c' in parameter list (expecting a sigil)", SVfARG(declarator), (int)c);
711         }
712
713         sigil = c;
714
715         lex_read_unichar(0);
716         lex_read_space(0);
717
718         if (!(name = my_scan_word(aTHX_ sen, FALSE))) {
719                 croak("In %"SVf": missing identifier after '%c'", SVfARG(declarator), sigil);
720         }
721         sv_insert(name, 0, 0, &sigil, 1);
722         *pname = name;
723
724         lex_read_space(0);
725         c = lex_peek_unichar(0);
726
727         if (c == '=') {
728                 lex_read_unichar(0);
729                 lex_read_space(0);
730
731
732                 if (!param_spec->invocant.name && SvTRUE(spec->shift)) {
733                         param_spec->invocant.name = spec->shift;
734                         param_spec->invocant.padoff = pad_add_name_sv(param_spec->invocant.name, 0, NULL, NULL);
735                 }
736
737                 *pinit = parse_termexpr(0);
738
739                 lex_read_space(0);
740                 c = lex_peek_unichar(0);
741         }
742
743         if (c == ':') {
744                 *pflags |= PARAM_INVOCANT;
745                 lex_read_unichar(0);
746                 lex_read_space(0);
747         } else if (c == ',') {
748                 lex_read_unichar(0);
749                 lex_read_space(0);
750         } else if (c != ')') {
751                 if (c == -1) {
752                         croak("In %"SVf": unterminated parameter list", SVfARG(declarator));
753                 }
754                 croak("In %"SVf": unexpected '%c' in parameter list (expecting ',')", SVfARG(declarator), (int)c);
755         }
756
757         return pad_add_name_sv(*pname, IF_HAVE_PERL_5_16(padadd_NO_DUP_CHECK, 0), NULL, NULL);
758 }
759
760 static OP *my_var_g(pTHX_ I32 type, I32 flags, PADOFFSET padoff) {
761         OP *var = newOP(type, flags);
762         var->op_targ = padoff;
763         return var;
764 }
765
766 static OP *my_var(pTHX_ I32 flags, PADOFFSET padoff) {
767         return my_var_g(aTHX_ OP_PADSV, flags, padoff);
768 }
769
770 static OP *mkhvelem(pTHX_ PADOFFSET h, OP *k) {
771         OP *hv = my_var_g(aTHX_ OP_PADHV, OPf_REF, h);
772         return newBINOP(OP_HELEM, 0, hv, k);
773 }
774
775 static OP *mkconstsv(pTHX_ SV *sv) {
776         return newSVOP(OP_CONST, 0, sv);
777 }
778
779 static OP *mkconstiv(pTHX_ IV i) {
780         return mkconstsv(aTHX_ newSViv(i));
781 }
782
783 static OP *mkconstpv(pTHX_ const char *p, size_t n) {
784         return mkconstsv(aTHX_ newSVpv(p, n));
785 }
786
787 #define mkconstpvs(S) mkconstpv(aTHX_ "" S "", sizeof S - 1)
788
789 static int parse_fun(pTHX_ Sentinel sen, OP **pop, const char *keyword_ptr, STRLEN keyword_len, const KWSpec *spec) {
790         ParamSpec *param_spec;
791         SV *declarator;
792         I32 floor_ix;
793         int save_ix;
794         SV *saw_name;
795         OP **prelude_sentinel;
796         SV *proto;
797         OP **attrs_sentinel, *body;
798         unsigned builtin_attrs;
799         I32 c;
800
801         declarator = sentinel_mortalize(sen, newSVpvn(keyword_ptr, keyword_len));
802
803         lex_read_space(0);
804
805         builtin_attrs = 0;
806
807         /* function name */
808         saw_name = NULL;
809         if ((spec->flags & FLAG_NAME_OK) && (saw_name = my_scan_word(aTHX_ sen, TRUE))) {
810
811                 if (PL_parser->expect != XSTATE) {
812                         /* bail out early so we don't predeclare $saw_name */
813                         croak("In %"SVf": I was expecting a function body, not \"%"SVf"\"", SVfARG(declarator), SVfARG(saw_name));
814                 }
815
816                 sv_catpvs(declarator, " ");
817                 sv_catsv(declarator, saw_name);
818
819                 if (
820                         sv_eq_pvs(saw_name, "BEGIN") ||
821                         sv_eq_pvs(saw_name, "END") ||
822                         sv_eq_pvs(saw_name, "INIT") ||
823                         sv_eq_pvs(saw_name, "CHECK") ||
824                         sv_eq_pvs(saw_name, "UNITCHECK")
825                 ) {
826                         builtin_attrs |= MY_ATTR_SPECIAL;
827                 }
828
829                 lex_read_space(0);
830         } else if (!(spec->flags & FLAG_ANON_OK)) {
831                 croak("I was expecting a function name, not \"%.*s\"", (int)(PL_parser->bufend - PL_parser->bufptr), PL_parser->bufptr);
832         } else {
833                 sv_catpvs(declarator, " (anon)");
834         }
835
836         /* we're a subroutine declaration */
837         floor_ix = start_subparse(FALSE, saw_name ? 0 : CVf_ANON);
838         SAVEFREESV(PL_compcv);
839
840         /* create outer block: '{' */
841         save_ix = S_block_start(aTHX_ TRUE);
842
843         /* initialize synthetic optree */
844         Newx(prelude_sentinel, 1, OP *);
845         *prelude_sentinel = NULL;
846         sentinel_register(sen, prelude_sentinel, free_ptr_op);
847
848         /* parameters */
849         param_spec = NULL;
850
851         c = lex_peek_unichar(0);
852         if (c == '(') {
853                 OP **init_sentinel;
854
855                 Newx(init_sentinel, 1, OP *);
856                 *init_sentinel = NULL;
857                 sentinel_register(sen, init_sentinel, free_ptr_op);
858
859                 Newx(param_spec, 1, ParamSpec);
860                 ps_init(param_spec);
861                 sentinel_register(sen, param_spec, ps_free_void);
862
863                 lex_read_unichar(0);
864                 lex_read_space(0);
865
866                 while ((c = lex_peek_unichar(0)) != ')') {
867                         int flags;
868                         SV *name;
869                         char sigil;
870                         PADOFFSET padoff;
871
872                         padoff = parse_param(aTHX_ sen, declarator, spec, param_spec, &flags, &name, init_sentinel);
873
874                         S_intro_my(aTHX);
875
876                         sigil = SvPV_nolen(name)[0];
877
878                         /* internal consistency */
879                         if (flags & PARAM_NAMED) {
880                                 if (flags & PARAM_INVOCANT) {
881                                         croak("In %"SVf": invocant %"SVf" can't be a named parameter", SVfARG(declarator), SVfARG(name));
882                                 }
883                                 if (sigil != '$') {
884                                         croak("In %"SVf": named parameter %"SVf" can't be a%s", SVfARG(declarator), SVfARG(name), sigil == '@' ? "n array" : " hash");
885                                 }
886                         } else if (flags & PARAM_INVOCANT) {
887                                 if (*init_sentinel) {
888                                         croak("In %"SVf": invocant %"SVf" can't have a default value", SVfARG(declarator), SVfARG(name));
889                                 }
890                                 if (sigil != '$') {
891                                         croak("In %"SVf": invocant %"SVf" can't be a%s", SVfARG(declarator), SVfARG(name), sigil == '@' ? "n array" : " hash");
892                                 }
893                         } else if (sigil != '$' && *init_sentinel) {
894                                 croak("In %"SVf": %s %"SVf" can't have a default value", SVfARG(declarator), sigil == '@' ? "array" : "hash", SVfARG(name));
895                         }
896
897                         /* external constraints */
898                         if (param_spec->slurpy.name) {
899                                 croak("In %"SVf": I was expecting \")\" after \"%"SVf"\", not \"%"SVf"\"", SVfARG(declarator), SVfARG(param_spec->slurpy.name), SVfARG(name));
900                         }
901                         if (sigil != '$') {
902                                 assert(!*init_sentinel);
903                                 param_spec->slurpy.name = name;
904                                 param_spec->slurpy.padoff = padoff;
905                                 continue;
906                         }
907
908                         if (!(flags & PARAM_NAMED) && count_named_params(param_spec)) {
909                                 croak("In %"SVf": positional parameter %"SVf" can't appear after named parameter %"SVf"", SVfARG(declarator), SVfARG(name), SVfARG((param_spec->named_required.used ? param_spec->named_required.data[0] : param_spec->named_optional.data[0].param).name));
910                         }
911
912                         if (flags & PARAM_INVOCANT) {
913                                 if (param_spec->invocant.name) {
914                                         croak("In %"SVf": invalid double invocants %"SVf", %"SVf"", SVfARG(declarator), SVfARG(param_spec->invocant.name), SVfARG(name));
915                                 }
916                                 if (count_positional_params(param_spec) || count_named_params(param_spec)) {
917                                         croak("In %"SVf": invocant %"SVf" must be first in parameter list", SVfARG(declarator), SVfARG(name));
918                                 }
919                                 if (!(spec->flags & FLAG_INVOCANT)) {
920                                         croak("In %"SVf": invocant %"SVf" not allowed here", SVfARG(declarator), SVfARG(name));
921                                 }
922                                 param_spec->invocant.name = name;
923                                 param_spec->invocant.padoff = padoff;
924                                 continue;
925                         }
926
927                         if (*init_sentinel && !(spec->flags & FLAG_DEFAULT_ARGS)) {
928                                 croak("In %"SVf": default argument for %"SVf" not allowed here", SVfARG(declarator), SVfARG(name));
929                         }
930
931                         if (ps_contains(aTHX_ param_spec, name)) {
932                                 croak("In %"SVf": %"SVf" can't appear twice in the same parameter list", SVfARG(declarator), SVfARG(name));
933                         }
934
935                         if (flags & PARAM_NAMED) {
936                                 if (!(spec->flags & FLAG_NAMED_PARAMS)) {
937                                         croak("In %"SVf": named parameter :%"SVf" not allowed here", SVfARG(declarator), SVfARG(name));
938                                 }
939
940                                 if (*init_sentinel) {
941                                         ParamInit *pi = piv_extend(&param_spec->named_optional);
942                                         pi->param.name = name;
943                                         pi->param.padoff = padoff;
944                                         pi->init = *init_sentinel;
945                                         *init_sentinel = NULL;
946                                         param_spec->named_optional.used++;
947                                 } else {
948                                         Param *p;
949
950                                         if (param_spec->positional_optional.used) {
951                                                 croak("In %"SVf": can't combine optional positional (%"SVf") and required named (%"SVf") parameters", SVfARG(declarator), SVfARG(param_spec->positional_optional.data[0].param.name), SVfARG(name));
952                                         }
953
954                                         p = pv_extend(&param_spec->named_required);
955                                         p->name = name;
956                                         p->padoff = padoff;
957                                         param_spec->named_required.used++;
958                                 }
959                         } else {
960                                 if (*init_sentinel || param_spec->positional_optional.used) {
961                                         ParamInit *pi = piv_extend(&param_spec->positional_optional);
962                                         pi->param.name = name;
963                                         pi->param.padoff = padoff;
964                                         pi->init = *init_sentinel;
965                                         *init_sentinel = NULL;
966                                         param_spec->positional_optional.used++;
967                                 } else {
968                                         Param *p = pv_extend(&param_spec->positional_required);
969                                         p->name = name;
970                                         p->padoff = padoff;
971                                         param_spec->positional_required.used++;
972                                 }
973                         }
974
975                 }
976                 lex_read_unichar(0);
977                 lex_read_space(0);
978                 *init_sentinel = NULL;
979
980                 if (!param_spec->invocant.name && SvTRUE(spec->shift)) {
981                         if (ps_contains(aTHX_ param_spec, spec->shift)) {
982                                 croak("In %"SVf": %"SVf" can't appear twice in the same parameter list", SVfARG(declarator), SVfARG(spec->shift));
983                         }
984
985                         param_spec->invocant.name = spec->shift;
986                         param_spec->invocant.padoff = pad_add_name_sv(param_spec->invocant.name, 0, NULL, NULL);
987                 }
988         }
989
990         /* prototype */
991         proto = NULL;
992         c = lex_peek_unichar(0);
993         if (c == ':') {
994                 lex_read_unichar(0);
995                 lex_read_space(0);
996
997                 c = lex_peek_unichar(0);
998                 if (c != '(') {
999                         lex_stuff_pvs(":", 0);
1000                         c = ':';
1001                 } else {
1002                         lex_read_unichar(0);
1003                         if (!(proto = my_scan_parens_tail(aTHX_ sen, FALSE))) {
1004                                 croak("In %"SVf": prototype not terminated", SVfARG(declarator));
1005                         }
1006                         my_check_prototype(aTHX_ sen, declarator, proto);
1007                         lex_read_space(0);
1008                         c = lex_peek_unichar(0);
1009                         if (!(c == ':' || c == '{')) {
1010                                 lex_stuff_pvs(":", 0);
1011                                 c = ':';
1012                         }
1013                 }
1014         }
1015
1016         /* attributes */
1017         Newx(attrs_sentinel, 1, OP *);
1018         *attrs_sentinel = NULL;
1019         sentinel_register(sen, attrs_sentinel, free_ptr_op);
1020
1021         if (c == ':' || c == '{') /* '}' - hi, vim */ {
1022
1023                 /* kludge default attributes in */
1024                 if (SvTRUE(spec->attrs) && SvPV_nolen(spec->attrs)[0] == ':') {
1025                         lex_stuff_sv(spec->attrs, 0);
1026                         c = ':';
1027                 }
1028
1029                 if (c == ':') {
1030                         lex_read_unichar(0);
1031                         lex_read_space(0);
1032                         c = lex_peek_unichar(0);
1033
1034                         for (;;) {
1035                                 SV *attr;
1036
1037                                 if (!(attr = my_scan_word(aTHX_ sen, FALSE))) {
1038                                         break;
1039                                 }
1040
1041                                 lex_read_space(0);
1042                                 c = lex_peek_unichar(0);
1043
1044                                 if (c != '(') {
1045                                         if (sv_eq_pvs(attr, "lvalue")) {
1046                                                 builtin_attrs |= MY_ATTR_LVALUE;
1047                                                 attr = NULL;
1048                                         } else if (sv_eq_pvs(attr, "method")) {
1049                                                 builtin_attrs |= MY_ATTR_METHOD;
1050                                                 attr = NULL;
1051                                         }
1052                                 } else {
1053                                         SV *sv;
1054                                         lex_read_unichar(0);
1055                                         if (!(sv = my_scan_parens_tail(aTHX_ sen, TRUE))) {
1056                                                 croak("In %"SVf": unterminated attribute parameter in attribute list", SVfARG(declarator));
1057                                         }
1058                                         sv_catpvs(attr, "(");
1059                                         sv_catsv(attr, sv);
1060                                         sv_catpvs(attr, ")");
1061
1062                                         lex_read_space(0);
1063                                         c = lex_peek_unichar(0);
1064                                 }
1065
1066                                 if (attr) {
1067                                         *attrs_sentinel = op_append_elem(OP_LIST, *attrs_sentinel, mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(attr)));
1068                                 }
1069
1070                                 if (c == ':') {
1071                                         lex_read_unichar(0);
1072                                         lex_read_space(0);
1073                                         c = lex_peek_unichar(0);
1074                                 }
1075                         }
1076                 }
1077         }
1078
1079         /* body */
1080         if (c != '{') /* '}' - hi, vim */ {
1081                 croak("In %"SVf": I was expecting a function body, not \"%c\"", SVfARG(declarator), (int)c);
1082         }
1083
1084         /* surprise predeclaration! */
1085         if (saw_name) {
1086                 /* 'sub NAME (PROTO);' to make name/proto known to perl before it
1087                    starts parsing the body */
1088                 const I32 sub_ix = start_subparse(FALSE, 0);
1089                 SAVEFREESV(PL_compcv);
1090
1091                 SvREFCNT_inc_simple_void(PL_compcv);
1092
1093                 newATTRSUB(
1094                         sub_ix,
1095                         mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(saw_name)),
1096                         proto ? mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(proto)) : NULL,
1097                         NULL,
1098                         NULL
1099                 );
1100         }
1101
1102         if (builtin_attrs & MY_ATTR_LVALUE) {
1103                 CvLVALUE_on(PL_compcv);
1104         }
1105         if (builtin_attrs & MY_ATTR_METHOD) {
1106                 CvMETHOD_on(PL_compcv);
1107         }
1108         if (builtin_attrs & MY_ATTR_SPECIAL) {
1109                 CvSPECIAL_on(PL_compcv);
1110         }
1111
1112         /* check number of arguments */
1113         if (spec->flags & FLAG_CHECK_NARGS) {
1114                 int amin, amax;
1115
1116                 amin = args_min(aTHX_ param_spec, spec);
1117                 if (amin > 0) {
1118                         OP *chk, *cond, *err, *xcroak;
1119
1120                         err = mkconstsv(aTHX_ newSVpvf("Not enough arguments for %"SVf" (expected %d, got ", SVfARG(declarator), amin));
1121                         err = newBINOP(
1122                                 OP_CONCAT, 0,
1123                                 err,
1124                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv))
1125                         );
1126                         err = newBINOP(
1127                                 OP_CONCAT, 0,
1128                                 err,
1129                                 mkconstpvs(")")
1130                         );
1131
1132                         xcroak = newCVREF(OPf_WANT_SCALAR,
1133                                           newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV)));
1134                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1135                                       op_append_elem(OP_LIST, err, xcroak));
1136
1137                         cond = newBINOP(OP_LT, 0,
1138                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1139                                         mkconstiv(aTHX_ amin));
1140                         chk = newLOGOP(OP_AND, 0, cond, err);
1141
1142                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1143                 }
1144
1145                 amax = args_max(param_spec);
1146                 if (amax >= 0) {
1147                         OP *chk, *cond, *err, *xcroak;
1148
1149                         err = mkconstsv(aTHX_ newSVpvf("Too many arguments for %"SVf" (expected %d, got ", SVfARG(declarator), amax));
1150                         err = newBINOP(
1151                                 OP_CONCAT, 0,
1152                                 err,
1153                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv))
1154                         );
1155                         err = newBINOP(
1156                                 OP_CONCAT, 0,
1157                                 err,
1158                                 mkconstpvs(")")
1159                         );
1160
1161                         xcroak = newCVREF(
1162                                 OPf_WANT_SCALAR,
1163                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1164                         );
1165                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1166                         op_append_elem(OP_LIST, err, xcroak));
1167
1168                         cond = newBINOP(
1169                                 OP_GT, 0,
1170                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1171                                 mkconstiv(aTHX_ amax)
1172                         );
1173                         chk = newLOGOP(OP_AND, 0, cond, err);
1174
1175                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1176                 }
1177
1178                 if (param_spec && (count_named_params(param_spec) || (param_spec->slurpy.name && SvPV_nolen(param_spec->slurpy.name)[0] == '%'))) {
1179                         OP *chk, *cond, *err, *xcroak;
1180                         const UV fixed = count_positional_params(param_spec) + !!param_spec->invocant.name;
1181
1182                         err = mkconstsv(aTHX_ newSVpvf("Odd number of paired arguments for %"SVf"", SVfARG(declarator)));
1183
1184                         xcroak = newCVREF(
1185                                 OPf_WANT_SCALAR,
1186                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1187                         );
1188                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1189                         op_append_elem(OP_LIST, err, xcroak));
1190
1191                         cond = newBINOP(OP_GT, 0,
1192                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1193                                         mkconstiv(aTHX_ fixed));
1194                         cond = newLOGOP(OP_AND, 0,
1195                                         cond,
1196                                         newBINOP(OP_MODULO, 0,
1197                                                  fixed
1198                                                  ? newBINOP(OP_SUBTRACT, 0,
1199                                                             newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1200                                                             mkconstiv(aTHX_ fixed))
1201                                                  : newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1202                                                  mkconstiv(aTHX_ 2)));
1203                         chk = newLOGOP(OP_AND, 0, cond, err);
1204
1205                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1206                 }
1207         }
1208
1209         if (!param_spec) {
1210                 /* my $invocant = shift; */
1211                 if (SvTRUE(spec->shift)) {
1212                         OP *var;
1213
1214                         var = my_var(
1215                                 aTHX_
1216                                 OPf_MOD | (OPpLVAL_INTRO << 8),
1217                                 pad_add_name_sv(spec->shift, 0, NULL, NULL)
1218                         );
1219                         var = newASSIGNOP(OPf_STACKED, var, 0, newOP(OP_SHIFT, 0));
1220
1221                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1222                 }
1223         } else {
1224                 /* my $invocant = shift; */
1225                 if (param_spec->invocant.name) {
1226                         OP *var;
1227
1228                         var = my_var(
1229                                 aTHX_
1230                                 OPf_MOD | (OPpLVAL_INTRO << 8),
1231                                 param_spec->invocant.padoff
1232                         );
1233                         var = newASSIGNOP(OPf_STACKED, var, 0, newOP(OP_SHIFT, 0));
1234
1235                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1236                 }
1237
1238                 /* my (...) = @_; */
1239                 {
1240                         OP *lhs;
1241                         size_t i, lim;
1242
1243                         lhs = NULL;
1244
1245                         for (i = 0, lim = param_spec->positional_required.used; i < lim; i++) {
1246                                 OP *const var = my_var(
1247                                         aTHX_
1248                                         OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1249                                         param_spec->positional_required.data[i].padoff
1250                                 );
1251                                 lhs = op_append_elem(OP_LIST, lhs, var);
1252                         }
1253
1254                         for (i = 0, lim = param_spec->positional_optional.used; i < lim; i++) {
1255                                 OP *const var = my_var(
1256                                         aTHX_
1257                                         OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1258                                         param_spec->positional_optional.data[i].param.padoff
1259                                 );
1260                                 lhs = op_append_elem(OP_LIST, lhs, var);
1261                         }
1262
1263                         {
1264                                 PADOFFSET padoff;
1265                                 I32 type;
1266                                 bool slurpy_hash;
1267
1268                                 /*
1269                                  * cases:
1270                                  *  1) no named params
1271                                  *   1.1) slurpy
1272                                  *       => put it in
1273                                  *   1.2) no slurpy
1274                                  *       => nop
1275                                  *  2) named params
1276                                  *   2.1) no slurpy
1277                                  *       => synthetic %{rest}
1278                                  *   2.2) slurpy is a hash
1279                                  *       => put it in
1280                                  *   2.3) slurpy is an array
1281                                  *       => synthetic %{rest}
1282                                  *          remember to declare array later
1283                                  */
1284
1285                                 slurpy_hash = param_spec->slurpy.name && SvPV_nolen(param_spec->slurpy.name)[0] == '%';
1286                                 if (!count_named_params(param_spec)) {
1287                                         if (param_spec->slurpy.name) {
1288                                                 padoff = param_spec->slurpy.padoff;
1289                                                 type = slurpy_hash ? OP_PADHV : OP_PADAV;
1290                                         } else {
1291                                                 padoff = NOT_IN_PAD;
1292                                                 type = OP_PADSV;
1293                                         }
1294                                 } else if (slurpy_hash) {
1295                                         padoff = param_spec->slurpy.padoff;
1296                                         type = OP_PADHV;
1297                                 } else {
1298                                         padoff = param_spec->rest_hash = pad_add_name_pvs("%{rest}", 0, NULL, NULL);
1299                                         type = OP_PADHV;
1300                                 }
1301
1302                                 if (padoff != NOT_IN_PAD) {
1303                                         OP *const var = my_var_g(
1304                                                 aTHX_
1305                                                 type,
1306                                                 OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1307                                                 padoff
1308                                         );
1309
1310                                         lhs = op_append_elem(OP_LIST, lhs, var);
1311
1312                                         if (type == OP_PADHV) {
1313                                                 param_spec->rest_hash = padoff;
1314                                         }
1315                                 }
1316                         }
1317
1318                         if (lhs) {
1319                                 OP *rhs;
1320                                 lhs->op_flags |= OPf_PARENS;
1321                                 rhs = newAVREF(newGVOP(OP_GV, 0, PL_defgv));
1322
1323                                 *prelude_sentinel = op_append_list(
1324                                         OP_LINESEQ, *prelude_sentinel,
1325                                         newSTATEOP(
1326                                                 0, NULL,
1327                                                 newASSIGNOP(OPf_STACKED, lhs, 0, rhs)
1328                                         )
1329                                 );
1330                         }
1331                 }
1332
1333                 /* default positional arguments */
1334                 {
1335                         size_t i, lim, req;
1336                         OP *nest;
1337
1338                         nest = NULL;
1339
1340                         req = param_spec->positional_required.used;
1341                         for (i = 0, lim = param_spec->positional_optional.used; i < lim; i++) {
1342                                 ParamInit *cur = &param_spec->positional_optional.data[i];
1343                                 OP *var, *cond;
1344
1345                                 cond = newBINOP(
1346                                         OP_LT, 0,
1347                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1348                                         mkconstiv(aTHX_ req + i + 1)
1349                                 );
1350
1351                                 var = my_var(aTHX_ 0, cur->param.padoff);
1352
1353                                 nest = op_append_list(
1354                                         OP_LINESEQ, nest,
1355                                         newASSIGNOP(OPf_STACKED, var, 0, cur->init)
1356                                 );
1357                                 cur->init = NULL;
1358                                 nest = newCONDOP(
1359                                         0,
1360                                         cond,
1361                                         nest,
1362                                         NULL
1363                                 );
1364                         }
1365
1366                         *prelude_sentinel = op_append_list(
1367                                 OP_LINESEQ, *prelude_sentinel,
1368                                 nest
1369                         );
1370                 }
1371
1372                 /* named parameters */
1373                 if (count_named_params(param_spec)) {
1374                         size_t i, lim;
1375
1376                         assert(param_spec->rest_hash != NOT_IN_PAD);
1377
1378                         for (i = 0, lim = param_spec->named_required.used; i < lim; i++) {
1379                                 Param *cur = &param_spec->named_required.data[i];
1380                                 size_t n;
1381                                 char *p = SvPV(cur->name, n);
1382                                 OP *var, *cond;
1383
1384                                 cond = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1385
1386                                 if (spec->flags & FLAG_CHECK_NARGS) {
1387                                         OP *xcroak, *msg;
1388
1389                                         var = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1390                                         var = newUNOP(OP_DELETE, 0, var);
1391
1392                                         msg = mkconstsv(aTHX_ newSVpvf("In %"SVf": missing named parameter: %.*s", SVfARG(declarator), (int)(n - 1), p + 1));
1393                                         xcroak = newCVREF(
1394                                                 OPf_WANT_SCALAR,
1395                                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1396                                         );
1397                                         xcroak = newUNOP(OP_ENTERSUB, OPf_STACKED, op_append_elem(OP_LIST, msg, xcroak));
1398
1399                                         cond = newUNOP(OP_EXISTS, 0, cond);
1400
1401                                         cond = newCONDOP(0, cond, var, xcroak);
1402                                 }
1403
1404                                 var = my_var(
1405                                         aTHX_
1406                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1407                                         cur->padoff
1408                                 );
1409                                 var = newASSIGNOP(OPf_STACKED, var, 0, cond);
1410
1411                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1412                         }
1413
1414                         for (i = 0, lim = param_spec->named_optional.used; i < lim; i++) {
1415                                 ParamInit *cur = &param_spec->named_optional.data[i];
1416                                 size_t n;
1417                                 char *p = SvPV(cur->param.name, n);
1418                                 OP *var, *cond;
1419
1420                                 var = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1421                                 var = newUNOP(OP_DELETE, 0, var);
1422
1423                                 cond = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1424                                 cond = newUNOP(OP_EXISTS, 0, cond);
1425
1426                                 cond = newCONDOP(0, cond, var, cur->init);
1427                                 cur->init = NULL;
1428
1429                                 var = my_var(
1430                                         aTHX_
1431                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1432                                         cur->param.padoff
1433                                 );
1434                                 var = newASSIGNOP(OPf_STACKED, var, 0, cond);
1435
1436                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1437                         }
1438
1439                         if (!param_spec->slurpy.name) {
1440                                 if (spec->flags & FLAG_CHECK_NARGS) {
1441                                         /* croak if %{rest} */
1442                                         OP *xcroak, *cond, *keys, *msg;
1443
1444                                         keys = newUNOP(OP_KEYS, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1445                                         keys = newLISTOP(OP_SORT, 0, newOP(OP_PUSHMARK, 0), keys);
1446                                         {
1447                                                 OP *first, *mid, *last;
1448
1449                                                 last = keys;
1450
1451                                                 mid = mkconstpvs(", ");
1452                                                 mid->op_sibling = last;
1453
1454                                                 first = newOP(OP_PUSHMARK, 0);
1455
1456                                                 keys = newLISTOP(OP_JOIN, 0, first, mid);
1457                                                 keys->op_targ = pad_alloc(OP_JOIN, SVs_PADTMP);
1458                                                 ((LISTOP *)keys)->op_last = last;
1459                                         }
1460
1461                                         msg = mkconstsv(aTHX_ newSVpvf("In %"SVf": no such named parameter: ", SVfARG(declarator)));
1462                                         msg = newBINOP(OP_CONCAT, 0, msg, keys);
1463
1464                                         xcroak = newCVREF(
1465                                                 OPf_WANT_SCALAR,
1466                                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1467                                         );
1468                                         xcroak = newUNOP(OP_ENTERSUB, OPf_STACKED, op_append_elem(OP_LIST, msg, xcroak));
1469
1470                                         cond = newUNOP(OP_KEYS, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1471                                         xcroak = newCONDOP(0, cond, xcroak, NULL);
1472
1473                                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, xcroak));
1474                                 } else {
1475                                         OP *clear;
1476
1477                                         clear = newASSIGNOP(
1478                                                 OPf_STACKED,
1479                                                 my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash),
1480                                                 0,
1481                                                 newNULLLIST()
1482                                         );
1483
1484                                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, clear));
1485                                 }
1486                         } else if (param_spec->slurpy.padoff != param_spec->rest_hash) {
1487                                 OP *var, *clear;
1488
1489                                 assert(SvPV_nolen(param_spec->slurpy.name)[0] == '@');
1490
1491                                 var = my_var_g(
1492                                         aTHX_
1493                                         OP_PADAV,
1494                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1495                                         param_spec->slurpy.padoff
1496                                 );
1497
1498                                 var = newASSIGNOP(OPf_STACKED, var, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1499
1500                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1501
1502                                 clear = newASSIGNOP(
1503                                         OPf_STACKED,
1504                                         my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash),
1505                                         0,
1506                                         newNULLLIST()
1507                                 );
1508
1509                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, clear));
1510                         }
1511                 }
1512         }
1513
1514         /* finally let perl parse the actual subroutine body */
1515         body = parse_block(0);
1516
1517         /* add '();' to make function return nothing by default */
1518         /* (otherwise the invisible parameter initialization can "leak" into
1519            the return value: fun ($x) {}->("asdf", 0) == 2) */
1520         if (*prelude_sentinel) {
1521                 body = newSTATEOP(0, NULL, body);
1522         }
1523
1524         body = op_append_list(OP_LINESEQ, *prelude_sentinel, body);
1525         *prelude_sentinel = NULL;
1526
1527         /* it's go time. */
1528         {
1529                 OP *const attrs = *attrs_sentinel;
1530                 *attrs_sentinel = NULL;
1531                 SvREFCNT_inc_simple_void(PL_compcv);
1532
1533                 /* close outer block: '}' */
1534                 S_block_end(aTHX_ save_ix, body);
1535
1536                 if (!saw_name) {
1537                         *pop = newANONATTRSUB(
1538                                 floor_ix,
1539                                 proto ? newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(proto)) : NULL,
1540                                 attrs,
1541                                 body
1542                         );
1543                         return KEYWORD_PLUGIN_EXPR;
1544                 }
1545
1546                 newATTRSUB(
1547                         floor_ix,
1548                         newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(saw_name)),
1549                         proto ? newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(proto)) : NULL,
1550                         attrs,
1551                         body
1552                 );
1553                 *pop = newOP(OP_NULL, 0);
1554                 return KEYWORD_PLUGIN_STMT;
1555         }
1556 }
1557
1558 static int my_keyword_plugin(pTHX_ char *keyword_ptr, STRLEN keyword_len, OP **op_ptr) {
1559         KWSpec spec;
1560         int ret;
1561         Sentinel sen = { NULL };
1562
1563         ENTER;
1564         SAVETMPS;
1565
1566         SAVEDESTRUCTOR_X(sentinel_clear_void, sen);
1567
1568         if (kw_flags(aTHX_ sen, keyword_ptr, keyword_len, &spec)) {
1569                 ret = parse_fun(aTHX_ sen, op_ptr, keyword_ptr, keyword_len, &spec);
1570         } else {
1571                 ret = next_keyword_plugin(aTHX_ keyword_ptr, keyword_len, op_ptr);
1572         }
1573
1574         FREETMPS;
1575         LEAVE;
1576
1577         return ret;
1578 }
1579
1580 WARNINGS_RESET
1581
1582 MODULE = Function::Parameters   PACKAGE = Function::Parameters
1583 PROTOTYPES: ENABLE
1584
1585 BOOT:
1586 WARNINGS_ENABLE {
1587         HV *const stash = gv_stashpvs(MY_PKG, GV_ADD);
1588         /**/
1589         newCONSTSUB(stash, "FLAG_NAME_OK",      newSViv(FLAG_NAME_OK));
1590         newCONSTSUB(stash, "FLAG_ANON_OK",      newSViv(FLAG_ANON_OK));
1591         newCONSTSUB(stash, "FLAG_DEFAULT_ARGS", newSViv(FLAG_DEFAULT_ARGS));
1592         newCONSTSUB(stash, "FLAG_CHECK_NARGS",  newSViv(FLAG_CHECK_NARGS));
1593         newCONSTSUB(stash, "FLAG_INVOCANT",     newSViv(FLAG_INVOCANT));
1594         newCONSTSUB(stash, "FLAG_NAMED_PARAMS", newSViv(FLAG_NAMED_PARAMS));
1595         newCONSTSUB(stash, "HINTK_KEYWORDS", newSVpvs(HINTK_KEYWORDS));
1596         newCONSTSUB(stash, "HINTK_FLAGS_",   newSVpvs(HINTK_FLAGS_));
1597         newCONSTSUB(stash, "HINTK_SHIFT_",   newSVpvs(HINTK_SHIFT_));
1598         newCONSTSUB(stash, "HINTK_ATTRS_",   newSVpvs(HINTK_ATTRS_));
1599         /**/
1600         next_keyword_plugin = PL_keyword_plugin;
1601         PL_keyword_plugin = my_keyword_plugin;
1602 } WARNINGS_RESET