542b078e13f5b544ce50bc8230cefde2bcfdb30b
[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 = uvchr_to_utf8(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                                         if (param_spec->positional_optional.used) {
949                                                 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));
950                                         }
951
952                                         Param *p = pv_extend(&param_spec->named_required);
953                                         p->name = name;
954                                         p->padoff = padoff;
955                                         param_spec->named_required.used++;
956                                 }
957                         } else {
958                                 if (*init_sentinel || param_spec->positional_optional.used) {
959                                         ParamInit *pi = piv_extend(&param_spec->positional_optional);
960                                         pi->param.name = name;
961                                         pi->param.padoff = padoff;
962                                         pi->init = *init_sentinel;
963                                         *init_sentinel = NULL;
964                                         param_spec->positional_optional.used++;
965                                 } else {
966                                         Param *p = pv_extend(&param_spec->positional_required);
967                                         p->name = name;
968                                         p->padoff = padoff;
969                                         param_spec->positional_required.used++;
970                                 }
971                         }
972
973                 }
974                 lex_read_unichar(0);
975                 lex_read_space(0);
976                 *init_sentinel = NULL;
977
978                 if (!param_spec->invocant.name && SvTRUE(spec->shift)) {
979                         if (ps_contains(aTHX_ param_spec, spec->shift)) {
980                                 croak("In %"SVf": %"SVf" can't appear twice in the same parameter list", SVfARG(declarator), SVfARG(spec->shift));
981                         }
982
983                         param_spec->invocant.name = spec->shift;
984                         param_spec->invocant.padoff = pad_add_name_sv(param_spec->invocant.name, 0, NULL, NULL);
985                 }
986         }
987
988         /* prototype */
989         proto = NULL;
990         c = lex_peek_unichar(0);
991         if (c == ':') {
992                 lex_read_unichar(0);
993                 lex_read_space(0);
994
995                 c = lex_peek_unichar(0);
996                 if (c != '(') {
997                         lex_stuff_pvs(":", 0);
998                         c = ':';
999                 } else {
1000                         lex_read_unichar(0);
1001                         if (!(proto = my_scan_parens_tail(aTHX_ sen, FALSE))) {
1002                                 croak("In %"SVf": prototype not terminated", SVfARG(declarator));
1003                         }
1004                         my_check_prototype(aTHX_ sen, declarator, proto);
1005                         lex_read_space(0);
1006                         c = lex_peek_unichar(0);
1007                         if (!(c == ':' || c == '{')) {
1008                                 lex_stuff_pvs(":", 0);
1009                                 c = ':';
1010                         }
1011                 }
1012         }
1013
1014         /* attributes */
1015         Newx(attrs_sentinel, 1, OP *);
1016         *attrs_sentinel = NULL;
1017         sentinel_register(sen, attrs_sentinel, free_ptr_op);
1018
1019         if (c == ':' || c == '{') /* '}' - hi, vim */ {
1020
1021                 /* kludge default attributes in */
1022                 if (SvTRUE(spec->attrs) && SvPV_nolen(spec->attrs)[0] == ':') {
1023                         lex_stuff_sv(spec->attrs, 0);
1024                         c = ':';
1025                 }
1026
1027                 if (c == ':') {
1028                         lex_read_unichar(0);
1029                         lex_read_space(0);
1030                         c = lex_peek_unichar(0);
1031
1032                         for (;;) {
1033                                 SV *attr;
1034
1035                                 if (!(attr = my_scan_word(aTHX_ sen, FALSE))) {
1036                                         break;
1037                                 }
1038
1039                                 lex_read_space(0);
1040                                 c = lex_peek_unichar(0);
1041
1042                                 if (c != '(') {
1043                                         if (sv_eq_pvs(attr, "lvalue")) {
1044                                                 builtin_attrs |= MY_ATTR_LVALUE;
1045                                                 attr = NULL;
1046                                         } else if (sv_eq_pvs(attr, "method")) {
1047                                                 builtin_attrs |= MY_ATTR_METHOD;
1048                                                 attr = NULL;
1049                                         }
1050                                 } else {
1051                                         SV *sv;
1052                                         lex_read_unichar(0);
1053                                         if (!(sv = my_scan_parens_tail(aTHX_ sen, TRUE))) {
1054                                                 croak("In %"SVf": unterminated attribute parameter in attribute list", SVfARG(declarator));
1055                                         }
1056                                         sv_catpvs(attr, "(");
1057                                         sv_catsv(attr, sv);
1058                                         sv_catpvs(attr, ")");
1059
1060                                         lex_read_space(0);
1061                                         c = lex_peek_unichar(0);
1062                                 }
1063
1064                                 if (attr) {
1065                                         *attrs_sentinel = op_append_elem(OP_LIST, *attrs_sentinel, mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(attr)));
1066                                 }
1067
1068                                 if (c == ':') {
1069                                         lex_read_unichar(0);
1070                                         lex_read_space(0);
1071                                         c = lex_peek_unichar(0);
1072                                 }
1073                         }
1074                 }
1075         }
1076
1077         /* body */
1078         if (c != '{') /* '}' - hi, vim */ {
1079                 croak("In %"SVf": I was expecting a function body, not \"%c\"", SVfARG(declarator), (int)c);
1080         }
1081
1082         /* surprise predeclaration! */
1083         if (saw_name) {
1084                 /* 'sub NAME (PROTO);' to make name/proto known to perl before it
1085                    starts parsing the body */
1086                 const I32 sub_ix = start_subparse(FALSE, 0);
1087                 SAVEFREESV(PL_compcv);
1088
1089                 SvREFCNT_inc_simple_void(PL_compcv);
1090
1091                 newATTRSUB(
1092                         sub_ix,
1093                         mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(saw_name)),
1094                         proto ? mkconstsv(aTHX_ SvREFCNT_inc_simple_NN(proto)) : NULL,
1095                         NULL,
1096                         NULL
1097                 );
1098         }
1099
1100         if (builtin_attrs & MY_ATTR_LVALUE) {
1101                 CvLVALUE_on(PL_compcv);
1102         }
1103         if (builtin_attrs & MY_ATTR_METHOD) {
1104                 CvMETHOD_on(PL_compcv);
1105         }
1106         if (builtin_attrs & MY_ATTR_SPECIAL) {
1107                 CvSPECIAL_on(PL_compcv);
1108         }
1109
1110         /* check number of arguments */
1111         if (spec->flags & FLAG_CHECK_NARGS) {
1112                 int amin, amax;
1113                 size_t named;
1114
1115                 amin = args_min(aTHX_ param_spec, spec);
1116                 if (amin > 0) {
1117                         OP *chk, *cond, *err, *croak;
1118
1119                         err = mkconstsv(aTHX_ newSVpvf("Not enough arguments for %"SVf" (expected %d, got ", SVfARG(declarator), amin));
1120                         err = newBINOP(
1121                                 OP_CONCAT, 0,
1122                                 err,
1123                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv))
1124                         );
1125                         err = newBINOP(
1126                                 OP_CONCAT, 0,
1127                                 err,
1128                                 mkconstpvs(")")
1129                         );
1130
1131                         croak = newCVREF(OPf_WANT_SCALAR,
1132                                          newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV)));
1133                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1134                                       op_append_elem(OP_LIST, err, croak));
1135
1136                         cond = newBINOP(OP_LT, 0,
1137                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1138                                         mkconstiv(aTHX_ amin));
1139                         chk = newLOGOP(OP_AND, 0, cond, err);
1140
1141                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1142                 }
1143
1144                 amax = args_max(param_spec);
1145                 if (amax >= 0) {
1146                         OP *chk, *cond, *err, *croak;
1147
1148                         err = mkconstsv(aTHX_ newSVpvf("Too many arguments for %"SVf" (expected %d, got ", SVfARG(declarator), amax));
1149                         err = newBINOP(
1150                                 OP_CONCAT, 0,
1151                                 err,
1152                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv))
1153                         );
1154                         err = newBINOP(
1155                                 OP_CONCAT, 0,
1156                                 err,
1157                                 mkconstpvs(")")
1158                         );
1159
1160                         croak = newCVREF(
1161                                 OPf_WANT_SCALAR,
1162                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1163                         );
1164                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1165                         op_append_elem(OP_LIST, err, croak));
1166
1167                         cond = newBINOP(
1168                                 OP_GT, 0,
1169                                 newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1170                                 mkconstiv(aTHX_ amax)
1171                         );
1172                         chk = newLOGOP(OP_AND, 0, cond, err);
1173
1174                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1175                 }
1176
1177                 if (param_spec && (count_named_params(param_spec) || (param_spec->slurpy.name && SvPV_nolen(param_spec->slurpy.name)[0] == '%'))) {
1178                         OP *chk, *cond, *err, *croak;
1179                         const UV fixed = count_positional_params(param_spec) + !!param_spec->invocant.name;
1180
1181                         err = mkconstsv(aTHX_ newSVpvf("Odd number of paired arguments for %"SVf"", SVfARG(declarator)));
1182
1183                         croak = newCVREF(
1184                                 OPf_WANT_SCALAR,
1185                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1186                         );
1187                         err = newUNOP(OP_ENTERSUB, OPf_STACKED,
1188                         op_append_elem(OP_LIST, err, croak));
1189
1190                         cond = newBINOP(OP_GT, 0,
1191                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1192                                         mkconstiv(aTHX_ fixed));
1193                         cond = newLOGOP(OP_AND, 0,
1194                                         cond,
1195                                         newBINOP(OP_MODULO, 0,
1196                                                  fixed
1197                                                  ? newBINOP(OP_SUBTRACT, 0,
1198                                                             newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1199                                                             mkconstiv(aTHX_ fixed))
1200                                                  : newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1201                                                  mkconstiv(aTHX_ 2)));
1202                         chk = newLOGOP(OP_AND, 0, cond, err);
1203
1204                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, chk));
1205                 }
1206         }
1207
1208         if (!param_spec) {
1209                 /* my $invocant = shift; */
1210                 if (SvTRUE(spec->shift)) {
1211                         OP *var;
1212
1213                         var = my_var(
1214                                 aTHX_
1215                                 OPf_MOD | (OPpLVAL_INTRO << 8),
1216                                 pad_add_name_sv(spec->shift, 0, NULL, NULL)
1217                         );
1218                         var = newASSIGNOP(OPf_STACKED, var, 0, newOP(OP_SHIFT, 0));
1219
1220                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1221                 }
1222         } else {
1223                 /* my $invocant = shift; */
1224                 if (param_spec->invocant.name) {
1225                         OP *var;
1226
1227                         var = my_var(
1228                                 aTHX_
1229                                 OPf_MOD | (OPpLVAL_INTRO << 8),
1230                                 param_spec->invocant.padoff
1231                         );
1232                         var = newASSIGNOP(OPf_STACKED, var, 0, newOP(OP_SHIFT, 0));
1233
1234                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1235                 }
1236
1237                 /* my (...) = @_; */
1238                 {
1239                         OP *lhs;
1240                         size_t i, lim;
1241
1242                         lhs = NULL;
1243
1244                         for (i = 0, lim = param_spec->positional_required.used; i < lim; i++) {
1245                                 OP *const var = my_var(
1246                                         aTHX_
1247                                         OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1248                                         param_spec->positional_required.data[i].padoff
1249                                 );
1250                                 lhs = op_append_elem(OP_LIST, lhs, var);
1251                         }
1252
1253                         for (i = 0, lim = param_spec->positional_optional.used; i < lim; i++) {
1254                                 OP *const var = my_var(
1255                                         aTHX_
1256                                         OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1257                                         param_spec->positional_optional.data[i].param.padoff
1258                                 );
1259                                 lhs = op_append_elem(OP_LIST, lhs, var);
1260                         }
1261
1262                         {
1263                                 PADOFFSET padoff;
1264                                 I32 type;
1265                                 bool slurpy_hash;
1266
1267                                 /*
1268                                  * cases:
1269                                  *  1) no named params
1270                                  *   1.1) slurpy
1271                                  *       => put it in
1272                                  *   1.2) no slurpy
1273                                  *       => nop
1274                                  *  2) named params
1275                                  *   2.1) no slurpy
1276                                  *       => synthetic %{rest}
1277                                  *   2.2) slurpy is a hash
1278                                  *       => put it in
1279                                  *   2.3) slurpy is an array
1280                                  *       => synthetic %{rest}
1281                                  *          remember to declare array later
1282                                  */
1283
1284                                 slurpy_hash = param_spec->slurpy.name && SvPV_nolen(param_spec->slurpy.name)[0] == '%';
1285                                 if (!count_named_params(param_spec)) {
1286                                         if (param_spec->slurpy.name) {
1287                                                 padoff = param_spec->slurpy.padoff;
1288                                                 type = slurpy_hash ? OP_PADHV : OP_PADAV;
1289                                         } else {
1290                                                 padoff = NOT_IN_PAD;
1291                                                 type = OP_PADSV;
1292                                         }
1293                                 } else if (slurpy_hash) {
1294                                         padoff = param_spec->slurpy.padoff;
1295                                         type = OP_PADHV;
1296                                 } else {
1297                                         padoff = param_spec->rest_hash = pad_add_name_pvs("%{rest}", 0, NULL, NULL);
1298                                         type = OP_PADHV;
1299                                 }
1300
1301                                 if (padoff != NOT_IN_PAD) {
1302                                         OP *const var = my_var_g(
1303                                                 aTHX_
1304                                                 type,
1305                                                 OPf_WANT_LIST | (OPpLVAL_INTRO << 8),
1306                                                 padoff
1307                                         );
1308
1309                                         lhs = op_append_elem(OP_LIST, lhs, var);
1310
1311                                         if (type == OP_PADHV) {
1312                                                 param_spec->rest_hash = padoff;
1313                                         }
1314                                 }
1315                         }
1316
1317                         if (lhs) {
1318                                 OP *rhs;
1319                                 lhs->op_flags |= OPf_PARENS;
1320                                 rhs = newAVREF(newGVOP(OP_GV, 0, PL_defgv));
1321
1322                                 *prelude_sentinel = op_append_list(
1323                                         OP_LINESEQ, *prelude_sentinel,
1324                                         newSTATEOP(
1325                                                 0, NULL,
1326                                                 newASSIGNOP(OPf_STACKED, lhs, 0, rhs)
1327                                         )
1328                                 );
1329                         }
1330                 }
1331
1332                 /* default positional arguments */
1333                 {
1334                         size_t i, lim, req;
1335                         OP *nest;
1336
1337                         nest = NULL;
1338
1339                         req = param_spec->positional_required.used;
1340                         for (i = 0, lim = param_spec->positional_optional.used; i < lim; i++) {
1341                                 ParamInit *cur = &param_spec->positional_optional.data[i];
1342                                 OP *var, *cond;
1343
1344                                 cond = newBINOP(
1345                                         OP_LT, 0,
1346                                         newAVREF(newGVOP(OP_GV, 0, PL_defgv)),
1347                                         mkconstiv(aTHX_ req + i + 1)
1348                                 );
1349
1350                                 var = my_var(aTHX_ 0, cur->param.padoff);
1351
1352                                 nest = op_append_list(
1353                                         OP_LINESEQ, nest,
1354                                         newASSIGNOP(OPf_STACKED, var, 0, cur->init)
1355                                 );
1356                                 cur->init = NULL;
1357                                 nest = newCONDOP(
1358                                         0,
1359                                         cond,
1360                                         nest,
1361                                         NULL
1362                                 );
1363                         }
1364
1365                         *prelude_sentinel = op_append_list(
1366                                 OP_LINESEQ, *prelude_sentinel,
1367                                 nest
1368                         );
1369                 }
1370
1371                 /* named parameters */
1372                 if (count_named_params(param_spec)) {
1373                         size_t i, lim;
1374
1375                         assert(param_spec->rest_hash != NOT_IN_PAD);
1376
1377                         for (i = 0, lim = param_spec->named_required.used; i < lim; i++) {
1378                                 Param *cur = &param_spec->named_required.data[i];
1379                                 size_t n;
1380                                 char *p = SvPV(cur->name, n);
1381                                 OP *var, *cond;
1382
1383                                 cond = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1384
1385                                 if (spec->flags & FLAG_CHECK_NARGS) {
1386                                         OP *croak, *msg;
1387
1388                                         var = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1389                                         var = newUNOP(OP_DELETE, 0, var);
1390
1391                                         msg = mkconstsv(aTHX_ newSVpvf("In %"SVf": missing named parameter: %.*s", SVfARG(declarator), (int)(n - 1), p + 1));
1392                                         croak = newCVREF(
1393                                                 OPf_WANT_SCALAR,
1394                                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1395                                         );
1396                                         croak = newUNOP(OP_ENTERSUB, OPf_STACKED, op_append_elem(OP_LIST, msg, croak));
1397
1398                                         cond = newUNOP(OP_EXISTS, 0, cond);
1399
1400                                         cond = newCONDOP(0, cond, var, croak);
1401                                 }
1402
1403                                 var = my_var(
1404                                         aTHX_
1405                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1406                                         cur->padoff
1407                                 );
1408                                 var = newASSIGNOP(OPf_STACKED, var, 0, cond);
1409
1410                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1411                         }
1412
1413                         for (i = 0, lim = param_spec->named_optional.used; i < lim; i++) {
1414                                 ParamInit *cur = &param_spec->named_optional.data[i];
1415                                 size_t n;
1416                                 char *p = SvPV(cur->param.name, n);
1417                                 OP *var, *cond;
1418
1419                                 var = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1420                                 var = newUNOP(OP_DELETE, 0, var);
1421
1422                                 cond = mkhvelem(aTHX_ param_spec->rest_hash, mkconstpv(aTHX_ p + 1, n - 1));
1423                                 cond = newUNOP(OP_EXISTS, 0, cond);
1424
1425                                 cond = newCONDOP(0, cond, var, cur->init);
1426                                 cur->init = NULL;
1427
1428                                 var = my_var(
1429                                         aTHX_
1430                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1431                                         cur->param.padoff
1432                                 );
1433                                 var = newASSIGNOP(OPf_STACKED, var, 0, cond);
1434
1435                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1436                         }
1437
1438                         if (!param_spec->slurpy.name) {
1439                                 if (spec->flags & FLAG_CHECK_NARGS) {
1440                                         /* croak if %{rest} */
1441                                         OP *croak, *cond, *keys, *msg;
1442
1443                                         keys = newUNOP(OP_KEYS, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1444                                         keys = newLISTOP(OP_SORT, 0, newOP(OP_PUSHMARK, 0), keys);
1445                                         {
1446                                                 OP *first, *mid, *last;
1447
1448                                                 last = keys;
1449
1450                                                 mid = mkconstpvs(", ");
1451                                                 mid->op_sibling = last;
1452
1453                                                 first = newOP(OP_PUSHMARK, 0);
1454
1455                                                 keys = newLISTOP(OP_JOIN, 0, first, mid);
1456                                                 keys->op_targ = pad_alloc(OP_JOIN, SVs_PADTMP);
1457                                                 ((LISTOP *)keys)->op_last = last;
1458                                         }
1459
1460                                         msg = mkconstsv(aTHX_ newSVpvf("In %"SVf": no such named parameter: ", SVfARG(declarator)));
1461                                         msg = newBINOP(OP_CONCAT, 0, msg, keys);
1462
1463                                         croak = newCVREF(
1464                                                 OPf_WANT_SCALAR,
1465                                                 newGVOP(OP_GV, 0, gv_fetchpvs("Carp::croak", 0, SVt_PVCV))
1466                                         );
1467                                         croak = newUNOP(OP_ENTERSUB, OPf_STACKED, op_append_elem(OP_LIST, msg, croak));
1468
1469                                         cond = newUNOP(OP_KEYS, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1470                                         croak = newCONDOP(0, cond, croak, NULL);
1471
1472                                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, croak));
1473                                 } else {
1474                                         OP *clear;
1475
1476                                         clear = newASSIGNOP(
1477                                                 OPf_STACKED,
1478                                                 my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash),
1479                                                 0,
1480                                                 newNULLLIST()
1481                                         );
1482
1483                                         *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, clear));
1484                                 }
1485                         } else if (param_spec->slurpy.padoff != param_spec->rest_hash) {
1486                                 OP *var, *clear;
1487
1488                                 assert(SvPV_nolen(param_spec->slurpy.name)[0] == '@');
1489
1490                                 var = my_var_g(
1491                                         aTHX_
1492                                         OP_PADAV,
1493                                         OPf_MOD | (OPpLVAL_INTRO << 8),
1494                                         param_spec->slurpy.padoff
1495                                 );
1496
1497                                 var = newASSIGNOP(OPf_STACKED, var, 0, my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash));
1498
1499                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, var));
1500
1501                                 clear = newASSIGNOP(
1502                                         OPf_STACKED,
1503                                         my_var_g(aTHX_ OP_PADHV, 0, param_spec->rest_hash),
1504                                         0,
1505                                         newNULLLIST()
1506                                 );
1507
1508                                 *prelude_sentinel = op_append_list(OP_LINESEQ, *prelude_sentinel, newSTATEOP(0, NULL, clear));
1509                         }
1510                 }
1511         }
1512
1513         /* finally let perl parse the actual subroutine body */
1514         body = parse_block(0);
1515
1516         /* add '();' to make function return nothing by default */
1517         /* (otherwise the invisible parameter initialization can "leak" into
1518            the return value: fun ($x) {}->("asdf", 0) == 2) */
1519         if (*prelude_sentinel) {
1520                 body = newSTATEOP(0, NULL, body);
1521         }
1522
1523         body = op_append_list(OP_LINESEQ, *prelude_sentinel, body);
1524         *prelude_sentinel = NULL;
1525
1526         /* it's go time. */
1527         {
1528                 OP *const attrs = *attrs_sentinel;
1529                 *attrs_sentinel = NULL;
1530                 SvREFCNT_inc_simple_void(PL_compcv);
1531
1532                 /* close outer block: '}' */
1533                 S_block_end(aTHX_ save_ix, body);
1534
1535                 if (!saw_name) {
1536                         *pop = newANONATTRSUB(
1537                                 floor_ix,
1538                                 proto ? newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(proto)) : NULL,
1539                                 attrs,
1540                                 body
1541                         );
1542                         return KEYWORD_PLUGIN_EXPR;
1543                 }
1544
1545                 newATTRSUB(
1546                         floor_ix,
1547                         newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(saw_name)),
1548                         proto ? newSVOP(OP_CONST, 0, SvREFCNT_inc_simple_NN(proto)) : NULL,
1549                         attrs,
1550                         body
1551                 );
1552                 *pop = newOP(OP_NULL, 0);
1553                 return KEYWORD_PLUGIN_STMT;
1554         }
1555 }
1556
1557 static int my_keyword_plugin(pTHX_ char *keyword_ptr, STRLEN keyword_len, OP **op_ptr) {
1558         KWSpec spec;
1559         int ret;
1560         Sentinel sen = { NULL };
1561
1562         ENTER;
1563         SAVETMPS;
1564
1565         SAVEDESTRUCTOR_X(sentinel_clear_void, sen);
1566
1567         if (kw_flags(aTHX_ sen, keyword_ptr, keyword_len, &spec)) {
1568                 ret = parse_fun(aTHX_ sen, op_ptr, keyword_ptr, keyword_len, &spec);
1569         } else {
1570                 ret = next_keyword_plugin(aTHX_ keyword_ptr, keyword_len, op_ptr);
1571         }
1572
1573         FREETMPS;
1574         LEAVE;
1575
1576         return ret;
1577 }
1578
1579 WARNINGS_RESET
1580
1581 MODULE = Function::Parameters   PACKAGE = Function::Parameters
1582 PROTOTYPES: ENABLE
1583
1584 BOOT:
1585 WARNINGS_ENABLE {
1586         HV *const stash = gv_stashpvs(MY_PKG, GV_ADD);
1587         /**/
1588         newCONSTSUB(stash, "FLAG_NAME_OK",      newSViv(FLAG_NAME_OK));
1589         newCONSTSUB(stash, "FLAG_ANON_OK",      newSViv(FLAG_ANON_OK));
1590         newCONSTSUB(stash, "FLAG_DEFAULT_ARGS", newSViv(FLAG_DEFAULT_ARGS));
1591         newCONSTSUB(stash, "FLAG_CHECK_NARGS",  newSViv(FLAG_CHECK_NARGS));
1592         newCONSTSUB(stash, "FLAG_INVOCANT",     newSViv(FLAG_INVOCANT));
1593         newCONSTSUB(stash, "FLAG_NAMED_PARAMS", newSViv(FLAG_NAMED_PARAMS));
1594         newCONSTSUB(stash, "HINTK_KEYWORDS", newSVpvs(HINTK_KEYWORDS));
1595         newCONSTSUB(stash, "HINTK_FLAGS_",   newSVpvs(HINTK_FLAGS_));
1596         newCONSTSUB(stash, "HINTK_SHIFT_",   newSVpvs(HINTK_SHIFT_));
1597         newCONSTSUB(stash, "HINTK_ATTRS_",   newSVpvs(HINTK_ATTRS_));
1598         /**/
1599         next_keyword_plugin = PL_keyword_plugin;
1600         PL_keyword_plugin = my_keyword_plugin;
1601 } WARNINGS_RESET