XS-Parse-Sublike-0.22000755001750001750 014643004052 13152 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/.editorconfig000444001750001750 5314643004052 15722 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 XS-Parse-Sublike-0.22/Build.PL000444001750001750 224614643004052 14607 0ustar00leoleo000000000000use v5; use strict; use warnings; use lib 'inc'; use Module::Build::with::XSTests; my @extra_compiler_flags = qw( -Ishare/include -Iinclude -Ihax ); # Perl 5.36 made -std=c99 standard; before then we'll have to request it specially push @extra_compiler_flags, qw( -std=c99 ) if $^V lt v5.36.0; push @extra_compiler_flags, qw( -DDEBUGGING=-g ) if $^X =~ m|/debugperl|; use Config; if( $Config{ccname} eq "gcc" ) { # Enable some extra gcc warnings, largely just for author interest push @extra_compiler_flags, qw( -Wall -Wno-unused-function -Wno-unused-value ); } my $build = Module::Build::with::XSTests->new( module_name => 'XS::Parse::Sublike', requires => { 'perl' => '5.016', # pad_add_name_pvn # Not actually needed but used by hax/lexer-additions.c.inc }, test_requires => { 'Sub::Util' => 0, 'Test2::V0' => 0, }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, share_dir => { dist => [ 'share' ], }, license => 'perl', create_license => 1, create_readme => 1, extra_compiler_flags => \@extra_compiler_flags, c_source => [ "src/" ], ); $build->create_build_script; XS-Parse-Sublike-0.22/Changes000444001750001750 1272314643004052 14627 0ustar00leoleo000000000000Revision history for XS-Parse-Sublike 0.22 2024-07-08 [CHANGES] * Use `File::ShareDir` for storing .h include file, rather than storing the contents in the `__DATA__` section of the build helper 0.21 2023-10-11 [BUGFIXES] * Ensure that exceptions thrown from runtime signature handling appear to come from the callsite and not declaration * Fix signedness of printf format when complaining about mismatched `->ver` 0.20 2023-09-09 [BUGFIXES] * Correct ->VERSION check for Object::Pad or Future::AsyncAwait cross-module tests (RT149700) * Don't upset gcc's -Wformat by passing an unbounded STRLEN into %.*s format (RT133035) * Avoid colons in filename of t/71extended+Object-Pad.t because Windows doesn't like them (RT149712) * Ensure that mixed positional + named params in signatures work properly (thanks alh) * Ensure name shadowing of param names prints the right diagnostic warning (thanks alh) 0.19 2023-09-07 [CHANGES] * Added `Sublike::Extended`, a prefix keyword to enable the extended signature parser for named params and attributes * Beginnings of an (experimental) XS-level API for attributes on parameters * Complain on attempts to register a sublike keyword with neither a permit function nor hinthash key 0.18 2023-06-14 [CHANGES] * Swap all the unit tests from Test::More to Test2::V0 [BUGFIXES] * Remember to set `-std=c99` compiler flag on Perls before v5.36 0.17 2023-03-21 [CHANGES] * Experimental support for named param syntax in parse_subsignature() * Support core perl's `method` syntax when available by setting CVf_IsMETHOD (perl >= 5.37.10) 0.16 2021-12-16 [CHANGES] * No longer support ABI version 3 even in back-compatibility mode [BUGFIXES] * Remember to adjust the SET_CVNAME and INSTALL_SYMBOL actions bits in the non-dynamic-actions case * Avoid using C99-style `//` comments as some compilers dislike it (mistagged RT140487) 0.15 2021-12-15 [CHANGES] * Added ctx->actions, the DYNAMIC_ACTIONS compat flag, and associated flags and machinery * Added ctx->moddata 0.14 2021-10-28 [CHANGES] * Added XS_PARSE_SUBLIKE_FLAG_PREFIX; discourage the _any() function to achieve similar effect * Added XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL to permit bodyless sublike declarations * Better compiletime warnings when a sub declaration lacks a body-delimiting brace [BUGFIXES] * Fix for Perl < 5.20 on Win32 (thanks ilmari) (RT139296) * Handle the new OP_ARGCHECK aux structure of perl 5.31.5 (thanks ilmari) (RT139295) * Accomodate newly-added core sv_setrv_*() functions 0.13 2021-08-30 [CHANGES] * New ABI version 4 + Set up functions in PL_modglobal instead of perl-visible global symbol table + Add a `permit_hintkey` convenient shortcut * Better code structure of XS::Parse::Sublike::Builder 0.12 2021-06-21 [BUGFIXES] * Try to work around parse_block()'s unbalanced scopestack messups * Namespace the static variables in the .h file appropriately in case both this as XSParseKeyword are loaded 0.11 2021-01-18 [BUGFIXES] * Don't SEGV on signature parse error (RT133865) * Account for change of signature validation error message in latest bleadperl (RT134012) 0.10 2020-06-20 [BREAKING CHANGES] * New ABI version 3 [CHANGES] * Pass an additional 'hookdata' parameter around between caller and hook stage functions 0.09 2020-06-15 [CHANGES] * Define API for an optional stage for filtering and applying attributes during parsing 0.08 2020-06-12 [CHANGES] * Define API to either require or skip parsing the name of a sub, or skip parsing attributes or signatures 0.07 2020-04-02 [BUGFIXES] * Ensure that empty-signature functions are still parsed correctly and include arg count check (RT132284) 0.06 2020-03-27 [CHANGES] * Pass a standard shared context struct through the various hook stages * Add an early hook stage before the call to start_subparse() 0.05 2020-03-26 [BUGFIXES] * Fix hax/parse_subsignature.c.inc to cope with whitespace between parameter declarations 0.04 2020-03-18 [CHANGES] * Pass a required module version number to boot_xs_parse_sublike() * Added lots of unit tests 0.03 2020-03-18 [CHANGES] * Added xs_parse_sublike_any() allowing custom keywords to combine with registered hooks [BUGFIXES] * Avoid double-free of sigops in case of parse failure * Fix hax/parse_subsignature.c.inc for named parameters with default expressions 0.02 2020-03-17 [CHANGES] * Added `register_xs_parse_sublike()` and the `permit` hook stage * Added toplevel PL_keyword_hook parser function 0.01 2020-03-15 First version, released on an unsuspecting world. XS-Parse-Sublike-0.22/LICENSE000444001750001750 4653414643004052 14350 0ustar00leoleo000000000000This software is copyright (c) 2024 by Paul Evans . This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. Terms of the Perl programming language system itself a) the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version, or b) the "Artistic License" --- The GNU General Public License, Version 1, February 1989 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The GNU General Public License, Version 1, February 1989 GNU GENERAL PUBLIC LICENSE Version 1, February 1989 Copyright (C) 1989 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The license agreements of most software companies try to keep users at the mercy of those companies. By contrast, our General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. The General Public License applies to the Free Software Foundation's software and to any other program whose authors commit to using it. You can use it for your programs, too. When we speak of free software, we are referring to freedom, not price. Specifically, the General Public License is designed to make sure that you have the freedom to give away or sell copies of free software, that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of a such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must tell them their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any work containing the Program or a portion of it, either verbatim or with modifications. Each licensee is addressed as "you". 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this General Public License and to the absence of any warranty; and give any other recipients of the Program a copy of this General Public License along with the Program. You may charge a fee for the physical act of transferring a copy. 2. You may modify your copy or copies of the Program or any portion of it, and copy and distribute such modifications under the terms of Paragraph 1 above, provided that you also do the following: a) cause the modified files to carry prominent notices stating that you changed the files and the date of any change; and b) cause the whole of any work that you distribute or publish, that in whole or in part contains the Program or any part thereof, either with or without modifications, to be licensed at no charge to all third parties under the terms of this General Public License (except that you may choose to grant warranty protection to some or all third parties, at your option). c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the simplest and most usual way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this General Public License. d) You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. Mere aggregation of another independent work with the Program (or its derivative) on a volume of a storage or distribution medium does not bring the other work under the scope of these terms. 3. You may copy and distribute the Program (or a portion or derivative of it, under Paragraph 2) in object code or executable form under the terms of Paragraphs 1 and 2 above provided that you also do one of the following: a) accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Paragraphs 1 and 2 above; or, b) accompany it with a written offer, valid for at least three years, to give any third party free (except for a nominal charge for the cost of distribution) a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Paragraphs 1 and 2 above; or, c) accompany it with the information you received as to where the corresponding source code may be obtained. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form alone.) Source code for a work means the preferred form of the work for making modifications to it. For an executable file, complete source code means all the source code for all modules it contains; but, as a special exception, it need not include source code for modules which are standard libraries that accompany the operating system on which the executable file runs, or for standard header files or definitions files that accompany that operating system. 4. You may not copy, modify, sublicense, distribute or transfer the Program except as expressly provided under this General Public License. Any attempt otherwise to copy, modify, sublicense, distribute or transfer the Program is void, and will automatically terminate your rights to use the Program under this License. However, parties who have received copies, or rights to use copies, from you under this General Public License will not have their licenses terminated so long as such parties remain in full compliance. 5. By copying, distributing or modifying the Program (or any work based on the Program) you indicate your acceptance of this license to do so, and all its terms and conditions. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. 7. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of the license which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the license, you may choose any version ever published by the Free Software Foundation. 8. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 9. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 10. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS Appendix: How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to humanity, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 19yy This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) 19xx name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (a program to direct compilers to make passes at assemblers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice That's all there is to it! --- The Perl Artistic License 1.0 --- This software is Copyright (c) 2024 by Paul Evans . This is free software, licensed under: The Perl Artistic License 1.0 The "Artistic License" Preamble The intent of this document is to state the conditions under which a Package may be copied, such that the Copyright Holder maintains some semblance of artistic control over the development of the package, while giving the users of the package the right to use and distribute the Package in a more-or-less customary fashion, plus the right to make reasonable modifications. Definitions: "Package" refers to the collection of files distributed by the Copyright Holder, and derivatives of that collection of files created through textual modification. "Standard Version" refers to such a Package if it has not been modified, or has been modified in accordance with the wishes of the Copyright Holder as specified below. "Copyright Holder" is whoever is named in the copyright or copyrights for the package. "You" is you, if you're thinking about copying or distributing this Package. "Reasonable copying fee" is whatever you can justify on the basis of media cost, duplication charges, time of people involved, and so on. (You will not be required to justify it to the Copyright Holder, but only to the computing community at large as a market that must bear the fee.) "Freely Available" means that no fee is charged for the item itself, though there may be fees involved in handling the item. It also means that recipients of the item may redistribute it under the same conditions they received it. 1. You may make and give away verbatim copies of the source form of the Standard Version of this Package without restriction, provided that you duplicate all of the original copyright notices and associated disclaimers. 2. You may apply bug fixes, portability fixes and other modifications derived from the Public Domain or from the Copyright Holder. A Package modified in such a way shall still be considered the Standard Version. 3. You may otherwise modify your copy of this Package in any way, provided that you insert a prominent notice in each changed file stating how and when you changed that file, and provided that you do at least ONE of the following: a) place your modifications in the Public Domain or otherwise make them Freely Available, such as by posting said modifications to Usenet or an equivalent medium, or placing the modifications on a major archive site such as uunet.uu.net, or by allowing the Copyright Holder to include your modifications in the Standard Version of the Package. b) use the modified Package only within your corporation or organization. c) rename any non-standard executables so the names do not conflict with standard executables, which must also be provided, and provide a separate manual page for each non-standard executable that clearly documents how it differs from the Standard Version. d) make other distribution arrangements with the Copyright Holder. 4. You may distribute the programs of this Package in object code or executable form, provided that you do at least ONE of the following: a) distribute a Standard Version of the executables and library files, together with instructions (in the manual page or equivalent) on where to get the Standard Version. b) accompany the distribution with the machine-readable source of the Package with your modifications. c) give non-standard executables non-standard names, and clearly document the differences in manual pages (or equivalent), together with instructions on where to get the Standard Version. d) make other distribution arrangements with the Copyright Holder. 5. You may charge a reasonable copying fee for any distribution of this Package. You may charge any fee you choose for support of this Package. You may not charge a fee for this Package itself. However, you may distribute this Package in aggregate with other (possibly commercial) programs as part of a larger (possibly commercial) software distribution provided that you do not advertise this Package as a product of your own. You may embed this Package's interpreter within an executable of yours (by linking); this shall be construed as a mere form of aggregation, provided that the complete Standard Version of the interpreter is so embedded. 6. The scripts and library files supplied as input to or produced as output from the programs of this Package do not automatically fall under the copyright of this Package, but belong to whoever generated them, and may be sold commercially, and may be aggregated with this Package. If such scripts or library files are aggregated with this Package via the so-called "undump" or "unexec" methods of producing a binary executable image, then distribution of such an image shall neither be construed as a distribution of this Package nor shall it fall under the restrictions of Paragraphs 3 and 4, provided that you do not represent such an executable image as a Standard Version of this Package. 7. C subroutines (or comparably compiled subroutines in other languages) supplied by you and linked into this Package in order to emulate subroutines and variables of the language defined by this Package shall not be considered part of this Package, but are the equivalent of input as in Paragraph 6, provided these subroutines do not change the language in any way that would cause it to fail the regression tests for the language. 8. Aggregation of this Package with a commercial distribution is always permitted provided that the use of this Package is embedded; that is, when no overt attempt is made to make this Package's interfaces visible to the end user of the commercial distribution. Such use shall not be construed as a distribution of this Package. 9. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 10. THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End XS-Parse-Sublike-0.22/MANIFEST000444001750001750 237314643004052 14445 0ustar00leoleo000000000000.editorconfig Build.PL Changes hax/block_end.c.inc hax/block_start.c.inc hax/COP_SEQ_RANGE_HIGH_set.c.inc hax/croak_from_caller.c.inc hax/lexer-additions.c.inc hax/LOGOP_ANY.c.inc hax/make_argcheck_aux.c.inc hax/newSV_with_free.c.inc hax/pad_block_start.c.inc hax/pad_leavemy.c.inc hax/scalarseq.c.inc hax/sv_setrv.c.inc hax/wrap_keyword_plugin.c.inc inc/Module/Build/with/XSTests.pm include/parse_subsignature_ex.h lib/Sublike/Extended.pm lib/Sublike/Extended.xs lib/XS/Parse/Sublike.pm lib/XS/Parse/Sublike.xs lib/XS/Parse/Sublike/Builder.pm LICENSE MANIFEST This list of files META.json META.yml README share/include/XSParseSublike.h src/parse_subsignature_ex.c t/00use.t t/01func.t t/02func-signatures.t t/03func-deparse.t t/04func-named-params.t t/05func-sig-attributes.t t/10stages-permit.t t/11stages-pre_subparse.t t/12stages-post_blockstart.t t/13stages-pre_blockend.t t/14stages-post_newcv.t t/15stages-filter_attr.t t/20registrations.t t/30any.t t/31prefix.t t/40parts-name.t t/41parts-attrs.t t/42parts-signature.t t/50flags-no-body.t t/60actions.t t/70extended.t t/80extended+async.t t/80extended+feature-class.t t/80extended+Object-Pad.t t/99pod.t t/actions.xs t/any.xs t/flags.xs t/func.xs t/parts.xs t/prefix.xs t/registrations.xs t/stages.xs t/testcase.pm XS-Parse-Sublike-0.22/META.json000444001750001750 266714643004052 14743 0ustar00leoleo000000000000{ "abstract" : "XS functions to assist in parsing C-like syntax", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4234", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "XS-Parse-Sublike", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "File::ShareDir" : "1.00", "perl" : "5.016" } }, "test" : { "requires" : { "Sub::Util" : "0", "Test2::V0" : "0" } } }, "provides" : { "Sublike::Extended" : { "file" : "lib/Sublike/Extended.pm", "version" : "0.22" }, "XS::Parse::Sublike" : { "file" : "lib/XS/Parse/Sublike.pm", "version" : "0.22" }, "XS::Parse::Sublike::Builder" : { "file" : "lib/XS/Parse/Sublike/Builder.pm", "version" : "0.22" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ] }, "version" : "0.22", "x_serialization_backend" : "JSON::PP version 4.16" } XS-Parse-Sublike-0.22/META.yml000444001750001750 160714643004052 14564 0ustar00leoleo000000000000--- abstract: 'XS functions to assist in parsing C-like syntax' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Sub::Util: '0' Test2::V0: '0' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4234, CPAN::Meta::Converter version 2.150010' license: perl meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: XS-Parse-Sublike provides: Sublike::Extended: file: lib/Sublike/Extended.pm version: '0.22' XS::Parse::Sublike: file: lib/XS/Parse/Sublike.pm version: '0.22' XS::Parse::Sublike::Builder: file: lib/XS/Parse/Sublike/Builder.pm version: '0.22' requires: File::ShareDir: '1.00' perl: '5.016' resources: license: http://dev.perl.org/licenses/ version: '0.22' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' XS-Parse-Sublike-0.22/README000444001750001750 3354014643004052 14214 0ustar00leoleo000000000000NAME XS::Parse::Sublike - XS functions to assist in parsing sub-like syntax DESCRIPTION This module provides some XS functions to assist in writing parsers for sub-like syntax, primarily for authors of keyword plugins using the PL_keyword_plugin hook mechanism. It is unlikely to be of much use to anyone else; and highly unlikely to be any use when writing perl code using these. Unless you are writing a keyword plugin using XS, this module is not for you. This module is also currently experimental, and the design is still evolving and subject to change. Later versions may break ABI compatibility, requiring changes or at least a rebuild of any module that depends on it. XS FUNCTIONS boot_xs_parse_sublike void boot_xs_parse_sublike(double ver) Call this function from your BOOT section in order to initialise the module and parsing hooks. ver should either be 0 or a decimal number for the module version requirement; e.g. boot_xs_parse_sublike(0.04); xs_parse_sublike int xs_parse_sublike(const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) This function performs the actual parsing of a sub-like keyword. It expects the lexer to be at a position just after the introduction keyword has been consumed, and will proceed to parse an optional name, list of attributes, signature (if enabled by use feature 'signatures'), and code body. The return value and op_ptr can be used directly from the keyword plugin function. It is intended this function be invoked from it, and the result returned directly. For a more automated handling of keywords, see "register_xs_parse_sublike". hooks should be a structure that can provide optional function pointers used to customise the parsing process at various stages. hookdata is an opaque pointer which is passed through to each of the hook stage functions. register_xs_parse_sublike void register_xs_parse_sublike(const char *keyword, const struct XSParseSublikeHooks *hooks, void *hookdata) This function installs a set of parsing hooks to be associated with the given keyword. Such a keyword will then be handled automatically by a keyword parser installed by XS::Parse::Sublike itself. When the keyword is encountered, the hook's permit function is first tested to see if the keyword is permitted at this point. If the function returns true then the keyword is consumed and parsed as per "xs_parse_sublike". hookdata is an opaque pointer which is passed through to each of the hook stage functions when they are invoked. xs_parse_sublike_any int xs_parse_sublike_any(const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) This function expects to consume an introduction keyword at the lexer position which is either sub or the name of another sub-like keyword, which has been previously registered using "register_xs_parse_sublike". It then proceeds to parse the subsequent syntax similar to how it would have parsed if encountered by the module's own keyword parser plugin, except that the second set of hooks given here also take effect. If a regular sub is encountered, then this is parsed using the hooks in a similar way to xs_parse_sublike(). If a different registered sub-like keyword is encountered, then parsing is performed using both sets of hooks - the ones given to this function as well as the ones registered with the keyword. This allows their effects to combined. The hooks given by the hooks argument are considered to be on the "outside" from those of the registered keyword "inside". The outside ones run first for all stages, except pre_blockend which runs them inside-out. hookdata is an opaque pointer which is passed through to each of the hook stage functions when they are invoked. Note that this function is now vaguely discouraged, in favour of using a prefixing keyword instead, by using the XS_PARSE_SUBLIKE_FLAG_PREFIX flag. PARSE CONTEXT The various hook stages all share state about the ongoing parse process using various fields of the XSParseSublikeContext structure. struct XSParseSublikeContext { SV *name; OP *attrs; OP *body; CV *cv; U32 actions; HV *moddata; } The actions field will contain a bitmask of action flags that control the various steps that XS::Parse::Sublike might take inbetween invoking hook stages. The initial value of this field is set after the name-parsing stage, depending on whether or not a name is found. Stage hook functions may modify the field to adjust the subsequent behaviour. At the current ABI version, a module will have to set the XS_PARSE_SUBLIKE_COMPAT_FLAG_DYNAMIC_ACTIONS bit of the flags field in order to make use of the actions field. A future ABI version may remove this restriction. XS_PARSE_SUBLIKE_ACTION_CVf_ANON If set, the start_subparse() call will be set up for an anonymous function protosub; if not it will be set for a named function. This is set by default if a name was not found. XS_PARSE_SUBLIKE_ACTION_SET_CVNAME If set, the newly-constructed CV will have the given name set on it. This is set by default if a name was found. On Perl versions 5.22 and above, this flag can be set even if XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL is not. In this case, the CV will not be reachable via the symbol table, even though it knows its own name and pretends that it is. On earlier versions of perl this flag will be ignored in that case. XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL If set, the newly-constructed CV will be installed into the symbol table at its given name. Note that it is not possible to enable this flag without also enabling XS_PARSE_SUBLIKE_ACTION_SET_CVNAME. This is set by default if a name was found. XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE If set, the syntax will yield the OP_REFGEN / OP_ANONCODE optree fragment typical of anonymous code expressions; if not it will be OP_NULL. This is set by default if a name was not found. XS_PARSE_SUBLIKE_ACTION_RET_EXPR If set, the syntax will parse like an expression; if not it will parse like a statement. This is set by default if a name was not found. The moddata field will point towards an HV that modules can used to store extra data between stages. As a naming convention a module should prefix its keys with its own module name and a slash character, "Some::Module/field". The field will point to a newly-created HV for every parse invocation, and will be released when each parse is complete. PARSE HOOKS The XSParseSublikeHooks structure provides the following hook stages, which are invoked in the given order. The structure has a flags field, which controls various optional parts of operation. The following flags are defined. XS_PARSE_SUBLIKE_FLAG_FILTERATTRS If set, the optional filter_attr stage will be invoked. XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL If not set, the require_parts field will imply the XS_PARSE_SUBLIKE_PART_BODY flag, making the body part required. By setting this flag this will no longer happen. If all hooks agree, then the body will become optional. XS_PARSE_SUBLIKE_FLAG_PREFIX If set, the keyword is considered to be a prefix that can be placed in front of sub or another sub-like keyword, to add its set of hooks in addition to those of the following keyword. These prefices may be further stacked. In addition there are two U8 fields named require_parts and skip_parts which control the behaviour of various parts of the syntax which are usually optional. Any parts with bits set in require_parts become non-optional, and an error if they are missing. Any parts with bits set in skip_parts will skip the relevant part of the parsing process. When multiple sets of hooks are combined by the xs_parse_sublike_any function, or as part of parsing prefixing keywords, these bitmasks are accumulated together with inclusive or. Any part required by any set of hooks will still be required; any step skipped by either will be skipped entirely. If the same bit is set in both fields then the relevant parsing step will not be performed but it will still be an error for that section to be missing. This is likely not useful. Note that for skipped parts, only the actual parsing steps are skipped. A hook function can still set the relevant fields in the context structure anyway to force a particular value for those parts. XS_PARSE_SUBLIKE_PART_NAME The name of the function. XS_PARSE_SUBLIKE_PART_ATTRS The attributes of the function. This part can be skipped, but the bit is ignored when in require_parts. It is always permitted to not provide any additional attributes to a function definition. XS_PARSE_SUBLIKE_PART_SIGNATURE The parameter signature of the function. This part can be skipped, but it is always permitted not to provide a signature for a function definition even if the bit it set in require_parts. This is because such syntax only applies when use feature 'signatures' is in effect, and only on supporting perl versions. However, setting the bit in require_parts instead has the effect of enabling use feature 'signatures' (at least on supporting perl versions), thus permitting the syntax to use a signature even if the signatures feature was not previously enabled. XS_PARSE_SUBLIKE_PART_BODY The actual body of the function, expressed as a brace-delimited block. This part cannot be skipped, but it can be made optional by omitting it from the require_parts field. Instead of the block, it is permitted to place a single semicolon (;) to act as a statement terminator; thus giving the same syntax as a subroutine forward declaration. In this case, the body and cv fields of the context structure will remain NULL. This flag is currently implied on the require_parts field if the hook does not supply the XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL flag; meaning that most use-cases will make it a required part. The permit Stage const char *permit_hintkey bool (*permit)(pTHX_ void *hookdata) Called by the installed keyword parser hook which is used to handle keywords registered by "register_xs_parse_sublike". As a shortcut for the common case, the permit_hintkey may point to a string to look up from the hints hash. If the given key name is not found in the hints hash then the keyword is not permitted. If the key is present then the permit function is invoked as normal. If not rejected by a hint key that was not found in the hints hash, the function part of the stage is called next and should inspect whether the keyword is permitted at this time perhaps by inspecting other lexical clues, and return true only if the keyword is permitted. Both the string and the function are optional. Either or both may be present. If neither is present then the keyword is always permitted - which is likely not what you wanted to do. Parse Name At this point, the optional name is parsed and filled into the name field of the context. The pre_subparse Stage void (*pre_subparse)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just before start_subparse() is called. Parse Attrs At this point the optional sub attributes are parsed and filled into the attrs field of the context, then block_start() is called. The optional filter_attr Stage bool (*filter_attr)(pTHX_ struct XSParseSublikeContext *ctx, SV *attr, SV *val, void *hookdata); If the flags field includes XS_PARSE_SUBLIKE_FLAG_FILTERATTRS then each individual attribute is passed through this optional filter function immediately as each is parsed. attr will be a string SV containing the name of the attribute, and val will either be NULL, or a string SV containing the contents of the parens after its name (without the parens themselves). If the filter returns true, it indicates that it has in some way handled the attribute and it should not be added to the list given to newATTRSUB(). If the filter returns false it will be handled in the usual way; equivalent to the case where the filter function did not exist. The post_blockstart Stage void (*post_blockstart)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked after the block_start() function has been called. This hook stage may wish to perform any alterations of PL_compcv or related, inspect or alter the lexical pad, provide hints hash values, or any other tasks before the signature and code body are parsed. Parse Body At this point, the main body of the function is parsed and the optree is stored in the body field of the context. If the perl version supports sub signatures and they are enabled and found, the body will be prefixed with the signature ops as well. The pre_blockend Stage void (*pre_blockend)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just before the block_end() function is invoked. The hook stage may wish to inspect or alter the optree stored in the body context field. The post_newcv Stage void (*post_newcv)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just after newATTRSUB() has been invoked on the optree. The hook stage may wish to inspect or alter the CV stored in the cv context field. AUTHOR Paul Evans XS-Parse-Sublike-0.22/hax000755001750001750 014643004052 13732 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/hax/COP_SEQ_RANGE_HIGH_set.c.inc000444001750001750 27314643004052 20504 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef COP_SEQ_RANGE_HIGH_set #define COP_SEQ_RANGE_HIGH_set(SV, VAL) \ STMT_START { ((XPVNV*)SvANY(SV))->xnv_u.xpad_cop_seq.xhigh = (VAL); } STMT_END #endif XS-Parse-Sublike-0.22/hax/LOGOP_ANY.c.inc000444001750001750 171314643004052 16374 0ustar00leoleo000000000000/* vi: set ft=c : */ struct logop_any { BASEOP OP *op_first; OP *op_other; ANY *op_any; }; typedef struct logop_any LOGOP_ANY; #define cLOGOP_ANYx(o) ((LOGOP_ANY *)o) #define cLOGOP_ANY cLOGOP_ANYx(PL_op) #define cLOGOP_ANYo cLOGOP_ANYx(o) #ifndef OpTYPE_set # define OpTYPE_set(op, type) \ STMT_START { \ op->op_type = (OPCODE)type; \ op->op_ppaddr = PL_ppaddr[type]; \ } STMT_END #endif #define alloc_LOGOP_ANY(type, first, other) MY_alloc_LOGOP_ANY(aTHX_ type, first, other) static LOGOP_ANY *MY_alloc_LOGOP_ANY(pTHX_ I32 type, OP *first, OP *other) { dVAR; LOGOP_ANY *logop; OP *kid = first; NewOp(1101, logop, 1, LOGOP_ANY); OpTYPE_set(logop, type); logop->op_first = first; logop->op_other = other; if (first) logop->op_flags = OPf_KIDS; while (kid && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid); if (kid) OpLASTSIB_set(kid, (OP*)logop); return logop; } XS-Parse-Sublike-0.22/hax/block_end.c.inc000444001750001750 215714643004052 16730 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef block_end #include "scalarseq.c.inc" #include "pad_leavemy.c.inc" #define block_end(A, B) S_block_end(aTHX_ A, B) static OP *S_block_end(pTHX_ I32 floor, OP *seq) { dVAR; const int needblockscope = PL_hints & HINT_BLOCK_SCOPE; OP *retval = scalarseq(seq); OP *o; CALL_BLOCK_HOOKS(bhk_pre_end, &retval); LEAVE_SCOPE(floor); #if !HAVE_PERL_VERSION(5, 19, 3) CopHINTS_set(&PL_compiling, PL_hints); #endif if (needblockscope) PL_hints |= HINT_BLOCK_SCOPE; /* propagate out */ o = pad_leavemy(); if (o) { #if HAVE_PERL_VERSION(5, 17, 4) OP *kid = o->op_flags & OPf_KIDS ? cLISTOPo->op_first : o; OP *const last = o->op_flags & OPf_KIDS ? cLISTOPo->op_last : o; for (;; kid = kid->op_sibling) { OP *newkid = newOP(OP_CLONECV, 0); newkid->op_targ = kid->op_targ; o = op_append_elem(OP_LINESEQ, o, newkid); if (kid == last) break; } retval = op_prepend_elem(OP_LINESEQ, o, retval); #endif } CALL_BLOCK_HOOKS(bhk_post_end, &retval); return retval; } #endif XS-Parse-Sublike-0.22/hax/block_start.c.inc000444001750001750 72414643004052 17275 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef block_start #include "pad_block_start.c.inc" #define block_start(A) S_block_start(aTHX_ A) static int S_block_start(pTHX_ int full) { dVAR; const int retval = PL_savestack_ix; pad_block_start(full); SAVEHINTS(); PL_hints &= ~HINT_BLOCK_SCOPE; SAVECOMPILEWARNINGS(); PL_compiling.cop_warnings = DUP_WARNINGS(PL_compiling.cop_warnings); CALL_BLOCK_HOOKS(bhk_start, full); return retval; } #endif XS-Parse-Sublike-0.22/hax/croak_from_caller.c.inc000444001750001750 154614643004052 20455 0ustar00leoleo000000000000/* vi: set ft=c : */ static void S_croaksv_from_caller(pTHX_ SV *msg_sv) __attribute__noreturn__; static void S_croaksv_from_caller(pTHX_ SV *msg_sv) { I32 count = 0; const PERL_CONTEXT *cx; while((cx = caller_cx(count, NULL))) { count++; /* TODO: Skip internal call frames? */ /* warn("TODO: maybe croak from caller where caller stash is %s\n", * HvNAME(CopSTASH(cx->blk_oldcop))); */ PL_curcop = cx->blk_oldcop; break; } croak_sv(msg_sv); } #define croak_from_caller(fmt, ...) S_croak_from_caller(aTHX_ fmt, __VA_ARGS__) static void S_croak_from_caller(pTHX_ const char *fmt, ...) __attribute__noreturn__; static void S_croak_from_caller(pTHX_ const char *fmt, ...) { va_list args; va_start(args, fmt); SV *msg_sv = sv_2mortal(vnewSVpvf(fmt, &args)); va_end(args); S_croaksv_from_caller(aTHX_ msg_sv); } XS-Parse-Sublike-0.22/hax/lexer-additions.c.inc000444001750001750 1525314643004052 20124 0ustar00leoleo000000000000/* vi: set ft=c : */ /* Perls before 5.18 lack isIDCONT_uni, but baring minor differences of weird * Unicode characters, isALNUM_uni is close enough */ #ifndef isIDCONT_uni #define isIDCONT_uni(c) isALNUM_uni(c) #endif #define sv_cat_c(sv, c) MY_sv_cat_c(aTHX_ sv, c) static void MY_sv_cat_c(pTHX_ SV *sv, U32 c) { char ds[UTF8_MAXBYTES + 1], *d; d = (char *)uvchr_to_utf8((U8 *)ds, c); if (d - ds > 1) { sv_utf8_upgrade(sv); } sv_catpvn(sv, ds, d - ds); } #define lex_consume(s) MY_lex_consume(aTHX_ s) static int MY_lex_consume(pTHX_ char *s) { /* I want strprefix() */ size_t i; for(i = 0; s[i]; i++) { if(s[i] != PL_parser->bufptr[i]) return 0; } lex_read_to(PL_parser->bufptr + i); return i; } enum { LEX_IDENT_PACKAGENAME = (1<<0), }; #define lex_scan_ident( ) MY_lex_scan_ident(aTHX_ 0) #define lex_scan_packagename() MY_lex_scan_ident(aTHX_ LEX_IDENT_PACKAGENAME) static SV *MY_lex_scan_ident(pTHX_ int flags) { I32 c; bool at_start = TRUE; char *ident = PL_parser->bufptr; while((c = lex_peek_unichar(0))) { if(at_start ? isIDFIRST_uni(c) : isALNUM_uni(c)) at_start = FALSE; /* TODO: This sucks in the case of a false Foo:Bar match */ else if((flags & LEX_IDENT_PACKAGENAME) && (c == ':')) { lex_read_unichar(0); if(lex_read_unichar(0) != ':') croak("Expected colon to be followed by another in package name"); } else break; lex_read_unichar(0); } STRLEN len = PL_parser->bufptr - ident; if(!len) return NULL; SV *ret = newSVpvn(ident, len); if(lex_bufutf8()) SvUTF8_on(ret); return ret; } #define lex_scan_attrval_into(name, val) MY_lex_scan_attrval_into(aTHX_ name, val) static bool MY_lex_scan_attrval_into(pTHX_ SV *name, SV *val) { /* TODO: really want lex_scan_ident_into() */ SV *n = lex_scan_ident(); if(!n) return FALSE; sv_setsv(name, n); SvREFCNT_dec(n); if(name != val) SvPOK_off(val); /* Do not read space here as space is not allowed between NAME(ARGS) */ if(lex_peek_unichar(0) != '(') return TRUE; lex_read_unichar(0); if(name == val) sv_cat_c(val, '('); else sv_setpvs(val, ""); int count = 1; I32 c = lex_peek_unichar(0); while(count && c != -1) { if(c == '(') count++; if(c == ')') count--; if(c == '\\') { /* The next char does not bump count even if it is ( or ); * the \\ is still captured */ sv_cat_c(val, lex_read_unichar(0)); c = lex_peek_unichar(0); if(c == -1) goto unterminated; } /* Don't append final closing ')' on split name/val */ if(count || (name == val)) sv_cat_c(val, c); lex_read_unichar(0); c = lex_peek_unichar(0); } if(c == -1) return FALSE; return TRUE; unterminated: croak("Unterminated attribute parameter in attribute list"); } #define lex_scan_attr() MY_lex_scan_attr(aTHX) static SV *MY_lex_scan_attr(pTHX) { SV *ret = newSV(0); if(MY_lex_scan_attrval_into(aTHX_ ret, ret)) return ret; SvREFCNT_dec(ret); return NULL; } #define lex_scan_attrs(compcv) MY_lex_scan_attrs(aTHX_ compcv) static OP *MY_lex_scan_attrs(pTHX_ CV *compcv) { /* Attributes are supplied to newATTRSUB() as an OP_LIST containing * OP_CONSTs, one attribute in each as a plain SV. Note that we don't have * to parse inside the contents of the parens; that is handled by the * attribute handlers themselves */ OP *attrs = NULL; SV *attr; lex_read_space(0); while((attr = lex_scan_attr())) { lex_read_space(0); if(compcv && strEQ(SvPV_nolen(attr), "lvalue")) { CvLVALUE_on(compcv); } if(!attrs) attrs = newLISTOP(OP_LIST, 0, NULL, NULL); attrs = op_append_elem(OP_LIST, attrs, newSVOP(OP_CONST, 0, attr)); /* Accept additional colons to prefix additional attrs */ if(lex_peek_unichar(0) == ':') { lex_read_unichar(0); lex_read_space(0); } } return attrs; } #define lex_scan_lexvar() MY_lex_scan_lexvar(aTHX) static SV *MY_lex_scan_lexvar(pTHX) { int sigil = lex_peek_unichar(0); switch(sigil) { case '$': case '@': case '%': lex_read_unichar(0); break; default: croak("Expected a lexical variable"); } SV *ret = lex_scan_ident(); if(!ret) return NULL; /* prepend sigil - which we know to be a single byte */ SvGROW(ret, SvCUR(ret) + 1); Move(SvPVX(ret), SvPVX(ret) + 1, SvCUR(ret), char); SvPVX(ret)[0] = sigil; SvCUR(ret)++; SvPVX(ret)[SvCUR(ret)] = 0; return ret; } #define lex_scan_parenthesized() MY_lex_scan_parenthesized(aTHX) static SV *MY_lex_scan_parenthesized(pTHX) { I32 c; int parencount = 0; SV *ret = newSVpvs(""); if(lex_bufutf8()) SvUTF8_on(ret); c = lex_peek_unichar(0); while(c != -1) { sv_cat_c(ret, lex_read_unichar(0)); switch(c) { case '(': parencount++; break; case ')': parencount--; break; } if(!parencount) break; c = lex_peek_unichar(0); } if(SvCUR(ret)) return ret; SvREFCNT_dec(ret); return NULL; } #define lex_scan_version(flags) MY_lex_scan_version(aTHX_ flags) static SV *MY_lex_scan_version(pTHX_ int flags) { I32 c; SV *tmpsv = sv_2mortal(newSVpvs("")); /* scan_version() expects a version to end in linefeed, semicolon or * openbrace; gets confused if other keywords are fine. We'll have to * extract it first. * https://rt.cpan.org/Ticket/Display.html?id=132903 */ while((c = lex_peek_unichar(0))) { /* Allow a single leading v before accepting only digits, dot, underscore */ if((!SvCUR(tmpsv) && (c == 'v')) || strchr("0123456789._", c)) sv_cat_c(tmpsv, lex_read_unichar(0)); else break; } if(!SvCUR(tmpsv) && (flags & PARSE_OPTIONAL)) return NULL; SV *ret = newSV(0); scan_version(SvPVX(tmpsv), ret, FALSE); return ret; } #define parse_lexvar() MY_parse_lexvar(aTHX) static PADOFFSET MY_parse_lexvar(pTHX) { /* TODO: Rewrite this in terms of using lex_scan_lexvar() */ char *lexname = PL_parser->bufptr; if(lex_read_unichar(0) != '$') croak("Expected a lexical scalar at %s", lexname); if(!isIDFIRST_uni(lex_peek_unichar(0))) croak("Expected a lexical scalar at %s", lexname); lex_read_unichar(0); while(isIDCONT_uni(lex_peek_unichar(0))) lex_read_unichar(0); /* Forbid $_ */ if(PL_parser->bufptr - lexname == 2 && lexname[1] == '_') croak("Can't use global $_ in \"my\""); return pad_add_name_pvn(lexname, PL_parser->bufptr - lexname, 0, NULL, NULL); } #define parse_scoped_block(flags) MY_parse_scoped_block(aTHX_ flags) static OP *MY_parse_scoped_block(pTHX_ int flags) { OP *ret; I32 save_ix = block_start(TRUE); ret = parse_block(flags); return block_end(save_ix, ret); } XS-Parse-Sublike-0.22/hax/make_argcheck_aux.c.inc000444001750001750 132314643004052 20423 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef make_argcheck_aux #define make_argcheck_aux(params, opt_params, slurpy) S_make_argcheck_aux(aTHX_ params, opt_params, slurpy) static inline UNOP_AUX_item *S_make_argcheck_aux(pTHX_ UV params, UV opt_params, char slurpy) { # if HAVE_PERL_VERSION(5, 31, 5) struct op_argcheck_aux *aux = (struct op_argcheck_aux*) PerlMemShared_malloc(sizeof(struct op_argcheck_aux)); aux->params = params; aux->opt_params = opt_params; aux->slurpy = slurpy; return (UNOP_AUX_item *)aux; # else UNOP_AUX_item *aux = (UNOP_AUX_item *)PerlMemShared_malloc(sizeof(UNOP_AUX_item) * 3); aux[0].iv = params; aux[1].iv = opt_params; aux[2].iv = slurpy; return aux; # endif } #endif XS-Parse-Sublike-0.22/hax/newSV_with_free.c.inc000444001750001750 101214643004052 20073 0ustar00leoleo000000000000/* vi: set ft=c : */ static int magic_free(pTHX_ SV *sv, MAGIC *mg) { void (*freefunc)(pTHX_ SV *sv) = (void *)mg->mg_ptr; (*freefunc)(aTHX_ sv); return 0; } static const MGVTBL vtbl_sv_with_free = { .svt_free = magic_free, }; #define newSV_with_free(size, freefunc) S_newSV_with_free(aTHX_ size, freefunc) static SV *S_newSV_with_free(pTHX_ STRLEN size, void (*freefunc)(pTHX_ SV *sv)) { SV *sv = newSV(size); sv_magicext(sv, NULL, PERL_MAGIC_ext, &vtbl_sv_with_free, (void *)freefunc, 0); return sv; } XS-Parse-Sublike-0.22/hax/pad_block_start.c.inc000444001750001750 124014643004052 20133 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef pad_block_start #define pad_block_start(A) S_pad_block_start(aTHX_ A) static void S_pad_block_start(pTHX_ int full) { dVAR; ASSERT_CURPAD_ACTIVE("pad_block_start"); SAVEI32(PL_comppad_name_floor); PL_comppad_name_floor = AvFILLp(PL_comppad_name); if (full) PL_comppad_name_fill = PL_comppad_name_floor; if (PL_comppad_name_floor < 0) PL_comppad_name_floor = 0; SAVEI32(PL_min_intro_pending); SAVEI32(PL_max_intro_pending); PL_min_intro_pending = 0; SAVEI32(PL_comppad_name_fill); SAVEI32(PL_padix_floor); PL_padix_floor = PL_padix; PL_pad_reset_pending = FALSE; } #endif XS-Parse-Sublike-0.22/hax/pad_leavemy.c.inc000444001750001750 435514643004052 17300 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef pad_leavemy #include "COP_SEQ_RANGE_HIGH_set.c.inc" #define pad_leavemy() S_pad_leavemy(aTHX) #if HAVE_PERL_VERSION(5, 19, 3) #define IF_HAVE_PERL_5_19_3(YES, NO) YES #else #define IF_HAVE_PERL_5_19_3(YES, NO) NO #endif static OP *S_pad_leavemy(pTHX) { dVAR; I32 off; OP *o = NULL; SV * const * const svp = AvARRAY(PL_comppad_name); PL_pad_reset_pending = FALSE; ASSERT_CURPAD_ACTIVE("pad_leavemy"); if (PL_min_intro_pending && PL_comppad_name_fill < PL_min_intro_pending) { for (off = PL_max_intro_pending; off >= PL_min_intro_pending; off--) { const SV * const sv = svp[off]; if (sv && IF_HAVE_PERL_5_19_3(PadnameLEN(sv), sv != &PL_sv_undef) && !SvFAKE(sv)) Perl_ck_warner_d(aTHX_ packWARN(WARN_INTERNAL), "%"SVf" never introduced", SVfARG(sv)); } } /* "Deintroduce" my variables that are leaving with this scope. */ for (off = AvFILLp(PL_comppad_name); off > PL_comppad_name_fill; off--) { SV * const sv = svp[off]; if (sv && IF_HAVE_PERL_5_19_3(PadnameLEN(sv), sv != &PL_sv_undef) && !SvFAKE(sv) && COP_SEQ_RANGE_HIGH(sv) == PERL_PADSEQ_INTRO) { COP_SEQ_RANGE_HIGH_set(sv, PL_cop_seqmax); DEBUG_Xv(PerlIO_printf(Perl_debug_log, "Pad leavemy: %ld \"%s\", (%lu,%lu)\n", (long)off, SvPVX_const(sv), (unsigned long)COP_SEQ_RANGE_LOW(sv), (unsigned long)COP_SEQ_RANGE_HIGH(sv)) ); #if HAVE_PERL_VERSION(5, 17, 4) if (!PadnameIsSTATE(sv) && !PadnameIsOUR(sv) && *PadnamePV(sv) == '&' && PadnameLEN(sv) > 1) { OP *kid = newOP(OP_INTROCV, 0); kid->op_targ = off; o = op_prepend_elem(OP_LINESEQ, kid, o); } #endif } } PL_cop_seqmax++; if (PL_cop_seqmax == PERL_PADSEQ_INTRO) /* not a legal value */ PL_cop_seqmax++; DEBUG_Xv(PerlIO_printf(Perl_debug_log, "Pad leavemy: seq = %ld\n", (long)PL_cop_seqmax)); return o; } #endif XS-Parse-Sublike-0.22/hax/scalarseq.c.inc000444001750001750 136214643004052 16763 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef scalarseq #define scalarseq(A) S_scalarseq(aTHX_ A) static OP *S_scalarseq(pTHX_ OP *o) { dVAR; if (o) { const OPCODE type = o->op_type; if (type == OP_LINESEQ || type == OP_SCOPE || type == OP_LEAVE || type == OP_LEAVETRY) { OP *kid; for (kid = cLISTOPo->op_first; kid; kid = kid->op_sibling) { if (kid->op_sibling) { op_contextualize(kid, G_VOID); } } PL_curcop = &PL_compiling; } o->op_flags &= ~OPf_PARENS; if (PL_hints & HINT_BLOCK_SCOPE) o->op_flags |= OPf_PARENS; } else o = newOP(OP_STUB, 0); return o; } #endif XS-Parse-Sublike-0.22/hax/sv_setrv.c.inc000444001750001750 46114643004052 16637 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef sv_setrv_noinc # define sv_setrv_noinc(sv, rv) S_sv_setrv(aTHX_ sv, rv) # define sv_setrv_inc(sv, rv) S_sv_setrv(aTHX_ sv, SvREFCNT_inc(rv)) #endif static void S_sv_setrv(pTHX_ SV *sv, SV *rv) { SV *tmp = newRV_noinc(rv); sv_setsv(sv, tmp); SvREFCNT_dec(tmp); } XS-Parse-Sublike-0.22/hax/wrap_keyword_plugin.c.inc000444001750001750 133114643004052 21074 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef OP_CHECK_MUTEX_LOCK /* < 5.15.8 */ # define OP_CHECK_MUTEX_LOCK ((void)0) # define OP_CHECK_MUTEX_UNLOCK ((void)0) #endif #define wrap_keyword_plugin(func, var) S_wrap_keyword_plugin(aTHX_ func, var) static void S_wrap_keyword_plugin(pTHX_ Perl_keyword_plugin_t func, Perl_keyword_plugin_t *var) { /* BOOT can potentially race with other threads (RT123547) */ /* Perl doesn't really provide us a nice mutex for doing this so this is the * best we can find. See also * https://rt.perl.org/Public/Bug/Display.html?id=132413 */ if(*var) return; OP_CHECK_MUTEX_LOCK; if(!*var) { *var = PL_keyword_plugin; PL_keyword_plugin = func; } OP_CHECK_MUTEX_UNLOCK; } XS-Parse-Sublike-0.22/inc000755001750001750 014643004052 13723 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/inc/Module000755001750001750 014643004052 15150 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/inc/Module/Build000755001750001750 014643004052 16207 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/inc/Module/Build/with000755001750001750 014643004052 17162 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/inc/Module/Build/with/XSTests.pm000444001750001750 174514643004052 21241 0ustar00leoleo000000000000package Module::Build::with::XSTests; use v5.14; use warnings; use base qw( Module::Build ); # Stolen and edited from Module::Build::Base::_infer_xs_spec sub _infer_xs_spec { my $self = shift; my ( $file ) = @_; my $spec = $self->SUPER::_infer_xs_spec( $file ); if( $file =~ m{^t/} ) { $spec->{$_} = File::Spec->catdir( "t", $spec->{$_} ) for qw( archdir bs_file lib_file ); } return $spec; } # Various bits stolen from Module::Build::Base:: # process_xs_files() sub ACTION_testlib { my $self = shift; my $testxsfiles = $self->_find_file_by_type('xs', 't'); foreach my $from ( sort keys %$testxsfiles ) { my $to = $testxsfiles->{$from}; if( $to ne $from ) { $self->add_to_cleanup( $to ); $self->copy_if_modified( from => $from, to => $to ); } $self->process_xs( $to ); } } sub ACTION_test { my $self = shift; $self->depends_on( "testlib" ); $self->SUPER::ACTION_test( @_ ); } 0x55AA; XS-Parse-Sublike-0.22/include000755001750001750 014643004052 14575 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/include/parse_subsignature_ex.h000444001750001750 177514643004052 21516 0ustar00leoleo000000000000/* vi: set ft=c : */ /* Some experimental extension flags. Not (currently) part of core perl API */ enum { PARSE_SUBSIGNATURE_NAMED_PARAMS = (1<<0), /* Permits ( :$foo, :$bar, :$splot = "default" ) named params * They are accumulated into a slurpy hash then extracted afterwards * As with positional params, any param without a defaulting expression is * required; an error is thrown if the caller did not provide it */ PARSE_SUBSIGNATURE_PARAM_ATTRIBUTES = (1<<1), /* Permits ( $param :Attribute(Value) ) attributes on params * These must be registered by calling register_subsignature_attribute() */ }; #define parse_subsignature_ex(flags) XPS_parse_subsignature_ex(aTHX_ flags) OP *XPS_parse_subsignature_ex(pTHX_ int flags); #define register_subsignature_attribute(name, funcs, funcdata) XPS_register_subsignature_attribute(aTHX_ name, funcs, funcdata) void XPS_register_subsignature_attribute(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata); XS-Parse-Sublike-0.22/lib000755001750001750 014643004052 13720 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/lib/Sublike000755001750001750 014643004052 15316 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/lib/Sublike/Extended.pm000444001750001750 700214643004052 17550 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2023 -- leonerd@leonerd.org.uk package Sublike::Extended 0.22; use v5.14; use warnings; require XSLoader; XSLoader::load( __PACKAGE__, our $VERSION ); =head1 NAME C - enable extended features when parsing C-like syntax =head1 SYNOPSIS use v5.26; use Sublike::Extended; use experimental 'signatures'; extended sub greet (:$name = "world") { say "Hello, $name"; } greet( name => $ENV{USER} ); =head1 DESCRIPTION This module extends the syntax for declaring named or anonymous subroutines using Perl's builtin C keyword, or other similar keywords provided by third-party modules, to enable parsing of extra features. Currently, the only extended features that are provided are related to the parsing of a subroutine signature. Since signatures are only available on Perl version 5.26 or later, this module is unlikely to be useful in earlier versions of Perl. =head2 Named parameters Extended subroutines can be declare named parameters in the signature, after any positional ones. These take the form of a name prefixed by a colon character. The caller of such a function should pass values for these parameters by the usual name-value pair syntax that would be used for passing into a regular hash. Within the body of the subroutine the values passed into these are unpacked into regular lexical variables. extended sub colour (:$red, :$green, :$blue) { ... # $red, $green and $blue are available as regular lexicals } # argument order at the caller site is not important colour(green => 1, blue => 2, red => 3); As with positional parameters, they are normally mandatory, but can be made optional by supplying a defaulting expression. If the caller fails to pass a value corresponding to the parameter, the default expression is evaluated and used instead. extended sub f (:$x0, :$x1, :$x2 = 0) { ... } # The caller must provide x0 and x1, but x2 is optional An optional slurpy hash is also permitted after all of these. It will contain the values of any other name-value pairs given by the caller, after those corresponding to named parameters have already been extracted. extended sub g (:$alpha, :$beta, %rest) { ... } =head2 Parameter Attributes Parameters to extended subroutines can use attribute syntax to apply extra attributes to individual parameters. extended sub info ($x :Attribute) { ... } Any attributes that are available are ones that have been previously registered with L using its XS-level API. The particular behaviour of such an attribute would be defined by whatever module provided the attribute. =head1 KEYWORDS =head2 extended extended sub NAME (SIGNATURE...) { BODY... } extended sub (SIGNATURE...) { BODY... }; This prefix keyword enables extra parsing features when handling a C (or other sub-like function keyword). This keyword can be freely mixed with other C-prefix keywords, such as C from L async extended sub f (:$param) { ... } This can also be used with other keywords that provide C-like syntax, such as C from L or the core C. extended method f (:$param) { ... } =cut sub import { $^H{"Sublike::Extended/extended"}++; } sub unimport { delete $^H{"Sublike::Extended/extended"}; } =head1 AUTHOR Paul Evans =cut 0x55AA; XS-Parse-Sublike-0.22/lib/Sublike/Extended.xs000444001750001750 132114643004052 17564 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2023 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static struct XSParseSublikeHooks hooks_extended = { .permit_hintkey = "Sublike::Extended/extended", .flags = XS_PARSE_SUBLIKE_FLAG_PREFIX| XS_PARSE_SUBLIKE_FLAG_SIGNATURE_NAMED_PARAMS| XS_PARSE_SUBLIKE_FLAG_SIGNATURE_PARAM_ATTRIBUTES, /* No hooks */ }; MODULE = Sublike::Extended PACKAGE = Sublike::Extended BOOT: boot_xs_parse_sublike(0); // TODO register_xs_parse_sublike("extended", &hooks_extended, NULL); XS-Parse-Sublike-0.22/lib/XS000755001750001750 014643004052 14252 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/lib/XS/Parse000755001750001750 014643004052 15324 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/lib/XS/Parse/Sublike.pm000444001750001750 3331214643004052 17437 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020-2021 -- leonerd@leonerd.org.uk package XS::Parse::Sublike 0.22; use v5.14; use warnings; require XSLoader; XSLoader::load( __PACKAGE__, our $VERSION ); =encoding UTF-8 =head1 NAME C - XS functions to assist in parsing C-like syntax =head1 DESCRIPTION This module provides some XS functions to assist in writing parsers for C-like syntax, primarily for authors of keyword plugins using the C hook mechanism. It is unlikely to be of much use to anyone else; and highly unlikely to be any use when writing perl code using these. Unless you are writing a keyword plugin using XS, this module is not for you. This module is also currently experimental, and the design is still evolving and subject to change. Later versions may break ABI compatibility, requiring changes or at least a rebuild of any module that depends on it. =head1 XS FUNCTIONS =head2 boot_xs_parse_sublike void boot_xs_parse_sublike(double ver) Call this function from your C section in order to initialise the module and parsing hooks. I should either be 0 or a decimal number for the module version requirement; e.g. boot_xs_parse_sublike(0.04); =head2 xs_parse_sublike int xs_parse_sublike(const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) This function performs the actual parsing of a C-like keyword. It expects the lexer to be at a position just after the introduction keyword has been consumed, and will proceed to parse an optional name, list of attributes, signature (if enabled by C), and code body. The return value and C can be used directly from the keyword plugin function. It is intended this function be invoked from it, and the result returned directly. For a more automated handling of keywords, see L. I should be a structure that can provide optional function pointers used to customise the parsing process at various stages. I is an opaque pointer which is passed through to each of the hook stage functions. =head2 register_xs_parse_sublike void register_xs_parse_sublike(const char *keyword, const struct XSParseSublikeHooks *hooks, void *hookdata) This function installs a set of parsing hooks to be associated with the given keyword. Such a keyword will then be handled automatically by a keyword parser installed by C itself. When the keyword is encountered, the hook's C function is first tested to see if the keyword is permitted at this point. If the function returns true then the keyword is consumed and parsed as per L. I is an opaque pointer which is passed through to each of the hook stage functions when they are invoked. =head2 xs_parse_sublike_any int xs_parse_sublike_any(const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) This function expects to consume an introduction keyword at the lexer position which is either C or the name of another C-like keyword, which has been previously registered using L. It then proceeds to parse the subsequent syntax similar to how it would have parsed if encountered by the module's own keyword parser plugin, except that the second set of hooks given here also take effect. If a regular C is encountered, then this is parsed using the I in a similar way to C. If a different registered C-like keyword is encountered, then parsing is performed using B sets of hooks - the ones given to this function as well as the ones registered with the keyword. This allows their effects to combined. The hooks given by the I argument are considered to be on the "outside" from those of the registered keyword "inside". The outside ones run first for all stages, except C which runs them inside-out. I is an opaque pointer which is passed through to each of the hook stage functions when they are invoked. Note that this function is now vaguely discouraged, in favour of using a prefixing keyword instead, by using the C flag. =head1 PARSE CONTEXT The various hook stages all share state about the ongoing parse process using various fields of the C structure. struct XSParseSublikeContext { SV *name; OP *attrs; OP *body; CV *cv; U32 actions; HV *moddata; } The C field will contain a bitmask of action flags that control the various steps that C might take inbetween invoking hook stages. The initial value of this field is set after the name-parsing stage, depending on whether or not a name is found. Stage hook functions may modify the field to adjust the subsequent behaviour. At the current ABI version, a module will have to set the C bit of the C field in order to make use of the I field. A future ABI version may remove this restriction. =over 4 =item XS_PARSE_SUBLIKE_ACTION_CVf_ANON If set, the C call will be set up for an anonymous function protosub; if not it will be set for a named function. This is set by default if a name was not found. =item XS_PARSE_SUBLIKE_ACTION_SET_CVNAME If set, the newly-constructed CV will have the given name set on it. This is set by default if a name was found. On Perl versions 5.22 and above, this flag can be set even if C is not. In this case, the CV will not be reachable via the symbol table, even though it knows its own name and pretends that it is. On earlier versions of perl this flag will be ignored in that case. =item XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL If set, the newly-constructed CV will be installed into the symbol table at its given name. Note that it is not possible to enable this flag without also enabling C. This is set by default if a name was found. =item XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE If set, the syntax will yield the C / C optree fragment typical of anonymous code expressions; if not it will be C. This is set by default if a name was not found. =item XS_PARSE_SUBLIKE_ACTION_RET_EXPR If set, the syntax will parse like an expression; if not it will parse like a statement. This is set by default if a name was not found. =back The I field will point towards an HV that modules can used to store extra data between stages. As a naming convention a module should prefix its keys with its own module name and a slash character, C<"Some::Module/field">. The field will point to a newly-created HV for every parse invocation, and will be released when each parse is complete. =head1 PARSE HOOKS The C structure provides the following hook stages, which are invoked in the given order. The structure has a I field, which controls various optional parts of operation. The following flags are defined. =over 4 =item XS_PARSE_SUBLIKE_FLAG_FILTERATTRS If set, the optional C stage will be invoked. =item XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL If B set, the I field will imply the C flag, making the body part required. By setting this flag this will no longer happen. If all hooks agree, then the body will become optional. =item XS_PARSE_SUBLIKE_FLAG_PREFIX If set, the keyword is considered to be a prefix that can be placed in front of C or another sub-like keyword, to add its set of hooks in addition to those of the following keyword. These prefices may be further stacked. =back In addition there are two C fields named I and I which control the behaviour of various parts of the syntax which are usually optional. Any parts with bits set in I become non-optional, and an error if they are missing. Any parts with bits set in I will skip the relevant part of the parsing process. When multiple sets of hooks are combined by the C function, or as part of parsing prefixing keywords, these bitmasks are accumulated together with inclusive or. Any part required by any set of hooks will still be required; any step skipped by either will be skipped entirely. If the same bit is set in both fields then the relevant parsing step will not be performed but it will still be an error for that section to be missing. This is likely not useful. Note that for skipped parts, only the actual parsing steps are skipped. A hook function can still set the relevant fields in the context structure anyway to force a particular value for those parts. =over 4 =item XS_PARSE_SUBLIKE_PART_NAME The name of the function. =item XS_PARSE_SUBLIKE_PART_ATTRS The attributes of the function. This part can be skipped, but the bit is ignored when in I. It is always permitted to not provide any additional attributes to a function definition. =item XS_PARSE_SUBLIKE_PART_SIGNATURE The parameter signature of the function. This part can be skipped, but it is always permitted not to provide a signature for a function definition even if the bit it set in I. This is because such syntax only applies when C is in effect, and only on supporting perl versions. However, setting the bit in I instead has the effect of enabling C (at least on supporting perl versions), thus permitting the syntax to use a signature even if the signatures feature was not previously enabled. =item XS_PARSE_SUBLIKE_PART_BODY The actual body of the function, expressed as a brace-delimited block. This part cannot be skipped, but it can be made optional by omitting it from the I field. Instead of the block, it is permitted to place a single semicolon (C<;>) to act as a statement terminator; thus giving the same syntax as a subroutine forward declaration. In this case, the C and C fields of the context structure will remain C. This flag is currently implied on the I field if the hook does not supply the C flag; meaning that most use-cases will make it a required part. =back =head2 The C Stage const char *permit_hintkey bool (*permit)(pTHX_ void *hookdata) Called by the installed keyword parser hook which is used to handle keywords registered by L. As a shortcut for the common case, the C may point to a string to look up from the hints hash. If the given key name is not found in the hints hash then the keyword is not permitted. If the key is present then the C function is invoked as normal. If not rejected by a hint key that was not found in the hints hash, the function part of the stage is called next and should inspect whether the keyword is permitted at this time perhaps by inspecting other lexical clues, and return true only if the keyword is permitted. Both the string and the function are optional. Either or both may be present. If neither is present then the keyword is always permitted - which is likely not what you wanted to do. =head2 Parse Name At this point, the optional name is parsed and filled into the C field of the context. =head2 The C Stage void (*pre_subparse)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just before C is called. =head2 Parse Attrs At this point the optional sub attributes are parsed and filled into the C field of the context, then C is called. =head2 The optional C Stage bool (*filter_attr)(pTHX_ struct XSParseSublikeContext *ctx, SV *attr, SV *val, void *hookdata); If the I field includes C then each individual attribute is passed through this optional filter function immediately as each is parsed. I will be a string SV containing the name of the attribute, and I will either be C, or a string SV containing the contents of the parens after its name (without the parens themselves). If the filter returns C, it indicates that it has in some way handled the attribute and it should not be added to the list given to C. If the filter returns C it will be handled in the usual way; equivalent to the case where the filter function did not exist. =head2 The C Stage void (*post_blockstart)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked after the C function has been called. This hook stage may wish to perform any alterations of C or related, inspect or alter the lexical pad, provide hints hash values, or any other tasks before the signature and code body are parsed. =head2 Parse Body At this point, the main body of the function is parsed and the optree is stored in the C field of the context. If the perl version supports sub signatures and they are enabled and found, the body will be prefixed with the signature ops as well. =head2 The C Stage void (*pre_blockend)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just before the C function is invoked. The hook stage may wish to inspect or alter the optree stored in the C context field. =head2 The C Stage void (*post_newcv)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) Invoked just after C has been invoked on the optree. The hook stage may wish to inspect or alter the CV stored in the C context field. =cut =head1 AUTHOR Paul Evans =cut 0x55AA; XS-Parse-Sublike-0.22/lib/XS/Parse/Sublike.xs000444001750001750 5027414643004052 17463 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2019-2023 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" /* We need to be able to see FEATURE_*_IS_ENABLED */ #define PERL_EXT #include "feature.h" #include "XSParseSublike.h" #define HAVE_PERL_VERSION(R, V, S) \ (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S)))))) #if HAVE_PERL_VERSION(5, 37, 10) /* feature 'class' first became available in 5.37.9 but it wasn't until * 5.37.10 that we could pass CVf_IsMETHOD to start_subparse() */ # define HAVE_FEATURE_CLASS #endif /* We always need this included to get the struct and function definitions * visible, even though we won't be calling it */ #include "parse_subsignature_ex.h" #if HAVE_PERL_VERSION(5, 26, 0) # include "make_argcheck_aux.c.inc" # if !HAVE_PERL_VERSION(5, 31, 3) # define parse_subsignature(flags) parse_subsignature_ex(0) /* ignore core flags as there are none */ # endif # define HAVE_PARSE_SUBSIGNATURE #endif #if !HAVE_PERL_VERSION(5, 22, 0) # include "block_start.c.inc" # include "block_end.c.inc" #endif #ifndef wrap_keyword_plugin # include "wrap_keyword_plugin.c.inc" #endif #include "lexer-additions.c.inc" #define QUOTED_PVNf "\"%.*s\"%s" #define QUOTED_PVNfARG(pv,len) ((len) <= 255 ? (int)(len) : 255), (pv), ((len) <= 255 ? "" : "...") struct HooksAndData { const struct XSParseSublikeHooks *hooks; void *data; }; #define FOREACH_HOOKS_FORWARD \ for(hooki = 0; \ (hooki < nhooks) && (hooks = hooksanddata[hooki].hooks, hookdata = hooksanddata[hooki].data), (hooki < nhooks); \ hooki++) #define FOREACH_HOOKS_REVERSE \ for(hooki = nhooks - 1; \ (hooki >= 0) && (hooks = hooksanddata[hooki].hooks, hookdata = hooksanddata[hooki].data), (hooki >= 0); \ hooki--) /* Non-documented internal flags we use for our own purposes */ enum { XS_PARSE_SUBLIKE_ACTION_CVf_IsMETHOD = (1<<31), /* do we set CVf_IsMETHOD? */ }; static int parse(pTHX_ struct HooksAndData hooksanddata[], size_t nhooks, OP **op_ptr) { struct XSParseSublikeContext ctx = { 0 }; IV hooki; const struct XSParseSublikeHooks *hooks; void *hookdata; U8 require_parts = 0, skip_parts = 0; bool have_dynamic_actions = FALSE; ENTER_with_name("parse_sublike"); /* From here onwards any `return` must be prefixed by LEAVE_with_name() */ U32 was_scopestack_ix = PL_scopestack_ix; ctx.moddata = newHV(); SAVEFREESV(ctx.moddata); FOREACH_HOOKS_FORWARD { require_parts |= hooks->require_parts; skip_parts |= hooks->skip_parts; if(!(hooks->flags & XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL)) require_parts |= XS_PARSE_SUBLIKE_PART_BODY; if(hooks->flags & XS_PARSE_SUBLIKE_COMPAT_FLAG_DYNAMIC_ACTIONS) have_dynamic_actions = TRUE; } if(!(skip_parts & XS_PARSE_SUBLIKE_PART_NAME)) { ctx.name = lex_scan_ident(); lex_read_space(0); } if((require_parts & XS_PARSE_SUBLIKE_PART_NAME) && !ctx.name) croak("Expected name for sub-like construction"); /* Initial idea of actions are determined by whether we have a name */ ctx.actions = ctx.name ? /* named */ XS_PARSE_SUBLIKE_ACTION_SET_CVNAME|XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL : /* anon */ XS_PARSE_SUBLIKE_ACTION_CVf_ANON|XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE|XS_PARSE_SUBLIKE_ACTION_RET_EXPR; FOREACH_HOOKS_FORWARD { if(hooks->pre_subparse) (*hooks->pre_subparse)(aTHX_ &ctx, hookdata); } #ifdef DEBUGGING if(PL_scopestack_ix != was_scopestack_ix) croak("ARGH: pre_subparse broke the scopestack (was %d, now %d)\n", was_scopestack_ix, PL_scopestack_ix); #endif if(!have_dynamic_actions) { if(ctx.name) ctx.actions &= ~XS_PARSE_SUBLIKE_ACTION_CVf_ANON; else ctx.actions |= XS_PARSE_SUBLIKE_ACTION_CVf_ANON; } int subparse_flags = 0; if(ctx.actions & XS_PARSE_SUBLIKE_ACTION_CVf_ANON) subparse_flags |= CVf_ANON; #ifdef HAVE_FEATURE_CLASS if(ctx.actions & XS_PARSE_SUBLIKE_ACTION_CVf_IsMETHOD) subparse_flags |= CVf_IsMETHOD; #endif I32 floor_ix = start_subparse(FALSE, subparse_flags); SAVEFREESV(PL_compcv); if(!(skip_parts & XS_PARSE_SUBLIKE_PART_ATTRS) && (lex_peek_unichar(0) == ':')) { lex_read_unichar(0); lex_read_space(0); ctx.attrs = newLISTOP(OP_LIST, 0, NULL, NULL); while(1) { SV *attr = newSV(0); SV *val = newSV(0); if(!lex_scan_attrval_into(attr, val)) break; lex_read_space(0); if(lex_peek_unichar(0) == ':') { lex_read_unichar(0); lex_read_space(0); } bool handled = FALSE; FOREACH_HOOKS_FORWARD { if((hooks->flags & XS_PARSE_SUBLIKE_FLAG_FILTERATTRS) && (hooks->filter_attr)) handled |= (*hooks->filter_attr)(aTHX_ &ctx, attr, val, hookdata); } if(handled) { SvREFCNT_dec(attr); SvREFCNT_dec(val); continue; } if(strEQ(SvPVX(attr), "lvalue")) { CvLVALUE_on(PL_compcv); continue; } if(SvPOK(val)) sv_catpvf(attr, "(%" SVf ")", val); SvREFCNT_dec(val); ctx.attrs = op_append_elem(OP_LIST, ctx.attrs, newSVOP(OP_CONST, 0, attr)); } } PL_hints |= HINT_LOCALIZE_HH; I32 save_ix = block_start(TRUE); FOREACH_HOOKS_FORWARD { if(hooks->post_blockstart) (*hooks->post_blockstart)(aTHX_ &ctx, hookdata); } #ifdef DEBUGGING if(PL_scopestack_ix != was_scopestack_ix) croak("ARGH: post_blockstart broke the scopestack (was %d, now %d)\n", was_scopestack_ix, PL_scopestack_ix); #endif #ifdef HAVE_PARSE_SUBSIGNATURE OP *sigop = NULL; if(!(skip_parts & XS_PARSE_SUBLIKE_PART_SIGNATURE) && (lex_peek_unichar(0) == '(')) { lex_read_unichar(0); lex_read_space(0); if(require_parts & XS_PARSE_SUBLIKE_PART_SIGNATURE) { #if HAVE_PERL_VERSION(5, 32, 0) SAVEI32(PL_compiling.cop_features); PL_compiling.cop_features |= FEATURE_SIGNATURES_BIT; #else /* So far this is only used by the "method" keyword hack for perl 5.38 * onwards so this doesn't technically matter. Yet... */ croak("TODO: import_pragma(\"feature\", \"signatures\")"); #endif } #if HAVE_PERL_VERSION(5, 31, 3) /* core's parse_subsignature doesn't seem able to handle empty sigs * RT132284 * https://github.com/Perl/perl5/issues/17689 */ if(lex_peek_unichar(0) == ')') { /* Inject an empty OP_ARGCHECK much as core would do if it encountered * an empty signature */ UNOP_AUX_item *aux = make_argcheck_aux(0, 0, 0); sigop = op_prepend_elem(OP_LINESEQ, newSTATEOP(0, NULL, NULL), newUNOP_AUX(OP_ARGCHECK, 0, NULL, aux)); /* a nextstate at the end handles context correctly for an empty * sub body */ sigop = op_append_elem(OP_LINESEQ, sigop, newSTATEOP(0, NULL, NULL)); #if HAVE_PERL_VERSION(5,31,5) /* wrap the list of arg ops in a NULL aux op. This serves two * purposes. First, it makes the arg list a separate subtree * from the body of the sub, and secondly the null op may in * future be upgraded to an OP_SIGNATURE when implemented. For * now leave it as ex-argcheck */ sigop = newUNOP_AUX(OP_ARGCHECK, 0, sigop, NULL); op_null(sigop); #endif } else #endif { U32 flags = 0; FOREACH_HOOKS_FORWARD { if(hooks->flags & XS_PARSE_SUBLIKE_FLAG_SIGNATURE_NAMED_PARAMS) flags |= PARSE_SUBSIGNATURE_NAMED_PARAMS; if(hooks->flags & XS_PARSE_SUBLIKE_FLAG_SIGNATURE_PARAM_ATTRIBUTES) flags |= PARSE_SUBSIGNATURE_PARAM_ATTRIBUTES; } if(flags) sigop = parse_subsignature_ex(flags); else sigop = parse_subsignature(0); if(PL_parser->error_count) { assert(PL_scopestack_ix == was_scopestack_ix); LEAVE_with_name("parse_sublike"); return 0; } } if(lex_peek_unichar(0) != ')') croak("Expected ')'"); lex_read_unichar(0); lex_read_space(0); } #endif if(lex_peek_unichar(0) == '{') { /* TODO: technically possible to have skip body flag */ ctx.body = parse_block(0); SvREFCNT_inc(PL_compcv); } else if(require_parts & XS_PARSE_SUBLIKE_PART_BODY) croak("Expected '{' for block body"); else if(lex_peek_unichar(0) == ';') { /* nothing to be done */ } else croak("Expected '{' for block body or ';'"); #ifdef HAVE_PARSE_SUBSIGNATURE if(ctx.body && sigop) { /* parse_block() returns an empy block as a stub op. * no need to keep that if we we have a signature. */ if (ctx.body->op_type == OP_STUB) { op_free(ctx.body); ctx.body = NULL; } ctx.body = op_append_list(OP_LINESEQ, sigop, ctx.body); } #endif if(PL_parser->error_count) { /* parse_block() still sometimes returns a valid body even if a parse * error happens. * We need to destroy this partial body before returning a valid(ish) * state to the keyword hook mechanism, so it will find the error count * correctly * See https://rt.cpan.org/Ticket/Display.html?id=130417 */ op_free(ctx.body); /* REALLY??! Do I really have to do this?? * See also: * https://www.nntp.perl.org/group/perl.perl5.porters/2021/06/msg260642.html */ while(PL_scopestack_ix > was_scopestack_ix) LEAVE; *op_ptr = newOP(OP_NULL, 0); if(ctx.name) { SvREFCNT_dec(ctx.name); assert(PL_scopestack_ix == was_scopestack_ix); LEAVE_with_name("parse_sublike"); return KEYWORD_PLUGIN_STMT; } else { assert(PL_scopestack_ix == was_scopestack_ix); LEAVE_with_name("parse_sublike"); return KEYWORD_PLUGIN_EXPR; } } FOREACH_HOOKS_REVERSE { if(hooks->pre_blockend) (*hooks->pre_blockend)(aTHX_ &ctx, hookdata); } #ifdef DEBUGGING if(PL_scopestack_ix != was_scopestack_ix) croak("ARGH: pre_blockend broke the scopestack (was %d, now %d)\n", was_scopestack_ix, PL_scopestack_ix); #endif if(ctx.body) { ctx.body = block_end(save_ix, ctx.body); if(!have_dynamic_actions) { if(ctx.name) ctx.actions |= XS_PARSE_SUBLIKE_ACTION_SET_CVNAME|XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL; else ctx.actions &= ~(XS_PARSE_SUBLIKE_ACTION_SET_CVNAME|XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL); } /* If we want both SET_CVNAME and INSTALL_SYMBOL actions we might as well * let newATTRSUB() do it. If we only wanted one we need to be more subtle */ bool action_set_cvname = ctx.actions & XS_PARSE_SUBLIKE_ACTION_SET_CVNAME; bool action_install_symbol = ctx.actions & XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL; OP *nameop = NULL; if(ctx.name && action_set_cvname && action_install_symbol) nameop = newSVOP(OP_CONST, 0, SvREFCNT_inc(ctx.name)); if(!nameop && action_install_symbol) warn("Setting XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL without _ACTION_SET_CVNAME is nonsensical"); ctx.cv = newATTRSUB(floor_ix, nameop, NULL, ctx.attrs, ctx.body); if(!nameop && action_set_cvname) { #if HAVE_PERL_VERSION(5,22,0) STRLEN namelen; const char *name = SvPV_const(ctx.name, namelen); U32 hash; PERL_HASH(hash, name, namelen); /* Core's CvNAME_HEK_set macro uses unshare_hek() which isn't exposed. But we * likely don't need it here */ #ifndef unshare_hek # define unshare_hek(h) (void)0 #endif assert(!CvNAME_HEK(ctx.cv)); CvNAME_HEK_set(ctx.cv, share_hek(name, SvUTF8(ctx.name) ? -namelen : namelen, hash)); #endif } ctx.attrs = NULL; ctx.body = NULL; } FOREACH_HOOKS_FORWARD { if(hooks->post_newcv) (*hooks->post_newcv)(aTHX_ &ctx, hookdata); } assert(PL_scopestack_ix == was_scopestack_ix); LEAVE_with_name("parse_sublike"); if(!have_dynamic_actions) { if(!ctx.name) ctx.actions |= XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE; else ctx.actions &= ~XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE; } if(!(ctx.actions & XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE)) { *op_ptr = newOP(OP_NULL, 0); SvREFCNT_dec(ctx.name); } else { *op_ptr = newUNOP(OP_REFGEN, 0, newSVOP(OP_ANONCODE, 0, (SV *)ctx.cv)); } if(!have_dynamic_actions) { if(!ctx.name) ctx.actions |= XS_PARSE_SUBLIKE_ACTION_RET_EXPR; else ctx.actions &= ~XS_PARSE_SUBLIKE_ACTION_RET_EXPR; } return (ctx.actions & XS_PARSE_SUBLIKE_ACTION_RET_EXPR) ? KEYWORD_PLUGIN_EXPR : KEYWORD_PLUGIN_STMT; } static int IMPL_xs_parse_sublike_v4(pTHX_ const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) { struct HooksAndData hd = { .hooks = hooks, .data = hookdata }; return parse(aTHX_ &hd, 1, op_ptr); } static int IMPL_xs_parse_sublike_v3(pTHX_ const void *hooks, void *hookdata, OP **op_ptr) { croak("XS::Parse::Sublike ABI v3 is no longer supported; the caller should be rebuilt to use v4"); } struct Registration; struct Registration { int ver; struct Registration *next; const char *kw; STRLEN kwlen; union { const struct XSParseSublikeHooks *hooks; }; void *hookdata; STRLEN permit_hintkey_len; }; #define REGISTRATIONS_LOCK OP_CHECK_MUTEX_LOCK #define REGISTRATIONS_UNLOCK OP_CHECK_MUTEX_UNLOCK static struct Registration *registrations; static void register_sublike(pTHX_ const char *kw, const void *hooks, void *hookdata, int ver) { struct Registration *reg; Newx(reg, 1, struct Registration); reg->kw = savepv(kw); reg->kwlen = strlen(kw); reg->ver = ver; reg->hooks = hooks; reg->hookdata = hookdata; if(reg->hooks->permit_hintkey) reg->permit_hintkey_len = strlen(reg->hooks->permit_hintkey); else reg->permit_hintkey_len = 0; if(!reg->hooks->permit && !reg->hooks->permit_hintkey) croak("Third-party sublike keywords require a permit callback or hinthash key"); REGISTRATIONS_LOCK; { reg->next = registrations; registrations = reg; } REGISTRATIONS_UNLOCK; } static void IMPL_register_xs_parse_sublike_v4(pTHX_ const char *kw, const struct XSParseSublikeHooks *hooks, void *hookdata) { register_sublike(aTHX_ kw, hooks, hookdata, 4); } static void IMPL_register_xs_parse_sublike_v3(pTHX_ const char *kw, const void *hooks, void *hookdata) { croak("XS::Parse::Sublike ABI v3 is no longer supported; the caller should be rebuilt to use v4"); } static const struct Registration *find_permitted(pTHX_ const char *kw, STRLEN kwlen) { const struct Registration *reg; HV *hints = GvHV(PL_hintgv); for(reg = registrations; reg; reg = reg->next) { if(reg->kwlen != kwlen || !strEQ(reg->kw, kw)) continue; if(reg->hooks->permit_hintkey && (!hints || !hv_fetch(hints, reg->hooks->permit_hintkey, reg->permit_hintkey_len, 0))) continue; if(reg->hooks->permit && !(*reg->hooks->permit)(aTHX_ reg->hookdata)) continue; return reg; } return NULL; } static int IMPL_xs_parse_sublike_any_v4(pTHX_ const struct XSParseSublikeHooks *hooksA, void *hookdataA, OP **op_ptr) { SV *kwsv = lex_scan_ident(); if(!kwsv || !SvCUR(kwsv)) croak("Expected a keyword to introduce a sub or sub-like construction"); const char *kw = SvPV_nolen(kwsv); STRLEN kwlen = SvCUR(kwsv); lex_read_space(0); const struct Registration *reg = NULL; /* We permit 'sub' as a NULL set of hooks; anything else should be a registered keyword */ if(kwlen != 3 || !strEQ(kw, "sub")) { reg = find_permitted(aTHX_ kw, kwlen); if(!reg) croak("Expected a keyword to introduce a sub or sub-like construction, found " QUOTED_PVNf, QUOTED_PVNfARG(kw, kwlen)); } SvREFCNT_dec(kwsv); struct HooksAndData hd[] = { { .hooks = hooksA, .data = hookdataA }, { 0 } }; if(reg) { hd[1].hooks = reg->hooks; hd[1].data = reg->hookdata; } return parse(aTHX_ hd, 1 + !!reg, op_ptr); } static int IMPL_xs_parse_sublike_any_v3(pTHX_ const void *hooksA, void *hookdataA, OP **op_ptr) { croak("XS::Parse::Sublike ABI v3 is no longer supported; the caller should be rebuilt to use v4"); } static void IMPL_register_xps_signature_attribute(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata) { if(funcs->ver < 5) croak("Mismatch in signature param attribute ABI version field: module wants %u; we require >= 5\n", funcs->ver); if(funcs->ver > XSPARSESUBLIKE_ABI_VERSION) croak("Mismatch in signature param attribute ABI version field: module wants %u; we support <= %d\n", funcs->ver, XSPARSESUBLIKE_ABI_VERSION); if(!name || !(name[0] >= 'A' && name[0] <= 'Z')) croak("Signature param attribute names must begin with a capital letter"); if(!funcs->permit_hintkey) croak("Signature param attributes require a permit hinthash key"); register_subsignature_attribute(name, funcs, funcdata); } #ifdef HAVE_FEATURE_CLASS static bool permit_core_method(pTHX_ void *hookdata) { return FEATURE_CLASS_IS_ENABLED; } static void pre_subparse_core_method(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata) { ctx->actions |= XS_PARSE_SUBLIKE_ACTION_CVf_IsMETHOD; } static const struct XSParseSublikeHooks hooks_core_method = { .permit = &permit_core_method, .pre_subparse = &pre_subparse_core_method, .require_parts = XS_PARSE_SUBLIKE_PART_SIGNATURE, /* enable signatures feature */ }; #endif static int (*next_keyword_plugin)(pTHX_ char *, STRLEN, OP **); static int my_keyword_plugin(pTHX_ char *kw, STRLEN kwlen, OP **op_ptr) { const struct Registration *reg = find_permitted(aTHX_ kw, kwlen); if(!reg) return (*next_keyword_plugin)(aTHX_ kw, kwlen, op_ptr); lex_read_space(0); /* We'll abuse the SvPVX storage of an SV to keep an array of HooksAndData * structures */ SV *hdlsv = newSV(4 * sizeof(struct HooksAndData)); SAVEFREESV(hdlsv); struct HooksAndData *hd = (struct HooksAndData *)SvPVX(hdlsv); size_t nhooks = 1; struct XSParseSublikeHooks *hooks = (struct XSParseSublikeHooks *)reg->hooks; hd[0].hooks = hooks; hd[0].data = reg->hookdata; while(hooks->flags & XS_PARSE_SUBLIKE_FLAG_PREFIX) { /* After a prefixing keyword, expect another one */ SV *kwsv = lex_scan_ident(); SAVEFREESV(kwsv); if(!kwsv || !SvCUR(kwsv)) croak("Expected a keyword to introduce a sub or sub-like construction"); kw = SvPV_nolen(kwsv); kwlen = SvCUR(kwsv); lex_read_space(0); /* We permit 'sub' as a NULL set of hooks; anything else should be a registered keyword */ if(kwlen == 3 && strEQ(kw, "sub")) break; reg = find_permitted(aTHX_ kw, kwlen); if(!reg) croak("Expected a keyword to introduce a sub or sub-like construction, found " QUOTED_PVNf, QUOTED_PVNfARG(kw, kwlen)); hooks = (struct XSParseSublikeHooks *)reg->hooks; if(SvLEN(hdlsv) < (nhooks + 1) * sizeof(struct HooksAndData)) { SvGROW(hdlsv, SvLEN(hdlsv) * 2); hd = (struct HooksAndData *)SvPVX(hdlsv); } hd[nhooks].hooks = hooks; hd[nhooks].data = reg->hookdata; nhooks++; } return parse(aTHX_ hd, nhooks, op_ptr); } MODULE = XS::Parse::Sublike PACKAGE = XS::Parse::Sublike BOOT: /* Legacy lookup mechanism using perl symbol table */ sv_setiv(get_sv("XS::Parse::Sublike::ABIVERSION", GV_ADDMULTI), 4); sv_setuv(get_sv("XS::Parse::Sublike::PARSE", GV_ADDMULTI), PTR2UV(&IMPL_xs_parse_sublike_v3)); sv_setuv(get_sv("XS::Parse::Sublike::REGISTER", GV_ADDMULTI), PTR2UV(&IMPL_register_xs_parse_sublike_v3)); sv_setuv(get_sv("XS::Parse::Sublike::PARSEANY", GV_ADDMULTI), PTR2UV(&IMPL_xs_parse_sublike_any_v3)); /* Newer mechanism */ sv_setiv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/ABIVERSION_MIN", 1), 4); sv_setiv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/ABIVERSION_MAX", 1), XSPARSESUBLIKE_ABI_VERSION); sv_setuv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/parse()@4", 1), PTR2UV(&IMPL_xs_parse_sublike_v4)); sv_setuv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/register()@4", 1), PTR2UV(&IMPL_register_xs_parse_sublike_v4)); sv_setuv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/parseany()@4", 1), PTR2UV(&IMPL_xs_parse_sublike_any_v4)); sv_setuv(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/register_sigattr()@5", 1), PTR2UV(&IMPL_register_xps_signature_attribute)); #ifdef HAVE_FEATURE_CLASS register_sublike(aTHX_ "method", &hooks_core_method, NULL, 4); #endif wrap_keyword_plugin(&my_keyword_plugin, &next_keyword_plugin); XS-Parse-Sublike-0.22/lib/XS/Parse/Sublike000755001750001750 014643004052 16722 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/lib/XS/Parse/Sublike/Builder.pm000444001750001750 403014643004052 21000 0ustar00leoleo000000000000# You may distribute under the terms of either the GNU General Public License # or the Artistic License (the same terms as Perl itself) # # (C) Paul Evans, 2020-2021 -- leonerd@leonerd.org.uk package XS::Parse::Sublike::Builder 0.22; use v5.14; use warnings; =head1 NAME C - build-time support for C =head1 SYNOPSIS In F: use XS::Parse::Sublike::Builder; my $build = Module::Build->new( ..., configure_requires => { ... 'XS::Parse::Sublike::Builder' => 0, } ); XS::Parse::Sublike::Builder->extend_module_build( $build ); ... =head1 DESCRIPTION This module provides a build-time helper to assist authors writing XS modules that use L. It prepares a L-using distribution to be able to make use of C. =cut =head1 FUNCTIONS =cut =head2 write_XSParseSublike_h XS::Parse::Sublike::Builder->write_XSParseSublike_h; This method no longer does anything I. =cut sub write_XSParseSublike_h { } =head2 extra_compiler_flags @flags = XS::Parse::Sublike::Builder->extra_compiler_flags; Returns a list of extra flags that the build scripts should add to the compiler invocation. This enables the C compiler to find the F file. =cut sub extra_compiler_flags { shift; require File::ShareDir; require File::Spec; return "-I" . File::Spec->catdir( File::ShareDir::dist_dir( "XS-Parse-Sublike" ), "include" ); } =head2 extend_module_build XS::Parse::Sublike::Builder->extend_module_build( $build ); A convenient shortcut for performing all the tasks necessary to make a L-based distribution use the helper. =cut sub extend_module_build { my $self = shift; my ( $build ) = @_; # preserve existing flags my @flags = @{ $build->extra_compiler_flags }; push @flags, $self->extra_compiler_flags; $build->extra_compiler_flags( @flags ); } =head1 AUTHOR Paul Evans =cut 0x55AA; XS-Parse-Sublike-0.22/share000755001750001750 014643004052 14254 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/share/include000755001750001750 014643004052 15677 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/share/include/XSParseSublike.h000444001750001750 1542314643004052 21076 0ustar00leoleo000000000000#ifndef __XS_PARSE_SUBLIKE_H__ #define __XS_PARSE_SUBLIKE_H__ #define XSPARSESUBLIKE_ABI_VERSION 5 struct XSParseSublikeContext { SV *name; /* may be NULL for anon subs */ /* STAGE pre_subparse */ OP *attrs; /* may be NULL */ /* STAGE post_blockstart */ OP *body; /* STAGE pre_blockend */ CV *cv; /* STAGE post_newcv */ U32 actions; /* Unused by XS::Parse::Sublike itself but can be handy for modules to store * data in between stages */ HV *moddata; }; enum { XS_PARSE_SUBLIKE_FLAG_FILTERATTRS = 1<<0, XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL = 1<<1, XS_PARSE_SUBLIKE_FLAG_PREFIX = 1<<2, /* *Experimental* named parameter parsing support */ XS_PARSE_SUBLIKE_FLAG_SIGNATURE_NAMED_PARAMS = 1<<3, /* *Experimental* parameter attribute parsing support */ XS_PARSE_SUBLIKE_FLAG_SIGNATURE_PARAM_ATTRIBUTES = 1<<4, /* Back-compat flags we hope to remove in the next ABI version */ XS_PARSE_SUBLIKE_COMPAT_FLAG_DYNAMIC_ACTIONS = 1<<15, }; enum { XS_PARSE_SUBLIKE_PART_NAME = 1<<0, XS_PARSE_SUBLIKE_PART_ATTRS = 1<<1, XS_PARSE_SUBLIKE_PART_SIGNATURE = 1<<2, XS_PARSE_SUBLIKE_PART_BODY = 1<<3, }; enum { XS_PARSE_SUBLIKE_ACTION_CVf_ANON = (1<<0), /* should start_subparse() take CVf_ANON ? */ XS_PARSE_SUBLIKE_ACTION_SET_CVNAME = (1<<1), /* do we set a CvNAME? */ XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL = (1<<2), /* do we install the new CV into the symbol table? */ XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE = (1<<3), /* do we emit OP_REFGEN of OP_ANONCODE, or simply OP_NULL ? */ XS_PARSE_SUBLIKE_ACTION_RET_EXPR = (1<<4), /* do we return KEYWORD_PLUGIN_EXPR, or KEYWORD_PLUGIN_STMT ? */ }; struct XSParseSublikeHooks { U16 flags; U8 require_parts; U8 skip_parts; /* These two hooks are ANDed together; both must pass, if present */ const char *permit_hintkey; bool (*permit)(pTHX_ void *hookdata); void (*pre_subparse) (pTHX_ struct XSParseSublikeContext *ctx, void *hookdata); void (*post_blockstart)(pTHX_ struct XSParseSublikeContext *ctx, void *hookdata); void (*pre_blockend) (pTHX_ struct XSParseSublikeContext *ctx, void *hookdata); void (*post_newcv) (pTHX_ struct XSParseSublikeContext *ctx, void *hookdata); /* if flags & XS_PARSE_SUBLIKE_FLAG_FILTERATTRS */ bool (*filter_attr) (pTHX_ struct XSParseSublikeContext *ctx, SV *attr, SV *val, void *hookdata); }; static int (*parse_xs_parse_sublike_func)(pTHX_ const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr); #define xs_parse_sublike(hooks, hookdata, op_ptr) S_xs_parse_sublike(aTHX_ hooks, hookdata, op_ptr) static int S_xs_parse_sublike(pTHX_ const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) { if(!parse_xs_parse_sublike_func) croak("Must call boot_xs_parse_sublike() first"); return (*parse_xs_parse_sublike_func)(aTHX_ hooks, hookdata, op_ptr); } static void (*register_xs_parse_sublike_func)(pTHX_ const char *kw, const struct XSParseSublikeHooks *hooks, void *hookdata); #define register_xs_parse_sublike(kw, hooks, hookdata) S_register_xs_parse_sublike(aTHX_ kw, hooks, hookdata) static void S_register_xs_parse_sublike(pTHX_ const char *kw, const struct XSParseSublikeHooks *hooks, void *hookdata) { if(!register_xs_parse_sublike_func) croak("Must call boot_xs_parse_sublike() first"); return (*register_xs_parse_sublike_func)(aTHX_ kw, hooks, hookdata); } static int (*parseany_xs_parse_sublike_func)(pTHX_ const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr); #define xs_parse_sublike_any(hooks, hookdata, op_ptr) S_xs_parse_sublike_any(aTHX_ hooks, hookdata, op_ptr) static int S_xs_parse_sublike_any(pTHX_ const struct XSParseSublikeHooks *hooks, void *hookdata, OP **op_ptr) { if(!parseany_xs_parse_sublike_func) croak("Must call boot_xs_parse_sublike() first"); return (*parseany_xs_parse_sublike_func)(aTHX_ hooks, hookdata, op_ptr); } /* Experimental support for subroutine parameter attributes. * Only supported on Perl v5.26 or later */ struct XPSSignatureParamContext { bool is_named; PADOFFSET padix; OP *varop; /* apply phase runs here */ OP *defop; OP *op; /* post_defop phase runs here */ }; struct XPSSignatureAttributeFuncs { U32 ver; /* caller must initialise to XSPARSESUBLIKE_ABI_VERSION */ U32 flags; const char *permit_hintkey; void (*apply)(pTHX_ struct XPSSignatureParamContext *ctx, SV *attrvalue, void **attrdata_ptr, void *funcdata); void (*post_defop)(pTHX_ struct XPSSignatureParamContext *ctx, void *attrdata, void *funcdata); void (*free)(pTHX_ void *attrdata, void *funcdata); }; static void (*register_xps_signature_attribute_func)(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata); #define register_xps_signature_attribute(name, funcs, funcdata) S_register_xps_signature_attribute(aTHX_ name, funcs, funcdata) static void S_register_xps_signature_attribute(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata) { if(!register_xps_signature_attribute_func) croak("Must call boot_xs_parse_sublike() first"); (*register_xps_signature_attribute_func)(aTHX_ name, funcs, funcdata); } #define boot_xs_parse_sublike(ver) S_boot_xs_parse_sublike(aTHX_ ver) static void S_boot_xs_parse_sublike(pTHX_ double ver) { SV **svp; SV *versv = ver ? newSVnv(ver) : NULL; load_module(PERL_LOADMOD_NOIMPORT, newSVpvs("XS::Parse::Sublike"), versv, NULL); svp = hv_fetchs(PL_modglobal, "XS::Parse::Sublike/ABIVERSION_MIN", 0); if(!svp) croak("XS::Parse::Sublike ABI minimum version missing"); int abi_ver = SvIV(*svp); if(abi_ver > XSPARSESUBLIKE_ABI_VERSION) croak("XS::Parse::Sublike ABI version mismatch - library supports >= %d, compiled for %d", abi_ver, XSPARSESUBLIKE_ABI_VERSION); svp = hv_fetchs(PL_modglobal, "XS::Parse::Sublike/ABIVERSION_MAX", 0); abi_ver = SvIV(*svp); if(abi_ver < XSPARSESUBLIKE_ABI_VERSION) croak("XS::Parse::Sublike ABI version mismatch - library supports <= %d, compiled for %d", abi_ver, XSPARSESUBLIKE_ABI_VERSION); parse_xs_parse_sublike_func = INT2PTR(int (*)(pTHX_ const struct XSParseSublikeHooks *, void *, OP**), SvUV(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/parse()@4", 0))); register_xs_parse_sublike_func = INT2PTR(void (*)(pTHX_ const char *, const struct XSParseSublikeHooks *, void *), SvUV(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/register()@4", 0))); parseany_xs_parse_sublike_func = INT2PTR(int (*)(pTHX_ const struct XSParseSublikeHooks *, void *, OP**), SvUV(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/parseany()@4", 0))); register_xps_signature_attribute_func = INT2PTR(void (*)(pTHX_ const char *, const struct XPSSignatureAttributeFuncs *, void *), SvUV(*hv_fetchs(PL_modglobal, "XS::Parse::Sublike/register_sigattr()@5", 0))); } #endif XS-Parse-Sublike-0.22/src000755001750001750 014643004052 13741 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/src/parse_subsignature_ex.c000444001750001750 3747214643004052 20700 0ustar00leoleo000000000000/* vi: set ft=c : */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #define HAVE_PERL_VERSION(R, V, S) \ (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S)))))) #include "XSParseSublike.h" /* Skip this entire file on perls older than OP_ARGCHECK */ #if HAVE_PERL_VERSION(5, 26, 0) #define PERL_EXT /* We need to be able to see FEATURE_*_IS_ENABLED */ #include "feature.h" /* Also need KEY_sigvar */ #include "keywords.h" #include "parse_subsignature_ex.h" #include "lexer-additions.c.inc" #include "LOGOP_ANY.c.inc" #include "croak_from_caller.c.inc" #include "make_argcheck_aux.c.inc" #include "newSV_with_free.c.inc" #define newSVpvx(ptr) S_newSVpvx(aTHX_ ptr) static SV *S_newSVpvx(pTHX_ void *ptr) { SV *sv = newSV(0); sv_upgrade(sv, SVt_PV); SvPVX(sv) = ptr; return sv; } /* * Need to grab some things that aren't quite core perl API */ /* yyerror() is a long function and hard to emulate or copy-paste for our * purposes; we'll reïmplement a smaller version of it */ #define LEX_IGNORE_UTF8_HINTS 0x00000002 #define PL_linestr (PL_parser->linestr) #ifdef USE_UTF8_SCRIPTS # define UTF cBOOL(!IN_BYTES) #else # define UTF cBOOL((PL_linestr && DO_UTF8(PL_linestr)) || ( !(PL_parser->lex_flags & LEX_IGNORE_UTF8_HINTS) && (PL_hints & HINT_UTF8))) #endif #define yyerror(s) S_yyerror(aTHX_ s) void S_yyerror(pTHX_ const char *s) { SV *message = sv_2mortal(newSVpvs_flags("", 0)); char *context = PL_parser->oldbufptr; STRLEN contlen = PL_parser->bufptr - PL_parser->oldbufptr; sv_catpvf(message, "%s at %s line %" IVdf, s, OutCopFILE(PL_curcop), (IV)CopLINE(PL_curcop)); if(context) sv_catpvf(message, ", near \"%" UTF8f "\"", UTF8fARG(UTF, contlen, context)); sv_catpvf(message, "\n"); PL_parser->error_count++; warn_sv(message); } /* Stolen from op.c */ #ifndef OpTYPE_set # define OpTYPE_set(op, type) \ STMT_START { \ op->op_type = (OPCODE)type; \ op->op_ppaddr = PL_ppaddr[type]; \ } STMT_END #endif #define alloc_LOGOP(a,b,c) S_alloc_LOGOP(aTHX_ a,b,c) static LOGOP *S_alloc_LOGOP(pTHX_ I32 type, OP *first, OP* other) { dVAR; LOGOP *logop; OP *kid = first; NewOp(1101, logop, 1, LOGOP); OpTYPE_set(logop, type); logop->op_first = first; logop->op_other = other; if (first) logop->op_flags = OPf_KIDS; while (kid && OpHAS_SIBLING(kid)) kid = OpSIBLING(kid); if (kid) OpLASTSIB_set(kid, (OP*)logop); return logop; } /* copypaste from core's pp.c */ static SV * S_find_runcv_name(pTHX) { CV *cv; GV *gv; SV *sv; cv = find_runcv(0); if (!cv) return &PL_sv_no; gv = CvGV(cv); if (!gv) return &PL_sv_no; sv = sv_newmortal(); gv_fullname4(sv, gv, NULL, TRUE); return sv; } static OP *pp_namedargdefelem(pTHX) { dSP; ANY *op_any = cLOGOP_ANY->op_any; SV *keysv = op_any[0].any_sv; HV *slurpy_hv = (HV *)PAD_SVl(op_any[1].any_iv); assert(slurpy_hv && SvTYPE(slurpy_hv) == SVt_PVHV); /* TODO: we could precompute the hash and store it in the ANY vector */ SV *value = hv_delete_ent(slurpy_hv, keysv, 0, 0); if(value) { EXTEND(SP, 1); PUSHs(value); RETURN; } if(cLOGOP->op_other) return cLOGOP->op_other; croak_from_caller("Missing argument '%" SVf "' for subroutine %" SVf, SVfARG(keysv), SVfARG(S_find_runcv_name(aTHX))); } static OP *pp_checknomorenamed(pTHX) { HV *slurpy_hv = (HV *)PAD_SVl(PL_op->op_targ); if(!hv_iterinit(slurpy_hv)) return NORMAL; /* There are remaining named arguments; concat their names into a message */ HE *he = hv_iternext(slurpy_hv); SV *keynames = newSVpvn("", 0); SAVEFREESV(keynames); sv_catpvf(keynames, "'%" SVf "'", SVfARG(HeSVKEY_force(he))); IV nkeys = 1; while((he = hv_iternext(slurpy_hv))) sv_catpvf(keynames, ", '%" SVf "'", SVfARG(HeSVKEY_force(he))), nkeys++; croak_from_caller("Unrecognised %s %" SVf " for subroutine %" SVf, nkeys > 1 ? "arguments" : "argument", SVfARG(keynames), SVfARG(S_find_runcv_name(aTHX))); } #define OP_IS_NAMED_PARAM(o) (o->op_type == OP_ARGELEM && cUNOPx(o)->op_first && \ cUNOPx(o)->op_first->op_type == OP_CUSTOM && \ cUNOPx(o)->op_first->op_ppaddr == &pp_namedargdefelem) /* Parameter attribute extensions */ typedef struct SignatureAttributeRegistration SignatureAttributeRegistration; struct SignatureAttributeRegistration { SignatureAttributeRegistration *next; const char *name; STRLEN permit_hintkeylen; const struct XPSSignatureAttributeFuncs *funcs; void *funcdata; }; static SignatureAttributeRegistration *sigattrs = NULL; #define find_registered_attribute(name) S_find_registered_attribute(aTHX_ name) static SignatureAttributeRegistration *S_find_registered_attribute(pTHX_ const char *name) { HV *hints = GvHV(PL_hintgv); SignatureAttributeRegistration *reg; for(reg = sigattrs; reg; reg = reg->next) { if(!strEQ(name, reg->name)) continue; if(reg->funcs->permit_hintkey && (!hints || !hv_fetch(hints, reg->funcs->permit_hintkey, reg->permit_hintkeylen, 0))) continue; return reg; } croak("Unrecognised signature parameter attribute :%s", name); } struct PendingSignatureFunc { const struct XPSSignatureAttributeFuncs *funcs; void *funcdata; void *attrdata; }; #define PENDING_FROM_SV(sv) ((struct PendingSignatureFunc *)SvPVX(sv)) static void pending_free(pTHX_ SV *sv) { struct PendingSignatureFunc *p = PENDING_FROM_SV(sv); if(p->funcs->free) (*p->funcs->free)(aTHX_ p->attrdata, p->funcdata); } #define NEW_SV_PENDING() newSV_with_free(sizeof(struct PendingSignatureFunc), &pending_free) struct SignatureParsingContext { AV *named_varops; /* SV ptrs to the varop of every named parameter */ OP *last_varop; /* the most recently-constructed varop */ }; static void free_parsing_ctx(pTHX_ void *_ctx) { struct SignatureParsingContext *ctx = _ctx; if(ctx->named_varops) SvREFCNT_dec((SV *)ctx->named_varops); } #define parse_sigelem(ctx, flags) S_parse_sigelem(aTHX_ ctx, flags) static OP *S_parse_sigelem(pTHX_ struct SignatureParsingContext *ctx, U32 flags) { bool permit_attributes = flags & PARSE_SUBSIGNATURE_PARAM_ATTRIBUTES; yy_parser *parser = PL_parser; int c = lex_peek_unichar(0); int private; struct XPSSignatureParamContext paramctx = {}; AV *pending = NULL; if((flags & PARSE_SUBSIGNATURE_NAMED_PARAMS) && c == ':') { lex_read_unichar(0); lex_read_space(0); paramctx.is_named = true; c = lex_peek_unichar(0); } switch(c) { case '$': private = OPpARGELEM_SV; break; case '@': private = OPpARGELEM_AV; break; case '%': private = OPpARGELEM_HV; break; default: croak("Expected a signature element at <%s>\n", parser->bufptr); } char *lexname = parser->bufptr; /* Consume sigil */ lex_read_unichar(0); char *lexname_end = NULL; if(isIDFIRST_uni(lex_peek_unichar(0))) { lex_read_unichar(0); while(isALNUM_uni(lex_peek_unichar(0))) lex_read_unichar(0); paramctx.varop = newUNOP_AUX(OP_ARGELEM, 0, NULL, INT2PTR(UNOP_AUX_item *, (parser->sig_elems))); paramctx.varop->op_private |= private; if(paramctx.is_named) { if(!ctx->named_varops) ctx->named_varops = newAV(); av_push(ctx->named_varops, newSVpvx(paramctx.varop)); } ctx->last_varop = paramctx.varop; ENTER; SAVEI16(PL_parser->in_my); PL_parser->in_my = KEY_sigvar; lexname_end = PL_parser->bufptr; paramctx.padix = paramctx.varop->op_targ = pad_add_name_pvn(lexname, lexname_end - lexname, 0, NULL, NULL); LEAVE; lex_read_space(0); } if(permit_attributes && lex_peek_unichar(0) == ':') { lex_read_unichar(0); lex_read_space(0); SV *attrname = sv_newmortal(), *attrval = sv_newmortal(); while(lex_scan_attrval_into(attrname, attrval)) { lex_read_space(0); SignatureAttributeRegistration *reg = find_registered_attribute(SvPV_nolen(attrname)); void *attrdata = NULL; if(reg->funcs->apply) (*reg->funcs->apply)(aTHX_ ¶mctx, attrval, &attrdata, reg->funcdata); if(attrdata || reg->funcs->post_defop) { if(!pending) { pending = newAV(); SAVEFREESV(pending); } SV *psv; av_push(pending, psv = NEW_SV_PENDING()); PENDING_FROM_SV(psv)->funcs = reg->funcs; PENDING_FROM_SV(psv)->funcdata = reg->funcdata; PENDING_FROM_SV(psv)->attrdata = attrdata; } if(lex_peek_unichar(0) == ':') { lex_read_unichar(0); lex_read_space(0); } } } if(c == '$') { SV *argname = NULL; if(paramctx.is_named) { parser->sig_slurpy = '+'; argname = newSVpvn(lexname + 1, lexname_end - lexname - 1); } else { if(parser->sig_slurpy) yyerror("Slurpy parameters not last"); parser->sig_elems++; } if(lex_peek_unichar(0) == '=') { lex_read_unichar(0); lex_read_space(0); if(!paramctx.is_named) parser->sig_optelems++; OP *defexpr = parse_termexpr(0); if(paramctx.is_named) { paramctx.defop = (OP *)alloc_LOGOP_ANY(OP_CUSTOM, defexpr, LINKLIST(defexpr)); paramctx.defop->op_ppaddr = &pp_namedargdefelem; } else { paramctx.defop = (OP *)alloc_LOGOP(OP_ARGDEFELEM, defexpr, LINKLIST(defexpr)); paramctx.defop->op_targ = (PADOFFSET)(parser->sig_elems - 1); } paramctx.varop->op_flags |= OPf_STACKED; op_sibling_splice(paramctx.varop, NULL, 0, paramctx.defop); paramctx.defop = op_contextualize(paramctx.defop, G_SCALAR); LINKLIST(paramctx.varop); paramctx.varop->op_next = paramctx.defop; defexpr->op_next = paramctx.varop; } else { if(parser->sig_optelems) yyerror("Mandatory parameter follows optional parameter"); } if(paramctx.is_named) { OP *defop = paramctx.defop; if(!defop) { defop = (OP *)alloc_LOGOP_ANY(OP_CUSTOM, NULL, NULL); defop->op_ppaddr = &pp_namedargdefelem; paramctx.varop->op_flags |= OPf_STACKED; op_sibling_splice(paramctx.varop, NULL, 0, defop); LINKLIST(paramctx.varop); paramctx.varop->op_next = defop; } ANY *op_any; Newx(op_any, 2, ANY); op_any[0].any_sv = argname; /* [1] is filled in later */ cLOGOP_ANYx(defop)->op_any = op_any; } } else { if(paramctx.is_named) yyerror("Slurpy parameters may not be named"); if(parser->sig_slurpy && parser->sig_slurpy != '+') yyerror("Multiple slurpy parameters not allowed"); parser->sig_slurpy = c; if(lex_peek_unichar(0) == '=') yyerror("A slurpy parameter may not have a default value"); } paramctx.op = paramctx.varop; if(pending) { for(int i = 0; i <= AvFILL(pending); i++) { struct PendingSignatureFunc *p = PENDING_FROM_SV(AvARRAY(pending)[i]); if(p->funcs->post_defop) (*p->funcs->post_defop)(aTHX_ ¶mctx, p->attrdata, p->funcdata); } } return paramctx.op ? newSTATEOP(0, NULL, paramctx.op) : NULL; } OP *XPS_parse_subsignature_ex(pTHX_ int flags) { /* Mostly reconstructed logic from perl 5.28.0's toke.c and perly.y */ yy_parser *parser = PL_parser; struct SignatureParsingContext ctx = {}; assert((flags & ~(PARSE_SUBSIGNATURE_NAMED_PARAMS|PARSE_SUBSIGNATURE_PARAM_ATTRIBUTES)) == 0); ENTER; SAVEDESTRUCTOR_X(&free_parsing_ctx, &ctx); SAVEIV(parser->sig_elems); SAVEIV(parser->sig_optelems); SAVEI8(parser->sig_slurpy); parser->sig_elems = 0; parser->sig_optelems = 0; parser->sig_slurpy = 0; OP *elems = NULL; OP *namedelems = NULL; OP *final_elem = NULL; while(lex_peek_unichar(0) != ')') { lex_read_space(0); OP *elem = parse_sigelem(&ctx, flags); /* placeholder anonymous elems are NULL */ if(elem) { /* elem should be an OP_LINESEQ[ OP_NEXTSTATE. actual elem ] */ assert(elem->op_type == OP_LINESEQ); assert(cLISTOPx(elem)->op_first); assert(OpSIBLING(cLISTOPx(elem)->op_first)); final_elem = OpSIBLING(cLISTOPx(elem)->op_first); if(OP_IS_NAMED_PARAM(ctx.last_varop)) namedelems = op_append_list(OP_LIST, namedelems, elem); else elems = op_append_list(OP_LINESEQ, elems, elem); } if(PL_parser->error_count) { LEAVE; return NULL; } lex_read_space(0); switch(lex_peek_unichar(0)) { case ')': goto endofelems; case ',': break; default: fprintf(stderr, "ARGH unsure how to proceed parse_subsignature at <%s>\n", parser->bufptr); croak("ARGH"); break; } lex_read_unichar(0); lex_read_space(0); } endofelems: if (!FEATURE_SIGNATURES_IS_ENABLED) croak("Experimental subroutine signatures not enabled"); #if !HAVE_PERL_VERSION(5, 37, 0) Perl_ck_warner_d(aTHX_ packWARN(WARN_EXPERIMENTAL__SIGNATURES), "The signatures feature is experimental"); #endif bool allow_extras_after_named = true; if(ctx.named_varops) { switch(PL_parser->sig_slurpy) { case 0: case '@': NOT_REACHED; case '+': { /* Pretend we have a new, unnamed slurpy hash */ OP *varop = newUNOP_AUX(OP_ARGELEM, 0, NULL, INT2PTR(UNOP_AUX_item *, (parser->sig_elems))); varop->op_private |= OPpARGELEM_HV; varop->op_targ = pad_add_name_pvs("%(params)", 0, NULL, NULL); final_elem = varop; OP *elem = newSTATEOP(0, NULL, varop); elems = op_append_list(OP_LINESEQ, elems, elem); PL_parser->sig_slurpy = '%'; allow_extras_after_named = false; } break; case '%': break; } } UNOP_AUX_item *aux = make_argcheck_aux( parser->sig_elems, parser->sig_optelems, parser->sig_slurpy); OP *checkop = newUNOP_AUX(OP_ARGCHECK, 0, NULL, aux); OP *ops = op_prepend_elem(OP_LINESEQ, newSTATEOP(0, NULL, NULL), op_prepend_elem(OP_LINESEQ, checkop, elems)); if(ctx.named_varops) { assert(final_elem->op_type == OP_ARGELEM); assert(final_elem->op_private == OPpARGELEM_HV); PADOFFSET slurpy_padix = final_elem->op_targ; /* Tell all the pp_namedargdefelem()s where to find the slurpy hash */ for(int i = 0; i <= AvFILL(ctx.named_varops); i++) { OP *elemop = (OP *)(SvPVX(AvARRAY(ctx.named_varops)[i])); assert(elemop); assert(OP_IS_NAMED_PARAM(elemop)); OP *defelemop = cUNOPx(elemop)->op_first; assert(defelemop); assert(defelemop->op_type == OP_CUSTOM && defelemop->op_ppaddr == &pp_namedargdefelem); ANY *op_any = cLOGOP_ANYx(defelemop)->op_any; op_any[1].any_iv = slurpy_padix; } ops = op_append_list(OP_LINESEQ, ops, namedelems); if(!allow_extras_after_named) { ops = op_append_list(OP_LINESEQ, ops, newSTATEOP(0, NULL, checkop = newOP(OP_CUSTOM, 0))); checkop->op_ppaddr = &pp_checknomorenamed; checkop->op_targ = slurpy_padix; } } /* a nextstate at the end handles context correctly for an empty * sub body */ ops = op_append_elem(OP_LINESEQ, ops, newSTATEOP(0, NULL, NULL)); LEAVE; return ops; } void XPS_register_subsignature_attribute(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata) { SignatureAttributeRegistration *reg; Newx(reg, 1, struct SignatureAttributeRegistration); *reg = (struct SignatureAttributeRegistration){ .name = name, .funcs = funcs, .funcdata = funcdata, }; if(funcs->permit_hintkey) reg->permit_hintkeylen = strlen(funcs->permit_hintkey); reg->next = sigattrs; sigattrs = reg; } #else /* !HAVE_PERL_VERSION(5, 26, 0) */ void XPS_register_subsignature_attribute(pTHX_ const char *name, const struct XPSSignatureAttributeFuncs *funcs, void *funcdata) { croak("Custom subroutine signature attributes are not supported on this verison of Perl"); } #endif XS-Parse-Sublike-0.22/t000755001750001750 014643004052 13415 5ustar00leoleo000000000000XS-Parse-Sublike-0.22/t/00use.t000444001750001750 20014643004052 14643 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; require XS::Parse::Sublike; pass( "Modules loaded" ); done_testing; XS-Parse-Sublike-0.22/t/01func.t000444001750001750 132214643004052 15031 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/func"}++ } # named func { func example { return 123; } is( example(), 123, 'named func' ); } # anon func { my $ex2 = func { return 456; }; is( $ex2->(), 456, 'anon func' ); } # func still obtains :ATTRS { my $modify_invoked; sub MODIFY_CODE_ATTRIBUTES { my ( $pkg, $sub, $attr ) = @_; $modify_invoked++; ::is( $attr, "MyCustomAttribute(value here)", 'MODIFY_CODE_ATTRIBUTES takes attribute' ); return (); } func withattr :MyCustomAttribute(value here) { } is( $modify_invoked, 1, 'MODIFY_CODE_ATTRIBUTES invoked' ); } done_testing; XS-Parse-Sublike-0.22/t/02func-signatures.t000444001750001750 315514643004052 17222 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/func"}++ } # basic sig { func withparam($x) { return $x + 1 } is( withparam( 4 ), 5, 'func with param' ); } # The following are additional tests that our pre-5.31.3 backported # parse_subsignature() works correctly { func sum(@x) { my $ret = 0; $ret += $_ for @x; return $ret; } is( sum( 10, 20, 30 ), 60, 'func with slurpy parameter' ); func firstandthird($x, $, $z) { return $x . $z; } is( firstandthird(qw( a b c )), "ac", 'func with unnamed parameter' ); func withoptparam($one = 1) { return $one + 2 } is( withoptparam, 3, 'func with optional param missing' ); is( withoptparam( 2 ), 4, 'func with optional param present' ); func has_whitespace ( $x ) { return $x; } is( has_whitespace( "value" ), "value", 'func with whitespace in signature' ); # RT132284 func noparams() { return "constant" } is( noparams, "constant", 'func with no params' ); like( dies { noparams( 1, 2, 3 ) }, # message was extended somewhere in perl 5.33 qr/^Too many arguments for subroutine 'main::noparams' (\(.*\) )?at /, 'Exception thrown from empty signature validation failure' ); } # RT131571 { func withattr :method ($self, @args) { } ok( scalar( grep { m/^method$/ } attributes::get( \&withattr ) ), 'func with attr and signture does not collide' ); } done_testing; XS-Parse-Sublike-0.22/t/03func-deparse.t000444001750001750 236514643004052 16464 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/func"}++ } use B::Deparse; my $deparser = B::Deparse->new(); # check that signatured functions deparse the right way # (RT132335) # with signature { my $sub = sub ($x, $y) { return $x + $y; }; my $func = func ($x, $y) { return $x + $y; }; my $code = $deparser->coderef2text( $sub ); # the reference source text is( $deparser->coderef2text( $func ), $code, 'Deparsed func with signature identical to deparsed code' ); } # empty signature { my $sub = sub () { return 123; }; my $func = func () { return 123; }; my $code = $deparser->coderef2text( $sub ); # the reference source text is( $deparser->coderef2text( $func ), $code, 'Deparsed func with empty signature identical to deparsed code' ); } # empty body { my $sub = sub () {}; my $func = func () {}; my $code = $deparser->coderef2text( $sub ); # the reference source text is( $deparser->coderef2text( $func ), $code, 'Deparsed func with empty body identical to deparsed code' ); } done_testing; XS-Parse-Sublike-0.22/t/04func-named-params.t000444001750001750 417314643004052 17406 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/nfunc"}++ } # a signature with experimental named parameter support { my %was_rest; nfunc withx(:$x, %rest) { %was_rest = %rest; return $x } is( withx( x => 123 ), 123, 'named param extracts value' ); is( \%was_rest, {}, 'named param not visible in %rest' ); withx( x => 1, y => 2 ); is( \%was_rest, { y => 2 }, 'other params still visible in %rest' ); my $LINE = __LINE__+1; like( dies { withx() }, qr/^Missing argument 'x' for subroutine main::withx at \S+ line $LINE\./, 'complaint from missing named param' ); nfunc with2x(:$x1, :$x2) { return "x1=$x1 x2=$x2"; } is( with2x( x1 => 10, x2 => 20 ), "x1=10 x2=20", 'supports multiple named params' ); } # named params can still have defaults { nfunc withy(:$y = "Y", %rest) { return $y } is( withy( y => 456 ), 456, 'named param with default' ); is( withy(), "Y", 'named param applies default' ); } # named params still work without a slurpy { nfunc withz(:$z) { return $z } is( withz( z => 789 ), 789, 'named param without slurpy' ); my $LINE = __LINE__+1; like( dies { withz( z => 1, w => 1 ); 1 }, qr/^Unrecognised argument 'w' for subroutine main::withz at \S+ line $LINE\./, 'complaint from unknown param' ); } # mixed positional+named { nfunc withboth($x, :$y = "def") { return "x=$x y=$y"; } is( withboth(1, y => 2), "x=1 y=2", 'supports mixed positional + named' ); is( withboth(1), "x=1 y=def", 'mixed still applies defaults' ); } # diagnostics on duplicates { sub warnings_from ( $code ) { my $warnings = ""; local $SIG{__WARN__} = sub { $warnings .= $_[0] }; eval( "$code; 1" ) or die $@; return $warnings; } like( warnings_from( 'nfunc diag1($x, :$x) { }' ), qr/^"my" variable \$x masks earlier declaration in same scope at /, 'warning from duplicated parameter name' ); } done_testing; XS-Parse-Sublike-0.22/t/05func-sig-attributes.t000444001750001750 101714643004052 20002 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/afunc"}++ } BEGIN { $^H{"t::func/Attribute"}++ } our @ATTRIBUTE_APPLIED; { afunc withattr($x :Attribute, $y :Attribute(Value)) { } is( \@ATTRIBUTE_APPLIED, [ '$x' => undef, '$y' => "Value" ], ':Attribute applied to subroutine parameters' ); } done_testing; XS-Parse-Sublike-0.22/t/10stages-permit.t000444001750001750 77514643004052 16655 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; sub stages { return $_[0] } # not permitted { my $ret = stages { one => "one" }; is( $ret, { one => "one" }, 'not permitted keyword falls through to regular symbol lookup' ); } # permitted { BEGIN { $^H{"t::stages/permit"} = 1; } my $ret = stages { two => "two" }; is( ref $ret, "CODE", 'permitted keyword becomes a CODE ref' ); } # TODO: test that it can throw done_testing; XS-Parse-Sublike-0.22/t/11stages-pre_subparse.t000444001750001750 61614643004052 20042 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; our $VAR; BEGIN { $^H{"t::stages/permit"} = 1; } { BEGIN { $^H{'t::stages/pre_subparse-capture'} = 1; } BEGIN { $VAR = "before" } stages capture { BEGIN { $VAR = "inside" } } is( $t::stages::captured, "before", 'captured value of $VAR before block' ); } done_testing; XS-Parse-Sublike-0.22/t/12stages-post_blockstart.t000444001750001750 62114643004052 20562 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; our $VAR; BEGIN { $^H{"t::stages/permit"} = 1; } { BEGIN { $^H{'t::stages/post_blockstart-capture'} = 1; } BEGIN { $VAR = "before" } stages capture { BEGIN { $VAR = "inside" } } is( $t::stages::captured, "before", 'captured value of $VAR before block' ); } done_testing; XS-Parse-Sublike-0.22/t/13stages-pre_blockend.t000444001750001750 61614643004052 20001 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; our $VAR; BEGIN { $^H{"t::stages/permit"} = 1; } { BEGIN { $^H{'t::stages/pre_blockend-capture'} = 1; } BEGIN { $VAR = "before" } stages capture { BEGIN { $VAR = "inside" } } is( $t::stages::captured, "inside", 'captured value of $VAR inside block' ); } done_testing; XS-Parse-Sublike-0.22/t/14stages-post_newcv.t000444001750001750 47314643004052 17543 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; BEGIN { $^H{"t::stages/permit"} = 1; } { BEGIN { $^H{'t::stages/post_newcv-capture-cv'} = 1; } stages capture { } is( $t::stages::captured, \&capture, 'captured value of new CV' ); } done_testing; XS-Parse-Sublike-0.22/t/15stages-filter_attr.t000444001750001750 55714643004052 17677 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::stages"; our $VAR; BEGIN { $^H{"t::stages/permit"} = 1; } { BEGIN { $^H{'t::stages/filter_attr-capture'} = 1; } stages withattr :atname(atvalue) { } is( $t::stages::captured, [ atname => "atvalue" ], 'captured an attribute by attr filter' ); } done_testing; XS-Parse-Sublike-0.22/t/20registrations.t000444001750001750 70414643004052 16757 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::registrations"; # Check the individual `func` registrations do not clash { { BEGIN { $^H{"t::registrations/red"} = 1 } func returns_red { } } { BEGIN { $^H{"t::registrations/blue"} = 1 } func returns_blue { } } is( returns_red(), "red", 'returns red' ); is( returns_blue(), "blue", 'returns blue' ); } done_testing; XS-Parse-Sublike-0.22/t/30any.t000444001750001750 44314643004052 14652 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::any"; BEGIN { $^H{"t::any/func"}++ } our $LOG; BEGIN { $LOG = "" }; prefixed func example { BEGIN { $LOG .= "B" } } is( $LOG, "SpSfEpEfBLfLpNpNf", 'stages run in correct order' ); done_testing; XS-Parse-Sublike-0.22/t/31prefix.t000444001750001750 51514643004052 15361 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::prefix"; BEGIN { $^H{"t::prefix/func"}++; $^H{"t::prefix/prefixed"}++; } our $LOG; BEGIN { $LOG = "" }; prefixed func example { BEGIN { $LOG .= "B" } } is( $LOG, "SpSfEpEfBLfLpNpNf", 'stages run in correct order' ); done_testing; XS-Parse-Sublike-0.22/t/40parts-name.t000444001750001750 106214643004052 16151 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::parts"; # name optional { parts NAME { } my $code = parts { }; is( ref $code, "CODE", '$code is CODEref' ); } # name required { BEGIN { $^H{"t::parts/require-name"} = 1; } ok( !defined eval 'my $code = parts { };', 'anon func fails to parse when name required' ); } # name skipped { BEGIN { $^H{"t::parts/skip-name"} = 1; } ok( !defined eval 'parts OTHERNAME { }; 1', 'named func fails to parse when name skipped' ); } done_testing; XS-Parse-Sublike-0.22/t/41parts-attrs.t000444001750001750 64314643004052 16353 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::parts"; # attrs optional { parts NAME { } parts ANAME :method { } pass( 'Optional attributes permitted but not required' ); } # attrs skipped { BEGIN { $^H{"t::parts/skip-attrs"} = 1; } ok( !defined eval 'parts OTHERNAME :method { }; 1', 'func with attrs to parse when attrs skipped' ); } done_testing; XS-Parse-Sublike-0.22/t/42parts-signature.t000444001750001750 106314643004052 17235 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use lib "t"; use testcase "t::parts"; # signature optional { parts NAME { } parts ANAME ($x) { } pass( 'Optional attributes permitted but not required' ); } # signature skipped { BEGIN { $^H{"t::parts/skip-signature"} = 1; } ok( !defined eval 'parts OTHERNAME ($x) { }; 1', 'func with signature to parse when signature skipped' ); } done_testing; XS-Parse-Sublike-0.22/t/50flags-no-body.t000444001750001750 45614643004052 16532 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use lib "t"; use testcase "t::flags"; BEGIN { $^H{"t::flags/no_body"} = 1 } { no_body justaname; my $name; BEGIN { $name = $t::flags::captured_name; } is( $name, "justaname", 'no_body saw just the function name' ); } done_testing; XS-Parse-Sublike-0.22/t/60actions.t000444001750001750 163414643004052 15551 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Sub::Util 'subname'; use lib "t"; use testcase "t::actions"; BEGIN { $^H{"t::actions/action"} = 1 } { action name { "OK" } ok( name(), 'default actions parses like named sub' ); ok( defined &name, '&name is on symbol table' ); is( subname( \&name ), "main::name", '&name has subname' ); } { my $code = action nameER { "OK" }; ok( $code->(), 'RET_EXRP + REFGEN_ANONCODE behaves as anon sub' ); ok( defined &nameER, '&nameER is on symbol table' ); is( subname( $code ), "main::nameER", '$code has subname' ); } { my $code = action nameiER { "OK" }; ok( $code->(), 'Unininstalled CV is still invokable' ); ok( !defined &nameiER, '&nameiER not on symbol table' ); # CvNAME_HEK_set() doesn't work before perl 5.22 is( subname( $code ), "main::nameiER", '$code still has a subname anyway' ) if $] >= 5.022; } done_testing; XS-Parse-Sublike-0.22/t/70extended.t000444001750001750 216514643004052 15712 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; } use feature 'signatures'; no warnings 'experimental'; use Sublike::Extended; # basic sub { extended sub t1 { return "named" } my $t2 = extended sub { return "anon" }; is( t1(), "named", 'extended sub can make basic named' ); is( $t2->(), "anon", 'extended sub can make basic anon' ); } # sub with named params { extended sub t3 (:$x, :$y) { return "x=$x y=$y"; } my $t4 = extended sub ( :$i, :$j ) { return "i=$i j=$j"; }; is( t3( x => 10, y => 20 ), "x=10 y=20", 'extended sub can make named param subs' ); is( $t4->( j => 40, i => 30 ), "i=30 j=40", 'extended sub can make named param anon subs' ); } use lib "t"; use testcase "t::func"; BEGIN { $^H{"t::func/Attribute"}++ } our @ATTRIBUTE_APPLIED; { extended sub t5 ($x :Attribute, $y :Attribute(Value)) { } # No need to call it just to see these is( \@ATTRIBUTE_APPLIED, [ '$x' => undef, '$y' => "Value" ], ':Attribute applied to subroutine parameters' ); } done_testing; XS-Parse-Sublike-0.22/t/80extended+Object-Pad.t000444001750001750 101714643004052 17612 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; eval { require Object::Pad; Object::Pad->VERSION( '0.800' ); 1; } or plan skip_all => "No Object::Pad"; Object::Pad->import; } use Sublike::Extended; # extended method { class C1 { extended method f (:$x, :$y) { return "x=$x y=$y" } } is( C1->new->f( x => "first", y => "second" ), "x=first y=second", 'async method' ); } done_testing; XS-Parse-Sublike-0.22/t/80extended+async.t000444001750001750 112414643004052 17016 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; eval { require Future::AsyncAwait; Future::AsyncAwait->VERSION( '0.66' ); 1; } or plan skip_all => "No Future::AsyncAwait"; Future::AsyncAwait->import; } use feature 'signatures'; no warnings 'experimental'; use Sublike::Extended; # async extended sub { async extended sub f (:$x, :$y) { return "x=$x y=$y" } is( await f( x => "first", y => "second" ), "x=first y=second", 'async extended sub' ); } done_testing; XS-Parse-Sublike-0.22/t/80extended+feature-class.t000444001750001750 113714643004052 20443 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { $] >= 5.026000 or plan skip_all => "No parse_subsignature()"; # version 5.37.10 added the ability to start_subparse() with CVf_IsMETHOD, # which we need plan skip_all => "feature 'class' is not available" unless $^V ge v5.37.10; } use Sublike::Extended; use feature 'class'; no warnings 'experimental::class'; # extended method { class C1 { extended method f (:$x, :$y) { return "x=$x y=$y" } } is( C1->new->f( x => "first", y => "second" ), "x=first y=second", 'async method' ); } done_testing; XS-Parse-Sublike-0.22/t/99pod.t000444001750001750 25514643004052 14665 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok(); XS-Parse-Sublike-0.22/t/actions.xs000444001750001750 206414643004052 15570 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2021 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static void action_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_) { const char *namestr = SvPVX(ctx->name); if(strchr(namestr, 'i')) ctx->actions &= ~XS_PARSE_SUBLIKE_ACTION_INSTALL_SYMBOL; if(strchr(namestr, 'R')) ctx->actions |= XS_PARSE_SUBLIKE_ACTION_REFGEN_ANONCODE; if(strchr(namestr, 'E')) ctx->actions |= XS_PARSE_SUBLIKE_ACTION_RET_EXPR; } static const struct XSParseSublikeHooks parse_action_hooks = { .permit_hintkey = "t::actions/action", .flags = XS_PARSE_SUBLIKE_COMPAT_FLAG_DYNAMIC_ACTIONS, .require_parts = XS_PARSE_SUBLIKE_PART_NAME, .pre_subparse = action_pre_subparse, }; MODULE = t::actions PACKAGE = t::actions BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("action", &parse_action_hooks, NULL); XS-Parse-Sublike-0.22/t/any.xs000444001750001750 505114643004052 14716 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020-2023 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" #ifndef wrap_keyword_plugin # include "wrap_keyword_plugin.c.inc" #endif static void func_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Sf"); } static void func_post_blockstart(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Ef"); } static void func_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Lf"); } static void func_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Nf"); } static const struct XSParseSublikeHooks parse_func_hooks = { .permit_hintkey = "t::any/func", .pre_subparse = func_pre_subparse, .post_blockstart = func_post_blockstart, .pre_blockend = func_pre_blockend, .post_newcv = func_post_newcv, }; static void prefixed_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Sp"); } static void prefixed_post_blockstart(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Ep"); } static void prefixed_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Lp"); } static void prefixed_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Np"); } static const struct XSParseSublikeHooks parse_prefixed_hooks = { .pre_subparse = prefixed_pre_subparse, .post_blockstart = prefixed_post_blockstart, .pre_blockend = prefixed_pre_blockend, .post_newcv = prefixed_post_newcv, }; static int (*next_keyword_plugin)(pTHX_ char *, STRLEN, OP **); static int my_keyword_plugin(pTHX_ char *kw, STRLEN kwlen, OP **op_ptr) { if(kwlen != 8 || !strEQ(kw, "prefixed")) return (*next_keyword_plugin)(aTHX_ kw, kwlen, op_ptr); lex_read_space(0); return xs_parse_sublike_any(&parse_prefixed_hooks, SvREFCNT_inc(get_sv("main::LOG", 0)), op_ptr); } MODULE = t::any PACKAGE = t::any BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("func", &parse_func_hooks, SvREFCNT_inc(get_sv("main::LOG", GV_ADD))); wrap_keyword_plugin(&my_keyword_plugin, &next_keyword_plugin); XS-Parse-Sublike-0.22/t/flags.xs000444001750001750 162314643004052 15224 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static void no_body_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_) { if(ctx->body) croak("Expected no_body to have ctx->body == NULL"); if(ctx->cv) croak("Expected no_body to have ctx->cv == NULL"); sv_setsv(get_sv("t::flags::captured_name", GV_ADD), ctx->name); } static const struct XSParseSublikeHooks parse_no_body_hooks = { .permit_hintkey = "t::flags/no_body", .flags = XS_PARSE_SUBLIKE_FLAG_BODY_OPTIONAL, .post_newcv = no_body_post_newcv, }; MODULE = t::flags PACKAGE = t::flags BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("no_body", &parse_no_body_hooks, NULL); XS-Parse-Sublike-0.22/t/func.xs000444001750001750 340314643004052 15061 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020-2023 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" #if PERL_REVISION > 5 || (PERL_REVISION == 5 && PERL_VERSION >= 26) # define HAVE_SUB_PARAM_ATTRIBUTES #endif static const struct XSParseSublikeHooks parse_func_hooks = { .permit_hintkey = "t::func/func", }; static const struct XSParseSublikeHooks parse_nfunc_hooks = { .permit_hintkey = "t::func/nfunc", .flags = XS_PARSE_SUBLIKE_FLAG_SIGNATURE_NAMED_PARAMS, }; static const struct XSParseSublikeHooks parse_afunc_hooks = { .permit_hintkey = "t::func/afunc", .flags = XS_PARSE_SUBLIKE_FLAG_SIGNATURE_PARAM_ATTRIBUTES, }; #ifdef HAVE_SUB_PARAM_ATTRIBUTES static void apply_Attribute(pTHX_ struct XPSSignatureParamContext *ctx, SV *attrvalue, void **attrdata_ptr, void *funcdata) { /* TODO: maybe the context should store a lexname string? */ PADNAME *pn = PadnamelistARRAY(PL_comppad_name)[ctx->padix]; AV *av = get_av("main::ATTRIBUTE_APPLIED", GV_ADD); av_push(av, newSVsv(PadnameSV(pn))); av_push(av, newSVsv(attrvalue)); } static const struct XPSSignatureAttributeFuncs attr_funcs = { .ver = XSPARSESUBLIKE_ABI_VERSION, .permit_hintkey = "t::func/Attribute", .apply = apply_Attribute, }; #endif MODULE = t::func PACKAGE = t::func BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("func", &parse_func_hooks, NULL); register_xs_parse_sublike("nfunc", &parse_nfunc_hooks, NULL); register_xs_parse_sublike("afunc", &parse_afunc_hooks, NULL); #ifdef HAVE_SUB_PARAM_ATTRIBUTES register_xps_signature_attribute("Attribute", &attr_funcs, NULL); #endif XS-Parse-Sublike-0.22/t/parts.xs000444001750001750 226014643004052 15257 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static bool parts_permit(pTHX_ void *_); static struct XSParseSublikeHooks parse_parts_hooks = { .permit = parts_permit, }; static bool parts_permit(pTHX_ void *_) { parse_parts_hooks.require_parts = 0; parse_parts_hooks.skip_parts = 0; if(hv_fetchs(GvHV(PL_hintgv), "t::parts/require-name", 0)) parse_parts_hooks.require_parts |= XS_PARSE_SUBLIKE_PART_NAME; if(hv_fetchs(GvHV(PL_hintgv), "t::parts/skip-name", 0)) parse_parts_hooks.skip_parts |= XS_PARSE_SUBLIKE_PART_NAME; if(hv_fetchs(GvHV(PL_hintgv), "t::parts/skip-attrs", 0)) parse_parts_hooks.skip_parts |= XS_PARSE_SUBLIKE_PART_ATTRS; if(hv_fetchs(GvHV(PL_hintgv), "t::parts/skip-signature", 0)) parse_parts_hooks.skip_parts |= XS_PARSE_SUBLIKE_PART_SIGNATURE; return TRUE; } MODULE = t::parts PACKAGE = t::parts BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("parts", &parse_parts_hooks, NULL); XS-Parse-Sublike-0.22/t/prefix.xs000444001750001750 435314643004052 15430 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static void func_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Sf"); } static void func_post_blockstart(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Ef"); } static void func_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Lf"); } static void func_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Nf"); } static const struct XSParseSublikeHooks parse_func_hooks = { .permit_hintkey = "t::prefix/func", .pre_subparse = func_pre_subparse, .post_blockstart = func_post_blockstart, .pre_blockend = func_pre_blockend, .post_newcv = func_post_newcv, }; static void prefixed_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Sp"); } static void prefixed_post_blockstart(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Ep"); } static void prefixed_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Lp"); } static void prefixed_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_logsv) { SV *logsv = _logsv; sv_catpvs(logsv, "Np"); } static const struct XSParseSublikeHooks parse_prefixed_hooks = { .flags = XS_PARSE_SUBLIKE_FLAG_PREFIX, .permit_hintkey = "t::prefix/prefixed", .pre_subparse = prefixed_pre_subparse, .post_blockstart = prefixed_post_blockstart, .pre_blockend = prefixed_pre_blockend, .post_newcv = prefixed_post_newcv, }; MODULE = t::prefix PACKAGE = t::prefix BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("func", &parse_func_hooks, SvREFCNT_inc(get_sv("main::LOG", GV_ADD))); register_xs_parse_sublike("prefixed", &parse_prefixed_hooks, SvREFCNT_inc(get_sv("main::LOG", GV_ADD))); XS-Parse-Sublike-0.22/t/registrations.xs000444001750001750 235114643004052 17024 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" static void red_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_) { /* Throw away the entire function body; replace it with a constant */ op_free(ctx->body); ctx->body = newSVOP(OP_CONST, 0, newSVpv("red", 0)); } static const struct XSParseSublikeHooks parse_red_hooks = { .permit_hintkey = "t::registrations/red", .pre_blockend = red_pre_blockend, }; static void blue_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_) { /* Throw away the entire function body; replace it with a constant */ op_free(ctx->body); ctx->body = newSVOP(OP_CONST, 0, newSVpv("blue", 0)); } static const struct XSParseSublikeHooks parse_blue_hooks = { .permit_hintkey = "t::registrations/blue", .pre_blockend = blue_pre_blockend, }; MODULE = t::registrations PACKAGE = t::registrations BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("func", &parse_red_hooks, NULL); register_xs_parse_sublike("func", &parse_blue_hooks, NULL); XS-Parse-Sublike-0.22/t/stages.xs000444001750001750 434714643004052 15424 0ustar00leoleo000000000000/* You may distribute under the terms of either the GNU General Public License * or the Artistic License (the same terms as Perl itself) * * (C) Paul Evans, 2020 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseSublike.h" #include "sv_setrv.c.inc" static bool stage_permit(pTHX_ void *_) { if(!hv_fetchs(GvHV(PL_hintgv), "t::stages/permit", 0)) return FALSE; return TRUE; } static void stage_pre_subparse(pTHX_ struct XSParseSublikeContext *ctx, void *_) { if(hv_fetchs(GvHV(PL_hintgv), "t::stages/pre_subparse-capture", 0)) { sv_setsv(get_sv("t::stages::captured", GV_ADD), get_sv("main::VAR", 0)); } } static void stage_post_blockstart(pTHX_ struct XSParseSublikeContext *ctx, void *_) { if(hv_fetchs(GvHV(PL_hintgv), "t::stages/post_blockstart-capture", 0)) { sv_setsv(get_sv("t::stages::captured", GV_ADD), get_sv("main::VAR", 0)); } } static void stage_pre_blockend(pTHX_ struct XSParseSublikeContext *ctx, void *_) { if(hv_fetchs(GvHV(PL_hintgv), "t::stages/pre_blockend-capture", 0)) { sv_setsv(get_sv("t::stages::captured", GV_ADD), get_sv("main::VAR", 0)); } } static void stage_post_newcv(pTHX_ struct XSParseSublikeContext *ctx, void *_) { if(hv_fetchs(GvHV(PL_hintgv), "t::stages/post_newcv-capture-cv", 0)) { sv_setrv_inc(get_sv("t::stages::captured", GV_ADD), (SV *)ctx->cv); } } static bool stage_filter_attr(pTHX_ struct XSParseSublikeContext *ctx, SV *attr, SV *value, void *_) { if(!hv_fetchs(GvHV(PL_hintgv), "t::stages/filter_attr-capture", 0)) return FALSE; AV *av = newAV(); av_push(av, SvREFCNT_inc(attr)); av_push(av, SvREFCNT_inc(value)); sv_setrv_noinc(get_sv("t::stages::captured", GV_ADD), (SV *)av); return TRUE; } static const struct XSParseSublikeHooks parse_stages_hooks = { .flags = XS_PARSE_SUBLIKE_FLAG_FILTERATTRS, .permit = stage_permit, .pre_subparse = stage_pre_subparse, .post_blockstart = stage_post_blockstart, .pre_blockend = stage_pre_blockend, .post_newcv = stage_post_newcv, .filter_attr = stage_filter_attr, }; MODULE = t::stages PACKAGE = t::stages BOOT: boot_xs_parse_sublike(0); register_xs_parse_sublike("stages", &parse_stages_hooks, NULL); XS-Parse-Sublike-0.22/t/testcase.pm000444001750001750 33114643004052 15700 0ustar00leoleo000000000000package testcase; use v5.14; use warnings; use lib "t/blib", "t/blib/arch"; use XS::Parse::Sublike; sub import { shift; require XSLoader; XSLoader::load( $_[0], $XS::Parse::Sublike::VERSION ); } 0x55AA;