Syntax-Keyword-Dynamically-0.09000755001750001750 014111701202 15324 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/AsyncAwait.h000444001750001750 706114111701202 17701 0ustar00leoleo000000000000#ifndef __FUTURE_ASYNCAWAIT_H__ #define __FUTURE_ASYNCAWAIT_H__ #include "perl.h" /* * The API contained in this file is even more experimental than the rest of * Future::AsyncAwait. It is primarily designed to allow suspend-aware dynamic * variables in Syntax::Keyword::Dynamically, but may be useful for other * tasks. * * There are no unit tests for these hooks inside this distribution, as testing * it would require more XS code. It is tested as a side-effect of the * integration with Syntax::Keyword::Dynamically. */ /* * This enum provides values for the `phase` hook parameter. */ enum { /* PRESUSPEND = 0x10, */ FAA_PHASE_POSTSUSPEND = 0x20, FAA_PHASE_PRERESUME = 0x30, /* POSTRESUME = 0x40, */ FAA_PHASE_FREE = 0xFF, }; /* * The type of suspend hook functions. * * `phase` indicates the point in the suspend/resume lifecycle, as one of * the values of the enum above. * `cv` points to the CV being suspended or resumed. This will be after it * has been cloned, if necessary. * `modhookdata` points to an HV associated with the CV state, and may be * used by modules as a scratchpad to store extra data relating to this * function. Callers should prefix keys with their own module name to * avoid collisions. */ typedef void SuspendHookFunc(pTHX_ U8 phase, CV *cv, HV *modhookdata); /* * Callers should use this function-like macro to set the value of the hook * function variable, by passing in the address of a new function and a pointer * to a variable to capture the previous value. * * static SuspendHookFunc *oldhook; * * future_asyncawait_wrap_suspendhook(&my_hook_func, &oldhook); * * The hook function itself should remember to chain to the oldhook function, * whose value will never be NULL; * * void my_hook_func(aTHX_ U8 phase, CV *cv, HV *modhookdata) * { * ... * (*oldhook)(phase, cv, modhookdata); * } */ static void S_null_suspendhook(pTHX_ U8 phase, CV *cv, HV *modhookdata) { /* empty */ } #ifndef OP_CHECK_MUTEX_LOCK /* < 5.15.8 */ # define OP_CHECK_MUTEX_LOCK ((void)0) # define OP_CHECK_MUTEX_UNLOCK ((void)0) #endif #define future_asyncawait_wrap_suspendhook(newfunc, oldhookp) S_future_asyncawait_wrap_suspendhook(aTHX_ newfunc, oldhookp) static void S_future_asyncawait_wrap_suspendhook(pTHX_ SuspendHookFunc *newfunc, SuspendHookFunc **oldhookp) { if(*oldhookp) return; /* Rather than define our own mutex for this very-rare usecase, we'll just * abuse core's opcheck mutex for it. At worst this leads to thread * contention at module load time for this very quick test */ OP_CHECK_MUTEX_LOCK; if(!*oldhookp) { SV **hookp = hv_fetchs(PL_modglobal, "Future::AsyncAwait/suspendhook", TRUE); if(hookp && SvOK(*hookp)) *oldhookp = INT2PTR(SuspendHookFunc *, SvUV(*hookp)); else *oldhookp = &S_null_suspendhook; sv_setuv(*hookp, PTR2UV(newfunc)); } OP_CHECK_MUTEX_UNLOCK; } #define future_asyncawait_on_activate(func, data) S_future_asyncawait_on_activate(aTHX_ func, data) static void S_future_asyncawait_on_activate(pTHX_ void (*func)(pTHX_ void *data), void *data) { SV **svp; if((svp = hv_fetchs(PL_modglobal, "Future::AsyncAwait/loaded", FALSE)) && SvOK(*svp)) { (*func)(aTHX_ data); } else { AV *av; svp = hv_fetchs(PL_modglobal, "Future::AsyncAwait/on_loaded", FALSE); if(svp) av = (AV *)*svp; else { av = newAV(); hv_stores(PL_modglobal, "Future::AsyncAwait/on_loaded", (SV *)av); } av_push(av, newSVuv(PTR2UV(func))); av_push(av, newSVuv(PTR2UV(data))); } } #endif Syntax-Keyword-Dynamically-0.09/Build.PL000444001750001750 206114111701202 16754 0ustar00leoleo000000000000use v5; use strict; use warnings; use Module::Build; use XS::Parse::Keyword::Builder; my $build = Module::Build->new( module_name => "Syntax::Keyword::Dynamically", test_requires => { 'Test::More' => '0.88', # done_testing }, configure_requires => { 'Module::Build' => '0.4004', # test_requires 'XS::Parse::Keyword::Builder' => '0.13', }, requires => { 'perl' => '5.014', # pluggable keywords, XOP 'XS::Parse::Keyword' => '0.13', }, extra_compiler_flags => [qw( -I. -Ihax -ggdb )], 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.41' ) } ) { Devel::MAT::Dumper::Helper->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.09/Changes000444001750001750 322014111701202 16751 0ustar00leoleo000000000000Revision history for Syntax-Keyword-Dynamically 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.09/LICENSE000444001750001750 4376214111701202 16522 0ustar00leoleo000000000000This software is copyright (c) 2021 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) 2021 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) 2021 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 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. The End Syntax-Keyword-Dynamically-0.09/MANIFEST000444001750001750 61314111701202 16572 0ustar00leoleo000000000000AsyncAwait.h Build.PL Changes hax/perl-additions.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 tom-test.pl Syntax-Keyword-Dynamically-0.09/META.json000444001750001750 244614111701202 17110 0ustar00leoleo000000000000{ "abstract" : "dynamically change the value of a variable", "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" : "Syntax-Keyword-Dynamically", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004", "XS::Parse::Keyword::Builder" : "0.13" } }, "runtime" : { "requires" : { "XS::Parse::Keyword" : "0.13", "perl" : "5.014" } }, "test" : { "requires" : { "Test::More" : "0.88" } } }, "provides" : { "Syntax::Keyword::Dynamically" : { "file" : "lib/Syntax/Keyword/Dynamically.pm", "version" : "0.09" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "x_IRC" : "irc://irc.perl.org/#io-async" }, "version" : "0.09", "x_serialization_backend" : "JSON::PP version 4.05" } Syntax-Keyword-Dynamically-0.09/META.yml000444001750001750 146414111701202 16737 0ustar00leoleo000000000000--- abstract: 'dynamically change the value of a variable' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test::More: '0.88' configure_requires: Module::Build: '0.4004' XS::Parse::Keyword::Builder: '0.13' 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: Syntax-Keyword-Dynamically provides: Syntax::Keyword::Dynamically: file: lib/Syntax/Keyword/Dynamically.pm version: '0.09' 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.09' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Syntax-Keyword-Dynamically-0.09/README000444001750001750 640714111701202 16350 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.09/tom-test.pl000444001750001750 77014111701202 17556 0ustar00leoleo000000000000#!/usr/bin/env perl use strict; use warnings; use Test::More; use Syntax::Keyword::Dynamically; use Syntax::Keyword::Try; use Future::AsyncAwait; use IO::Async::Loop; our $TRACE; my $loop = IO::Async::Loop->new; my $pending = $loop->new_future; (async sub { my ($f) = @_; try { dynamically $TRACE = 'async sub'; is($TRACE, 'async sub'); await $f; is($TRACE, 'async sub'); } catch { fail('exception - ' . $@); } })->($pending); done_testing; Syntax-Keyword-Dynamically-0.09/hax000755001750001750 014111701202 16104 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/hax/perl-additions.c.inc000444001750001750 1571114111701202 22120 0ustar00leoleo000000000000/* vi: set ft=c : */ #ifndef av_count # define av_count(av) (AvFILL(av) + 1) #endif #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 #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; } #define sv_setrv(s, r) S_sv_setrv(aTHX_ s, r) static void S_sv_setrv(pTHX_ SV *sv, SV *rv) { sv_setiv(sv, (IV)rv); #if !HAVE_PERL_VERSION(5, 24, 0) SvIOK_off(sv); #endif SvROK_on(sv); } #define newPADxVOP(type, padix, flags, private) S_newPADxVOP(aTHX_ type, padix, flags, private) static OP *S_newPADxVOP(pTHX_ I32 type, PADOFFSET padix, I32 flags, U32 private) { OP *op = newOP(type, flags); op->op_targ = padix; op->op_private = private; return op; } /* 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 has nothing interesting for OP_CUSTOM */ /* 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; } static char *PL_savetype_name[] = { /* 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 }; Syntax-Keyword-Dynamically-0.09/lib000755001750001750 014111701202 16072 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/lib/Syntax000755001750001750 014111701202 17360 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/lib/Syntax/Keyword000755001750001750 014111701202 21004 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/lib/Syntax/Keyword/Dynamically.pm000444001750001750 750714111701202 23756 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-2020 -- leonerd@leonerd.org.uk package Syntax::Keyword::Dynamically 0.09; 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 $class = shift; my $caller = caller; $class->import_into( $caller, @_ ); } sub import_into { my $class = shift; my ( $caller, @syms ) = @_; my %syms = map { $_ => 1 } @syms; $^H{"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.09/lib/Syntax/Keyword/Dynamically.xs000444001750001750 3316714111701202 24015 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 # 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-additions.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_ 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_ 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) { DynamicVar *dyn = (void *)SvPVX(av_top(dynamicstack)); if(dyn->var != (SV *)_data) croak("ARGH: dynamicstack top mismatch"); SV *sv = av_pop(dynamicstack); 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_ HV *modhookdata) { IV i, max = av_top_index(dynamicstack); SV **avp = AvARRAY(dynamicstack); 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(dynamicstack, 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_ HV *modhookdata) { 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 SuspendHookFunc *nexthook; static void S_suspendhook(pTHX_ U8 phase, CV *cv, HV *modhookdata) { switch(phase) { case FAA_PHASE_POSTSUSPEND: (*nexthook)(aTHX_ phase, cv, modhookdata); hook_postsuspend(aTHX_ modhookdata); break; case FAA_PHASE_PRERESUME: hook_preresume(aTHX_ modhookdata); (*nexthook)(aTHX_ phase, cv, modhookdata); break; default: (*nexthook)(aTHX_ phase, cv, modhookdata); break; } } /* 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; 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; dynamicstack = newAV(); av_extend(dynamicstack, 50); future_asyncawait_wrap_suspendhook(&S_suspendhook, &nexthook); } 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.09/t000755001750001750 014111701202 15567 5ustar00leoleo000000000000Syntax-Keyword-Dynamically-0.09/t/00use.t000444001750001750 16514111701202 17027 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; use_ok( "Syntax::Keyword::Dynamically" ); done_testing; Syntax-Keyword-Dynamically-0.09/t/01dynamically.t000444001750001750 511014111701202 20555 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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' ); }; done_testing; Syntax-Keyword-Dynamically-0.09/t/02tiescalar.t000444001750001750 123314111701202 20221 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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_deeply( \@stored_values, [ "new", "saved" ], 'STORE magic invoked' ); }; done_testing; Syntax-Keyword-Dynamically-0.09/t/03lost-values.t000444001750001750 123114111701202 20527 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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.09/t/04scopes.t000444001750001750 51114111701202 17526 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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.09/t/80await+dynamically.t000444001750001750 1173114111701202 21713 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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.01 is not available" unless eval { require Syntax::Keyword::Dynamically; Syntax::Keyword::Dynamically->VERSION( '0.01' ) }; 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_deeply( \%hash, { key => "new", newkey => "added" }, '%hash after await' ); return "result"; } my $f1 = Future->new; my $fret = with_dynamically_helem( $f1 ); is_deeply( \%hash, \%orig, '%hash while suspended '); $f1->done; is( scalar $fret->get, "result", '$fret for dynamically helem in async sub' ); is_deeply( \%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_deeply( \%state, { orig => "LIVE", new => "LIVE" }, '%state initially' ); $f1->done; $fret->get; is_deeply( \%state, { orig => "LIVE", new => "DEAD" }, '%state after done' ); undef $var; is_deeply( \%state, { orig => "DEAD", new => "DEAD" }, '%state finally' ); } done_testing; Syntax-Keyword-Dynamically-0.09/t/80dynamically+Object-Pad.t000444001750001750 135514111701202 22477 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; BEGIN { plan skip_all => "Syntax::Keyword::Dynamically is not available" unless eval { require Syntax::Keyword::Dynamically }; plan skip_all => "Object::Pad is not available" unless eval { require Object::Pad }; Syntax::Keyword::Dynamically->import; Object::Pad->import; } class Datum { has $value = 1; method value { $value } method test { Test::More::is( $self->value, 1, 'value is 1 initially' ); { dynamically $value = 2; Test::More::is( $self->value, 2, 'value is 2 inside dynamically-assigned block' ); } Test::More::is( $self->value, 1, 'value is 1 finally' ); } } Datum->new->test; done_testing; Syntax-Keyword-Dynamically-0.09/t/80dynamically+Sentinel.t000444001750001750 155214111701202 22347 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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_deeply( \@set_values, [ "new", "saved" ], 'STORE magic invoked' ); }; done_testing; Syntax-Keyword-Dynamically-0.09/t/81async-method+dynamically.t000444001750001750 336114111701202 23162 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; 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.15 is not available" unless eval { require Object::Pad; Object::Pad->VERSION( '0.15' ) }; 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 { has $_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.09/t/99pod.t000444001750001750 25614111701202 17040 0ustar00leoleo000000000000#!/usr/bin/perl use v5.14; use warnings; use Test::More; eval "use Test::Pod 1.00"; plan skip_all => "Test::Pod 1.00 required for testing POD" if $@; all_pod_files_ok();