List-Keywords-0.11000755001750001750 014455772471 12714 5ustar00leoleo000000000000List-Keywords-0.11/.editorconfig000444001750001750 5314455772471 15464 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 List-Keywords-0.11/Build.PL000444001750001750 135214455772471 14346 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; use XS::Parse::Keyword::Builder; my $build = Module::Build->new( module_name => "List::Keywords", test_requires => { 'Test2::V0' => '0.000148', }, configure_requires => { 'Module::Build' => '0.4004', # test_requires 'XS::Parse::Keyword::Builder' => '0.35', }, requires => { 'perl' => '5.014', 'XS::Parse::Keyword' => '0.05', }, license => 'perl', create_license => 1, create_readme => 1, meta_merge => { resources => { x_IRC => "irc://irc.perl.org/#io-async", }, }, extra_compiler_flags => [qw( -Ihax )], ); XS::Parse::Keyword::Builder->extend_module_build( $build ); $build->create_build_script; List-Keywords-0.11/Changes000444001750001750 460014455772471 14344 0ustar00leoleo000000000000Revision history for List-Keywords 0.11 2023-07-19 [CHANGES] * Use is_refcount() from Test2::V0 rather than Test::Refcount * Remember to implement `no List::Keywords` to disable the syntax 0.10 2023-02-02 [CHANGES] * Added `ngrep` and `nmap` [BUGFIXES] * Ensure that lexical block variables have the same aliasing behaviour as global `$_` would do * Ensure that result lists that are supposed to contain aliases are in fact actually aliased 0.09 2023-02-01 [CHANGES] * Recognise a `my $var` declaration in front of single-argument blocks (first, any/all/none/notall); use that instead of global $_ * Switch all the unit tests from Test::More to Test::V2 [BUGFIXES] * Support latest bleadperl which needs `PERL_USE_VOLATILE_API` to get access to optimize_optree() and finalize_optree() * Don't confuse custom RPEEP hooks into an infinite spin by putting the op start pointer into the optree fragment root too soon (RT142471) 0.08 2021-05-31 [CHANGES] * Use the new XPK_*CTX versions of token macros to simplify needing to call op_contextualize() / op_scope() 0.07 2021-05-27 [CHANGES] * Added 'reductions' [BUGFIXES] * Remember to declare dependency on XS::Parse::Keyword 0.04 0.06 2021-05-24 [CHANGES] * Updated for XS::Parse::Keyword 0.04 API change 0.05 2021-05-12 [CHANGES] * Added 'reduce' [BUGFIXES] * Make sure to optimize/finalize the optree of the code block, as some ops need this (e.g. for dTARG allocation) 0.04 2021-04-30 [CHANGES] * Implement B::Deparse hackery so code deparses properly * Now works back to perl 5.14 so declare that as such [BUGFIXES] * Fix POD error in docs * Fix maths error in t/95benchmark.t 0.03 2021-04-28 [CHANGES] * Added 'first', 'none', 'notall' 0.02 2021-04-27 [CHANGES] * Added a benchmarking test to print comparisons with List::Util [BUGFIXES] * Back-compat to perl 5.16 * Yield correct result when any/all are given an empty list of items 0.01 2021-04-27 First version, released on an unsuspecting world. List-Keywords-0.11/LICENSE000444001750001750 4375514455772471 14114 0ustar00leoleo000000000000This software is copyright (c) 2023 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) 2023 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 Artistic License 1.0 --- This software is Copyright (c) 2023 by Paul Evans . This is free software, licensed under: The 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. - "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 ftp.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) accompany any non-standard executables with their corresponding Standard Version executables, giving the non-standard executables non-standard names, and clearly documenting 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. 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 whomever generated them, and may be sold commercially, and may be aggregated with this Package. 7. C or perl subroutines supplied by you and linked into this Package shall not be considered part of this Package. 8. The name of the Copyright Holder may not be used to endorse or promote products derived from this software without specific prior written permission. 9. 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 List-Keywords-0.11/MANIFEST000444001750001750 53614455772471 14166 0ustar00leoleo000000000000.editorconfig Build.PL Changes hax/op_sibling_splice.c.inc hax/perl-backcompat.c.inc lib/List/Keywords.pm lib/List/Keywords.xs LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01first.t t/02any.t t/03all.t t/04none.t t/05notall.t t/10reduce.t t/11reductions.t t/20ngrep.t t/21nmap.t t/70deparse.t t/95benchmark.t t/99pod.t List-Keywords-0.11/META.json000444001750001750 237314455772471 14477 0ustar00leoleo000000000000{ "abstract" : "a selection of list utility keywords", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4231", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "List-Keywords", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004", "XS::Parse::Keyword::Builder" : "0.35" } }, "runtime" : { "requires" : { "XS::Parse::Keyword" : "0.05", "perl" : "5.014" } }, "test" : { "requires" : { "Test2::V0" : "0.000148" } } }, "provides" : { "List::Keywords" : { "file" : "lib/List/Keywords.pm", "version" : "0.11" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "x_IRC" : "irc://irc.perl.org/#io-async" }, "version" : "0.11", "x_serialization_backend" : "JSON::PP version 4.07" } List-Keywords-0.11/META.yml000444001750001750 141114455772471 14317 0ustar00leoleo000000000000--- abstract: 'a selection of list utility keywords' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test2::V0: '0.000148' configure_requires: Module::Build: '0.4004' XS::Parse::Keyword::Builder: '0.35' dynamic_config: 1 generated_by: 'Module::Build version 0.4231, 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: List-Keywords provides: List::Keywords: file: lib/List/Keywords.pm version: '0.11' requires: XS::Parse::Keyword: '0.05' perl: '5.014' resources: IRC: irc://irc.perl.org/#io-async license: http://dev.perl.org/licenses/ version: '0.11' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' List-Keywords-0.11/README000444001750001750 1777114455772471 13766 0ustar00leoleo000000000000NAME List::Keywords - a selection of list utility keywords SYNOPSIS use List::Keywords 'any'; my @boxes = ...; if( any { $_->size > 100 } @boxes ) { say "There are some large boxes here"; } DESCRIPTION This module provides keywords that behave (almost) identically to familiar functions from List::Util, but implemented as keyword plugins instead of functions. As a result these run more efficiently, especially in small code cases. Blocks vs Anonymous Subs In the description above the word "almost" refers to the fact that as this module provides true keywords, the code blocks to them can be parsed as true blocks rather than anonymous functions. As a result, both caller and return will behave rather differently here. For example, use List::Keywords 'any'; sub func { any { say "My caller is ", caller; return "ret" } 1, 2, 3; say "This is never printed"; } Here, the caller will see func as its caller, and the return statement makes the entire containing function return, so the second line is never printed. The same example written using List::Util will instead print the List::Util::any function as being the caller, before making just that one item return the value, then the message on the second line is printed as normal. In regular operation where the code is just performing some test on each item, and does not make use of caller or return, this should not cause any noticable differences. Lexical Variable Syntax Newly added in version 0.09 many of the functions in this module support a new syntax idea that may be added to Perl core eventually, whereby a lexical variable can be declared before the code block. In that case, this lexical variable takes the place of the global $_ for the purpose of carrying values from the input list. This syntax is currently under discussion for Perl's map and grep blocks, and may be added in a future release of Perl. https://github.com/Perl/RFCs/pull/33 Aliasing and Modification Each time the block code is executed, the global $_ or the lexical variable being used is aliased to an element of the input list (in the same way as it would be for perl's map or foreach loops, for example). If the block attempts to modify the value of this variable, such modifications are visible in the input list. You almost certainly want to avoid doing this. For example: my @numbers = ...; my $x = first my $x { $x++ > 10 } @numbers; This will modify values in the @numbers array, but due to the short-circuit nature of first, will only have modified values up to the selected element by the time it returns. This will likely confuse later uses of the input array. Additionally, the result of first is also aliased to the input list, much as it is for core perl's grep. This may mean that values passed in to other functions have an ability to mutate at a distance. For example: func( first { ... } @numbers ); Here, the invoked func() may be able to modify the @numbers array, for example by modifying its own @_ array. Performance The following example demonstrates a simple case and shows how the performance differs. my @nums = (1 .. 100); my $ret = any { $_ > 50 } @nums; When run for 5 seconds each, the following results were obtained on my machine: List::Util::any 648083/s List::Keyword/any 816135/s The List::Keyword version here ran 26% faster. KEYWORDS first $val = first { CODE } LIST Since verison 0.03. Repeatedly calls the block of code, with $_ locally set to successive values from the given list. Returns the value and stops at the first item to make the block yield a true value. If no such item exists, returns undef. $val = first my $var { CODE } LIST Since version 0.09. Optionally the code block can be prefixed with a lexical variable declaration. In this case, that variable will contain each value from the list, and the global $_ will remain untouched. any $bool = any { CODE } LIST Repeatedly calls the block of code, with $_ locally set to successive values from the given list. Returns true and stops at the first item to make the block yield a true value. If no such item exists, returns false. $val = any my $var { CODE } LIST Since version 0.09. Uses the lexical variable instead of global $_, similar to "first". all $bool = all { CODE } LIST Repeatedly calls the block of code, with $_ locally set to successive values from the given list. Returns false and stops at the first item to make the block yield a false value. If no such item exists, returns true. $val = all my $var { CODE } LIST Since version 0.09. Uses the lexical variable instead of global $_, similar to "first". none notall $bool = none { CODE } LIST $bool = notall { CODE } LISt Since verison 0.03. Same as "any" and "all" but with the return value inverted. $val = none my $var { CODE } LIST $val = notall my $var { CODE } LIST Since version 0.09. Uses the lexical variable instead of global $_, similar to "first". reduce $final = reduce { CODE } INITIAL, LIST Since verison 0.05. Repeatedly calls a block of code, using the $a package lexical as an accumulator and setting $b to each successive value from the list in turn. The first value of the list sets the initial value of the accumulator, and each returned result from the code block gives its new value. The final value of the accumulator is returned. reductions @partials = reductions { CODE } INITIAL, LIST Since version 0.06. Similar to reduce, but returns a full list of all the partial results of every invocation, beginning with the initial value itself and ending with the final result. N-AT-A-TIME FUNCTIONS The following two functions are a further experiment to try out n-at-a-time lexical variable support on the core grep and map operators. They are differently named, because keyword plugins cannot replace existing core keywords, only add new ones. ngrep @values = ngrep my ($var1, $var2, ...) { CODE } LIST $values = ngrep my ($var1, $var2, ...) { CODE } LIST Since version 0.10. A variation on core's grep, which uses lexical variable syntax to request a number of items at once. The input list is broken into bundles sized according to the number of variables declared. The block of code is called in scalar context with the variables set to each corresponding bundle of values, and the bundles for which the block returned true are saved for the resulting list. In scalar context, returns the number of values that would have been present in the resulting list (i.e. this is not the same as the number of times the block returned true). nmap @results = nmap my ($var1, $var2, ...) { CODE } LIST $results = nmap my ($var1, $var2, ...) { CODE } LIST Since version 0.10. A variation on core's map, which uses lexical variable syntax to request a number of items at once. The input list is broken into bundles sized according to the number of variables declared. The block of code is called in list context with the variables set to each corresponding bundle of values, and the results of the block from each bundle are concatenated together to form the result list. In scalar context, returns the number of values that would have been present in the resulting list. TODO More functions from List::Util: pairfirst pairgrep pairmap Maybe also consider some from List::UtilsBy. ACKNOWLEDGEMENTS With thanks to Matthew Horsfall (alh) for much assistance with performance optimizations. AUTHOR Paul Evans List-Keywords-0.11/hax000755001750001750 014455772471 13474 5ustar00leoleo000000000000List-Keywords-0.11/hax/op_sibling_splice.c.inc000444001750001750 167714455772471 20244 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef op_sibling_splice # define op_sibling_splice(parent, start, del_count, insert) S_op_sibling_splice(aTHX_ parent, start, del_count, insert) static OP *S_op_sibling_splice(pTHX_ OP *parent, OP *start, int del_count, OP *insert) { OP *deleted = NULL; if(!insert && !del_count) return NULL; OP **prevp; if(start) prevp = &(start->op_sibling); else prevp = &(cLISTOPx(parent)->op_first); OP *after = *prevp; if(del_count) { croak("Back-compat op_sibling_splice with del_count != 0 not yet implemented"); /* THIS IS AS YET UNTESTED deleted = *prevp; OP *o = deleted; while(del_count > 1) o = o->op_sibling, del_count--; after = o->op_sibling; o->op_sibling = NULL; */ } if(insert) { *prevp = insert; OP *o = insert; while(o->op_sibling) o = o->op_sibling; o->op_sibling = after; } else *prevp = after; return deleted; } #endif List-Keywords-0.11/hax/perl-backcompat.c.inc000444001750001750 1361614455772471 17640 0ustar00leoleo000000000000/* vi: set ft=c : */ #define HAVE_PERL_VERSION(R, V, S) \ (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S)))))) #ifndef NOT_REACHED # define NOT_REACHED assert(0) #endif #ifndef SvTRUE_NN # define SvTRUE_NN(sv) SvTRUE(sv) #endif #ifndef G_LIST # define G_LIST G_ARRAY #endif #if !HAVE_PERL_VERSION(5, 18, 0) typedef AV PADNAMELIST; # define PadlistARRAY(pl) ((PAD **)AvARRAY(pl)) # define PadlistNAMES(pl) (*PadlistARRAY(pl)) typedef SV PADNAME; # define PadnamePV(pn) (SvPOKp(pn) ? SvPVX(pn) : NULL) # define PadnameLEN(pn) SvCUR(pn) # define PadnameIsSTATE(pn) (!!SvPAD_STATE(pn)) # define PadnameOUTER(pn) (SvFAKE(pn) && !SvPAD_STATE(pn)) # define PadnamelistARRAY(pnl) AvARRAY(pnl) # define PadnamelistMAX(pnl) AvFILLp(pnl) # define PadARRAY(p) AvARRAY(p) # define PadMAX(pad) AvFILLp(pad) #endif #if !HAVE_PERL_VERSION(5, 22, 0) # define CvPADLIST_set(cv, padlist) (CvPADLIST(cv) = padlist) # define newPADNAMEpvn(p,n) S_newPADNAMEpvn(aTHX_ p,n) static PADNAME *S_newPADNAMEpvn(pTHX_ const char *pv, STRLEN n) { PADNAME *pn = newSVpvn(pv, n); /* PADNAMEs need to be at least SVt_PVNV in order to store the COP_SEQ_* * fields */ sv_upgrade(pn, SVt_PVNV); return pn; } # define PadnameREFCNT_dec(pn) SvREFCNT_dec(pn) #endif #ifndef av_count # define av_count(av) (AvFILL(av) + 1) #endif #ifndef av_top_index # define av_top_index(av) AvFILL(av) #endif #ifndef block_end # define block_end(a,b) Perl_block_end(aTHX_ a,b) #endif #ifndef block_start # define block_start(a) Perl_block_start(aTHX_ a) #endif #ifndef cophh_exists_pvs # define cophh_exists_pvs(a,b,c) cBOOL(cophh_fetch_pvs(a,b,c)) #endif #ifndef cv_clone # define cv_clone(a) Perl_cv_clone(aTHX_ a) #endif #ifndef intro_my # define intro_my() Perl_intro_my(aTHX) #endif #ifndef pad_alloc # define pad_alloc(a,b) Perl_pad_alloc(aTHX_ a,b) #endif #ifndef CX_CUR # define CX_CUR() (&cxstack[cxstack_ix]) #endif #if HAVE_PERL_VERSION(5, 24, 0) # define OLDSAVEIX(cx) (cx->blk_oldsaveix) #else # define OLDSAVEIX(cx) (PL_scopestack[cx->blk_oldscopesp-1]) #endif #ifndef OpSIBLING # define OpSIBLING(op) ((op)->op_sibling) #endif #ifndef OpHAS_SIBLING # define OpHAS_SIBLING(op) (cBOOL(OpSIBLING(op))) #endif #ifndef OpMORESIB_set # define OpMORESIB_set(op,sib) ((op)->op_sibling = (sib)) #endif #ifndef OpLASTSIB_set /* older perls don't need to store this at all */ # define OpLASTSIB_set(op,parent) #endif #ifndef op_convert_list # define op_convert_list(type, flags, o) S_op_convert_list(aTHX_ type, flags, o) static OP *S_op_convert_list(pTHX_ I32 type, I32 flags, OP *o) { /* A minimal recreation just for our purposes */ assert( /* A hardcoded list of the optypes we know this will work for */ type == OP_ENTERSUB || type == OP_JOIN || type == OP_PUSH || 0); o->op_type = type; o->op_flags |= flags; o->op_ppaddr = PL_ppaddr[type]; o = PL_check[type](aTHX_ o); /* op_std_init() */ if(PL_opargs[type] & OA_RETSCALAR) o = op_contextualize(o, G_SCALAR); if(PL_opargs[type] & OA_TARGET && !o->op_targ) o->op_targ = pad_alloc(type, SVs_PADTMP); return o; } #endif #ifndef newMETHOP_named # define newMETHOP_named(type, flags, name) newSVOP(type, flags, name) #endif #ifndef PARENT_PAD_INDEX_set # if HAVE_PERL_VERSION(5, 22, 0) # define PARENT_PAD_INDEX_set(pn,val) (PARENT_PAD_INDEX(pn) = val) # else /* stolen from perl-5.20.0's pad.c */ # define PARENT_PAD_INDEX_set(sv,val) \ STMT_START { ((XPVNV*)SvANY(sv))->xnv_u.xpad_cop_seq.xlow = (val); } STMT_END # endif #endif /* On Perl 5.14 this had a different name */ #ifndef pad_add_name_pvn #define pad_add_name_pvn(name, len, flags, typestash, ourstash) MY_pad_add_name(aTHX_ name, len, flags, typestash, ourstash) static PADOFFSET MY_pad_add_name(pTHX_ const char *name, STRLEN len, U32 flags, HV *typestash, HV *ourstash) { /* perl 5.14's Perl_pad_add_name requires a NUL-terminated name */ SV *namesv = sv_2mortal(newSVpvn(name, len)); return Perl_pad_add_name(aTHX_ SvPV_nolen(namesv), SvCUR(namesv), flags, typestash, ourstash); } #endif #if !HAVE_PERL_VERSION(5, 26, 0) # define isIDFIRST_utf8_safe(s, e) (PERL_UNUSED_ARG(e), isIDFIRST_utf8(s)) # define isIDCONT_utf8_safe(s, e) (PERL_UNUSED_ARG(e), isIDCONT_utf8(s)) #endif #ifndef CXp_EVALBLOCK /* before perl 5.34 this was called CXp_TRYBLOCK */ # define CXp_EVALBLOCK CXp_TRYBLOCK #endif #if !HAVE_PERL_VERSION(5, 26, 0) # define sv_set_undef(sv) sv_setsv(sv, &PL_sv_undef) #endif #ifndef newAVav # define newAVav(av) S_newAVav(aTHX_ av) static AV *S_newAVav(pTHX_ AV *av) { AV *ret = newAV(); U32 count = av_count(av); U32 i; for(i = 0; i < count; i++) av_push(ret, newSVsv(AvARRAY(av)[i])); return ret; } #endif #if !defined(sv_derived_from_hv) && HAVE_PERL_VERSION(5, 16, 0) # define sv_derived_from_hv(sv, hv) MY_sv_derived_from_hv(aTHX_ sv, hv) static bool MY_sv_derived_from_hv(pTHX_ SV *sv, HV *hv) { char *hvname = HvNAME(hv); if(!hvname) return FALSE; return sv_derived_from_pvn(sv, hvname, HvNAMELEN(hv), HvNAMEUTF8(hv) ? SVf_UTF8 : 0); } #endif #ifndef xV_FROM_REF # ifdef PERL_USE_GCC_BRACE_GROUPS # define xV_FROM_REF(XV, ref) \ ({ SV *_ref = ref; assert(SvROK(_ref)); assert(SvTYPE(SvRV(_ref)) == SVt_PV ## XV); (XV *)(SvRV(_ref)); }) # else # define xV_FROM_REF(XV, ref) ((XV *)SvRV(ref)) # endif # define AV_FROM_REF(ref) xV_FROM_REF(AV, ref) # define CV_FROM_REF(ref) xV_FROM_REF(CV, ref) # define HV_FROM_REF(ref) xV_FROM_REF(HV, ref) #endif #ifndef newPADxVOP # define newPADxVOP(type, flags, padix) S_newPADxVOP(aTHX_ type, flags, padix) static OP *S_newPADxVOP(pTHX_ I32 type, I32 flags, PADOFFSET padix) { OP *op = newOP(type, flags); op->op_targ = padix; return op; } #endif List-Keywords-0.11/lib000755001750001750 014455772471 13462 5ustar00leoleo000000000000List-Keywords-0.11/lib/List000755001750001750 014455772471 14375 5ustar00leoleo000000000000List-Keywords-0.11/lib/List/Keywords.pm000444001750001750 2521714455772471 16726 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-2023 -- leonerd@leonerd.org.uk package List::Keywords 0.11; use v5.14; use warnings; use Carp; require XSLoader; XSLoader::load( __PACKAGE__, our $VERSION ); =head1 NAME C - a selection of list utility keywords =head1 SYNOPSIS use List::Keywords 'any'; my @boxes = ...; if( any { $_->size > 100 } @boxes ) { say "There are some large boxes here"; } =head1 DESCRIPTION This module provides keywords that behave (almost) identically to familiar functions from L, but implemented as keyword plugins instead of functions. As a result these run more efficiently, especially in small code cases. =head2 Blocks vs Anonymous Subs In the description above the word "almost" refers to the fact that as this module provides true keywords, the code blocks to them can be parsed as true blocks rather than anonymous functions. As a result, both C and C will behave rather differently here. For example, use List::Keywords 'any'; sub func { any { say "My caller is ", caller; return "ret" } 1, 2, 3; say "This is never printed"; } Here, the C will see C as its caller, and the C statement makes the entire containing function return, so the second line is never printed. The same example written using C will instead print the C function as being the caller, before making just that one item return the value, then the message on the second line is printed as normal. In regular operation where the code is just performing some test on each item, and does not make use of C or C, this should not cause any noticable differences. =head2 Lexical Variable Syntax Newly added in I many of the functions in this module support a new syntax idea that may be added to Perl core eventually, whereby a lexical variable can be declared before the code block. In that case, this lexical variable takes the place of the global C<$_> for the purpose of carrying values from the input list. This syntax is currently under discussion for Perl's C and C blocks, and may be added in a future release of Perl. L =head2 Aliasing and Modification Each time the block code is executed, the global C<$_> or the lexical variable being used is aliased to an element of the input list (in the same way as it would be for perl's C or C loops, for example). If the block attempts to modify the value of this variable, such modifications are visible in the input list. You almost certainly want to avoid doing this. For example: my @numbers = ...; my $x = first my $x { $x++ > 10 } @numbers; This will modify values in the C<@numbers> array, but due to the short-circuit nature of C, will only have modified values up to the selected element by the time it returns. This will likely confuse later uses of the input array. Additionally, the result of C is also aliased to the input list, much as it is for core perl's C. This may mean that values passed in to other functions have an ability to mutate at a distance. For example: func( first { ... } @numbers ); Here, the invoked C may be able to modify the C<@numbers> array, for example by modifying its own C<@_> array. =head2 Performance The following example demonstrates a simple case and shows how the performance differs. my @nums = (1 .. 100); my $ret = any { $_ > 50 } @nums; When run for 5 seconds each, the following results were obtained on my machine: List::Util::any 648083/s List::Keyword/any 816135/s The C version here ran 26% faster. =cut my %KEYWORD_OK = map { $_ => 1 } qw( first any all none notall reduce reductions ngrep nmap ); sub import { shift->apply( sub { $^H{ $_[0] }++ }, @_ ) } sub unimport { shift->apply( sub { delete $^H{ $_[0] } }, @_ ) } sub apply { shift; my ( $cb, @syms ) = @_; foreach ( @syms ) { if( $_ eq ":all" ) { push @syms, keys %KEYWORD_OK; next; } $KEYWORD_OK{$_} or croak "Unrecognised import symbol '$_'"; $cb->( "List::Keywords/$_" ); } } sub B::Deparse::pp_firstwhile { my ($self, $op, $cx) = @_; # first, any, all, none, notall my $private = $op->private; my $name = ( $private == 0 ) ? "first" : ( $private == 6 ) ? "none" : ( $private == 9 ) ? "any" : ( $private == 22 ) ? "all" : ( $private == 25 ) ? "notall" : "firstwhile[op_private=$private]"; # We can't just call B::Deparse::mapop because of the possibility of `my $var` # So we'll inline it here my $kid = $op->first; $kid = $kid->first->sibling; # skip PUSHMARK my $code = $kid->first; $kid = $kid->sibling; if(B::Deparse::is_scope $code) { $code = "{" . $self->deparse($code, 0) . "} "; if($op->targ) { my $varname = $self->padname($op->targ); $code = "my $varname $code"; } } else { $code = $self->deparse($code, 24); $code .= ", " if !B::Deparse::null($kid); } my @exprs; for (; !B::Deparse::null($kid); $kid = $kid->sibling) { my $expr = $self->deparse($kid, 6); push @exprs, $expr if defined $expr; } return $self->maybe_parens_func($name, $code . join(" ", @exprs), $cx, 5); } sub B::Deparse::pp_reducewhile { return B::Deparse::mapop(@_, "reduce"); } sub deparse_niter { my ($name, $self, $op, $cx) = @_; my $targ = $op->targ; my $targcount = $op->private; # We can't just call B::Deparse::mapop because of the `my ($var)` list my $kid = $op->first; $kid = $kid->first->sibling; # skip PUSHMARK my $block = $kid->first; my @varnames = map { $self->padname($_) } $targ .. $targ + $targcount - 1; $kid = $kid->sibling; my @exprs; for(; !B::Deparse::null($kid); $kid = $kid->sibling) { my $expr = $self->deparse($kid, 6); push @exprs, $expr if defined $expr; } my $code = "my (" . join(", ", @varnames) . ") {" . $self->deparse($block, 0) . "} " . join(", ", @exprs); return $self->maybe_parens_func($name, $code, $cx, 5); } sub B::Deparse::pp_ngrepwhile { deparse_niter(ngrep => @_) } sub B::Deparse::pp_nmapwhile { deparse_niter(nmap => @_) } =head1 KEYWORDS =cut =head2 first $val = first { CODE } LIST I Repeatedly calls the block of code, with C<$_> locally set to successive values from the given list. Returns the value and stops at the first item to make the block yield a true value. If no such item exists, returns C. $val = first my $var { CODE } LIST I Optionally the code block can be prefixed with a lexical variable declaration. In this case, that variable will contain each value from the list, and the global C<$_> will remain untouched. =head2 any $bool = any { CODE } LIST Repeatedly calls the block of code, with C<$_> locally set to successive values from the given list. Returns true and stops at the first item to make the block yield a true value. If no such item exists, returns false. $val = any my $var { CODE } LIST I Uses the lexical variable instead of global C<$_>, similar to L. =head2 all $bool = all { CODE } LIST Repeatedly calls the block of code, with C<$_> locally set to successive values from the given list. Returns false and stops at the first item to make the block yield a false value. If no such item exists, returns true. $val = all my $var { CODE } LIST I Uses the lexical variable instead of global C<$_>, similar to L. =head2 none =head2 notall $bool = none { CODE } LIST $bool = notall { CODE } LISt I Same as L and L but with the return value inverted. $val = none my $var { CODE } LIST $val = notall my $var { CODE } LIST I Uses the lexical variable instead of global C<$_>, similar to L. =cut =head2 reduce $final = reduce { CODE } INITIAL, LIST I Repeatedly calls a block of code, using the C<$a> package lexical as an accumulator and setting C<$b> to each successive value from the list in turn. The first value of the list sets the initial value of the accumulator, and each returned result from the code block gives its new value. The final value of the accumulator is returned. =head2 reductions @partials = reductions { CODE } INITIAL, LIST I Similar to C, but returns a full list of all the partial results of every invocation, beginning with the initial value itself and ending with the final result. =cut =head1 N-AT-A-TIME FUNCTIONS The following two functions are a further experiment to try out n-at-a-time lexical variable support on the core C and C operators. They are differently named, because keyword plugins cannot replace existing core keywords, only add new ones. =head2 ngrep @values = ngrep my ($var1, $var2, ...) { CODE } LIST $values = ngrep my ($var1, $var2, ...) { CODE } LIST I A variation on core's C, which uses lexical variable syntax to request a number of items at once. The input list is broken into bundles sized according to the number of variables declared. The block of code is called in scalar context with the variables set to each corresponding bundle of values, and the bundles for which the block returned true are saved for the resulting list. In scalar context, returns the number of values that would have been present in the resulting list (i.e. this is not the same as the number of times the block returned true). =cut =head2 nmap @results = nmap my ($var1, $var2, ...) { CODE } LIST $results = nmap my ($var1, $var2, ...) { CODE } LIST I A variation on core's C, which uses lexical variable syntax to request a number of items at once. The input list is broken into bundles sized according to the number of variables declared. The block of code is called in list context with the variables set to each corresponding bundle of values, and the results of the block from each bundle are concatenated together to form the result list. In scalar context, returns the number of values that would have been present in the resulting list. =cut =head1 TODO More functions from C: pairfirst pairgrep pairmap Maybe also consider some from L. =head1 ACKNOWLEDGEMENTS With thanks to Matthew Horsfall (alh) for much assistance with performance optimizations. =cut =head1 AUTHOR Paul Evans =cut 0x55AA; List-Keywords-0.11/lib/List/Keywords.xs000444001750001750 5534414455772471 16750 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-2023 -- leonerd@leonerd.org.uk */ #define PERL_NO_GET_CONTEXT /* needed on latest perl to get optimize_optree/finalize_optree */ #define PERL_USE_VOLATILE_API #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "XSParseKeyword.h" #include "perl-backcompat.c.inc" #include "op_sibling_splice.c.inc" #ifndef optimize_optree # if HAVE_PERL_VERSION(5,28,0) # define optimize_optree(op) Perl_optimize_optree(aTHX_ op) # else # define optimize_optree(op) # endif #endif #ifndef finalize_optree # if HAVE_PERL_VERSION(5,16,0) # define finalize_optree(op) Perl_finalize_optree(aTHX_ op) # else # define finalize_optree(op) # endif #endif #if HAVE_PERL_VERSION(5,28,0) # define XPUSHzero XPUSHs(&PL_sv_zero) #else /* perls before 5.28 do not have PL_sv_zero */ # define XPUSHzero mXPUSHi(0) #endif /* We can't newLOGOP because that will force scalar context */ #define allocLOGOP_CUSTOM(func, flags, first, other) MY_allocLOGOP_CUSTOM(aTHX_ func, flags, first, other) static LOGOP *MY_allocLOGOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags, OP *first, OP *other) { LOGOP *logop; NewOp(1101, logop, 1, LOGOP); logop->op_type = OP_CUSTOM; logop->op_ppaddr = func; logop->op_flags = OPf_KIDS | (U8)(flags); logop->op_first = first; logop->op_other = other; return logop; } static OP *build_blocklist(pTHX_ PADOFFSET varix, OP *block, OP *list, OP *(*pp_start)(pTHX), OP *(*pp_while)(pTHX), U8 op_private) { /* Follow the same optree shape as grep: * LOGOP whileop * LISTOP startop * NULOP pushmark * UNOP null * {block scope goes here} * ... {list values go here} * * the null op protects the block body from being executed initially, * allowing it to be deferred * whileop's ->op_other points at the start of the block */ /* Link block in execution order and remember its start */ OP *blockstart = LINKLIST(block); /* Hide the block inside an OP_NULL with no execution */ block = newUNOP(OP_NULL, 0, block); block->op_next = block; /* Make startop op as the list with (shielded) block prepended */ OP *startop = list; if(startop->op_type != OP_LIST) startop = newLISTOP(OP_LIST, 0, startop, NULL); op_sibling_splice(startop, cLISTOPx(startop)->op_first, 0, block); startop->op_type = OP_CUSTOM; startop->op_ppaddr = pp_start; startop->op_targ = varix; LOGOP *whileop = allocLOGOP_CUSTOM(pp_while, 0, startop, blockstart); whileop->op_private = startop->op_private = op_private; whileop->op_targ = varix; OpLASTSIB_set(startop, (OP *)whileop); /* Temporarily set the whileop's op_next to NULL so as not to confuse * a custom RPEEP that might be set. We'll store the real start value in * there afterwards. See also * https://rt.cpan.org/Ticket/Display.html?id=142471 */ OP *whilestart = LINKLIST(startop); whileop->op_next = NULL; startop->op_next = (OP *)whileop; cUNOPx(block)->op_first->op_next = (OP *)whileop; /* Since the body of the block is now hidden from the peephole optimizer * we'll have to run that manually now */ optimize_optree(block); PL_rpeepp(aTHX_ blockstart); finalize_optree(block); whileop->op_next = whilestart; return (OP *)whileop; } /* The same ppfuncs that implement `first` can also do `any` and `all` with * minor changes of behaviour */ enum { FIRST_EMPTY_NO = (1<<0), /* \ */ FIRST_EMPTY_YES = (1<<1), /* - if neither, returns undef */ FIRST_RET_NO = (1<<2), /* \ */ FIRST_RET_YES = (1<<3), /* - if neither, returns $_ itself */ FIRST_STOP_ON_FALSE = (1<<4), }; static XOP xop_firststart; static XOP xop_firstwhile; static OP *pp_firststart(pTHX) { /* Insired by perl core's pp_grepstart() */ dSP; PADOFFSET targ = PL_op->op_targ; if(PL_stack_base + TOPMARK == SP) { /* Empty */ U8 mode = PL_op->op_private; (void)POPMARK; XPUSHs((mode & FIRST_EMPTY_NO ) ? &PL_sv_no : (mode & FIRST_EMPTY_YES) ? &PL_sv_yes : &PL_sv_undef); RETURNOP(PL_op->op_next->op_next); } PL_stack_sp = PL_stack_base + TOPMARK + 1; PUSHMARK(PL_stack_sp); /* current src item */ ENTER_with_name("first"); SV *src = PL_stack_base[TOPMARK]; if(SvPADTMP(src)) { src = PL_stack_base[TOPMARK] = sv_mortalcopy(src); PL_tmps_floor++; } SvTEMP_off(src); if(targ) { SV **padentry = &PAD_SVl(targ); save_sptr(padentry); *padentry = SvREFCNT_inc(src); } else { SAVE_DEFSV; DEFSV_set(src); } PUTBACK; /* Jump to body of block */ return (cLOGOPx(PL_op->op_next))->op_other; } static OP *pp_firstwhile(pTHX) { /* Inspired by perl core's pp_grepwhile() */ dSP; dPOPss; U8 mode = PL_op->op_private; PADOFFSET targ = PL_op->op_targ; SV *targsv = targ ? PAD_SVl(targ) : DEFSV; bool ret = SvTRUE_NN(sv); (*PL_markstack_ptr)++; if((mode & FIRST_STOP_ON_FALSE) ? !ret : ret) { /* Stop */ /* Technically this means that `first` will not necessarily return the * value from the list, but instead returns whatever the var was set to * after the block has run; differing if the block modified it. * I'm unsure how I feel about this, but both `CORE::grep` and * `List::Util::first` do the same thing, so we are in good company */ SV *ret = (mode & FIRST_RET_NO ) ? &PL_sv_no : (mode & FIRST_RET_YES) ? &PL_sv_yes : SvREFCNT_inc(targsv); if(targ) SvREFCNT_dec(targsv); LEAVE_with_name("first"); (void)POPMARK; SP = PL_stack_base + POPMARK; PUSHs(ret); RETURN; } if(UNLIKELY(PL_stack_base + *PL_markstack_ptr > SP)) { /* Empty */ LEAVE_with_name("first"); (void)POPMARK; SP = PL_stack_base + POPMARK; PUSHs((mode & FIRST_EMPTY_NO ) ? &PL_sv_no : (mode & FIRST_EMPTY_YES) ? &PL_sv_yes : &PL_sv_undef); RETURN; } SV *src = PL_stack_base[TOPMARK]; if(SvPADTMP(src)) { src = PL_stack_base[TOPMARK] = sv_mortalcopy(src); PL_tmps_floor++; } SvTEMP_off(src); if(targ) { SV **padentry = &PAD_SVl(targ); SvREFCNT_dec(*padentry); *padentry = SvREFCNT_inc(src); } else DEFSV_set(src); PUTBACK; return cLOGOP->op_other; } static int build_first(pTHX_ OP **out, XSParseKeywordPiece *args[], size_t nargs, void *hookdata) { size_t argi = 0; PADOFFSET varix = 0; bool has_optvar = args[argi++]->i; if(has_optvar) { varix = args[argi++]->padix; } OP *block = op_contextualize(op_scope(args[argi++]->op), G_SCALAR); OP *list = args[argi++]->op; *out = build_blocklist(aTHX_ varix, block, list, &pp_firststart, &pp_firstwhile, SvIV((SV *)hookdata)); return KEYWORD_PLUGIN_EXPR; } static const struct XSParseKeywordPieceType pieces_optvar_blocklist[] = { XPK_PREFIXED_BLOCK( XPK_OPTIONAL(XPK_KEYWORD("my"), XPK_LEXVAR_MY(XPK_LEXVAR_SCALAR)) ), XPK_LISTEXPR_LISTCTX, {0}, }; static const struct XSParseKeywordHooks hooks_first = { .permit_hintkey = "List::Keywords/first", .pieces = pieces_optvar_blocklist, .build = &build_first, }; static const struct XSParseKeywordHooks hooks_any = { .permit_hintkey = "List::Keywords/any", .pieces = pieces_optvar_blocklist, .build = &build_first, }; static const struct XSParseKeywordHooks hooks_all = { .permit_hintkey = "List::Keywords/all", .pieces = pieces_optvar_blocklist, .build = &build_first, }; static const struct XSParseKeywordHooks hooks_none = { .permit_hintkey = "List::Keywords/none", .pieces = pieces_optvar_blocklist, .build = &build_first, }; static const struct XSParseKeywordHooks hooks_notall = { .permit_hintkey = "List::Keywords/notall", .pieces = pieces_optvar_blocklist, .build = &build_first, }; static XOP xop_reducestart; static XOP xop_reducewhile; enum { REDUCE_REDUCE, REDUCE_REDUCTIONS, }; static OP *pp_reducestart(pTHX) { dSP; U8 mode = PL_op->op_private; if(PL_stack_base + TOPMARK == SP) { /* Empty */ (void)POPMARK; if(GIMME_V == G_SCALAR) XPUSHs(&PL_sv_undef); RETURNOP(PL_op->op_next->op_next); } if(PL_stack_base + TOPMARK + 1 == SP) { /* Single item */ (void)POPMARK; /* Leave the singleton there it will be fine */ RETURNOP(PL_op->op_next->op_next); } PL_stack_sp = PL_stack_base + TOPMARK + 1; if(mode == REDUCE_REDUCTIONS) PUSHMARK(PL_stack_sp); PUSHMARK(PL_stack_sp); ENTER_with_name("reduce"); GV *firstgv = gv_fetchpvs("a", GV_ADD|GV_NOTQUAL, SVt_PV); GV *secondgv = gv_fetchpvs("b", GV_ADD|GV_NOTQUAL, SVt_PV); save_gp(firstgv, 0); save_gp(secondgv, 0); GvINTRO_off(firstgv); GvINTRO_off(secondgv); SAVEGENERICSV(GvSV(firstgv)); SAVEGENERICSV(GvSV(secondgv)); SvREFCNT_inc(GvSV(firstgv)); SvREFCNT_inc(GvSV(secondgv)); /* Initial accumulator */ SV *sv = PL_stack_base[TOPMARK]; if(mode == REDUCE_REDUCTIONS) PL_stack_base[PL_markstack_ptr[-1]++] = sv_mortalcopy(sv); if(SvPADTMP(sv)) { sv = PL_stack_base[TOPMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); GvSV(firstgv) = SvREFCNT_inc(sv); (*PL_markstack_ptr)++; /* value */ sv = PL_stack_base[TOPMARK]; if(SvPADTMP(sv)) { sv = PL_stack_base[TOPMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); GvSV(secondgv) = SvREFCNT_inc(sv); PUTBACK; /* Jump to body of block */ return (cLOGOPx(PL_op->op_next))->op_other; } static OP *pp_reducewhile(pTHX) { dSP; U8 mode = PL_op->op_private; dPOPss; if(mode == REDUCE_REDUCTIONS) PL_stack_base[PL_markstack_ptr[-1]++] = SvPADTMP(sv) ? sv_mortalcopy(sv) : sv; (*PL_markstack_ptr)++; if(UNLIKELY(PL_stack_base + *PL_markstack_ptr > SP)) { U8 gimme = GIMME_V; LEAVE_with_name("reduce"); if(mode == REDUCE_REDUCTIONS) { (void)POPMARK; I32 retcount = --*PL_markstack_ptr - PL_markstack_ptr[-1]; (void)POPMARK; SP = PL_stack_base + POPMARK; if(gimme == G_SCALAR) { SP[1] = SP[retcount]; SP += 1; } else if(gimme == G_ARRAY) SP += retcount; } else { (void)POPMARK; SP = PL_stack_base + POPMARK; PUSHs(SvREFCNT_inc(sv)); } RETURN; } GV *firstgv = gv_fetchpvs("a", GV_ADD|GV_NOTQUAL, SVt_PV); GV *secondgv = gv_fetchpvs("b", GV_ADD|GV_NOTQUAL, SVt_PV); SvREFCNT_dec(GvSV(firstgv)); GvSV(firstgv) = SvREFCNT_inc(sv); /* next value */ sv = PL_stack_base[TOPMARK]; if(SvPADTMP(sv)) { sv = PL_stack_base[TOPMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); GvSV(secondgv) = SvREFCNT_inc(sv); PUTBACK; return cLOGOP->op_other; } static int build_reduce(pTHX_ OP **out, XSParseKeywordPiece *args[], size_t nargs, void *hookdata) { #if !HAVE_PERL_VERSION(5,20,0) GV *firstgv = gv_fetchpvs("a", GV_ADD|GV_NOTQUAL, SVt_PV); GV *secondgv = gv_fetchpvs("b", GV_ADD|GV_NOTQUAL, SVt_PV); GvMULTI_on(firstgv); GvMULTI_on(secondgv); #endif *out = build_blocklist(aTHX_ 0, args[0]->op, args[1]->op, &pp_reducestart, &pp_reducewhile, SvIV((SV *)hookdata)); return KEYWORD_PLUGIN_EXPR; } static const struct XSParseKeywordPieceType pieces_blocklist[] = { XPK_BLOCK_SCALARCTX, XPK_LISTEXPR_LISTCTX, {0}, }; static const struct XSParseKeywordHooks hooks_reduce = { .permit_hintkey = "List::Keywords/reduce", .pieces = pieces_blocklist, .build = &build_reduce, }; static const struct XSParseKeywordHooks hooks_reductions = { .permit_hintkey = "List::Keywords/reductions", .pieces = pieces_blocklist, .build = &build_reduce, }; static XOP xop_ngrepstart; static XOP xop_ngrepwhile; /* During the operation of ngrep, the top two marks on the markstack keep * track of the input values and return values, respectively */ #define VALMARK (PL_markstack_ptr[0]) #define RETMARK (PL_markstack_ptr[-1]) static OP *pp_ngrepstart(pTHX) { /* Inspired by perl core's pp_grepstart() */ dSP; PADOFFSET targ = PL_op->op_targ; U8 targcount = PL_op->op_private; if(PL_stack_base + TOPMARK == SP) { /* Empty */ (void)POPMARK; if(GIMME_V == G_SCALAR) XPUSHzero; RETURNOP(PL_op->op_next->op_next); } PL_stack_sp = PL_stack_base + TOPMARK + 1; PUSHMARK(PL_stack_sp); PUSHMARK(PL_stack_sp); ENTER_with_name("ngrep"); for(U8 targi = 0; targi < targcount; targi++) { SV **svp = PL_stack_base + TOPMARK; SV *sv = svp <= SP ? *svp : &PL_sv_undef; if(SvPADTMP(sv)) { sv = PL_stack_base[TOPMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); SV **padentry = &PAD_SVl(targ + targi); save_sptr(padentry); *padentry = SvREFCNT_inc(sv); VALMARK++; } PUTBACK; /* Jump to body of block */ return (cLOGOPx(PL_op->op_next))->op_other; } static OP *pp_ngrepwhile(pTHX) { dSP; PADOFFSET targ = PL_op->op_targ; U8 targcount = PL_op->op_private; dPOPss; if(SvTRUE_NN(sv)) { /* VALMARK has already been updated to point at next chunk; * we'll have to look backwards */ SV **chunksvs = PL_stack_base + VALMARK - targcount; for(U8 targi = 0; targi < targcount; targi++) { if(chunksvs + targi > SP) break; PL_stack_base[RETMARK++] = chunksvs[targi]; } } if(UNLIKELY(PL_stack_base + VALMARK > SP)) { U8 gimme = GIMME_V; I32 retcount = --RETMARK - PL_markstack_ptr[-2]; /* origmark */ LEAVE_with_name("ngrep"); (void)POPMARK; (void)POPMARK; SP = PL_stack_base + POPMARK; if(gimme == G_SCALAR) { /* No need to X this because we know we consumed at least one stack item */ mPUSHi(retcount); } else if(gimme == G_LIST) SP += retcount; RETURN; } /* next round */ for(U8 targi = 0; targi < targcount; targi++) { SV **svp = PL_stack_base + VALMARK; SV *sv = svp <= SP ? *svp : &PL_sv_undef; if(SvPADTMP(sv)) { sv = PL_stack_base[VALMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); SV **padentry = &PAD_SVl(targ + targi); SvREFCNT_dec(*padentry); *padentry = SvREFCNT_inc(sv); VALMARK++; } PUTBACK; return cLOGOP->op_other; } #undef VALMARK #undef RETMARK static XOP xop_nmapstart; static XOP xop_nmapwhile; static OP *pp_nmapstart(pTHX) { /* Inspired by perl core's pp_grepstart() */ dSP; PADOFFSET targ = PL_op->op_targ; U8 targcount = PL_op->op_private; if(PL_stack_base + TOPMARK == SP) { /* Empty */ (void)POPMARK; if(GIMME_V == G_SCALAR) XPUSHzero; RETURNOP(PL_op->op_next->op_next); } PL_stack_sp = PL_stack_base + TOPMARK + 1; PUSHMARK(PL_stack_sp); PUSHMARK(PL_stack_sp); ENTER_with_name("nmap"); SAVETMPS; ENTER_with_name("nmap_item"); for(U8 targi = 0; targi < targcount; targi++) { SV **svp = PL_stack_base + TOPMARK; SV *sv = svp <= SP ? *svp : &PL_sv_undef; if(SvPADTMP(sv)) { sv = PL_stack_base[TOPMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); SV **padentry = &PAD_SVl(targ + targi); save_sptr(padentry); *padentry = SvREFCNT_inc(sv); (*PL_markstack_ptr)++; } PUTBACK; PUSHMARK(PL_stack_sp); /* Jump to body of block */ return (cLOGOPx(PL_op->op_next))->op_other; } /* During the operation of ngrep_while, the top three marks on the markstack * keep track of the block result list, the input values, and the output * values, respectively */ #define BLOCKMARK (PL_markstack_ptr[0]) #define VALMARK (PL_markstack_ptr[-1]) #define RETMARK (PL_markstack_ptr[-2]) static OP *pp_nmapwhile(pTHX) { /* Inspired by perl core's pp_mapwhile() */ dSP; U8 gimme = GIMME_V; PADOFFSET targ = PL_op->op_targ; U8 targcount = PL_op->op_private; I32 items = (SP - PL_stack_base) - BLOCKMARK; if(items && gimme != G_VOID) { if(items > (VALMARK - RETMARK)) { I32 shift = items - (VALMARK - RETMARK); I32 count = (SP - PL_stack_base) - (VALMARK - targcount); /* avoid needing to reshuffle the stack too often, even at the cost of * making holes in it */ if(shift < count) shift = count; /* make a hole 'shift' SV*s wide */ EXTEND(SP, shift); SV **src = SP; SV **dst = (SP += shift); VALMARK += shift; BLOCKMARK += shift; /* move the values up into it */ while(count--) *(dst--) = *(src--); } SV **dst = PL_stack_base + (RETMARK += items) - 1; if(gimme == G_LIST) { EXTEND_MORTAL(items); I32 tmpsbase = PL_tmps_floor + 1; Move(PL_tmps_stack + tmpsbase, PL_tmps_stack + tmpsbase + items, PL_tmps_ix - PL_tmps_floor, SV *); PL_tmps_ix += items; I32 i = items; while(i-- > 0) { SV *sv = POPs; if(!SvTEMP(sv)) sv = sv_mortalcopy(sv); *dst-- = sv; PL_tmps_stack[tmpsbase++] = SvREFCNT_inc_simple(sv); } PL_tmps_floor += items; FREETMPS; i = items; while(i-- > 0) SvTEMP_on(PL_tmps_stack[--tmpsbase]); } else { /* No point mortalcopying temporary values in scalar context */ I32 i = items; while(i-- > 0) { (void)POPs; *dst-- = &PL_sv_undef; } FREETMPS; } } else { FREETMPS; } LEAVE_with_name("nmap_item"); if(UNLIKELY(PL_stack_base + VALMARK > SP)) { I32 retcount = --RETMARK - PL_markstack_ptr[-3]; /* origmark */ (void)POPMARK; LEAVE_with_name("nmap"); (void)POPMARK; (void)POPMARK; SP = PL_stack_base + POPMARK; if(gimme == G_SCALAR) { /* No need to X this because we know we consumed at least one stack item */ mPUSHi(retcount); } else if(gimme == G_LIST) SP += retcount; RETURN; } /* next round */ ENTER_with_name("nmap_item"); for(U8 targi = 0; targi < targcount; targi++) { SV **svp = PL_stack_base + VALMARK; SV *sv = svp <= SP ? *svp : &PL_sv_undef; if(SvPADTMP(sv)) { sv = PL_stack_base[VALMARK] = sv_mortalcopy(sv); PL_tmps_floor++; } SvTEMP_off(sv); SV **padentry = &PAD_SVl(targ + targi); SvREFCNT_dec(*padentry); *padentry = SvREFCNT_inc(sv); VALMARK++; } PUTBACK; return cLOGOP->op_other; } #undef BLOCKMARK #undef VALMARK #undef RETMARK enum { NITER_NGREP, NITER_NMAP, }; static int build_niter(pTHX_ OP **out, XSParseKeywordPiece *args[], size_t nargs, void *hookdata) { size_t argi = 0; int varcount = args[argi++]->i; /* It's very unlikely but lets just check */ if(varcount > 255) croak("Using more than 255 lexical variables to an iterated block function is not currently supported"); PADOFFSET varix = args[argi++]->padix; /* Because of how these vars were constructed, it really ought to be the * case that they have consequitive padix values. Lets just check to be sure */ for(int vari = 1; vari < varcount; vari++) if(args[argi++]->padix != varix + vari) croak("ARGH: Expected consequitive padix for lexical variables"); OP *block = op_scope(args[argi++]->op); OP *list = args[argi++]->op; switch(SvIV((SV *)hookdata)) { case NITER_NGREP: block = op_contextualize(block, G_SCALAR); *out = build_blocklist(aTHX_ varix, block, list, &pp_ngrepstart, &pp_ngrepwhile, (U8)varcount); break; case NITER_NMAP: block = op_contextualize(block, G_LIST); *out = build_blocklist(aTHX_ varix, block, list, &pp_nmapstart, &pp_nmapwhile, (U8)varcount); break; } return KEYWORD_PLUGIN_EXPR; } static const struct XSParseKeywordHooks hooks_ngrep = { .permit_hintkey = "List::Keywords/ngrep", .pieces = (const struct XSParseKeywordPieceType []){ XPK_PREFIXED_BLOCK( XPK_KEYWORD("my"), XPK_PARENS(XPK_COMMALIST(XPK_LEXVAR_MY(XPK_LEXVAR_SCALAR))) ), XPK_LISTEXPR_LISTCTX, {0}, }, .build = &build_niter, }; static const struct XSParseKeywordHooks hooks_nmap = { .permit_hintkey = "List::Keywords/nmap", .pieces = (const struct XSParseKeywordPieceType []){ XPK_PREFIXED_BLOCK( XPK_KEYWORD("my"), XPK_PARENS(XPK_COMMALIST(XPK_LEXVAR_MY(XPK_LEXVAR_SCALAR))) ), XPK_LISTEXPR_LISTCTX, {0}, }, .build = &build_niter, }; MODULE = List::Keywords PACKAGE = List::Keywords BOOT: boot_xs_parse_keyword(0.35); register_xs_parse_keyword("first", &hooks_first, newSViv(0)); /* Variations on first */ register_xs_parse_keyword("any", &hooks_any, newSViv(FIRST_EMPTY_NO |FIRST_RET_YES)); register_xs_parse_keyword("all", &hooks_all, newSViv(FIRST_EMPTY_YES|FIRST_RET_NO|FIRST_STOP_ON_FALSE)); register_xs_parse_keyword("none", &hooks_none, newSViv(FIRST_EMPTY_YES|FIRST_RET_NO)); register_xs_parse_keyword("notall", &hooks_notall, newSViv(FIRST_EMPTY_NO |FIRST_RET_YES|FIRST_STOP_ON_FALSE)); XopENTRY_set(&xop_firststart, xop_name, "firststart"); XopENTRY_set(&xop_firststart, xop_desc, "first"); XopENTRY_set(&xop_firststart, xop_class, OA_LISTOP); Perl_custom_op_register(aTHX_ &pp_firststart, &xop_firststart); XopENTRY_set(&xop_firstwhile, xop_name, "firstwhile"); XopENTRY_set(&xop_firstwhile, xop_desc, "first iter"); XopENTRY_set(&xop_firstwhile, xop_class, OA_LOGOP); Perl_custom_op_register(aTHX_ &pp_firstwhile, &xop_firstwhile); register_xs_parse_keyword("reduce", &hooks_reduce, newSViv(REDUCE_REDUCE)); register_xs_parse_keyword("reductions", &hooks_reductions, newSViv(REDUCE_REDUCTIONS)); XopENTRY_set(&xop_reducestart, xop_name, "reducestart"); XopENTRY_set(&xop_reducestart, xop_desc, "reduce"); XopENTRY_set(&xop_reducestart, xop_class, OA_LISTOP); Perl_custom_op_register(aTHX_ &pp_reducestart, &xop_reducestart); XopENTRY_set(&xop_reducewhile, xop_name, "reducewhile"); XopENTRY_set(&xop_reducewhile, xop_desc, "reduce iter"); XopENTRY_set(&xop_reducewhile, xop_class, OA_LOGOP); Perl_custom_op_register(aTHX_ &pp_reducewhile, &xop_reducewhile); register_xs_parse_keyword("ngrep", &hooks_ngrep, newSViv(NITER_NGREP)); XopENTRY_set(&xop_ngrepstart, xop_name, "ngrepstart"); XopENTRY_set(&xop_ngrepstart, xop_desc, "ngrep"); XopENTRY_set(&xop_ngrepstart, xop_class, OA_LISTOP); Perl_custom_op_register(aTHX_ &pp_ngrepstart, &xop_ngrepstart); XopENTRY_set(&xop_ngrepwhile, xop_name, "ngrepwhile"); XopENTRY_set(&xop_ngrepwhile, xop_desc, "ngrep iter"); XopENTRY_set(&xop_ngrepwhile, xop_class, OA_LOGOP); Perl_custom_op_register(aTHX_ &pp_ngrepwhile, &xop_ngrepwhile); register_xs_parse_keyword("nmap", &hooks_nmap, newSViv(NITER_NMAP)); XopENTRY_set(&xop_nmapstart, xop_name, "nmapstart"); XopENTRY_set(&xop_nmapstart, xop_desc, "nmap"); XopENTRY_set(&xop_nmapstart, xop_class, OA_LISTOP); Perl_custom_op_register(aTHX_ &pp_nmapstart, &xop_nmapstart); XopENTRY_set(&xop_nmapwhile, xop_name, "nmapwhile"); XopENTRY_set(&xop_nmapwhile, xop_desc, "nmap iter"); XopENTRY_set(&xop_nmapwhile, xop_class, OA_LOGOP); Perl_custom_op_register(aTHX_ &pp_nmapwhile, &xop_nmapwhile); List-Keywords-0.11/t000755001750001750 014455772471 13157 5ustar00leoleo000000000000List-Keywords-0.11/t/00use.t000444001750001750 16514455772471 14417 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords; pass "Modules loaded"; done_testing; List-Keywords-0.11/t/01first.t000444001750001750 472114455772471 14775 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0 0.000148; # is_refcount use List::Keywords 'first'; # Basic true/false testing is( (first { $_ > 10 } 1 .. 20), 11, 'list contains a value above ten' ); ok( !(first { $_ > 10 } 1 .. 9), 'list does not contain a value above ten' ); # first empty list is undef { my $invoked; my $ret = first { $invoked++ } (); ok( !defined $ret, 'first on empty list is not defined' ); ok( !$invoked, 'first on empty list did not invoke block' ); } # short-circuiting { my @seen; first { push @seen, $_; $_ > 10 } 10, 20, 30, 40; is( \@seen, [ 10, 20 ], 'short-circuits after first true result' ); } # stack discipline { is( [ 1, 2, (first { $_ eq "x" } "x", "y"), 3, 4 ], [ 1, 2, "x", 3, 4 ], 'first() preserves stack discipline' ); } # first my $x { BLOCK } { local $_ = "outer"; my @dollarsmudge; is( (first my $x { push @dollarsmudge, $_; $x > 10 } 1 .. 20), 11, 'list contains a value found by first my $x' ); is( \@dollarsmudge, [ ("outer")x11 ], '$_ was untouched during first my $x block' ); } # variable is aliased to input list; mutations are visible { my @input; my $output; $output = first { ++$_ } @input = (1); is( $output, 2, 'result value sees modification of $_' ); is( \@input, [ 2 ], 'input list sees modification of $_' ); $output = first my $x { ++$x } @input = (1); is( $output, 2, 'result value sees modification of lexical $x' ); is( \@input, [ 2 ], 'input list sees modification of lexical $x' ); } # result is aliased to input list; mutations are visible { my @input; sub incr { $_[0]++ } incr first { 1 } @input = (1); is( \@input, [ 2 ], 'result was aliased to input list of $_' ); incr first my $x { 1 } @input = (1); is( \@input, [ 2 ], 'result was aliased to input list of lexical $x' ); } # refcounts { my $arr = []; is_oneref( $arr, '$arr has one reference before test' ); my $result; $result = first { defined $_ } undef, $arr, undef; is_refcount( $arr, 2, '$arr has two references after first BLOCK' ); $result = first my $x { defined $x } undef, $arr, undef; is_refcount( $arr, 2, '$arr has two references after first my $x BLOCK' ); undef $result; is_oneref( $arr, '$arr has one reference at end of test' ); } # unimport { no List::Keywords 'first'; sub first { return "normal function" } is( first, "normal function", 'first() parses as a normal function call' ); } done_testing; List-Keywords-0.11/t/02any.t000444001750001750 225314455772471 14434 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'any'; # Basic true/false testing ok( (any { $_ > 10 } 1 .. 20), 'list contains a value above ten' ); ok( !(any { $_ > 10 } 1 .. 9), 'list does not contain a value above ten' ); # any empty list is false { my $invoked; my $ret = any { $invoked++ } (); ok( defined $ret, 'any on empty list is defined' ); ok( !$ret, 'any on empty list is false' ); ok( !$invoked, 'any on empty list did not invoke block' ); } # any failure yields false in list context { my @ret; @ret = any { $_ > 10 } 1 .. 9; ok( !!@ret, 'any nothing yielded false in list context' ); @ret = any { $_ > 10 } (); ok( !!@ret, 'any nothing yielded false in list context on empty input' ); } # short-circuiting { my @seen; any { push @seen, $_; $_ > 10 } 10, 20, 30, 40; is( \@seen, [ 10, 20 ], 'short-circuits after first true result' ); } # stack discipline { is( [ 1, 2, (any { $_ eq "x" } "x", "y"), 3, 4 ], [ 1, 2, 1, 3, 4 ], 'any() preserves stack discipline' ); } # any my $x { BLOCK } { ok( (any my $x { $x > 10 } 1 .. 20), 'list contains a value found by any my $x' ); } done_testing; List-Keywords-0.11/t/03all.t000444001750001750 212114455772471 14410 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'all'; # Basic true/false testing ok( !(all { $_ < 10 } 1 .. 20), 'not all list values below ten' ); ok( (all { $_ < 10 } 1 .. 9), 'all list values below ten' ); # all empty list is true { my $invoked; ok( (all { $invoked } ()), 'all on empty list is true' ); ok( !$invoked, 'all on empty list did not invoke block' ); } # all failure yields false in list context { my @ret; @ret = all { $_ > 10 } 1 .. 9; ok( !!@ret, 'all nothing yielded false in list context' ); @ret = all { $_ > 10 } (); ok( !!@ret, 'all nothing yielded false in list context on empty input' ); } # short-circuiting { my @seen; all { push @seen, $_; $_ < 20 } 10, 20, 30, 40; is( \@seen, [ 10, 20 ], 'short-circuits after first false result' ); } # stack discipline { is( [ 1, 2, (all { $_ eq "x" } "x", "x"), 3, 4 ], [ 1, 2, 1, 3, 4 ], 'all() preserves stack discipline' ); } # all my $x { BLOCK } { ok( (all my $x { $x < 10 } 1 .. 9), 'list contains all values found by all my $x' ); } done_testing; List-Keywords-0.11/t/04none.t000444001750001750 134214455772471 14604 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'none'; # Basic true/false testing ok( !(none { $_ > 10 } 1 .. 20), 'list contains a value above ten' ); ok( (none { $_ > 10 } 1 .. 9), 'list does not contain a value above ten' ); # none empty list is true { my $invoked; my $ret = none { $invoked++ } (); ok( $ret, 'none on empty list is true' ); ok( !$invoked, 'none on empty list did not invoke block' ); } # none failure yields scalar in list context { my @ret; @ret = none { $_ > 10 } 1 .. 9; ok( !!@ret, 'none nothing yielded false in list context' ); @ret = none { $_ > 10 } (); ok( !!@ret, 'none nothing yielded false in list context on empty input' ); } done_testing; List-Keywords-0.11/t/05notall.t000444001750001750 145414455772471 15143 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'notall'; # Basic true/false testing ok( (notall { $_ < 10 } 1 .. 20), 'notall list values below ten' ); ok( !(notall { $_ < 10 } 1 .. 9), 'not notall list values below ten' ); # notall empty list is true { my $invoked; my $ret = notall { $invoked++ } (); ok( defined $ret, 'notall on empty list is defined' ); ok( !$ret, 'notall on empty list is false' ); ok( !$invoked, 'notall on empty list did not invoke block' ); } # notall failure yields scalar in list context { my @ret; @ret = notall { $_ > 10 } 1 .. 9; ok( !!@ret, 'notall nothing yielded false in list context' ); @ret = notall { $_ > 10 } (); ok( !!@ret, 'notall nothing yielded false in list context on empty input' ); } done_testing; List-Keywords-0.11/t/10reduce.t000444001750001750 76714455772471 15103 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'reduce'; # Short cornercases { is( ( reduce { die "ARGH" } () ), undef, 'reduce on empty list yields undef' ); is( ( reduce { die "ARGH" } 123 ), 123, 'reduce on singleton list yields value directly' ); } # basic sum is( ( reduce { $a + $b } 1 .. 5 ), 15, 'sum of 1..5 is 15' ); # reduce is definitely a left-fold is( ( reduce { "($a+$b)" } "a" .. "d" ), "(((a+b)+c)+d)", 'reduce is a left-fold' ); done_testing; List-Keywords-0.11/t/11reductions.t000444001750001750 144214455772471 16023 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords 'reductions'; # Short cornercases { is( [ reductions { die "ARGH" } () ], [], 'reductions on empty list yields empty' ); is( [ reductions { die "ARGH" } 123 ], [ 123 ], 'reductions on singleton list yields value directly' ); } # basic sum is( [ reductions { $a + $b } 1 .. 5 ], [ 1, 3, 6, 10, 15 ], 'partial sums of 1..5' ); # reduce is definitely a left-fold is( [ reductions { "($a+$b)" } "a" .. "d" ], [ "a", "(a+b)", "((a+b)+c)", "(((a+b)+c)+d)" ], 'reductions is a left-fold' ); # We don't guarantee what this will return but it definitely shouldn't crash { my $ret = reductions { $a + $b } 1 .. 5; pass( 'reductions in scalar context does not crash' ); } done_testing; List-Keywords-0.11/t/20ngrep.t000444001750001750 260114455772471 14755 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0 0.000148; # is_refcount use List::Keywords 'ngrep'; # 2-at-a-time { is( [ngrep my ($k, $v) { } ()], [], 'ngrep empty in list context'); is( scalar(ngrep my ($k, $v) { } ()), 0, 'ngrep empty in scalar context'); my @values; is( [ngrep my ($k, $v) { @values = ($k, $v); length $k == 3 } ( one => 1, two => 2, three => 3 )], [one => 1, two => 2], 'ngrep in list context' ); is( \@values, [ three => 3 ], 'ngrep code block saw correct values' ); is( scalar(ngrep my ($k, $v) { length $k == 3 } ( one => 1, two => 2, three => 3 )), 4, 'ngrep in scalar context' ); is( [ngrep my ($k, $v) { @values = ($k, $v) } ( one => 1, missing => )], [one => 1, missing => ], 'ngrep with short list does not invent undef' ); is( \@values, [ missing => undef ], 'ngrep code block still saw missing value as undef' ); } # stack discipline { is( [1, (ngrep my ($x) { 1 } 2), 3], [1, 2, 3], 'ngrep behaves correctly as list operator' ); } # refcounts { my $arr = []; is_oneref( $arr, '$arr has one reference before test' ); my $result; ( $result ) = ngrep my ($x) { defined $x } undef, $arr, undef; is_refcount( $arr, 2, '$arr has two references after ngrep my ($x) BLOCK' ); undef $result; is_oneref( $arr, '$arr has one reference at end of test' ); } done_testing; List-Keywords-0.11/t/21nmap.t000444001750001750 264314455772471 14604 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0 0.000148; # is_refcount use List::Keywords 'nmap'; # 2-at-a-time, no growth { is( [nmap my ($k, $v) { } ()], [], 'nmap empty in list context'); is( scalar(nmap my ($k, $v) { } ()), 0, 'nmap empty in scalar context'); my @values; is( [nmap my ($k, $v) { @values = ($k, $v); (uc $k, $v + 1) } ( one => 1, two => 2, three => 3 )], [ONE => 2, TWO => 3, THREE => 4], 'nmap in list context' ); is( \@values, [ three => 3 ], 'nmap code block saw correct values' ); is( scalar(nmap my ($k, $v) { ($k, $v) } ( one => 1, two => 2, three => 3 )), 6, 'nmap in scalar context' ); } # 3-at-a-time, shorter output { is( [nmap my ($x, $y, $z) { $x + $y + $z } (1, 2, 3, 4, 5, 6)], [6, 15], 'nmap with shorter output' ); } # result stack can grow { is( [nmap my ($x, $y) { ($x, "$x$y", $y) } qw(a b c d)], [qw(a ab b c cd d)], 'nmap with longer output can grow' ); } # stack discipline { is( [1, (nmap my ($x) { $x } 2), 3], [1, 2, 3], 'nmap behaves correctly as list operator' ); } # refcounts { my $arr = []; is_oneref( $arr, '$arr has one reference before test' ); my $result; ( $result ) = nmap my ($x) { $x } $arr; is_refcount( $arr, 2, '$arr has two references after nmap my ($x) BLOCK' ); undef $result; is_oneref( $arr, '$arr has one reference at end of test' ); } done_testing; List-Keywords-0.11/t/70deparse.t000444001750001750 313114455772471 15271 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use List::Keywords ':all'; use B::Deparse; my $deparser = B::Deparse->new(); sub is_deparsed { my ( $sub, $exp, $name ) = @_; my $got = $deparser->coderef2text( $sub ); # Deparsed output is '{ ... }'-wrapped $got = ( $got =~ m/^{\n(.*)\n}$/s )[0]; # Deparsed output will have a lot of pragmata and so on; just grab the # final line $got = ( split m/\n/, $got )[-1]; $got =~ s/^\s+//; is( $got, $exp, $name ); } is_deparsed sub { first { $_ > 10 } 1 .. 10 }, 'first {$_ > 10;} 1..10;', 'first {}'; is_deparsed sub { first my $x { $x > 10 } 1 .. 10 }, 'first my $x {$x > 10;} 1..10;', 'first my $x {}'; is_deparsed sub { any { $_ > 10 } 1 .. 10 }, 'any {$_ > 10;} 1..10;', 'any {}'; is_deparsed sub { all { $_ > 10 } 1 .. 10 }, 'all {$_ > 10;} 1..10;', 'all {}'; is_deparsed sub { none { $_ > 10 } 1 .. 10 }, 'none {$_ > 10;} 1..10;', 'none {}'; is_deparsed sub { notall { $_ > 10 } 1 .. 10 }, 'notall {$_ > 10;} 1..10;', 'notall {}'; is_deparsed sub { reduce { $a + $b } 1 .. 5 }, 'reduce {$a + $b;} 1..5;', 'reduce {}'; my $listcode = "'one', 1"; # Perls before 5.22 deparsed without parens here, later ones add parens $listcode = "($listcode)" if $^V ge v5.22.0; is_deparsed sub { ngrep my ($k, $v) { length $k } one => 1 }, 'ngrep my ($k, $v) {length $k;} '.$listcode.';', 'ngrep my ($k, $v) {}'; is_deparsed sub { nmap my ($k, $v) { ($v, $k) } one => 1 }, 'nmap my ($k, $v) {$v, $k;} '.$listcode.';', 'nmap my ($k, $v) {}'; done_testing; List-Keywords-0.11/t/95benchmark.t000444001750001750 240514455772471 15612 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; # This "test" never fails, but prints a benchmark comparison between these # util functions and the ones provided by List::Util use Time::HiRes qw( gettimeofday tv_interval ); sub measure(&) { my ( $code ) = @_; my $start = [ gettimeofday ]; $code->(); return tv_interval $start; } my @nums = ( 1 .. 100 ); my $COUNT = 10_000; my $LK_elapsed = 0; my $LU_elapsed = 0; # To reduce the influence of bursts of timing noise, interleave many small runs # of each type. foreach ( 1 .. 20 ) { my $overhead = measure {}; $LK_elapsed += -$overhead + measure { use List::Keywords 'first'; my $ret; ( $ret = first { $_ > 50 } @nums ) for 1 .. $COUNT; }; $LU_elapsed += -$overhead + measure { use List::Util 'first'; my $ret; ( $ret = first { $_ > 50 } @nums ) for 1 .. $COUNT; }; } pass( "Benchmarked" ); if( $LK_elapsed > $LU_elapsed ) { diag( sprintf "List::Util took %.3fsec, ** this was SLOWER at %.3fsec **", $LU_elapsed, $LK_elapsed ); } else { my $speedup = ( $LU_elapsed - $LK_elapsed ) / $LU_elapsed; diag( sprintf "List::Util took %.3fsec, this was %d%% faster at %.3fsec", $LU_elapsed, $speedup * 100, $LK_elapsed ); } done_testing; List-Keywords-0.11/t/99pod.t000444001750001750 25514455772471 14427 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();