Syntax-Keyword-Dynamically-0.13000755001750001750 014503050617 15333 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/.editorconfig000444001750001750 5314503050617 20103 0ustar00leoleo000000000000root = true [*.{pm,pl,t}] indent_size = 3 Syntax-Keyword-Dynamically-0.13/Build.PL000444001750001750 256414503050617 16773 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; use Future::AsyncAwait::ExtensionBuilder; use XS::Parse::Keyword::Builder; my @extra_compiler_flags = qw( -I. -Ihax -ggdb ); # MSWin32 needs NO_XSLOCKS to make longjmp work. if( $^O eq "MSWin32" ) { push @extra_compiler_flags, "-DNO_XSLOCKS=1"; } my $build = Module::Build->new( module_name => "Syntax::Keyword::Dynamically", test_requires => { 'Test2::V0' => 0, }, configure_requires => { 'Module::Build' => '0.4004', # test_requires 'Future::AsyncAwait::ExtensionBuilder' => '0.60', 'XS::Parse::Keyword::Builder' => '0.13', }, requires => { 'perl' => '5.014', # pluggable keywords, XOP 'XS::Parse::Keyword' => '0.13', }, extra_compiler_flags => \@extra_compiler_flags, license => 'perl', create_license => 1, create_readme => 1, meta_merge => { resources => { x_IRC => "irc://irc.perl.org/#io-async", }, }, ); if( eval { require Devel::MAT::Dumper::Helper and Devel::MAT::Dumper::Helper->VERSION( '0.44' ) } ) { Devel::MAT::Dumper::Helper->extend_module_build( $build ); } Future::AsyncAwait::ExtensionBuilder->extend_module_build( $build ); XS::Parse::Keyword::Builder->extend_module_build( $build ); # Much cheating $build->add_property( 'optimize' ); $build->config( optimize => '' ); $build->create_build_script; Syntax-Keyword-Dynamically-0.13/Changes000444001750001750 500514503050617 16763 0ustar00leoleo000000000000Revision history for Syntax-Keyword-Dynamically 0.13 2023-09-21 [CHANGES] * Remember to implement `no Syntax::Keyword::Dynamically` * Avoid multiple accesses to `PL_modglobal` at once when in `-DMULTIPLICITY` [BUGFIXES] * Need to set `-DNO_XLOCKS=1` to keep MSWin32 happy (RT149716) 0.12 2023-03-04 [CHANGES] * Swap all unit tests from `Test::More` to `Test2::V0` [BUGFIXES] * Remember to clear the OPf_KIDS flag when nulling out an op before op_free() 0.11 2022-11-22 [CHANGES] * Use the new Future::AsyncAwait::ExtensionBuilder * Use the new extension API of Future::AsyncAwait v0.60 0.10 2022-03-16 [CHANGES] * Updates for Devel::MAT::Dumper v0.44 * Updates to hax/ files [BUGFIXES] * `-async` mode needs SKD version 0.02 for shared unit test 0.09 2021-08-26 [CHANGES] * Updated to XS::Parse::Keyword 0.13 0.08 2021-05-01 [CHANGES] * Rewrite parsing logic to use XS::Parse::Keyword 0.07 2021-02-02 [CHANGES] * Use the proper future_asyncawait_on_loaded() mechanism to enable async mode * Update to latest hax/ files * Added some more unit tests for multiple nested scopes 0.06 2020-11-01 [BUGFIXES] * When restoring an HELEM we should sv_setsv() on it rather than hv_store() so as not to create a new SV * Ensure that `dynamically HELEM` preserves the svref identity of existing elements (RT132545) * Avoid upsetting -DDEBUGGING perls with complaints about SVs_PADTMP 0.05 2020-07-06 [CHANGES] * Added explicit use VERSION declarations to every perl file [BUGFIXES] * Fixes to keep perl built with -DDEBUGGING happy 0.04 2020-02-25 18:00:37 [BUGFIXES] * Support various operators assigning into pad lexicals which the peephole optimiser turns into OPpTARGET_MY-using ops instead of OP_SASSIGN. 0.03 2020-02-17 15:21:44 [CHANGES] * Remember to add hax/*.c.inc files to MANIFEST 0.02 2020-02-17 14:15:18 [CHANGES] * Perform dynamic (and repeatable) suspend & resume around async/await from Future::AsyncAwait * Handle hash keys specially, deleting them again as required (RT131738) 0.01 2018-08-18 17:34:28 First version, released on an unsuspecting world. Syntax-Keyword-Dynamically-0.13/LICENSE000444001750001750 4375514503050617 16533 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 Syntax-Keyword-Dynamically-0.13/MANIFEST000444001750001750 66114503050617 16604 0ustar00leoleo000000000000.editorconfig Build.PL Changes hax/newOP_CUSTOM.c.inc hax/perl-additions.c.inc hax/perl-backcompat.c.inc lib/Syntax/Keyword/Dynamically.pm lib/Syntax/Keyword/Dynamically.xs LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01dynamically.t t/02tiescalar.t t/03lost-values.t t/04scopes.t t/80await+dynamically.t t/80dynamically+Object-Pad.t t/80dynamically+Sentinel.t t/81async-method+dynamically.t t/99pod.t Syntax-Keyword-Dynamically-0.13/META.json000444001750001750 253714503050617 17120 0ustar00leoleo000000000000{ "abstract" : "dynamically change the value of a variable", "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" : "Syntax-Keyword-Dynamically", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Future::AsyncAwait::ExtensionBuilder" : "0.60", "Module::Build" : "0.4004", "XS::Parse::Keyword::Builder" : "0.13" } }, "runtime" : { "requires" : { "XS::Parse::Keyword" : "0.13", "perl" : "5.014" } }, "test" : { "requires" : { "Test2::V0" : "0" } } }, "provides" : { "Syntax::Keyword::Dynamically" : { "file" : "lib/Syntax/Keyword/Dynamically.pm", "version" : "0.13" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "x_IRC" : "irc://irc.perl.org/#io-async" }, "version" : "0.13", "x_serialization_backend" : "JSON::PP version 4.07" } Syntax-Keyword-Dynamically-0.13/META.yml000444001750001750 153714503050617 16747 0ustar00leoleo000000000000--- abstract: 'dynamically change the value of a variable' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test2::V0: '0' configure_requires: Future::AsyncAwait::ExtensionBuilder: '0.60' Module::Build: '0.4004' XS::Parse::Keyword::Builder: '0.13' 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: Syntax-Keyword-Dynamically provides: Syntax::Keyword::Dynamically: file: lib/Syntax/Keyword/Dynamically.pm version: '0.13' requires: XS::Parse::Keyword: '0.13' perl: '5.014' resources: IRC: irc://irc.perl.org/#io-async license: http://dev.perl.org/licenses/ version: '0.13' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Syntax-Keyword-Dynamically-0.13/README000444001750001750 640714503050617 16357 0ustar00leoleo000000000000NAME Syntax::Keyword::Dynamically - dynamically change the value of a variable SYNOPSIS use Syntax::Keyword::Dynamically; my $logger = ...; sub operate { dynamically $logger->level = LOG_DEBUG; do_things(); } DESCRIPTION This module provides a syntax plugin that implements a single keyword, dynamically, which alters the behaviour of a scalar assignment operation. Syntactically and semantically it is similar to the built-in perl keyword local, but is implemented somewhat differently to give two key advantages over regular local: * You can dynamically assign to lvalue functions and accessors. * You can dynamically assign to regular lexical variables. Semantically, the behaviour can be considered equivalent to { my $old = $VAR; $VAR = "new value"; ... $VAR = $old; } Except that the old value will also be restored in the case of exceptions, goto, next/last/redo or similar ways to leave the controlling block scope. KEYWORDS dynamically { dynamically LVALUE = EXPR; ... } The dynamically keyword modifies the behaviour of the following expression. which must be a scalar assignment. Before the new value is assigned to the lvalue, its current value is captured and stored internally within the Perl interpreter. When execution leaves the controlling block for whatever reason, as part of block scope cleanup the saved value is restored. The LVALUE may be any kind of expression that allows normal scalar assignment; lexical or package scalar variables, elements of arrays or hashes, or the result of calling an :lvalue function or method. If the LVALUE has any GET magic associated with it (including a FETCH method of a tied scalar) then this will be executed exactly once when the dynamically expression is evaluated. If the LVALUE has any SET magic associated with it (including a STORE method of a tied scalar) then this will be executed exactly once when the dynamically expression is evaluated, and again a second time when the controlling scope is unwound. When the LVALUE being assigned to is a hash element, e.g. one of the following forms dynamically $hash{key} = EXPR; dynamically $href->{key} = EXPR; the assignment additionally ensures to remove the key if it is newly-added, and restores by adding the key back again if it had been deleted in the meantime. WITH Future::AsyncAwait As of Future::AsyncAwait version 0.32, cross-module integration tests assert that the dynamically correctly works across an await boundary. use Future::AsyncAwait; use Syntax::Keyword::Dynamically; our $var; async sub trial { dynamically $var = "value"; await func(); say "Var is still $var"; } When context-switching between scopes in which a variable is dynamically modified, the value of the variable will be swapped in and out, possibly multiple times if necessary, to ensure the visible value remains as expected. AUTHOR Paul Evans Syntax-Keyword-Dynamically-0.13/hax000755001750001750 014503050617 16113 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/hax/newOP_CUSTOM.c.inc000444001750001750 610214503050617 21305 0ustar00leoleo000000000000/* vi: set ft=c : */ /* Before perl 5.22 under -DDEBUGGING, various new*OP() functions throw assert * failures on OP_CUSTOM. * https://rt.cpan.org/Ticket/Display.html?id=128562 */ #define newOP_CUSTOM(func, flags) S_newOP_CUSTOM(aTHX_ func, flags) #define newUNOP_CUSTOM(func, flags, first) S_newUNOP_CUSTOM(aTHX_ func, flags, first) #define newSVOP_CUSTOM(func, flags, sv) S_newSVOP_CUSTOM(aTHX_ func, flags, sv) #define newBINOP_CUSTOM(func, flags, first, last) S_newBINOP_CUSTOM(aTHX_ func, flags, first, last) #define newLOGOP_CUSTOM(func, flags, first, other) S_newLOGOP_CUSTOM(aTHX_ func, flags, first, other) static OP *S_newOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags) { OP *op = newOP(OP_CUSTOM, flags); op->op_ppaddr = func; return op; } static OP *S_newUNOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags, OP *first) { UNOP *unop; #if HAVE_PERL_VERSION(5,22,0) unop = (UNOP *)newUNOP(OP_CUSTOM, flags, first); #else NewOp(1101, unop, 1, UNOP); unop->op_type = (OPCODE)OP_CUSTOM; unop->op_first = first; unop->op_flags = (U8)(flags | OPf_KIDS); unop->op_private = (U8)(1 | (flags >> 8)); #endif unop->op_ppaddr = func; return (OP *)unop; } static OP *S_newSVOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags, SV *sv) { SVOP *svop; #if HAVE_PERL_VERSION(5,22,0) svop = (SVOP *)newSVOP(OP_CUSTOM, flags, sv); #else NewOp(1101, svop, 1, SVOP); svop->op_type = (OPCODE)OP_CUSTOM; svop->op_sv = sv; svop->op_next = (OP *)svop; svop->op_flags = 0; svop->op_private = 0; #endif svop->op_ppaddr = func; return (OP *)svop; } static OP *S_newBINOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags, OP *first, OP *last) { BINOP *binop; #if HAVE_PERL_VERSION(5,22,0) binop = (BINOP *)newBINOP(OP_CUSTOM, flags, first, last); #else NewOp(1101, binop, 1, BINOP); binop->op_type = (OPCODE)OP_CUSTOM; binop->op_first = first; first->op_sibling = last; binop->op_last = last; binop->op_flags = (U8)(flags | OPf_KIDS); binop->op_private = (U8)(2 | (flags >> 8)); #endif binop->op_ppaddr = func; return (OP *)binop; } static OP *S_newLOGOP_CUSTOM(pTHX_ OP *(*func)(pTHX), U32 flags, OP *first, OP *other) { OP *o; #if HAVE_PERL_VERSION(5,22,0) o = newLOGOP(OP_CUSTOM, flags, first, other); #else /* Parts of this code copypasted from perl 5.20.0's op.c S_new_logop() */ LOGOP *logop; first = op_contextualize(first, G_SCALAR); NewOp(1101, logop, 1, LOGOP); logop->op_type = (OPCODE)OP_CUSTOM; logop->op_ppaddr = NULL; /* Because caller only overrides it anyway */ logop->op_first = first; logop->op_flags = (U8)(flags | OPf_KIDS); logop->op_other = LINKLIST(other); logop->op_private = (U8)(1 | (flags >> 8)); /* Link in postfix order */ logop->op_next = LINKLIST(first); first->op_next = (OP *)logop; first->op_sibling = other; /* No CHECKOP for OP_CUSTOM */ o = newUNOP(OP_NULL, 0, (OP *)logop); other->op_next = o; #endif /* the returned op is actually an UNOP that's either NULL or NOT; the real * logop is the op_next of it */ cUNOPx(o)->op_first->op_ppaddr = func; return o; } Syntax-Keyword-Dynamically-0.13/hax/perl-additions.c.inc000444001750001750 1640614503050617 22131 0ustar00leoleo000000000000/* vi: set ft=c : */ #if HAVE_PERL_VERSION(5, 22, 0) # define PadnameIsNULL(pn) (!(pn)) #else # define PadnameIsNULL(pn) (!(pn) || (pn) == &PL_sv_undef) #endif #ifndef hv_deletes # define hv_deletes(hv, skey, flags) hv_delete((hv), ("" skey ""), (sizeof(skey) - 1), flags) #endif #ifndef gv_fetchmeth_pvs # define gv_fetchmeth_pvs(stash, name, level, flags) gv_fetchmeth_pvn((stash), ("" name ""), (sizeof(name) - 1), level, flags) #endif #if HAVE_PERL_VERSION(5, 22, 0) # define PadnameOUTER_off(pn) (PadnameFLAGS(pn) &= ~PADNAMEt_OUTER) #else /* PadnameOUTER is really the SvFAKE flag */ # define PadnameOUTER_off(pn) SvFAKE_off(pn) #endif #define save_strndup(s, l) S_save_strndup(aTHX_ s, l) static char *S_save_strndup(pTHX_ char *s, STRLEN l) { /* savepvn doesn't put anything on the save stack, despite its name */ char *ret = savepvn(s, l); SAVEFREEPV(ret); return ret; } static char *PL_savetype_name[] PERL_UNUSED_DECL = { /* These have been present since 5.16 */ [SAVEt_ADELETE] = "ADELETE", [SAVEt_AELEM] = "AELEM", [SAVEt_ALLOC] = "ALLOC", [SAVEt_APTR] = "APTR", [SAVEt_AV] = "AV", [SAVEt_BOOL] = "BOOL", [SAVEt_CLEARSV] = "CLEARSV", [SAVEt_COMPILE_WARNINGS] = "COMPILE_WARNINGS", [SAVEt_COMPPAD] = "COMPPAD", [SAVEt_DELETE] = "DELETE", [SAVEt_DESTRUCTOR] = "DESTRUCTOR", [SAVEt_DESTRUCTOR_X] = "DESTRUCTOR_X", [SAVEt_FREECOPHH] = "FREECOPHH", [SAVEt_FREEOP] = "FREEOP", [SAVEt_FREEPV] = "FREEPV", [SAVEt_FREESV] = "FREESV", [SAVEt_GENERIC_PVREF] = "GENERIC_PVREF", [SAVEt_GENERIC_SVREF] = "GENERIC_SVREF", [SAVEt_GP] = "GP", [SAVEt_GVSV] = "GVSV", [SAVEt_HELEM] = "HELEM", [SAVEt_HINTS] = "HINTS", [SAVEt_HPTR] = "HPTR", [SAVEt_HV] = "HV", [SAVEt_I16] = "I16", [SAVEt_I32] = "I32", [SAVEt_I32_SMALL] = "I32_SMALL", [SAVEt_I8] = "I8", [SAVEt_INT] = "INT", [SAVEt_INT_SMALL] = "INT_SMALL", [SAVEt_ITEM] = "ITEM", [SAVEt_IV] = "IV", [SAVEt_LONG] = "LONG", [SAVEt_MORTALIZESV] = "MORTALIZESV", [SAVEt_NSTAB] = "NSTAB", [SAVEt_OP] = "OP", [SAVEt_PADSV_AND_MORTALIZE] = "PADSV_AND_MORTALIZE", [SAVEt_PARSER] = "PARSER", [SAVEt_PPTR] = "PPTR", [SAVEt_REGCONTEXT] = "REGCONTEXT", [SAVEt_SAVESWITCHSTACK] = "SAVESWITCHSTACK", [SAVEt_SET_SVFLAGS] = "SET_SVFLAGS", [SAVEt_SHARED_PVREF] = "SHARED_PVREF", [SAVEt_SPTR] = "SPTR", [SAVEt_STACK_POS] = "STACK_POS", [SAVEt_SVREF] = "SVREF", [SAVEt_SV] = "SV", [SAVEt_VPTR] = "VPTR", #if HAVE_PERL_VERSION(5,18,0) [SAVEt_CLEARPADRANGE] = "CLEARPADRANGE", [SAVEt_GVSLOT] = "GVSLOT", #endif #if HAVE_PERL_VERSION(5,20,0) [SAVEt_READONLY_OFF] = "READONLY_OFF", [SAVEt_STRLEN] = "STRLEN", #endif #if HAVE_PERL_VERSION(5,22,0) [SAVEt_FREEPADNAME] = "FREEPADNAME", #endif #if HAVE_PERL_VERSION(5,24,0) [SAVEt_TMPSFLOOR] = "TMPSFLOOR", #endif #if HAVE_PERL_VERSION(5,34,0) [SAVEt_STRLEN_SMALL] = "STRLEN_SMALL", [SAVEt_HINTS_HH] = "HINTS_HH", #endif }; #define dKWARG(count) \ U32 kwargi = count; \ U32 kwarg; \ SV *kwval; \ /* TODO: complain about odd number of args */ #define KWARG_NEXT(args) \ S_kwarg_next(aTHX_ args, &kwargi, items, ax, &kwarg, &kwval) static bool S_kwarg_next(pTHX_ const char *args[], U32 *kwargi, U32 argc, U32 ax, U32 *kwarg, SV **kwval) { if(*kwargi >= argc) return FALSE; SV *argname = ST(*kwargi); (*kwargi)++; if(!SvOK(argname)) croak("Expected string for next argument name, got undef"); *kwarg = 0; while(args[*kwarg]) { if(strEQ(SvPV_nolen(argname), args[*kwarg])) { *kwval = ST(*kwargi); (*kwargi)++; return TRUE; } (*kwarg)++; } croak("Unrecognised argument name '%" SVf "'", SVfARG(argname)); } #define import_pragma(pragma, arg) S_import_pragma(aTHX_ pragma, arg) static void S_import_pragma(pTHX_ const char *pragma, const char *arg) { dSP; bool unimport = FALSE; if(pragma[0] == '-') { unimport = TRUE; pragma++; } SAVETMPS; EXTEND(SP, 2); PUSHMARK(SP); mPUSHp(pragma, strlen(pragma)); if(arg) mPUSHp(arg, strlen(arg)); PUTBACK; call_method(unimport ? "unimport" : "import", G_VOID); FREETMPS; } #define ensure_module_version(module, version) S_ensure_module_version(aTHX_ module, version) static void S_ensure_module_version(pTHX_ SV *module, SV *version) { dSP; ENTER; PUSHMARK(SP); PUSHs(module); PUSHs(version); PUTBACK; call_method("VERSION", G_VOID); LEAVE; } #if HAVE_PERL_VERSION(5, 16, 0) /* TODO: perl 5.14 lacks HvNAMEUTF8, gv_fetchmeth_pvn() */ # define fetch_superclass_method_pv(stash, pv, len, level) S_fetch_superclass_method_pv(aTHX_ stash, pv, len, level) static CV *S_fetch_superclass_method_pv(pTHX_ HV *stash, const char *pv, STRLEN len, U32 level) { # if HAVE_PERL_VERSION(5, 18, 0) GV *gv = gv_fetchmeth_pvn(stash, pv, len, level, GV_SUPER); # else SV *superclassname = newSVpvf("%*s::SUPER", HvNAMELEN_get(stash), HvNAME_get(stash)); if(HvNAMEUTF8(stash)) SvUTF8_on(superclassname); SAVEFREESV(superclassname); HV *superstash = gv_stashsv(superclassname, GV_ADD); GV *gv = gv_fetchmeth_pvn(superstash, pv, len, level, 0); # endif if(!gv) return NULL; return GvCV(gv); } #endif /* HAVE_PERL_VERSION(5, 16, 0) */ #define get_class_isa(stash) S_get_class_isa(aTHX_ stash) static AV *S_get_class_isa(pTHX_ HV *stash) { GV **gvp = (GV **)hv_fetchs(stash, "ISA", 0); if(!gvp || !GvAV(*gvp)) croak("Expected %s to have a @ISA list", HvNAME(stash)); return GvAV(*gvp); } #define find_cop_for_lvintro(padix, o, copp) S_find_cop_for_lvintro(aTHX_ padix, o, copp) static COP *S_find_cop_for_lvintro(pTHX_ PADOFFSET padix, OP *o, COP **copp) { for( ; o; o = OpSIBLING(o)) { if(OP_CLASS(o) == OA_COP) { *copp = (COP *)o; } else if(o->op_type == OP_PADSV && o->op_targ == padix && o->op_private & OPpLVAL_INTRO) { return *copp; } else if(o->op_flags & OPf_KIDS) { COP *ret = find_cop_for_lvintro(padix, cUNOPx(o)->op_first, copp); if(ret) return ret; } } return NULL; } #define lex_consume_unichar(c) MY_lex_consume_unichar(aTHX_ c) static bool MY_lex_consume_unichar(pTHX_ U32 c) { if(lex_peek_unichar(0) != c) return FALSE; lex_read_unichar(0); return TRUE; } #define av_push_from_av_inc(dst, src) S_av_push_from_av(aTHX_ dst, src, TRUE) #define av_push_from_av_noinc(dst, src) S_av_push_from_av(aTHX_ dst, src, FALSE) static void S_av_push_from_av(pTHX_ AV *dst, AV *src, bool refcnt_inc) { SSize_t count = av_count(src); SSize_t i; av_extend(dst, av_count(dst) + count - 1); SV **vals = AvARRAY(src); for(i = 0; i < count; i++) { SV *sv = vals[i]; av_push(dst, refcnt_inc ? SvREFCNT_inc(sv) : sv); } } Syntax-Keyword-Dynamically-0.13/hax/perl-backcompat.c.inc000444001750001750 1410114503050617 22245 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_fetch_simple # define av_fetch_simple(av, idx, lval) av_fetch(av, idx, lval) #endif #ifndef av_push_simple # define av_push_simple(av, sv) av_push(av, sv) #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 Syntax-Keyword-Dynamically-0.13/lib000755001750001750 014503050617 16101 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/lib/Syntax000755001750001750 014503050617 17367 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/lib/Syntax/Keyword000755001750001750 014503050617 21013 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/lib/Syntax/Keyword/Dynamically.pm000444001750001750 1006514503050617 23776 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, 2018-2023 -- leonerd@leonerd.org.uk package Syntax::Keyword::Dynamically 0.13; use v5.14; use warnings; use Carp; require XSLoader; XSLoader::load( __PACKAGE__, our $VERSION ); =head1 NAME C - dynamically change the value of a variable =head1 SYNOPSIS use Syntax::Keyword::Dynamically; my $logger = ...; sub operate { dynamically $logger->level = LOG_DEBUG; do_things(); } =head1 DESCRIPTION This module provides a syntax plugin that implements a single keyword, C, which alters the behaviour of a scalar assignment operation. Syntactically and semantically it is similar to the built-in perl keyword C, but is implemented somewhat differently to give two key advantages over regular C: =over 2 =item * You can C assign to lvalue functions and accessors. =item * You can C assign to regular lexical variables. =back Semantically, the behaviour can be considered equivalent to { my $old = $VAR; $VAR = "new value"; ... $VAR = $old; } Except that the old value will also be restored in the case of exceptions, C, C or similar ways to leave the controlling block scope. =cut =head1 KEYWORDS =head2 dynamically { dynamically LVALUE = EXPR; ... } The C keyword modifies the behaviour of the following expression. which must be a scalar assignment. Before the new value is assigned to the lvalue, its current value is captured and stored internally within the Perl interpreter. When execution leaves the controlling block for whatever reason, as part of block scope cleanup the saved value is restored. The LVALUE may be any kind of expression that allows normal scalar assignment; lexical or package scalar variables, elements of arrays or hashes, or the result of calling an C<:lvalue> function or method. If the LVALUE has any GET magic associated with it (including a C method of a tied scalar) then this will be executed exactly once when the C expression is evaluated. If the LVALUE has any SET magic associated with it (including a C method of a tied scalar) then this will be executed exactly once when the C expression is evaluated, and again a second time when the controlling scope is unwound. When the LVALUE being assigned to is a hash element, e.g. one of the following forms dynamically $hash{key} = EXPR; dynamically $href->{key} = EXPR; the assignment additionally ensures to remove the key if it is newly-added, and restores by adding the key back again if it had been deleted in the meantime. =cut sub import { my $pkg = shift; my $caller = caller; $pkg->import_into( $caller, @_ ); } sub unimport { my $pkg = shift; my $caller = caller; $pkg->unimport_into( $caller, @_ ); } sub import_into { shift->apply( sub { $^H{ $_[0] }++ }, @_ ) } sub unimport_into { shift->apply( sub { delete $^H{ $_[0] } }, @_ ) } sub apply { my $pkg = shift; my ( $cb, $caller, @syms ) = @_; my %syms = map { $_ => 1 } @syms; $cb->( "Syntax::Keyword::Dynamically/dynamically" ); _enable_async_mode() if delete $syms{'-async'}; croak "Unrecognised import symbols @{[ keys %syms ]}" if keys %syms; } =head1 WITH Future::AsyncAwait As of L version 0.32, cross-module integration tests assert that the C correctly works across an C boundary. use Future::AsyncAwait; use Syntax::Keyword::Dynamically; our $var; async sub trial { dynamically $var = "value"; await func(); say "Var is still $var"; } When context-switching between scopes in which a variable is C modified, the value of the variable will be swapped in and out, possibly multiple times if necessary, to ensure the visible value remains as expected. =head1 AUTHOR Paul Evans =cut 0x55AA; Syntax-Keyword-Dynamically-0.13/lib/Syntax/Keyword/Dynamically.xs000444001750001750 3302714503050617 24017 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, 2018 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #include "AsyncAwait.h" #include "XSParseKeyword.h" #ifdef HAVE_DMD_HELPER # define WANT_DMD_API_044 # include "DMD_helper.h" #endif #define HAVE_PERL_VERSION(R, V, S) \ (PERL_REVISION > (R) || (PERL_REVISION == (R) && (PERL_VERSION > (V) || (PERL_VERSION == (V) && (PERL_SUBVERSION >= (S)))))) #include "perl-backcompat.c.inc" #include "perl-additions.c.inc" #include "newOP_CUSTOM.c.inc" static bool is_async = FALSE; #ifdef MULTIPLICITY # define dynamicstack \ *((AV **)hv_fetchs(PL_modglobal, "Syntax::Keyword::Dynamically/dynamicstack", GV_ADD)) #else /* without MULTIPLICITY there's only one, so we might as well just store it * in a static */ static AV *dynamicstack; #endif typedef struct { SV *var; /* is HV * if keysv is set; indicates an HELEM */ SV *keysv; SV *oldval; /* is NULL for HELEMs if we should delete at pop time */ int saveix; } DynamicVar; #define newSVdynamicvar() S_newSVdynamicvar(aTHX) static SV *S_newSVdynamicvar(pTHX) { SV *ret = newSV(sizeof(DynamicVar)); #ifdef HAVE_DMD_HELPER if(DMD_IS_ACTIVE()) { SV *tmpRV = newRV_inc(ret); sv_bless(tmpRV, get_hv("Syntax::Keyword::Dynamically::_DynamicVar::", GV_ADD)); SvREFCNT_dec(tmpRV); } #endif return ret; } #ifdef HAVE_DMD_HELPER static int dmd_help_dynamicvar(pTHX_ DMDContext *ctx, const SV *sv) { int ret = 0; DynamicVar *dyn = (void *)SvPVX((SV *)sv); if(dyn->keysv) { ret += DMD_ANNOTATE_SV(sv, dyn->var, "the helem HV"); ret += DMD_ANNOTATE_SV(sv, dyn->keysv, "the helem key"); } else ret += DMD_ANNOTATE_SV(sv, dyn->var, "the variable slot"); if(dyn->oldval) ret += DMD_ANNOTATE_SV(sv, dyn->oldval, "the old value slot"); return ret; } #endif typedef struct { SV *var; /* is HV * if keysv is set; indicates an HELEM */ SV *keysv; SV *curval; /* is NULL for HELEMs if we should delete at resume time */ bool is_outer; } SuspendedDynamicVar; #define newSVsuspendeddynamicvar() S_newSVsuspendeddynamicvar(aTHX) static SV *S_newSVsuspendeddynamicvar(pTHX) { SV *ret = newSV(sizeof(SuspendedDynamicVar)); #ifdef HAVE_DMD_HELPER if(DMD_IS_ACTIVE()) { SV *tmpRV = newRV_inc(ret); sv_bless(tmpRV, get_hv("Syntax::Keyword::Dynamically::_SuspendedDynamicVar::", GV_ADD)); SvREFCNT_dec(tmpRV); } #endif return ret; } #ifdef HAVE_DMD_HELPER static int dmd_help_suspendeddynamicvar(pTHX_ DMDContext *ctx, const SV *sv) { int ret = 0; SuspendedDynamicVar *suspdyn = (void *)SvPVX((SV *)sv); if(suspdyn->keysv) { ret += DMD_ANNOTATE_SV(sv, suspdyn->var, "the helem HV"); ret += DMD_ANNOTATE_SV(sv, suspdyn->keysv, "the helem key"); } else ret += DMD_ANNOTATE_SV(sv, suspdyn->var, "the variable slot"); if(suspdyn->curval) ret += DMD_ANNOTATE_SV(sv, suspdyn->curval, "the current value slot"); return ret; } #endif #ifndef av_top_index # define av_top_index(av) AvFILL(av) #endif static SV *av_top(AV *av) { return AvARRAY(av)[av_top_index(av)]; } static SV *av_push_r(AV *av, SV *sv) { av_push(av, sv); return sv; } #ifndef hv_deletes # define hv_deletes(hv, key, flags) \ hv_delete((hv), ("" key ""), (sizeof(key)-1), (flags)) #endif #define hv_setsv_or_delete(hv, key, val) S_hv_setsv_or_delete(aTHX_ hv, key, val) static void S_hv_setsv_or_delete(pTHX_ HV *hv, SV *key, SV *val) { if(!val) { hv_delete_ent(hv, key, G_DISCARD, 0); } else sv_setsv(HeVAL(hv_fetch_ent(hv, key, 1, 0)), val); } #define ENSURE_HV(sv) S_ensure_hv(aTHX_ sv) static HV *S_ensure_hv(pTHX_ SV *sv) { if(SvTYPE(sv) == SVt_PVHV) return (HV *)sv; croak("Expected HV, got SvTYPE(sv)=%d", SvTYPE(sv)); } #define pushdyn(var) S_pushdyn(aTHX_ var) static void S_pushdyn(pTHX_ SV *var) { DynamicVar *dyn = (void *)SvPVX( av_push_r(dynamicstack, newSVdynamicvar()) ); dyn->var = var; dyn->keysv = NULL; dyn->oldval = newSVsv(var); dyn->saveix = PL_savestack_ix; } #define pushdynhelem(hv,keysv,curval) S_pushdynhelem(aTHX_ hv,keysv,curval) static void S_pushdynhelem(pTHX_ HV *hv, SV *keysv, SV *curval) { DynamicVar *dyn = (void *)SvPVX( av_push_r(dynamicstack, newSVdynamicvar()) ); dyn->var = (SV *)hv; dyn->keysv = keysv; dyn->oldval = newSVsv(curval); dyn->saveix = PL_savestack_ix; } static void S_popdyn(pTHX_ void *_data) { AV *stack = dynamicstack; DynamicVar *dyn = (void *)SvPVX(av_top(stack)); if(dyn->var != (SV *)_data) croak("ARGH: dynamicstack top mismatch"); SV *sv = av_pop(stack); if(dyn->keysv) { HV *hv = ENSURE_HV(dyn->var); hv_setsv_or_delete(hv, dyn->keysv, dyn->oldval); SvREFCNT_dec(dyn->keysv); } else { sv_setsv_mg(dyn->var, dyn->oldval); } SvREFCNT_dec(dyn->var); SvREFCNT_dec(dyn->oldval); SvREFCNT_dec(sv); } static void hook_postsuspend(pTHX_ CV *cv, HV *modhookdata, void *hookdata) { AV *stack = dynamicstack; IV i, max = av_top_index(stack); SV **avp = AvARRAY(stack); int height = PL_savestack_ix; AV *suspendedvars = NULL; for(i = max; i >= 0; i--) { DynamicVar *dyn = (void *)SvPVX(avp[i]); if(dyn->saveix < height) break; /* An inner dynamic variable - capture and restore */ if(!suspendedvars) { suspendedvars = newAV(); hv_stores(modhookdata, "Syntax::Keyword::Dynamically/suspendedvars", (SV *)suspendedvars); } SuspendedDynamicVar *suspdyn = (void *)SvPVX( av_push_r(suspendedvars, newSVsuspendeddynamicvar()) ); suspdyn->var = dyn->var; /* steal */ suspdyn->keysv = dyn->keysv; /* steal */ suspdyn->is_outer = FALSE; if(dyn->keysv) { HV *hv = ENSURE_HV(dyn->var); HE *he = hv_fetch_ent(hv, dyn->keysv, 0, 0); suspdyn->curval = he ? newSVsv(HeVAL(he)) : NULL; hv_setsv_or_delete(hv, dyn->keysv, dyn->oldval); } else { suspdyn->curval = newSVsv(dyn->var); sv_setsv_mg(dyn->var, dyn->oldval); } SvREFCNT_dec(dyn->oldval); } if(i < max) /* truncate */ av_fill(stack, i); for( ; i >= 0; i--) { DynamicVar *dyn = (void *)SvPVX(avp[i]); /* An outer dynamic variable - capture but do not restore */ if(!suspendedvars) { suspendedvars = newAV(); hv_stores(modhookdata, "Syntax::Keyword::Dynamically/suspendedvars", (SV *)suspendedvars); } SuspendedDynamicVar *suspdyn = (void *)SvPVX( av_push_r(suspendedvars, newSVsuspendeddynamicvar()) ); suspdyn->var = SvREFCNT_inc(dyn->var); suspdyn->is_outer = TRUE; if(dyn->keysv) { HV *hv = ENSURE_HV(dyn->var); HE *he = hv_fetch_ent(hv, dyn->keysv, 0, 0); suspdyn->keysv = SvREFCNT_inc(dyn->keysv); suspdyn->curval = he ? newSVsv(HeVAL(he)) : NULL; } else { suspdyn->keysv = NULL; suspdyn->curval = newSVsv(dyn->var); } } } static void hook_preresume(pTHX_ CV *cv, HV *modhookdata, void *hookdata) { AV *suspendedvars = (AV *)hv_deletes(modhookdata, "Syntax::Keyword::Dynamically/suspendedvars", 0); if(!suspendedvars) return; SV **avp = AvARRAY(suspendedvars); IV i, max = av_top_index(suspendedvars); for(i = max; i >= 0; i--) { SuspendedDynamicVar *suspdyn = (void *)SvPVX(avp[i]); if(suspdyn->keysv) { HV *hv = ENSURE_HV(suspdyn->var); HE *he = hv_fetch_ent(hv, suspdyn->keysv, 0, 0); pushdynhelem(hv, suspdyn->keysv, he ? HeVAL(he) : NULL); hv_setsv_or_delete(hv, suspdyn->keysv, suspdyn->curval); } else { SV *var = suspdyn->var; pushdyn(var); sv_setsv_mg(var, suspdyn->curval); } SvREFCNT_dec(suspdyn->curval); if(suspdyn->is_outer) { SAVEDESTRUCTOR_X(&S_popdyn, suspdyn->var); } else { /* Don't SAVEDESTRUCTOR_X a second time because F-AA restored it */ } } } static const struct AsyncAwaitHookFuncs faa_hooks = { .post_suspend = &hook_postsuspend, .pre_resume = &hook_preresume, }; /* STARTDYN is the primary op that makes this work. It is used in two ways: * With OPf_STACKED it takes an optree, which pushes an SV to the stack. * Without OPf_STACKED it uses op->op_targ to select a lexical * Either way, it saves the current value of the SV and arranges for that * value to be assigned back in on scope exit * * This op is _not_ used for dynamic assignments to hash elements; for that * see HELEMDYN */ static XOP xop_startdyn; static OP *pp_startdyn(pTHX) { dSP; SV *var = (PL_op->op_flags & OPf_STACKED) ? TOPs : PAD_SV(PL_op->op_targ); if(is_async) { pushdyn(SvREFCNT_inc(var)); SAVEDESTRUCTOR_X(&S_popdyn, var); } else { save_freesv(SvREFCNT_inc(var)); /* When save_item() is restored it won't reset the SvPADMY flag properly. * This upsets -DDEBUGGING perls, so we'll have to save the flags too */ if(SvFLAGS(var) & SVs_PADMY) save_set_svflags(var, SvFLAGS(var), SvFLAGS(var)); save_item(var); } return cUNOP->op_next; } /* HELEMDYN is a variant of core's HELEM op which arranges for the existing * value (or absence of) the key in the hash to be restored again on scope * exit. It copes with missing keys by deleting them again to "restore". */ static void S_restore(pTHX_ void *_data) { DynamicVar *dyn = _data; if(dyn->keysv) { hv_setsv_or_delete(ENSURE_HV(dyn->var), dyn->keysv, dyn->oldval); SvREFCNT_dec(dyn->var); SvREFCNT_dec(dyn->keysv); SvREFCNT_dec(dyn->oldval); } else croak("ARGH: Expected a keysv"); Safefree(dyn); } static XOP xop_helemdyn; static OP *pp_helemdyn(pTHX) { /* Contents inspired by core's pp_helem */ dSP; SV * keysv = POPs; HV * const hv = MUTABLE_HV(POPs); bool preexisting; HE *he; SV **svp; /* Take a long-lived copy of keysv */ keysv = newSVsv(keysv); preexisting = hv_exists_ent(hv, keysv, 0); he = hv_fetch_ent(hv, keysv, 1, 0); svp = &HeVAL(he); if(is_async) { SvREFCNT_inc((SV *)hv); if(preexisting) pushdynhelem(hv, keysv, *svp); else pushdynhelem(hv, keysv, NULL); SAVEDESTRUCTOR_X(&S_popdyn, (SV *)hv); } else { DynamicVar *dyn; Newx(dyn, 1, DynamicVar); dyn->var = SvREFCNT_inc(hv); dyn->keysv = SvREFCNT_inc(keysv); dyn->oldval = preexisting ? newSVsv(*svp) : NULL; SAVEDESTRUCTOR_X(&S_restore, dyn); } PUSHs(*svp); RETURN; } static int build_dynamically(pTHX_ OP **out, XSParseKeywordPiece *arg0, void *hookdata) { OP *aop = arg0->op; OP *lvalop = NULL, *rvalop = NULL; /* While most scalar assignments become OP_SASSIGN, some cases of assignment * from a binary operator into a pad lexical instead set OPpTARGET_MY and use * op->op_targ instead. */ if((PL_opargs[aop->op_type] & OA_TARGLEX) && (aop->op_private & OPpTARGET_MY)) { /* dynamically LEXVAR = EXPR */ /* Since LEXVAR is a pad lexical we can generate a non-stacked STARTDYN * and set the same targ on it, then perform that just before the * otherwise-unmodified op */ OP *dynop = newUNOP_CUSTOM(&pp_startdyn, 0, newOP(OP_NULL, 0)); dynop->op_targ = aop->op_targ; *out = op_prepend_elem(OP_LINESEQ, dynop, aop); return KEYWORD_PLUGIN_EXPR; } if(aop->op_type != OP_SASSIGN) croak("Expected scalar assignment for 'dynamically'"); rvalop = cBINOPx(aop)->op_first; lvalop = cBINOPx(aop)->op_last; if(lvalop->op_type == OP_HELEM) { /* dynamically $h{key} = EXPR */ /* In order to handle with the added complexities around delete $h{key} * we need to use our special version of OP_HELEM here instead of simply * calling STARTDYN on the fetched SV */ /* Change the OP_HELEM into our custom one. * To ensure the peephole optimiser doesn't turn this into multideref we * have to change the op_type too */ lvalop->op_type = OP_CUSTOM; lvalop->op_ppaddr = &pp_helemdyn; *out = aop; } else { /* dynamimcally LEXPR = EXPR */ /* Rather than splicing in STARTDYN op, we'll just make a new optree */ *out = newBINOP(aop->op_type, aop->op_flags, rvalop, newUNOP_CUSTOM(&pp_startdyn, aop->op_flags & OPf_STACKED, lvalop)); /* op_free will destroy the entire optree so replace the child ops first */ cBINOPx(aop)->op_first = NULL; cBINOPx(aop)->op_last = NULL; aop->op_flags &= ~OPf_KIDS; op_free(aop); } return KEYWORD_PLUGIN_EXPR; } static const struct XSParseKeywordHooks hooks_dynamically = { .permit_hintkey = "Syntax::Keyword::Dynamically/dynamically", .piece1 = XPK_TERMEXPR, .build1 = &build_dynamically, }; static void enable_async_mode(pTHX_ void *_unused) { if(is_async) return; is_async = TRUE; AV *stack = dynamicstack = newAV(); av_extend(stack, 50); boot_future_asyncawait(0.60); register_future_asyncawait_hook(&faa_hooks, NULL); } MODULE = Syntax::Keyword::Dynamically PACKAGE = Syntax::Keyword::Dynamically void _enable_async_mode() CODE: enable_async_mode(aTHX_ NULL); BOOT: XopENTRY_set(&xop_startdyn, xop_name, "startdyn"); XopENTRY_set(&xop_startdyn, xop_desc, "starts a dynamic variable scope"); XopENTRY_set(&xop_startdyn, xop_class, OA_UNOP); Perl_custom_op_register(aTHX_ &pp_startdyn, &xop_startdyn); boot_xs_parse_keyword(0.13); register_xs_parse_keyword("dynamically", &hooks_dynamically, NULL); #ifdef HAVE_DMD_HELPER DMD_SET_PACKAGE_HELPER("Syntax::Keyword::Dynamically::_DynamicVar", &dmd_help_dynamicvar); DMD_SET_PACKAGE_HELPER("Syntax::Keyword::Dynamically::_SuspendedDynamicVar", &dmd_help_suspendeddynamicvar); #endif future_asyncawait_on_activate(&enable_async_mode, NULL); Syntax-Keyword-Dynamically-0.13/t000755001750001750 014503050617 15576 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.13/t/00use.t000444001750001750 20714503050617 17033 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; require Syntax::Keyword::Dynamically; pass "Modules loaded"; done_testing; Syntax-Keyword-Dynamically-0.13/t/01dynamically.t000444001750001750 537514503050617 20601 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Syntax::Keyword::Dynamically; subtest "package variable" => sub { our $pvar = "old"; { dynamically $pvar = "new"; is( $pvar, "new", 'new value within scope' ); } is( $pvar, "old", 'value restored after block leave' ); eval { dynamically $pvar = "before die"; die "oops\n"; }; is( $pvar, "old", 'value restored after eval die' ); }; subtest "lexical variable" => sub { my $lvar = "old"; { dynamically $lvar = "new"; is( $lvar, "new", 'new value within scope' ); } is( $lvar, "old", 'value restored after block leave' ); eval { dynamically $lvar = "before die"; die "oops\n"; }; is( $lvar, "old", 'value restored after eval die' ); }; subtest "lexical with target" => sub { my $lvar = 42; { dynamically $lvar = $lvar + 1; is( $lvar, 43, 'new value from BINOP within scope' ); } is( $lvar, 42, 'value resored after block leave from BINOP' ); { dynamically $lvar = sin($lvar); is( $lvar, sin(42), 'new value from UNOP within scope' ); } is( $lvar, 42, 'value resored after block leave from UNOP' ); }; subtest "array element" => sub { my @arr = qw( a old c ); { dynamically $arr[1] = "new"; is( $arr[1], "new", 'new value within scope' ); } is( $arr[1], "old", 'value restored after block leave' ); }; subtest "hash element" => sub { my %hash = ( key => "old" ); # RT132545 my $svref = \$hash{key}; { dynamically $hash{key} = "new"; is( $hash{key}, "new", 'new value within scope' ); is( $$svref, "new", 'new value by SV ref' ); } is( $hash{key}, "old", 'value restored after block leave' ); is( $$svref, "old", 'old value by SV ref is restored' ); { dynamically $hash{newkey} = "val"; is( $hash{newkey}, "val", 'created key within scope' ); } ok( !exists $hash{newkey}, 'key removed after block leave' ); { dynamically $hash{key} = "new"; delete $hash{key}; } is( $hash{key}, "old", 'value recreated after block leave' ); }; my $value; sub func :lvalue { $value } subtest "lvalue function" => sub { func = "old"; { dynamically func = "new"; is( $value, "new", 'new value within scope' ); } is( $value, "old", 'value restored after block leave' ); }; subtest "lvalue accessor" => sub { main->func = "old"; { dynamically main->func = "new"; is( $value, "new", 'new value within scope' ); } is( $value, "old", 'value restored after block leave' ); }; { no Syntax::Keyword::Dynamically; sub dynamically { return "normal function" } is( dynamically, "normal function", 'dynamically() parses as a normal function call' ); } done_testing; Syntax-Keyword-Dynamically-0.13/t/02tiescalar.t000444001750001750 122314503050617 20227 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Syntax::Keyword::Dynamically; my @fetched_values; my @stored_values; package TestScalar { sub TIESCALAR { bless [], shift } sub FETCH { return shift @fetched_values } sub STORE { push @stored_values, $_[1] } } tie my $scalar, "TestScalar"; subtest "tied scalar" => sub { @fetched_values = ( "saved", "inside", "restored" ); { dynamically $scalar = "new"; is( $scalar, "inside", 'new value within scope' ); } is( $scalar, "restored", 'value restored after block leave' ); is( \@stored_values, [ "new", "saved" ], 'STORE magic invoked' ); }; done_testing; Syntax-Keyword-Dynamically-0.13/t/03lost-values.t000444001750001750 123014503050617 20535 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Syntax::Keyword::Dynamically; subtest "lost array element" => sub { my @array = ( "value" ); { dynamically $array[0] = "new"; # simply shift'ing the element leaves the underlying SV struct in the # AvARRAY, so we need to do something stronger @array = (); } pass( "shifting dynamically-assigned array element does not crash" ); }; subtest "lost hash entry" => sub { my %hash = ( key => "value" ); { dynamically $hash{key} = "new"; delete $hash{key}; } pass( "deleting dynamically-assigned hash entry does not crash" ); }; done_testing; Syntax-Keyword-Dynamically-0.13/t/04scopes.t000444001750001750 51014503050617 17534 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; use Syntax::Keyword::Dynamically; my $var = 1; { dynamically $var = 2; { dynamically $var = 3; is( $var, 3, '$var is 3 in inner scope' ); } is( $var, 2, '$var is 2 in middle scope' ); } is( $var, 1, '$var is 1 at toplevel' ); done_testing; Syntax-Keyword-Dynamically-0.13/t/80await+dynamically.t000444001750001750 1165614503050617 21730 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { plan skip_all => "Future is not available" unless eval { require Future }; plan skip_all => "Future::AsyncAwait >= 0.31_002 is not available" unless eval { require Future::AsyncAwait; Future::AsyncAwait->VERSION( '0.31_002' ) }; plan skip_all => "Syntax::Keyword::Dynamically >= 0.02 is not available" unless eval { require Syntax::Keyword::Dynamically; Syntax::Keyword::Dynamically->VERSION( '0.02' ) }; Future::AsyncAwait->import; Syntax::Keyword::Dynamically->import(qw( -async )); diag( "Future::AsyncAwait $Future::AsyncAwait::VERSION, " . "Syntax::Keyword::Dynamically $Syntax::Keyword::Dynamically::VERSION" ); } { my $var = 1; async sub with_dynamically { my $f = shift; dynamically $var = 2; is( $var, 2, '$var is 2 before await' ); await $f; is( $var, 2, '$var is 2 after await' ); return "result"; } my $f1 = Future->new; my $fret = with_dynamically( $f1 ); is( $var, 1, '$var is 1 while suspended' ); $f1->done; is( scalar $fret->get, "result", '$fret for dynamically in async sub' ); is( $var, 1, '$var is 1 after finish' ); } # multiple nested scopes { my $var = 1; my @f; sub tick { push @f, my $f = Future->new; return $f } async sub with_dynamically_nested { dynamically $var = 2; { dynamically $var = 3; await tick(); is( $var, 3, '$var is 3 in inner scope' ); } is( $var, 2, '$var is 2 in outer scope' ); await tick(); is( $var, 2, '$var is still 2 in outer scope' ); } my $fret = with_dynamically_nested(); is( $var, 1, '$var is 1 while suspended' ); while( @f ) { ( shift @f )->done; is( $var, 1, '$var is still 1' ); } $fret->get; is( $var, 1, '$var is 1 after finish' ); } # OP_HELEM_DYN is totally different in async mode { my %hash = my %orig = ( key => "old", delkey => "gone", ); async sub with_dynamically_helem { my $f = shift; dynamically $hash{key} = "new"; dynamically $hash{newkey} = "added"; dynamically $hash{delkey} = "begone!"; delete $hash{delkey}; await $f; is( \%hash, { key => "new", newkey => "added" }, '%hash after await' ); return "result"; } my $f1 = Future->new; my $fret = with_dynamically_helem( $f1 ); is( \%hash, \%orig, '%hash while suspended '); $f1->done; is( scalar $fret->get, "result", '$fret for dynamically helem in async sub' ); is( \%hash, \%orig, '%hash after finish' ); } # dynamically set variables in outer scopes during await { my $var = 1; async sub outer { dynamically $var = 2; await inner(); is( $var, 2, '$var is 2 after await in outer()' ); } my $f1 = Future->new; async sub inner { is( $var, 2, '$var is 2 before await in inner()' ); await $f1; is( $var, 2, '$var is 2 after await in inner()' ); } my $fret = outer(); is( $var, 1, '$var is 1 while suspended' ); $f1->done; $fret->get; is( $var, 1, '$var is 1 after finish' ); } # captured outer dynamic can be re-captured by later async sub { my $var = 1; my %hash = ( key => 3 ); my $f1 = Future->new; my $f2 = Future->new; my $fret = do { dynamically $var = 2; dynamically $hash{key} = 4; (async sub { await $f1; is( $var, 2, '$var is 2 before later await' ); is( $hash{key}, 4, '$var is 4 before later await' ); await +(async sub { await $f2; is( $var, 2, '$var is 2 inside inner async sub' ); is( $hash{key}, 4, '$var is 4 inside inner async sub' ); })->(); })->(); }; is( $var, 1, '$var is 1 before $f1->done' ); is( $hash{key}, 3, '$hash{key} is 3 before $f1->done' ); $f1->done; is( $var, 1, '$var is 1 before $f2->done' ); is( $hash{key}, 3, '$hash{key} is 3 before $f2->done' ); $f2->done; is( $var, 1, '$var is 1 after $f2->done' ); is( $hash{key}, 3, '$hash{key} is 3 after $f2->done' ); $fret->get; } # destroy test { my %state; package DestroyChecker { sub new { my $class = shift; my $self = bless [ @_ ], $class; $state{$self->[0]} = "LIVE"; return $self; } sub DESTROY { my $self = shift; $state{$self->[0]} = "DEAD"; } } dynamically my $var = DestroyChecker->new( "orig" ); my $f1 = Future->new; my $fret = (async sub { dynamically $var = DestroyChecker->new( "new" ); await $f1; })->(); is( \%state, { orig => "LIVE", new => "LIVE" }, '%state initially' ); $f1->done; $fret->get; is( \%state, { orig => "LIVE", new => "DEAD" }, '%state after done' ); undef $var; is( \%state, { orig => "DEAD", new => "DEAD" }, '%state finally' ); } done_testing; Syntax-Keyword-Dynamically-0.13/t/80dynamically+Object-Pad.t000444001750001750 162214503050617 22503 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { plan skip_all => "Syntax::Keyword::Dynamically is not available" unless eval { require Syntax::Keyword::Dynamically }; plan skip_all => "Object::Pad >= 0.800 is not available" unless eval { require Object::Pad; Object::Pad->VERSION( '0.800' ) }; Syntax::Keyword::Dynamically->import; Object::Pad->import; diag( "Syntax::Keyword::Dynamically $Syntax::Keyword::Dynamically::VERSION, " . "Object::Pad $Object::Pad::VERSION" ); } class Datum { field $value = 1; method value { $value } method test { ::is( $self->value, 1, 'value is 1 initially' ); { dynamically $value = 2; ::is( $self->value, 2, 'value is 2 inside dynamically-assigned block' ); } ::is( $self->value, 1, 'value is 1 finally' ); } } Datum->new->test; done_testing; Syntax-Keyword-Dynamically-0.13/t/80dynamically+Sentinel.t000444001750001750 154214503050617 22355 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { plan skip_all => "Syntax::Keyword::Dynamically is not available" unless eval { require Syntax::Keyword::Dynamically }; plan skip_all => "Sentinel is not available" unless eval { require Sentinel }; Syntax::Keyword::Dynamically->import; Sentinel->import; } my @get_values; my @set_values; sub accessor :lvalue { sentinel get => sub { return shift @get_values }, set => sub { push @set_values, $_[0] }; } subtest "dynamically setting a Sentinel" => sub { @get_values = ( "saved", "inside", "restored" ); { dynamically accessor = "new"; is( accessor, "inside", 'value within scope' ); } is( accessor, "restored", 'value restored after block leave' ); is( \@set_values, [ "new", "saved" ], 'STORE magic invoked' ); }; done_testing; Syntax-Keyword-Dynamically-0.13/t/81async-method+dynamically.t000444001750001750 336414503050617 23174 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test2::V0; BEGIN { plan skip_all => "Future is not available" unless eval { require Future }; plan skip_all => "Future::AsyncAwait >= 0.40 is not available" unless eval { require Future::AsyncAwait; Future::AsyncAwait->VERSION( '0.40' ) }; plan skip_all => "Object::Pad >= 0.800 is not available" unless eval { require Object::Pad; Object::Pad->VERSION( '0.800' ) }; plan skip_all => "Syntax::Keyword::Dynamically >= 0.04 is not available" unless eval { require Syntax::Keyword::Dynamically; Syntax::Keyword::Dynamically->VERSION( '0.04' ) }; Future::AsyncAwait->import; Object::Pad->import; Syntax::Keyword::Dynamically->import; diag( "Future::AsyncAwait $Future::AsyncAwait::VERSION, " . "Object::Pad $Object::Pad::VERSION, " . "Syntax::Keyword::Dynamically $Syntax::Keyword::Dynamically::VERSION" ); } # dynamically inside an async method { my $after_level; class Logger { field $_level = 1; method level { $_level } async method verbosely { my ( $code ) = @_; dynamically $_level = $_level + 1; await $code->(); $after_level = $_level; } } my $logger = Logger->new; is( $logger->level, 1, '$logger->level initially' ); my $during_level; my $f1 = Future->new; my $fret = $logger->verbosely(async sub { $during_level = $logger->level; await $f1; }); is( $logger->level, 1, '$logger->level while verbosely suspended' ); is( $during_level, 2, '$during_level' ); $f1->done; is( $after_level, 2, '$after_level' ); is( $logger->level, 1, '$logger->level finally' ); } done_testing; Syntax-Keyword-Dynamically-0.13/t/99pod.t000444001750001750 25514503050617 17046 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();