Debian Codegraph @

lib/XS/Parse/Infix.pm

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-2024 -- [email protected]
5
6 package XS::Parse::Infix 0.51;
7
8 use v5.14;
9 use warnings;
10
11 # No actual .xs file; the code is implemented in XS::Parse::Keyword
12 require XS::Parse::Keyword;
13
14 use Carp;
15
16 =head1 NAME
17
18 C<XS::Parse::Infix> - XS functions to assist in parsing infix operators
19
20 =head1 DESCRIPTION
21
22 This module provides some XS functions to assist in writing syntax modules
23 that provide new infix operators as perl syntax, primarily for authors of
24 syntax plugins. It is unlikely to be of much use to anyone else; and highly
25 unlikely to be of any use when writing perl code using these. Unless you are
26 writing a syntax plugin using XS, this module is not for you.
27
28 This module is also currently experimental, and the design is still evolving
29 and subject to change. Later versions may break ABI compatibility, requiring
30 changes or at least a rebuild of any module that depends on it.
31
32 In addition, the places this functionality can be used are relatively small.
33 Support for custom infix operators as added in Perl development release
34 C<v5.37.7>, and is therefore present in Perl C<v5.38.0>.
35
36 In addition, the various C<XPK_INFIX_*> token types of L<XS::Parse::Keyword>
37 support querying on this module, so some syntax provided by other modules may
38 be able to make use of these new infix operators.
39
40 =head2 Lexically-named vs. Globally-named Operators
41
42 At version 0.43, the way this module operates has changed. Since this version,
43 the preferred method of operation for infix operators is that the module that
44 registers them creates them with a fully-qualified name (i.e. including the
45 name of the package that implements them). Other code which wishes to import
46 the operator can then provide a local name for it visible within a scope. This
47 acts as an alias for the fully-qualified registered one. The imported name
48 needs not be the same in various scopes - this allows imported operators to be
49 renamed in specific scopes to avoid name clashes.
50
51 Prior versions of this module only supported operators that have one global
52 name that may or may not be enabled in lexical scopes. With this model, while
53 the visiblity of an operator can be controlled per scope, if it is visible it
54 must always have the same name and cannot be renamed to avoid a name clash.
55
56 At some future version of this module the older method may be removed, once
57 all of the existing CPAN modules have been updated to the new model.
58
59 =cut
60
61 =head1 CONSTANTS
62
63 =for highlighter language=perl
64
65 =head2 HAVE_PL_INFIX_PLUGIN
66
67 if( XS::Parse::Infix::HAVE_PL_INFIX_PLUGIN ) { ... }
68
69 This constant is true if built on a perl that supports the C<PL_infix_plugin>
70 extension mechanism, meaning that custom infix operators registered with this
71 module will actually be recognised by the perl parser.
72
73 No actual production releases of perl yet support this feature, but see above
74 for details of development versions which do.
75
76 =cut
77
78 =head1 PERL FUNCTIONS
79
80 =head2 apply_infix
81
82 $pkg->apply_infix( $on, $args, @infix );
83
84 I<Since version 0.43.>
85
86 Intended to be called by the C<import> and C<unimport> methods of a module
87 that implements infix operators. This sets up the various keys required in the
88 lexical hints hash to create a lexical alias for the requested operator(s).
89
90 I<$on> should be a true value for C<import> or a false value for C<unimport>.
91 I<$args> should be an array reference to the arguments array, which will be
92 modified to splice out recognised values, leaving behind anything else
93 unrecognised. I<@infix> should be a list of names of operators implemented by
94 the importing package, named by I<$pkg>.
95
96 After invoking this method, the caller should inspect for any remaining values
97 in the arguments array, either to handle them in some other way, or just
98 complain about them.
99
100 package Some::Infix::Module;
101
102 sub import
103 {
104 my $pkg = shift;
105 $pkg->XS::Parse::Infix::apply_infix( 1, \@_, qw( operator names here ) );
106 die "Unrecognised symbols: @_" if @_;
107 }
108
109 When this module is C<use>d, named operators are aliased from the
110 fully-qualified names.
111
112 use Some::Infix::Module qw( operator );
113
114 my $z = $x operator $y;
115
116 At this point, the name C<operator> becomes a lexical alias to
117 C<Some::Infix::Module::operator>.
118
119 Each imported operator name can optionally be followed by import options,
120 given in a hash reference. Currently the only named option recognised is
121 C<-as>, which allows the importing scope to provide a different name for the
122 imported operator, perhaps to avoid name clashes, or for neatness.
123
124 use Some::Infix::Module operator => { -as => "myname" };
125
126 my $z = $x myname $y; # invokes Some::Infix::Module::operator
127
128 =cut
129
130 # helper functions for infix operator modules
131 sub apply_infix
132 {
133 my $pkg = shift;
134 my ( $on, $args, @infix ) = @_;
135
136 my %infix = map { $_ => 1 } @infix;
137
138 for ( my $idx = 0; 1; $idx++ ) {
139 $idx < @$args or last;
140
141 my $name = $args->[$idx];
142 $infix{$name} or next;
143
144 splice @$args, $idx, 1, ();
145
146 my %opts;
147 %opts = %{ splice @$args, $idx, 1, () } if "HASH" eq ref $args->[$idx];
148
149 my $localname = $name;
150 $localname = delete $opts{-as} if exists $opts{-as};
151
152 croak "Unrecognised apply_infix options " . join( ", ", sort keys %opts )
153 if %opts;
154
155 XS::Parse::Infix::check_opname( $localname ) or
156 croak "Local name '$localname' for imported operator $name is invalid";
157
158 my $hintkey = "XS::Parse::Infix/$localname";
159 my $fqname = "${pkg}::${name}";
160
161 $on ? $^H{$hintkey} = $fqname
162 : delete $^H{$hintkey};
163
164 redo;
165 }
166 }
167
168 =head1 XS FUNCTIONS
169
170 =for highlighter language=c
171
172 =head2 boot_xs_parse_infix
173
174 void boot_xs_parse_infix(double ver);
175
176 Call this function from your C<BOOT> section in order to initialise the module
177 and parsing hooks.
178
179 I<ver> should either be 0 or a decimal number for the module version
180 requirement; e.g.
181
182 boot_xs_parse_infix(0.14);
183
184 =head2 parse_infix
185
186 bool parse_infix(enum XSParseInfixSelection select, struct XSParseInfixInfo **infop);
187
188 I<Since version 0.27.>
189
190 This function attempts to parse syntax for an infix operator from the current
191 parser position. If it is successful, it fills in the variable pointed to by
192 I<infop> with a pointer to the actual information structure and returns
193 C<true>. If no suitable operator is found, returns C<false>.
194
195 =head2 xs_parse_infix_new_op
196
197 OP *xs_parse_infix_new_op(const struct XSParseInfixInfo *info, U32 flags,
198 OP *lhs, OP *rhs);
199
200 This function constructs a new optree fragment to represent invoking the infix
201 operator with the given operands. It should be used much the same as core
202 perl's C<newBINOP> function.
203
204 The C<info> structure pointer would be obtained from the C<infix> field of the
205 result of invoking the various C<XPK_INFIX_*> token types from
206 C<XS::Parse::Keyword>, or by calling L</parse_infix> directly.
207
208 =head2 register_xs_parse_infix
209
210 void register_xs_parse_infix(const char *opname,
211 const struct XSParseInfixHooks *hooks, void *hookdata);
212
213 This function installs a set of parsing hooks to be associated with the given
214 operator name. This new operator will then be available via
215 L<XS::Parse::Keyword> by the various C<XPK_INFIX_*> token types,
216 L</parse_infix>, or to core perl's C<PL_infix_plugin> if available.
217
218 These tokens will all yield an info structure, with the following fields:
219
220 struct XSParseInfixInfo {
221 const char *opname;
222 OPCODE opcode; /* for built-in operators, or OP_CUSTOM for
223 custom-registered ones */
224
225 struct XSParseInfixHooks *hooks;
226 void *hookdata;
227
228 enum XSParseInfixClassification cls; /* since version 0.28 */
229 };
230
231 If the operator name contains any non-ASCII characters they are presumed to be
232 in UTF-8 encoding. This will matter for deparse purposes.
233
234 If I<opname> contains a double-colon (C<::>) sequence, it is presumed to be a
235 fully-qualified operator name in the new interface style. If not, it is
236 presumed to be an older globally-named one.
237
238 =cut
239
240 =head1 PARSE HOOKS
241
242 The C<XSParseInfixHooks> structure provides the following fields which are
243 used at various stages of parsing.
244
245 struct XSParseInfixHooks {
246 U16 flags;
247 U8 lhs_flags;
248 U8 rhs_flags;
249 enum XSParseInfixClassification cls;
250
251 const char *wrapper_func_name;
252
253 const char *permit_hintkey;
254 bool (*permit)(pTHX_ void *hookdata);
255
256 OP *(*new_op)(pTHX_ U32 flags, OP *lhs, OP *rhs, SV **parsedata, void *hookdata);
257 OP *(*ppaddr)(pTHX);
258
259 /* optional */
260 void (*parse)(pTHX_ U32 flags, SV **parsedata, void *hookdata);
261 };
262
263 =head2 Flags
264
265 The C<flags> field gives details on how to handle the operator overall. It
266 should be a bitmask of the following constants, or left as zero:
267
268 =over 4
269
270 =item XPI_FLAG_LISTASSOC
271
272 I<Since version 0.40.>
273
274 If set, the operator supports n-way list-associative syntax; written in the
275 form
276
277 =for highlighter
278
279 OPERAND op OPERAND op OPERAND op ...
280
281 =for highlighter language=c
282
283 In this case, the custom operator will be a LISTOP rather than a BINOP, and
284 every operand of the entire chain will be stored as a child op of it. The op
285 function will need to know how many operands it is working on. There are two
286 ways this may be indicated, depending on whether it was known at compile-time.
287
288 If the number operands is known at compile-time, the C<OPf_STACKED> flag is
289 not set, and the C<op_private> field indicates the number of operand
290 expressions that were present.
291
292 If the number is not known (for example, the operator is being used as the
293 body of a generated wrapper function), the C<OPf_STACKED> flag is set. The
294 number of arguments will be passed as the UV of an extra SV which is pushed
295 last to the stack. The op function should pop this first to find out.
296
297 It is typical to begin a list-associative op function with code such as:
298
299 int n = (PL_op->op_flags & OPf_STACKED) ? POPu : PL_op->op_private;
300
301 If the operator is list-associative, then C<lhs_flags> and C<rhs_flags> must
302 be equal.
303
304 =back
305
306 The C<lhs_flags> and C<rhs_flags> fields give details on how to handle the
307 left- and right-hand side operands, respectively.
308
309 It should be set to one of the following constants, or left as zero:
310
311 =over 4
312
313 =item XPI_OPERAND_TERM_LIST
314
315 The operand will be foced into list context, preserving the C<OP_PUSHMARK> at
316 the beginning. This means that the ppfunc for this infix operator will have to
317 C<POPMARK> to find that.
318
319 =item XPI_OPERAND_LIST
320
321 The same as above.
322
323 =back
324
325 Older versions used to provide constants named C<XPI_OPERAND_ARITH> and
326 C<XPI_OPERAND_TERM> but they related to an older version of the core perl
327 branch. These names are now aliases for zero, and can be removed from new
328 code.
329
330 In addition the following extra bitflags are defined:
331
332 =over 4
333
334 =item XPI_OPERAND_ONLY_LOOK
335
336 If set, the operator function promises that it will not mutate any of its
337 passed values, nor allow leaking of direct alias pointers to them via return
338 value or other locations.
339
340 This flag is optional; omitting it when applicable will not change any
341 observed behaviour. Setting it may enable certain optimisations to be
342 performed.
343
344 Currently, this flag simply enables an optimisation in the call-checker for
345 infix operator wrapper functions that take list-shaped operands. This
346 optimisation discards an C<OP_ANONLIST> operation which would create a
347 temporary anonymous array reference for its operand values, allowing a slight
348 saving of memory use and CPU time. This optimisation is only safe to perform
349 if the operator does not mutate or retain aliases of any of the arguments, as
350 otherwise the caller might see unexpected modifications or value references to
351 the values passed.
352
353 =back
354
355 =head2 The Selection Stage
356
357 The C<cls> field gives a "classification" of the operator, suggesting what
358 sort of operation it provides. This is used as a filter by the various
359 C<XS::Parse::Keyword> selection macros.
360
361 The classification should be one of the C<XPI_CLS_*> constants found and
362 described further in the main F<XSParseInfix.h> file.
363
364 =head2 The C<permit> Stage
365
366 As a shortcut for the common case, the C<permit_hintkey> may point to a string
367 to look up from the hints hash. If the given key name is not found in the
368 hints hash then the keyword is not permitted. If the key is present then the
369 C<permit> function is invoked as normal.
370
371 If not rejected by a hint key that was not found in the hints hash, the
372 function part of the stage is called next and should inspect whether the
373 keyword is permitted at this time perhaps by inspecting other lexical clues,
374 and return true only if the keyword is permitted.
375
376 Both the string and the function are optional. Either or both may be present.
377 If neither is present then the keyword is always permitted - which is likely
378 not what you wanted to do.
379
380 =head2 The C<parse> Stage
381
382 If the optional C<parse> hook function is present, it is called immediately
383 after the parser has recognised the presence of the named operator itself but
384 before it attempts to consume the right-hand side term. This hook function can
385 attempt further parsing, in order to implement more complex syntax such as
386 hyper-operators.
387
388 When invoked, it is passed a pointer to an C<SV *>-typed storage variable. It
389 is free to use this variable it desires to store a result, which will then
390 later be made available to the C<new_op> function.
391
392 =head2 The Op Generation Stage
393
394 If the infix operator is going to be used, then one of the C<new_op> or the
395 C<ppaddr> fields explain how to create a new optree fragment.
396
397 If C<new_op> is defined then it will be used, and is expected to return an
398 optree fragment that consumes the LHS and RHS arguments to implement the
399 semantics of the operator. If the optional C<parse> stage had been present
400 earlier, the C<SV **> pointer passed here will point to the same storage that
401 C<parse> had previously had access to, so it can retrieve the results.
402
403 If C<new_op> is not present, then the C<ppaddr> will be used instead to
404 construct a new BINOP or LISTOP of the C<OP_CUSTOM> type. If an earlier
405 C<parse> stage had stored additional results into the C<SV *> variable these
406 will be lost here.
407
408 =head2 The Wrapper Function
409
410 =for highlighter language=perl
411
412 Additionally, if the C<wrapper_func_name> field is set to a string, this gives
413 the (fully-qualified) name for a function to be generated as part of
414 registering the operator. This newly-generated function will act as a wrapper
415 for the operator.
416
417 For operators whose RHS is a scalar, the wrapper function is assumed to take
418 two simple scalar arguments. The result of invoking the function on those
419 arguments will be determined by using the operator code.
420
421 $result = $lhs OP $rhs;
422
423 $result = WRAPPERFUNC( $lhs, $rhs );
424
425 For operators whose RHS is a list, the wrapper function takes at least one
426 argument, possibly more. The first argument is the scalar on the LHS, and the
427 remaining arguments, however many there are, form the RHS:
428
429 $result = $lhs OP @rhs;
430
431 $result = WRAPPERFUNC( $lhs, @rhs );
432
433 For operators whose LHS and RHS is a list, the wrapper function takes two
434 arguments which must be array references containing the lists.
435
436 $result = @lhs OP @rhs;
437
438 $result = WRAPPERFUNC( \@lhs, \@rhs );
439
440 This creates a convenience for accessing the operator from perls that do not
441 support C<PL_infix_plugin>.
442
443 In the case of scalar infix operators, the wrapper function also includes a
444 call-checker which attempts to inline the operator directly into the callsite.
445 Thus, in simple cases where the function is called directly on exactly two
446 scalar arguments (such as in the following), no C<ENTERSUB> overhead will be
447 incurred and the generated optree will be identical to that which would have
448 been generated by using infix operator syntax directly:
449
450 WRAPPERFUNC( $lhs, $rhs );
451 WRAPPERFUNC( $lhs, CONSTANT );
452 WRAPPERFUNC( $args[0], $args[1] );
453 WRAPPERFUNC( $lhs, scalar otherfunc() );
454
455 The checker is very pessimistic and will only rewrite callsites where it
456 determines this can be done safely. It will not rewrite any of the following
457 forms:
458
459 WRAPPERFUNC( $onearg ); # not enough args
460 WRAPPERFUNC( $x, $y, $z ); # too many args
461 WRAPPERFUNC( @args[0,1] ); # not a scalar
462 WRAPPERFUNC( $lhs, otherfunc() ); # not a scalar
463
464 The wrapper function for infix operators which take lists on both sides also
465 has a call-checker which will attempt to inline the operator in similar
466 circumstances. In addition to the optimisations described above for scalar
467 operators, this checker will also inline an array-reference operator and omit
468 the resulting dereference behaviour. Thus, the two following lines emit the
469 same optree, without an C<OP_SREFGEN> or C<OP_RV2AV>:
470
471 @lhs OP @rhs;
472 WRAPPERFUNC( \@lhs, \@rhs );
473
474 B<Note> that technically, this optimisation isn't strictly transparent in the
475 odd cornercase that one of the referenced arrays is also the backing store for
476 a blessed object reference, and that object class has a C<@{}> overload.
477
478 my @arr;
479 package SomeClass {
480 use overload '@{}' => sub { return ["values", "go", "here"]; };
481 }
482 bless \@arr, "SomeClass";
483
484 # this will not actually invoke the overload operator
485 WRAPPERFUNC( \@arr, [4, 5, 6] );
486
487 As this cornercase relates to taking duplicate references to the same blessed
488 object's backing store variable, it should not matter to any real code;
489 regular objects that are passed by reference into the wrapper function will
490 run their overload methods as normal.
491
492 The callchecker for list operands can optionally also discard an op of the
493 C<OP_ANONLIST> type, which is used by anonymous array-ref construction:
494
495 ($u, $v, $w) OP ($x, $y, $z);
496 WRAPPERFUNC( [$u, $v, $w], [$x, $y, $z] );
497
498 This optimisation is only performed if the operator declared it safe to do so,
499 via the C<XPI_OPERAND_ONLY_LOOK> flag.
500
501 If a function of the given name already exists at registration time it will be
502 left undisturbed and no new wrapper will be created. This permits the same
503 infix operator to have multiple spellings of its name; for example to allow
504 both a real Unicode and a fallback ASCII transliteration of the same operator.
505 The first registration will create the wrapper function; the subsequent one
506 will skip it because it would otherwise be identical.
507
508 Note that when generating an optree for a wrapper function call, the C<new_op>
509 hook function will be invoked with a C<NULL> pointer for the C<SV *>-typed
510 parse data storage, as there won't be an opporunity for the C<parse> hook to
511 run in this case.
512
513 =cut
514
515 =head1 DEPARSE
516
517 This module operates with L<B::Deparse> in order to automatically provide
518 deparse support for infix operators. Every infix operator that is implemented
519 as a custom op (and thus has the C<ppaddr> hook field set) will have deparse
520 logic added. This will allow it to deparse to either the named wrapper
521 function, or to the infix operator syntax if on a C<PL_infix_plugin>-enabled
522 perl and the appropriate lexical hint is enabled at the callsite.
523
524 In order for this to work, it is important that your custom operator is I<not>
525 registered as a custom op using the C<Perl_register_custom_op()> function.
526 This registration will be performed by C<XS::Parse::Infix> itself at the time
527 the infix operator is registered.
528
529 =cut
530
531 sub B::Deparse::_deparse_infix_wrapperfunc_scalarscalar
532 {
533 my ( $self, $wrapper_func_name, $op, $ctx ) = @_;
534
535 my $lhs = $op->first;
536 my $rhs = $op->last;
537
538 $_ = $self->deparse( $_, 6 ) for $lhs, $rhs;
539
540 return "$wrapper_func_name($lhs, $rhs)";
541 }
542
543 sub B::Deparse::_deparse_infix_wrapperfunc_listlist
544 {
545 my ( $self, $wrapper_func_name, $op, $ctx ) = @_;
546
547 my $lhs = $op->first;
548 my $rhs = $op->last;
549
550 foreach my $var ( \$lhs, \$rhs ) {
551 my $argop = $$var;
552 my $kid;
553
554 if( $argop->name eq "null" and
555 $argop->first->name eq "pushmark" and
556 ($kid = $argop->first->sibling) and
557 B::Deparse::null($kid->sibling) ) {
558 my $add_refgen;
559
560 # A list of a single item
561 if( $kid->name eq "rv2av" and $kid->first->name ne "gv" ) {
562 $argop = $kid->first;
563 }
564 elsif( $kid->name eq "padav" or $kid->name eq "rv2av" ) {
565 $add_refgen++;
566 }
567 else {
568 print STDERR "Maybe UNWRAP list ${\ $kid->name }\n";
569 }
570
571 $$var = $self->deparse( $argop, 6 );
572
573 $$var = "\\$$var" if $add_refgen;
574 }
575 else {
576 # Pretend the entire list was anonlist
577 my @args;
578 $argop = $argop->first->sibling; # skip pushmark
579 while( not B::Deparse::null($argop) ) {
580 push @args, $self->deparse( $argop, 6 );
581 $argop = $argop->sibling;
582 }
583
584 $$var = "[" . join( ", ", @args ) . "]";
585 }
586 }
587
588 return "$wrapper_func_name($lhs, $rhs)";
589 }
590
591 sub B::Deparse::_deparse_infix_named
592 {
593 my ( $self, $opname, $op, $ctx ) = @_;
594
595 # Cope with list-associatives
596 my $kid = $op->first;
597
598 my @operands = ( $self->deparse_binop_left( $op, $kid, 14 ) );
599 $kid = $kid->sibling;
600
601 while( !B::Deparse::null( $kid ) ) {
602 push @operands, $self->deparse_binop_right( $op, $kid, 14 );
603 $kid = $kid->sibling;
604 }
605
606 return join " $opname ", @operands;
607 }
608
609 =head1 TODO
610
611 =over 4
612
613 =item *
614
615 Have the entersub checker for list/list operators unwrap arrayref or
616 anon-array argument forms (C<WRAPPERFUNC( \@lhs, \@rhs )> or
617 C<WRAPPERFUNC( [LHS], [RHS] )>).
618
619 =item *
620
621 Further thoughts about how infix operators with C<parse> hooks will work with
622 automatic deparse, and also how to integrate them with L<XS::Parse::Keyword>'s
623 grammar piece.
624
625 =back
626
627 =cut
628
629 =head1 AUTHOR
630
631 Paul Evans <[email protected]>
632
633 =cut
634
635 0x55AA;