Debian Codegraph @

src/infix.c

raw
1 /* You may distribute under the terms of either the GNU General Public License
2 * or the Artistic License (the same terms as Perl itself)
3 *
4 * (C) Paul Evans, 2021-2026 -- [email protected]
5 */
6
7 #include "EXTERN.h"
8 #include "perl.h"
9 #include "XSUB.h"
10
11 #include "XSParseInfix.h"
12
13 #include "infix.h"
14
15 #include "perl-backcompat.c.inc"
16 #include "optree-additions.c.inc"
17
18 #include "force_list_keeping_pushmark.c.inc"
19 #include "make_argcheck_ops.c.inc"
20 #include "newOP_CUSTOM.c.inc"
21 #include "op_sibling_splice.c.inc"
22
23 #if HAVE_PERL_VERSION(5,37,7)
24 # define HAVE_PL_INFIX_PLUGIN
25 #endif
26
27 #if HAVE_PERL_VERSION(5,32,0)
28 # define HAVE_OP_ISA
29 #endif
30
31 #if HAVE_PERL_VERSION(5,22,0)
32 /* assert() can be used as an expression */
33 # define HAVE_ASSERT_AS_EXPRESSION
34 #endif
35
36 #if HAVE_PERL_VERSION(5,45,3)
37 # define HAVE_UNDEF_AWARE_EQUALITY
38 #endif
39
40 /* These only became full API macros at perl v5.22, but they're available as
41 * the full Perl_... name before that
42 */
43 #ifndef block_start
44 # define block_start(a) Perl_block_start(aTHX_ a)
45 #endif
46
47 #ifndef block_end
48 # define block_end(a,b) Perl_block_end(aTHX_ a,b)
49 #endif
50
51 #ifndef XS_INTERNAL
52 /* copypasta from perl-v5.16.0/XSUB.h */
53 # if defined(__CYGWIN__) && defined(USE_DYNAMIC_LOADING)
54 # define XS_INTERNAL(name) STATIC XSPROTO(name)
55 # endif
56 # if defined(__SYMBIAN32__)
57 # define XS_INTERNAL(name) EXPORT_C STATIC XSPROTO(name)
58 # endif
59 # ifndef XS_INTERNAL
60 # if defined(HASATTRIBUTE_UNUSED) && !defined(__cplusplus)
61 # define XS_INTERNAL(name) STATIC void name(pTHX_ CV* cv __attribute__unused__)
62 # else
63 # ifdef __cplusplus
64 # define XS_INTERNAL(name) static XSPROTO(name)
65 # else
66 # define XS_INTERNAL(name) STATIC XSPROTO(name)
67 # endif
68 # endif
69 # endif
70 #endif
71
72 struct HooksAndData {
73 const struct XSParseInfixHooks *hooks;
74 void *data;
75 };
76
77 enum OperandShape {
78 SHAPE_SCALARSCALAR,
79 SHAPE_SCALARLIST,
80 SHAPE_LISTLIST,
81 SHAPE_LISTASSOC_SCALARS,
82 SHAPE_LISTASSOC_LISTS,
83 };
84
85 static enum OperandShape operand_shape(const struct HooksAndData *hd)
86 {
87 U8 lhs_gimme;
88 switch(hd->hooks->lhs_flags & 0x07) {
89 case 0:
90 lhs_gimme = G_SCALAR;
91 break;
92
93 case XPI_OPERAND_TERM_LIST:
94 case XPI_OPERAND_LIST:
95 lhs_gimme = G_LIST;
96 break;
97
98 default:
99 croak("TODO: Unsure how to classify operand shape of .lhs_flags=%02X\n",
100 hd->hooks->lhs_flags & 0x07);
101 }
102
103 if(hd->hooks->flags & XPI_FLAG_LISTASSOC) {
104 switch(lhs_gimme) {
105 case G_SCALAR:
106 return SHAPE_LISTASSOC_SCALARS;
107
108 case G_LIST:
109 return SHAPE_LISTASSOC_LISTS;
110 }
111 }
112
113 U8 rhs_gimme;
114 switch(hd->hooks->rhs_flags & 0x07) {
115 case 0:
116 rhs_gimme = G_SCALAR;
117 break;
118
119 case XPI_OPERAND_TERM_LIST:
120 case XPI_OPERAND_LIST:
121 rhs_gimme = G_LIST;
122 break;
123
124 default:
125 croak("TODO: Unsure how to classify operand shape of .rhs_flags=%02X\n",
126 hd->hooks->rhs_flags & 0x07);
127 }
128
129 switch((lhs_gimme << 4) | (rhs_gimme)) {
130 /* scalar OP scalar */
131 case (G_SCALAR<<4) | G_SCALAR:
132 return SHAPE_SCALARSCALAR;
133
134 /* scalar OP list */
135 case (G_SCALAR<<4) | G_LIST:
136 return SHAPE_SCALARLIST;
137
138 /* list OP list */
139 case (G_LIST<<4) | G_LIST:
140 return SHAPE_LISTLIST;
141
142 default:
143 croak("TODO: Unsure how to classify operand shape of lhs_gimme=%d rhs_gimme=%d\n",
144 lhs_gimme, rhs_gimme);
145 break;
146 }
147 }
148
149 struct Registration;
150 struct Registration {
151 #ifdef HAVE_PL_INFIX_PLUGIN
152 struct Perl_custom_infix def; /* must be first */
153 #endif
154
155 struct Registration *next;
156 struct XSParseInfixInfo info;
157
158 STRLEN oplen;
159
160 struct HooksAndData hd;
161
162 STRLEN permit_hintkey_len;
163
164 int opname_is_WIDE : 1;
165 int opname_is_ident : 1;
166 int opname_is_fq : 1;
167 };
168
169 static struct Registration *registrations, /* for legacy-style global key-enabled ones */
170 *fqregistrations; /* for new lexically named ones */
171
172 static OP *new_op(pTHX_ const struct HooksAndData hd, U32 flags, OP *lhs, OP *rhs, SV **parsedata)
173 {
174 if(hd.hooks->new_op) {
175 if(hd.hooks->flags & (1<<15)) {
176 OP *(*new_op_v1)(pTHX_ U32, OP *, OP *, void *) = (OP *(*)(pTHX_ U32, OP *, OP *, void *))hd.hooks->new_op;
177 return (*new_op_v1)(aTHX_ flags, lhs, rhs, hd.data); /* no parsedata */
178 }
179
180 return (*hd.hooks->new_op)(aTHX_ flags, lhs, rhs, parsedata, hd.data);
181 }
182
183 assert(hd.hooks->ppaddr);
184
185 OP *ret;
186 if(hd.hooks->flags & XPI_FLAG_LISTASSOC) {
187 OP *listop = lhs;
188 /* Skip an ex-list + pushmark structure */
189 if(listop->op_type == OP_NULL && cUNOPx(listop)->op_first &&
190 cUNOPx(listop)->op_first->op_type == OP_PUSHMARK)
191 listop = OpSIBLING(cUNOPx(listop)->op_first);
192
193 if(listop &&
194 listop->op_type == OP_CUSTOM && listop->op_ppaddr == hd.hooks->ppaddr &&
195 !(listop->op_flags & OPf_PARENS)) {
196 /* combine new operand with existing listop */
197 if(listop->op_private == 255)
198 croak("TODO: Unable to handle a list-associative infix operator with > 255 operands");
199
200 OP *last = cLISTOPx(listop)->op_last;
201 OpMORESIB_set(last, rhs);
202 cLISTOPx(listop)->op_last = rhs;
203 OpLASTSIB_set(rhs, listop);
204
205 listop->op_private++;
206
207 ret = lhs;
208 }
209 else {
210 /* base case */
211 ret = newLISTOP_CUSTOM(hd.hooks->ppaddr, flags, lhs, rhs);
212 ret->op_private = 2;
213 }
214 }
215 else
216 ret = newBINOP_CUSTOM(hd.hooks->ppaddr, flags, lhs, rhs);
217
218 /* TODO: opchecker? */
219
220 return ret;
221 }
222
223 static bool op_extract_onerefgen(OP *o, OP **kidp)
224 {
225 OP *first;
226 switch(o->op_type) {
227 case OP_SREFGEN:
228 first = cUNOPo->op_first;
229 if(first->op_type == OP_NULL && first->op_targ == OP_LIST &&
230 (*kidp = cLISTOPx(first)->op_first))
231 return TRUE;
232 break;
233
234 case OP_REFGEN:
235 first = cUNOPo->op_first;
236 if(first->op_type == OP_NULL && first->op_targ == OP_LIST &&
237 #ifdef HAVE_ASSERT_AS_EXPRESSION
238 (assert(cLISTOPx(first)->op_first->op_type == OP_PUSHMARK), 1) &&
239 #endif
240 (*kidp = OpSIBLING(cLISTOPx(first)->op_first)) &&
241 !OpSIBLING(*kidp))
242 return TRUE;
243
244 op_dump(first);
245 }
246
247 return FALSE;
248 }
249
250 #define unwrap_list(o, may_unwrap_anonlist) S_unwrap_list(aTHX_ o, may_unwrap_anonlist)
251 static OP *S_unwrap_list(pTHX_ OP *o, bool may_unwrap_anonlist)
252 {
253 OP *kid;
254
255 /* Look out for some sort of \THING */
256 if(op_extract_onerefgen(o, &kid)) {
257 if(kid->op_type == OP_PADAV) {
258 /* \@padav can just yield the array directly */
259 cLISTOPx(cUNOPo->op_first)->op_first = NULL;
260 cLISTOPx(cUNOPo->op_first)->op_flags &= ~OPf_KIDS;
261 op_free(o);
262
263 kid->op_flags &= ~(OPf_MOD|OPf_REF);
264 return force_list_keeping_pushmark(kid);
265 }
266 if(kid->op_type == OP_RV2AV) {
267 /* we can just yield this op directly at this point. It might be \@pkgav
268 * or something else, but whatever it is we might as well do it
269 */
270 cLISTOPx(cUNOPo->op_first)->op_first = NULL;
271 cLISTOPx(cUNOPo->op_first)->op_flags &= ~OPf_KIDS;
272 op_free(o);
273
274 kid->op_flags &= ~(OPf_MOD|OPf_REF);
275 return force_list_keeping_pushmark(kid);
276 }
277 }
278
279 /* We might be permitted to unwrap a [THING] */
280 if(may_unwrap_anonlist &&
281 o->op_type == OP_ANONLIST) {
282 /* Just turn it into a list and we're already done */
283 o->op_type = OP_LIST;
284 return force_list_keeping_pushmark(o);
285 }
286
287 return force_list_keeping_pushmark(newUNOP(OP_RV2AV, 0, o));
288 }
289
290 enum {
291 FINDREG_SKIP_BUILTIN = (1<<0),
292 };
293
294 #define find_reg(op, oplen, regp, flags) S_find_reg(aTHX_ op, oplen, regp, flags)
295 static STRLEN S_find_reg(pTHX_ const char *op, STRLEN oplen, struct Registration **regp, U32 flags)
296 {
297 HV *hints = GvHV(PL_hintgv);
298
299 /* New-style lexically named operators */
300 {
301 bool opname_is_ident = isIDFIRST_utf8_safe(op, op + oplen);
302
303 SV *keysv = sv_newmortal();
304 for(int len = oplen; len > 0; len--) {
305 sv_setpvf(keysv, "XS::Parse::Infix/%.*s", len, op);
306 HE *ophe = hv_fetch_ent(hints, keysv, 0, 0);
307 if(!ophe && opname_is_ident)
308 break;
309 if(!ophe)
310 continue;
311
312 /* We found something suitable. Commit to this or fail */
313
314 char *fqop = SvPVX(HeVAL(ophe));
315 STRLEN fqoplen = SvCUR(HeVAL(ophe));
316
317 for(struct Registration *reg = fqregistrations; reg; reg = reg->next) {
318 if(!reg->hd.hooks)
319 continue;
320
321 if(reg->oplen != fqoplen || !strEQ(reg->info.opname, fqop))
322 continue;
323
324 if(reg->hd.hooks->permit &&
325 !(*reg->hd.hooks->permit)(aTHX_ reg->hd.data))
326 continue;
327
328 *regp = reg;
329 return len;
330 }
331
332 croak("XS::Parse::Infix does not know of a registered infix operator named '%" SVf "'",
333 SVfARG(HeVAL(ophe)));
334 }
335 }
336
337 /* Legacy hinthash-enabled global operators */
338 struct Registration *reg, *bestreg = NULL;
339 for(reg = registrations; reg; reg = reg->next) {
340 /* custom registrations have hooks, builtin ones do not */
341 if((flags & FINDREG_SKIP_BUILTIN) && !reg->hd.hooks)
342 continue;
343
344 if(reg->oplen > oplen || !strnEQ(reg->info.opname, op, reg->oplen))
345 continue;
346 /* names like identifiers must match the whole length */
347 if(reg->opname_is_ident && reg->oplen != oplen)
348 continue;
349
350 if(reg->hd.hooks && reg->hd.hooks->permit_hintkey &&
351 (!hints || !hv_fetch(hints, reg->hd.hooks->permit_hintkey, reg->permit_hintkey_len, 0)))
352 continue;
353
354 if(reg->hd.hooks && reg->hd.hooks->permit &&
355 !(*reg->hd.hooks->permit)(aTHX_ reg->hd.data))
356 continue;
357
358 /* This is a candidate and the best one, unless we already have something
359 * longer
360 */
361 if(bestreg && bestreg->oplen > reg->oplen)
362 continue;
363
364 bestreg = reg;
365 }
366
367 if(!bestreg)
368 return 0;
369
370 *regp = bestreg;
371 return bestreg->oplen;
372 }
373
374 #ifdef HAVE_PL_INFIX_PLUGIN
375
376 static void parse(pTHX_ SV **parsedata, struct Perl_custom_infix *def)
377 {
378 struct Registration *reg = (struct Registration *)def;
379
380 (*reg->hd.hooks->parse)(aTHX_ 0, parsedata, reg->hd.data);
381 }
382
383 static OP *build_op(pTHX_ SV **parsedata, OP *lhs, OP *rhs, struct Perl_custom_infix *def)
384 {
385 struct Registration *reg = (struct Registration *)def;
386
387 switch(reg->hd.hooks->lhs_flags & 0x07) {
388 case 0:
389 break;
390
391 case XPI_OPERAND_TERM_LIST:
392 case XPI_OPERAND_LIST:
393 lhs = force_list_keeping_pushmark(lhs);
394 break;
395 }
396
397 /* TODO: maybe operator has a 'parse' hook? */
398
399 switch(reg->hd.hooks->rhs_flags & 0x07) {
400 case 0:
401 break;
402
403 case XPI_OPERAND_TERM_LIST:
404 case XPI_OPERAND_LIST:
405 rhs = force_list_keeping_pushmark(rhs);
406 break;
407 }
408
409 return new_op(aTHX_ reg->hd, 0, lhs, rhs, parsedata);
410 }
411
412 static STRLEN (*next_infix_plugin)(pTHX_ char *, STRLEN, struct Perl_custom_infix **);
413
414 static STRLEN my_infix_plugin(pTHX_ char *op, STRLEN oplen, struct Perl_custom_infix **def)
415 {
416 if(PL_parser && PL_parser->error_count)
417 return (*next_infix_plugin)(aTHX_ op, oplen, def);
418
419 struct Registration *reg = NULL;
420 STRLEN consumed = find_reg(op, oplen, &reg, FINDREG_SKIP_BUILTIN);
421 if(!consumed)
422 return (*next_infix_plugin)(aTHX_ op, oplen, def);
423
424 *def = &reg->def;
425 return consumed;
426 }
427 #endif
428
429 /* What classifications are included in what selections? */
430 static const U32 infix_selections[] = {
431 [XPI_SELECT_ANY] = 0xFFFFFFFF,
432
433 [XPI_SELECT_PREDICATE] = (1<<XPI_CLS_PREDICATE)|(1<<XPI_CLS_RELATION)|(1<<XPI_CLS_EQUALITY),
434 [XPI_SELECT_RELATION] = (1<<XPI_CLS_RELATION)|(1<<XPI_CLS_EQUALITY),
435 [XPI_SELECT_EQUALITY] = (1<<XPI_CLS_EQUALITY),
436
437 [XPI_SELECT_ORDERING] = (1<<XPI_CLS_ORDERING),
438
439 [XPI_SELECT_MATCH_NOSMART] = (1<<XPI_CLS_EQUALITY)|(1<<XPI_CLS_MATCHRE)|(1<<XPI_CLS_ISA)|(1<<XPI_CLS_MATCH_MISC),
440 [XPI_SELECT_MATCH_SMART] = (1<<XPI_CLS_EQUALITY)|(1<<XPI_CLS_MATCHRE)|(1<<XPI_CLS_ISA)|(1<<XPI_CLS_MATCH_MISC)|
441 (1<<XPI_CLS_SMARTMATCH),
442 };
443
444 bool XSParseInfix_parse(pTHX_ enum XSParseInfixSelection select, struct XSParseInfixInfo **infop)
445 {
446 /* PL_parser->bufptr now points exactly at where we expect to find an operator name */
447
448 int selection = infix_selections[select];
449
450 HV *hints = GvHV(PL_hintgv);
451
452 const char *op = PL_parser->bufptr, *opend;
453
454 if(isIDFIRST_utf8_safe(op, PL_parser->bufend)) {
455 /* If the operator name is an identifer then we don't want to capture a
456 * longer identifier from the incoming source of which this is just a
457 * prefix
458 */
459 opend = op + UTF8SKIP(op);
460 while(opend < PL_parser->bufend && isIDCONT_utf8_safe(opend, PL_parser->bufend))
461 opend += UTF8SKIP(opend);
462 }
463 else {
464 opend = PL_parser->bufend;
465 }
466
467 struct Registration *reg = NULL;
468 STRLEN consumed = find_reg(op, opend - op, &reg, 0);
469 if(!consumed)
470 return FALSE;
471
472 if(!(selection & (1 << reg->info.cls)))
473 return FALSE;
474
475 *infop = &reg->info;
476
477 lex_read_to(PL_parser->bufptr + consumed);
478 return TRUE;
479 }
480
481 OP *XSParseInfix_new_op(pTHX_ const struct XSParseInfixInfo *info, U32 flags, OP *lhs, OP *rhs)
482 {
483 if(info->opcode == OP_CUSTOM)
484 return new_op(aTHX_ (struct HooksAndData) {
485 .hooks = info->hooks,
486 .data = info->hookdata,
487 }, flags, lhs, rhs, NULL);
488
489 return newBINOP(info->opcode, flags, lhs, rhs);
490 }
491
492 static bool op_yields_oneval(OP *o)
493 {
494 if(OP_GIMME(o, 0) == G_SCALAR)
495 return TRUE;
496
497 if(PL_opargs[o->op_type] & OA_RETSCALAR)
498 return TRUE;
499
500 /* It might still yield a single value, we'll just have to check harder */
501 switch(o->op_type) {
502 case OP_REFGEN:
503 {
504 OP *list = cUNOPo->op_first;
505 OP *kid;
506 assert(cLISTOPx(list)->op_first->op_type == OP_PUSHMARK);
507 if((kid = OpSIBLING(cLISTOPx(list)->op_first)) &&
508 !OpSIBLING(kid) &&
509 (kid->op_flags & OPf_REF))
510 return TRUE;
511 }
512 }
513
514 return FALSE;
515 }
516
517 static bool extract_wrapper2_args(pTHX_ OP *op, OP **leftp, OP **rightp)
518 {
519 assert(op->op_type == OP_ENTERSUB);
520
521 /* Attempt to extract the LHS and RHS operands, if we can find them */
522
523 OP *kid = cUNOPx(op)->op_first;
524 /* The first kid is usually an ex-list whose ->op_first begins the actual args list */
525 if(kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
526 kid = cUNOPx(kid)->op_first;
527
528 assert(kid->op_type == OP_PUSHMARK);
529 OP *pushmark = kid;
530
531 OP *left = OpSIBLING(kid);
532 if(!left)
533 return FALSE;
534 if(!op_yields_oneval(left))
535 return FALSE;
536
537 OP *right = OpSIBLING(left);
538 if(!right)
539 return FALSE;
540 if(!op_yields_oneval(right))
541 return FALSE;
542
543 kid = OpSIBLING(right);
544 if(!kid)
545 return FALSE;
546 if(OpSIBLING(kid))
547 return FALSE;
548
549 /* Check that kid is now OP_NULL[ OP_GV ] */
550 if(kid->op_type != OP_NULL || kid->op_targ != OP_RV2CV)
551 return FALSE;
552 if(cUNOPx(kid)->op_first->op_type != OP_GV)
553 return FALSE;
554
555 /* Splice out these two args and throw away the old optree */
556 OpMORESIB_set(left, NULL);
557 OpMORESIB_set(right, NULL);
558 OpMORESIB_set(pushmark, kid);
559 op_free(op);
560
561 OpLASTSIB_set(left, NULL);
562 OpLASTSIB_set(right, NULL);
563
564 *leftp = left;
565 *rightp = right;
566 return TRUE;
567 }
568
569 static OP *ckcall_wrapper_func_scalarscalar(pTHX_ OP *op, GV *namegv, SV *ckobj)
570 {
571 struct HooksAndData *hd = NUM2PTR(struct HooksAndData *, SvUV(ckobj));
572
573 OP *left, *right;
574 if(!extract_wrapper2_args(aTHX_ op, &left, &right))
575 return op;
576
577 return new_op(aTHX_ *hd, 0, left, right, NULL);
578 }
579
580 static OP *ckcall_wrapper_func_listlist(pTHX_ OP *op, GV *namegv, SV *ckobj)
581 {
582 struct HooksAndData *hd = NUM2PTR(struct HooksAndData *, SvUV(ckobj));
583
584 OP *left, *right;
585 if(!extract_wrapper2_args(aTHX_ op, &left, &right))
586 return op;
587
588 return new_op(aTHX_ *hd, 0,
589 unwrap_list(left, hd->hooks->lhs_flags & XPI_OPERAND_ONLY_LOOK),
590 unwrap_list(right, hd->hooks->rhs_flags & XPI_OPERAND_ONLY_LOOK),
591 NULL);
592 }
593
594 static OP *ckcall_wrapper_func_listassoc_scalars(pTHX_ OP *op, GV *namegv, SV *ckobj)
595 {
596 struct HooksAndData *hd = NUM2PTR(struct HooksAndData *, SvUV(ckobj));
597
598 /* We'll convert this if it looks like a compiletime-constant number of
599 * scalar arguments
600 */
601 assert(op->op_type == OP_ENTERSUB);
602
603 OP *kid = cUNOPx(op)->op_first;
604 /* The first kid is usually an ex-list whose ->op_first begins the actual args list */
605 if(kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
606 kid = cUNOPx(kid)->op_first;
607
608 assert(kid->op_type == OP_PUSHMARK);
609 OP *pushmark = kid;
610
611 kid = OpSIBLING(kid);
612 OP *firstarg = kid, *lastarg;
613
614 int argcount = 0;
615 OP *nextkid;
616 while(kid && (nextkid = OpSIBLING(kid))) {
617 if(!op_yields_oneval(kid))
618 goto no_wrapper;
619
620 argcount++;
621 lastarg = kid;
622 kid = nextkid;
623 }
624 /* kid now points at final op which is the gvop of the OP_ENTERSUB */
625
626 if(!argcount) {
627 op_free(op);
628 return newLISTOP_CUSTOM(hd->hooks->ppaddr, 0, NULL, NULL);
629 }
630
631 /* Splice out the args list and throw away the old optree */
632 OpMORESIB_set(pushmark, kid);
633 op_free(op);
634
635 /* newLISTOP_CUSTOM doesn't quite handle already created child op chains. We
636 * must pass in NULL then set the child ops manually */
637 op = newLISTOP_CUSTOM(hd->hooks->ppaddr, 0, NULL, NULL);
638 op->op_private = argcount;
639
640 op->op_flags |= OPf_KIDS;
641 cLISTOPx(op)->op_first = firstarg;
642 cLISTOPx(op)->op_last = lastarg;
643 OpLASTSIB_set(lastarg, op);
644
645 return op;
646
647 no_wrapper:
648 op = ck_entersub_args_proto_or_list(op, namegv, &PL_sv_undef);
649 return op;
650 }
651
652 static OP *ckcall_wrapper_func_listassoc_lists(pTHX_ OP *op, GV *namegv, SV *ckobj)
653 {
654 struct HooksAndData *hd = NUM2PTR(struct HooksAndData *, SvUV(ckobj));
655
656 /* We'll convert this if it looks like a compiletime-constant number of
657 * scalar arguments
658 */
659 assert(op->op_type == OP_ENTERSUB);
660
661 OP *kid = cUNOPx(op)->op_first;
662 /* The first kid is usually an ex-list whose ->op_first begins the actual args list */
663 if(kid->op_type == OP_NULL && kid->op_targ == OP_LIST)
664 kid = cUNOPx(kid)->op_first;
665
666 assert(kid->op_type == OP_PUSHMARK);
667 OP *pushmark = kid;
668
669 kid = OpSIBLING(kid);
670 OP *firstarg = kid, *lastarg;
671
672 int argcount = 0;
673 OP *nextkid;
674 while(kid && (nextkid = OpSIBLING(kid))) {
675 if(!op_yields_oneval(kid))
676 goto no_wrapper;
677
678 argcount++;
679 lastarg = kid;
680 kid = nextkid;
681 }
682 /* kid now points at final op which is the gvop of the OP_ENTERSUB */
683
684 if(!argcount) {
685 op_free(op);
686 return newLISTOP_CUSTOM(hd->hooks->ppaddr, 0, NULL, NULL);
687 }
688
689 /* Splice out the args list and throw away the old optree */
690 OpMORESIB_set(pushmark, kid);
691 OpLASTSIB_set(lastarg, NULL);
692 op_free(op);
693
694 /* We now need to unwrap_list() on each of the args ops */
695
696 kid = firstarg;
697 firstarg = NULL;
698 lastarg = NULL;
699 while(kid) {
700 OP *nextkid = OpSIBLING(kid);
701 OpLASTSIB_set(kid, NULL);
702
703 OP *newkid = unwrap_list(kid, hd->hooks->lhs_flags & XPI_OPERAND_ONLY_LOOK);
704
705 if(lastarg)
706 OpMORESIB_set(lastarg, newkid);
707
708 if(!firstarg)
709 firstarg = newkid;
710 lastarg = newkid;
711
712 kid = nextkid;
713 }
714
715 /* newLISTOP_CUSTOM doesn't quite handle already created child op chains. We
716 * must pass in NULL and then set the child ops manually */
717 op = newLISTOP_CUSTOM(hd->hooks->ppaddr, 0, NULL, NULL);
718 op->op_private = argcount;
719
720 op->op_flags |= OPf_KIDS;
721 cLISTOPx(op)->op_first = firstarg;
722 cLISTOPx(op)->op_last = lastarg;
723 OpLASTSIB_set(lastarg, op);
724
725 return op;
726
727 no_wrapper:
728 op = ck_entersub_args_proto_or_list(op, namegv, &PL_sv_undef);
729 return op;
730 }
731
732 static OP *pp_push_defav_with_count(pTHX)
733 {
734 dSP;
735 AV *defav = GvAV(PL_defgv);
736 bool explode = (PL_op->op_flags & OPf_SPECIAL);
737
738 U32 count = av_count(defav);
739 SV **svp = AvARRAY(defav);
740 if(!explode)
741 EXTEND(SP, count);
742 for(U32 i = 0; i < count; i++)
743 if(explode) {
744 if(!SvROK(svp[i]) || SvTYPE(SvRV(svp[i])) != SVt_PVAV)
745 croak("Expected an ARRAY reference, got %" SVf, SVfARG(svp[i]));
746 AV *av = (AV *)SvRV(svp[i]);
747 PUSHMARK(SP);
748 U32 acount = av_count(av);
749 SV **asvp = AvARRAY(av);
750 EXTEND(SP, acount);
751 for(U32 i = 0; i < acount; i++)
752 PUSHs(asvp[i]);
753 }
754 else
755 PUSHs(svp[i]);
756
757 mXPUSHu(count);
758
759 RETURN;
760 }
761
762 static void make_wrapper_func(pTHX_ const struct HooksAndData *hd)
763 {
764 SV *funcname = newSVpvn(hd->hooks->wrapper_func_name, strlen(hd->hooks->wrapper_func_name));
765
766 GV *gv;
767 if((gv = gv_fetchsv(funcname, 0, 0)) && GvCV(gv)) {
768 /* The wrapper function already exists. We presume this is due to a duplicate
769 * registration of identical hooks under a different name and just skip
770 */
771 return;
772 }
773
774 /* Prepare to make a new optree-based CV */
775 I32 floor_ix = start_subparse(FALSE, 0);
776 SAVEFREESV(PL_compcv);
777
778 I32 save_ix = block_start(TRUE);
779
780 OP *body = NULL;
781 OP *(*ckcall)(pTHX_ OP *, GV *, SV *) = NULL;
782
783 switch(operand_shape(hd)) {
784 case SHAPE_SCALARSCALAR:
785 body = op_append_list(OP_LINESEQ, body,
786 make_argcheck_ops(2, 0, 0, funcname));
787
788 body = op_append_list(OP_LINESEQ, body,
789 newSTATEOP(0, NULL, NULL));
790
791 /* Body of the function is just $_[0] OP $_[1] */
792 body = op_append_list(OP_LINESEQ, body,
793 new_op(aTHX_ *hd, 0, newSLUGOP(0), newSLUGOP(1), NULL));
794
795 ckcall = &ckcall_wrapper_func_scalarscalar;
796 break;
797
798 case SHAPE_SCALARLIST:
799 body = op_append_list(OP_LINESEQ, body,
800 make_argcheck_ops(1, 0, '@', funcname));
801
802 body = op_append_list(OP_LINESEQ, body,
803 newSTATEOP(0, NULL, NULL));
804
805 /* Body of the function is just shift OP @_ */
806 body = op_append_list(OP_LINESEQ, body,
807 new_op(aTHX_ *hd, 0,
808 newOP(OP_SHIFT, 0),
809 force_list_keeping_pushmark(newUNOP(OP_RV2AV, OPf_WANT_LIST, newGVOP(OP_GV, 0, PL_defgv))),
810 NULL));
811
812 /* no ckcall */
813 break;
814
815 case SHAPE_LISTLIST:
816 body = op_append_list(OP_LINESEQ, body,
817 make_argcheck_ops(2, 0, 0, funcname));
818
819 body = op_append_list(OP_LINESEQ, body,
820 newSTATEOP(0, NULL, NULL));
821
822 /* Body of the function is @{ $_[0] } OP @{ $_[1] } */
823 body = op_append_list(OP_LINESEQ, body,
824 new_op(aTHX_ *hd, 0,
825 force_list_keeping_pushmark(newUNOP(OP_RV2AV, 0, newSLUGOP(0))),
826 force_list_keeping_pushmark(newUNOP(OP_RV2AV, 0, newSLUGOP(1))),
827 NULL));
828
829 ckcall = &ckcall_wrapper_func_listlist;
830 break;
831
832 case SHAPE_LISTASSOC_SCALARS:
833 if(hd->hooks->new_op)
834 croak("TODO: Cannot make wrapper func for list-associative operator that has hooks->new_op");
835
836 body = op_append_list(OP_LINESEQ, body,
837 newSTATEOP(0, NULL, NULL));
838
839 /* Body of the function invokes the op with the values from @_, and an extra IV giving the count */
840 body = op_append_list(OP_LINESEQ, body,
841 newLISTOP_CUSTOM(hd->hooks->ppaddr, OPf_STACKED,
842 newOP_CUSTOM(&pp_push_defav_with_count, 0),
843 NULL));
844
845 ckcall = &ckcall_wrapper_func_listassoc_scalars;
846 break;
847
848 case SHAPE_LISTASSOC_LISTS:
849 if(hd->hooks->new_op)
850 croak("TODO: Cannot make wrapper func for list-associative operator that has hooks->new_op");
851
852 body = op_append_list(OP_LINESEQ, body,
853 newSTATEOP(0, NULL, NULL));
854
855 /* Body of the function invokes the op with the values from all the
856 * ARRAYs refed by @_, plus marks on the markstack, and an extra IV
857 * giving the count */
858 body = op_append_list(OP_LINESEQ, body,
859 newLISTOP_CUSTOM(hd->hooks->ppaddr, OPf_STACKED /* explode */,
860 newOP_CUSTOM(&pp_push_defav_with_count, OPf_SPECIAL),
861 NULL));
862
863 ckcall = &ckcall_wrapper_func_listassoc_lists;
864 break;
865 }
866
867 SvREFCNT_inc(PL_compcv);
868 body = block_end(save_ix, body);
869
870 CV *cv = newATTRSUB(floor_ix, newSVOP(OP_CONST, 0, funcname), NULL, NULL, body);
871
872 if(ckcall)
873 cv_set_call_checker(cv, ckcall, newSVuv(PTR2UV(hd)));
874 }
875
876 XS_INTERNAL(deparse_infix);
877 XS_INTERNAL(deparse_infix)
878 {
879 dXSARGS;
880 struct Registration *reg = XSANY.any_ptr;
881
882 SV *deparseobj = ST(0);
883 SV *ret;
884
885 #ifdef HAVE_PL_INFIX_PLUGIN
886 SV **hinthashsvp = hv_fetchs(MUTABLE_HV(SvRV(deparseobj)), "hinthash", 0);
887 HV *hinthash = hinthashsvp ? MUTABLE_HV(SvRV(*hinthashsvp)) : NULL;
888
889 SV *opnamesv;
890
891 bool infix_is_visible = FALSE;
892 /* Operator visibility rules differ for fully-qualified operator names */
893 if(reg->opname_is_fq) {
894 hv_iterinit(hinthash);
895 HE *he;
896 while((he = hv_iternext(hinthash))) {
897 #define PREFIXLEN 17
898 STRLEN len;
899 if(!strnEQ(HePV(he, len), "XS::Parse::Infix/", PREFIXLEN))
900 continue;
901
902 if(!strEQ(SvPV_nolen(HeVAL(he)), reg->info.opname))
903 continue;
904
905 infix_is_visible = TRUE;
906 opnamesv = newSVpvn_flags(HePV(he, len) + PREFIXLEN, len - PREFIXLEN, HeUTF8(he) ? SVf_UTF8 : 0);
907 break;
908 }
909 }
910 else {
911 infix_is_visible = (hinthash && hv_fetch(hinthash, reg->hd.hooks->permit_hintkey, reg->permit_hintkey_len, 0));
912 opnamesv = newSVpvn_flags(reg->info.opname, reg->oplen, reg->opname_is_WIDE ? SVf_UTF8 : 0);
913 }
914
915 if(infix_is_visible) {
916 ENTER;
917 SAVETMPS;
918
919 EXTEND(SP, 4);
920 PUSHMARK(SP);
921 PUSHs(deparseobj);
922 mPUSHs(opnamesv);
923 PUSHs(ST(1));
924 PUSHs(ST(2));
925 PUTBACK;
926
927 call_method("_deparse_infix_named", G_SCALAR);
928
929 SPAGAIN;
930 ret = SvREFCNT_inc(POPs);
931
932 FREETMPS;
933 LEAVE;
934 }
935 else
936 #endif
937 {
938 ENTER;
939 SAVETMPS;
940
941 EXTEND(SP, 4);
942 PUSHMARK(SP);
943 PUSHs(deparseobj);
944 mPUSHp(reg->hd.hooks->wrapper_func_name, strlen(reg->hd.hooks->wrapper_func_name));
945 PUSHs(ST(1));
946 PUSHs(ST(2));
947 PUTBACK;
948
949 switch(operand_shape(&reg->hd)) {
950 case SHAPE_SCALARSCALAR:
951 case SHAPE_SCALARLIST: /* not really */
952 call_method("_deparse_infix_wrapperfunc_scalarscalar", G_SCALAR);
953 break;
954
955 case SHAPE_LISTLIST:
956 call_method("_deparse_infix_wrapperfunc_listlist", G_SCALAR);
957 break;
958 }
959
960 SPAGAIN;
961 ret = SvREFCNT_inc(POPs);
962
963 FREETMPS;
964 LEAVE;
965 }
966
967 ST(0) = sv_2mortal(ret);
968 XSRETURN(1);
969 }
970
971 static void reg_builtin(pTHX_ const char *opname, enum XSParseInfixClassification cls, OPCODE opcode)
972 {
973 struct Registration *reg;
974 Newx(reg, 1, struct Registration);
975
976 reg->info.opname = savepv(opname);
977 reg->info.opcode = opcode;
978 reg->info.hooks = NULL;
979 reg->info.cls = cls;
980
981 reg->oplen = strlen(opname);
982 reg->opname_is_ident = isIDFIRST_utf8_safe(opname, opname + strlen(opname));
983
984 reg->hd.hooks = NULL;
985 reg->hd.data = NULL;
986
987 reg->permit_hintkey_len = 0;
988
989 {
990 reg->next = registrations;
991 registrations = reg;
992 }
993 }
994
995 bool XSParseInfix_check_opname(pTHX_ const char *opname, STRLEN oplen)
996 {
997 const char *opname_end = opname + oplen;
998
999 bool opname_is_fq = strstr(opname, "::") != NULL;
1000 bool opname_is_ident = !opname_is_fq && isIDFIRST_utf8_safe(opname, opname_end);
1001
1002 const char *s = opname;
1003 s += UTF8SKIP(s);
1004
1005 while(s < opname_end) {
1006 if(opname_is_ident) {
1007 if(!isIDCONT_utf8_safe(s, opname_end))
1008 // name that starts with an identifier may not have non-identifier characters in it
1009 return FALSE;
1010 }
1011 else {
1012 if(isIDFIRST_utf8_safe(s, opname_end))
1013 // name that does not start with an identifer may not have identifier characters in it
1014 return FALSE;
1015 }
1016 s += UTF8SKIP(s);
1017 }
1018
1019 return TRUE;
1020 }
1021
1022 void XSParseInfix_register(pTHX_ const char *opname, const struct XSParseInfixHooks *hooks, void *hookdata)
1023 {
1024 STRLEN oplen = strlen(opname);
1025 const char *opname_end = opname + oplen;
1026 bool opname_is_fq = strstr(opname, "::") != NULL;
1027 bool opname_is_ident = !opname_is_fq && isIDFIRST_utf8_safe(opname, opname_end);
1028
1029 if(!opname_is_fq) {
1030 if(!XSParseInfix_check_opname(aTHX_ opname, oplen))
1031 croak("Infix operator name is invalid; must be an identifier or entirely non-identifier characters");
1032 }
1033
1034 bool is_listassoc = hooks->flags & XPI_FLAG_LISTASSOC;
1035 if(hooks->flags & ~(XPI_FLAG_LISTASSOC | (1<<15)))
1036 /* (1<<15) == undocumented internal flag to indicate v1-compatible ->new_op hook function */
1037 croak("Unrecognised XSParseInfixHooks.flags value 0x%X", hooks->flags);
1038
1039 switch(hooks->lhs_flags & ~(XPI_OPERAND_ONLY_LOOK)) {
1040 case 0:
1041 case XPI_OPERAND_TERM_LIST:
1042 case XPI_OPERAND_LIST:
1043 break;
1044 default:
1045 croak("Unrecognised XSParseInfixHooks.lhs_flags value 0x%X", hooks->lhs_flags);
1046 }
1047
1048 switch(hooks->rhs_flags & ~(XPI_OPERAND_ONLY_LOOK)) {
1049 case 0:
1050 case XPI_OPERAND_TERM_LIST:
1051 case XPI_OPERAND_LIST:
1052 break;
1053 default:
1054 croak("Unrecognised XSParseInfixHooks.rhs_flags value 0x%X", hooks->rhs_flags);
1055
1056 case (1 << 7) /* was XPI_OPERAND_CUSTOM */:
1057 croak("TODO: Currently XPI_OPERAND_CUSTOM is not supported");
1058 }
1059
1060 if(is_listassoc) {
1061 if(hooks->lhs_flags != hooks->rhs_flags)
1062 croak("Cannot register a list-associative infix operator with lhs_flags=%02X not equal to rhs_flags=%02X",
1063 hooks->lhs_flags, hooks->rhs_flags);
1064 }
1065
1066 #ifdef HAVE_PL_INFIX_PLUGIN
1067 enum Perl_custom_infix_precedence prec = 0;
1068
1069 switch(hooks->cls) {
1070 case 0:
1071 warn("Unspecified operator classification for %s; treating it as RELATION for precedence", opname);
1072 case XPI_CLS_RELATION:
1073 case XPI_CLS_EQUALITY:
1074 case XPI_CLS_MATCH_MISC:
1075 prec = INFIX_PREC_REL;
1076 break;
1077
1078 case XPI_CLS_LOW_MISC:
1079 prec = INFIX_PREC_LOW;
1080 break;
1081
1082 case XPI_CLS_LOGICAL_OR_LOW_MISC:
1083 prec = INFIX_PREC_LOGICAL_OR_LOW;
1084 break;
1085
1086 case XPI_CLS_LOGICAL_AND_LOW_MISC:
1087 prec = INFIX_PREC_LOGICAL_AND_LOW;
1088 break;
1089
1090 case XPI_CLS_ASSIGN_MISC:
1091 prec = INFIX_PREC_ASSIGN;
1092 break;
1093
1094 case XPI_CLS_LOGICAL_OR_MISC:
1095 prec = INFIX_PREC_LOGICAL_OR;
1096 break;
1097
1098 case XPI_CLS_LOGICAL_AND_MISC:
1099 prec = INFIX_PREC_LOGICAL_AND;
1100 break;
1101
1102 case XPI_CLS_ADD_MISC:
1103 prec = INFIX_PREC_ADD;
1104 break;
1105
1106 case XPI_CLS_MUL_MISC:
1107 prec = INFIX_PREC_MUL;
1108 break;
1109
1110 case XPI_CLS_POW_MISC:
1111 prec = INFIX_PREC_POW;
1112 break;
1113
1114 case XPI_CLS_HIGH_MISC:
1115 prec = INFIX_PREC_HIGH;
1116 break;
1117
1118 default:
1119 croak("TODO: need to write code for hooks->cls == %d\n", hooks->cls);
1120 }
1121 #endif
1122
1123 if(!hooks->new_op && !hooks->ppaddr)
1124 croak("Cannot register third-party infix operator without at least one of .new_op or .ppaddr");
1125
1126 struct Registration *reg;
1127 Newx(reg, 1, struct Registration);
1128
1129 #ifdef HAVE_PL_INFIX_PLUGIN
1130 reg->def.prec = prec;
1131 if(hooks->parse)
1132 reg->def.parse = &parse;
1133 else
1134 reg->def.parse = NULL;
1135 reg->def.build_op = &build_op;
1136 #endif
1137
1138 reg->info.opname = savepv(opname);
1139 reg->info.opcode = OP_CUSTOM;
1140 reg->info.hooks = hooks;
1141 reg->info.hookdata = hookdata;
1142 reg->info.cls = hooks->cls;
1143
1144 reg->oplen = oplen;
1145 reg->opname_is_ident = opname_is_ident;
1146 reg->opname_is_fq = opname_is_fq;
1147
1148 reg->hd.hooks = hooks;
1149 reg->hd.data = hookdata;
1150
1151 reg->opname_is_WIDE = FALSE;
1152 int i;
1153 for(i = 0; i < reg->oplen; i++) {
1154 if(opname[i] & 0x80) {
1155 reg->opname_is_WIDE = TRUE;
1156 break;
1157 }
1158 }
1159
1160 if(hooks->permit_hintkey)
1161 reg->permit_hintkey_len = strlen(hooks->permit_hintkey);
1162 else
1163 reg->permit_hintkey_len = 0;
1164
1165 if(opname_is_fq) {
1166 reg->next = fqregistrations;
1167 fqregistrations = reg;
1168 }
1169 else {
1170 reg->next = registrations;
1171 registrations = reg;
1172 }
1173
1174 if(hooks->wrapper_func_name) {
1175 make_wrapper_func(aTHX_ &reg->hd);
1176 }
1177
1178 if(hooks->ppaddr) {
1179 XOP *xop;
1180 Newx(xop, 1, XOP);
1181
1182 /* Use both the opname for human-readability, and the address of its
1183 * ppfunc for disambiguating in case of name clashes
1184 */
1185 SV *namesv = newSVpvf("B::Deparse::pp_infix_%s_0x%p", opname, hooks->ppaddr);
1186 {
1187 char *doublecolon;
1188 while((doublecolon = strstr(SvPVX(namesv)+sizeof("B::Deparse::pp::"), "::")))
1189 /* Turn '::' into '__', a length-preserving operation */
1190 doublecolon[0] = '_', doublecolon[1] = '_';
1191 }
1192 if(reg->opname_is_WIDE)
1193 SvUTF8_on(namesv);
1194 SAVEFREESV(namesv);
1195
1196 XopENTRY_set(xop, xop_name, savepv(SvPVX(namesv) + sizeof("B::Deparse::pp")));
1197 XopENTRY_set(xop, xop_desc, "custom infix operator");
1198 XopENTRY_set(xop, xop_class, is_listassoc ? OA_LISTOP : OA_BINOP);
1199 XopENTRY_set(xop, xop_peep, NULL);
1200
1201 Perl_custom_op_register(aTHX_ hooks->ppaddr, xop);
1202
1203 CV *cv = newXS(SvPVX(namesv), deparse_infix, __FILE__);
1204 CvXSUBANY(cv).any_ptr = reg;
1205 }
1206 }
1207
1208 void XSParseInfix_boot(pTHX)
1209 {
1210 /* stringy relations */
1211 reg_builtin(aTHX_ "eq", XPI_CLS_EQUALITY, OP_SEQ);
1212 reg_builtin(aTHX_ "ne", XPI_CLS_RELATION, OP_SNE);
1213 reg_builtin(aTHX_ "lt", XPI_CLS_RELATION, OP_SLT);
1214 reg_builtin(aTHX_ "le", XPI_CLS_RELATION, OP_SLE);
1215 reg_builtin(aTHX_ "ge", XPI_CLS_RELATION, OP_SGE);
1216 reg_builtin(aTHX_ "gt", XPI_CLS_RELATION, OP_SGT);
1217 reg_builtin(aTHX_ "cmp", XPI_CLS_ORDERING, OP_SCMP);
1218 #ifdef HAVE_UNDEF_AWARE_EQUALITY
1219 reg_builtin(aTHX_ "equ", XPI_CLS_EQUALITY, OP_SEQU);
1220 reg_builtin(aTHX_ "neu", XPI_CLS_EQUALITY, OP_SNEU);
1221 #endif
1222
1223 /* numerical relations */
1224 reg_builtin(aTHX_ "==", XPI_CLS_EQUALITY, OP_EQ);
1225 reg_builtin(aTHX_ "!=", XPI_CLS_RELATION, OP_NE);
1226 reg_builtin(aTHX_ "<", XPI_CLS_RELATION, OP_LT);
1227 reg_builtin(aTHX_ "<=", XPI_CLS_RELATION, OP_LE);
1228 reg_builtin(aTHX_ ">=", XPI_CLS_RELATION, OP_GE);
1229 reg_builtin(aTHX_ ">", XPI_CLS_RELATION, OP_GT);
1230 reg_builtin(aTHX_ "<=>", XPI_CLS_ORDERING, OP_NCMP);
1231 #ifdef HAVE_UNDEF_AWARE_EQUALITY
1232 reg_builtin(aTHX_ "===", XPI_CLS_EQUALITY, OP_EQU);
1233 reg_builtin(aTHX_ "!==", XPI_CLS_EQUALITY, OP_NEU);
1234 #endif
1235
1236 /* other predicates */
1237 #ifdef OP_SMARTMATCH /* removed in perl 5.41.3 */
1238 reg_builtin(aTHX_ "~~", XPI_CLS_SMARTMATCH, OP_SMARTMATCH);
1239 #endif
1240 reg_builtin(aTHX_ "=~", XPI_CLS_MATCHRE, OP_MATCH);
1241 /* TODO: !~ */
1242 #ifdef HAVE_OP_ISA
1243 reg_builtin(aTHX_ "isa", XPI_CLS_ISA, OP_ISA);
1244 #endif
1245
1246 /* TODO:
1247 * Other numerics
1248 * + - * / % **
1249 * << >>
1250 *
1251 * Bitwise
1252 * & | ^
1253 * Stringwise
1254 * &. |. ^.
1255 *
1256 * Boolean
1257 * && || //
1258 */
1259
1260 HV *stash = gv_stashpvs("XS::Parse::Infix", TRUE);
1261 bool have_pl_infix_plugin =
1262 #ifdef HAVE_PL_INFIX_PLUGIN
1263 TRUE
1264 #else
1265 FALSE
1266 #endif
1267 ;
1268
1269 newCONSTSUB(stash, "HAVE_PL_INFIX_PLUGIN", boolSV(have_pl_infix_plugin));
1270
1271 #ifdef HAVE_PL_INFIX_PLUGIN
1272 wrap_infix_plugin(&my_infix_plugin, &next_infix_plugin);
1273 #endif
1274 }