Syntax-Keyword-Try-0.11000755001750001750 013534573717 13657 5ustar00leoleo000000000000Syntax-Keyword-Try-0.11/Build.PL000444001750001750 106013534573717 15305 0ustar00leoleo000000000000use strict; use warnings; use Module::Build; my $build = Module::Build->new( module_name => "Syntax::Keyword::Try", test_requires => { 'Test::More' => '0.88', # done_testing }, configure_requires => { 'Module::Build' => '0.4004', # test_requires }, requires => { 'perl' => '5.014', # pluggable keywords, XOP }, license => 'perl', create_license => 1, create_readme => 1, meta_merge => { resources => { x_IRC => "irc://irc.perl.org/#io-async", }, }, ); $build->create_build_script; Syntax-Keyword-Try-0.11/Changes000444001750001750 531213534573717 15310 0ustar00leoleo000000000000Revision history for Syntax-Keyword-Try 0.11 2019-09-07 [CHANGES] * Use wrap_keyword_plugin() instead of direct access to PL_keyword_plugin [BUGFIXES] * Build OP_ENTER/OP_LEAVE structure the correct way so perl 5.31.3 doesn't crash * Fix OP_NEXT/OP_LAST/OP_REDO mangling for perl 5.31.3 to avoid CPU spin (RT129975) 0.10 2019-06-13 [CHANGES] * Added experimental value-semantic expression form (RT121267) * Document that the module works nicely with Future::AsyncAwait * Ignore import symbols `catch` and `finally` [BUGFIXES] * Fixed spelling mistakes in documentation (patch from debian) (RT124140) 0.09 2017-11-08 14:33:19 [BUGFIXES] * Make module loading thread-safe on perls 5.16 and above. (RT123547) Safety on perl 5.14 is still an unsolved problem. 0.08 2017-09-14 17:26:20 [BUGFIXES] * Handle the OpSIBLING of an OP_{NEXT,LAST,REDO} correctly (RT123040) 0.07 2017-08-13 23:11:39 [CHANGES] * Capture 80await+try.t unit test from Future-AsyncAwait * Improved implementation of OP_PUSHFINALLY to help make try/finally inside async/await subs work [BUGFIXES] * Make 'eval { try { return ... } }' work correctly * Make 'return LIST' inside try{} blocks work correctly (RT122795) - with thanks to Zefram for code inspiration 0.06 2017/06/06 14:59:30 [CHANGES] * Clarify documentation about the behaviour of try {} blocks without catch {}; include comparison with other modules [BUGFIXES] * Fix typo in #ifdef test (RT119709) * Restore C89 compatibility again (RT119665) 0.05 2017/06/05 14:04:06 [CHANGES] * Add a SEE ALSO link pointing at the value-semantics RT ticket [BUGFIXES] * Fix cLISTOP->op_last field to keep DEBUGGING builds happy (RT119095) 0.04 2016/11/25 15:06:18 [CHANGES] * Removed stale documentation about now-fixed warnings from next/last/redo [BUGFIXES] * Fix C code for C89 compatibility (RT118950) * Localise $@ around try/catch (RT118415) 0.03 2016/11/24 10:27:45 [CHANGES] * Default import of 'try' keyword * Suppress 'exiting' warning around next/last/redo inside a try block * Don't bother outputting a Makefile.PL 0.02 2016/09/06 21:29:25 [BUGFIXES] * Use OpSIBLING() macro for compatibility for perl 5.25.x * Documentation fixes 0.01 2016/09/05 22:19:33 First version, released on an unsuspecting world. Syntax-Keyword-Try-0.11/LICENSE000444001750001750 4376213534573717 15055 0ustar00leoleo000000000000This software is copyright (c) 2019 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) 2019 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) 2019 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-Try-0.11/MANIFEST000444001750001750 55413534573717 15131 0ustar00leoleo000000000000Build.PL Changes lib/Syntax/Keyword/Try.pm lib/Syntax/Keyword/Try.xs LICENSE MANIFEST This list of files META.json META.yml README t/00use.t t/01trycatch.t t/02tryfinally.t t/03trycatchfinally.t t/10snail.t t/11loop.t t/12return.t t/13die-in-finally.t t/14try-localises.t t/20try-do.t t/21try-do-finally.t t/80await+try.t t/90rt123547.t t/90rt125971.t t/99pod.t Syntax-Keyword-Try-0.11/META.json000444001750001750 225313534573717 15437 0ustar00leoleo000000000000{ "abstract" : "a C syntax for perl", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.4224", "license" : [ "perl_5" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Syntax-Keyword-Try", "prereqs" : { "build" : { "requires" : { "ExtUtils::CBuilder" : "0" } }, "configure" : { "requires" : { "Module::Build" : "0.4004" } }, "runtime" : { "requires" : { "perl" : "5.014" } }, "test" : { "requires" : { "Test::More" : "0.88" } } }, "provides" : { "Syntax::Keyword::Try" : { "file" : "lib/Syntax/Keyword/Try.pm", "version" : "0.11" } }, "release_status" : "stable", "resources" : { "license" : [ "http://dev.perl.org/licenses/" ], "x_IRC" : "irc://irc.perl.org/#io-async" }, "version" : "0.11", "x_serialization_backend" : "JSON::PP version 4.04" } Syntax-Keyword-Try-0.11/META.yml000444001750001750 132513534573717 15266 0ustar00leoleo000000000000--- abstract: 'a C syntax for perl' author: - 'Paul Evans ' build_requires: ExtUtils::CBuilder: '0' Test::More: '0.88' configure_requires: Module::Build: '0.4004' dynamic_config: 1 generated_by: 'Module::Build version 0.4224, 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-Try provides: Syntax::Keyword::Try: file: lib/Syntax/Keyword/Try.pm version: '0.11' requires: perl: '5.014' resources: IRC: irc://irc.perl.org/#io-async license: http://dev.perl.org/licenses/ version: '0.11' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Syntax-Keyword-Try-0.11/README000444001750001750 3104113534573717 14713 0ustar00leoleo000000000000NAME Syntax::Keyword::Try - a try/catch/finally syntax for perl SYNOPSIS use Syntax::Keyword::Try; sub foo { try { attempt_a_thing(); return "success"; } catch { warn "It failed - $@"; return "failure"; } } DESCRIPTION This module provides a syntax plugin that implements exception-handling semantics in a form familiar to users of other languages, being built on a block labeled with the try keyword, followed by at least one of a catch or finally block. As well as providing a handy syntax for this useful behaviour, this module also serves to contain a number of code examples for how to implement parser plugins and manipulate optrees to provide new syntax and behaviours for perl code. KEYWORDS try try { STATEMENTS... } ... A try statement provides the main body of code that will be invoked, and must be followed by either a catch statement, a finally statement, or both. Execution of the try statement itself begins from the block given to the statement and continues until either it throws an exception, or completes successfully by reaching the end of the block. What will happen next depends on the presence of a catch or finally statement immediately following it. The body of a try {} block may contain a return expression. If executed, such an expression will cause the entire containing function to return with the value provided. This is different from a plain eval {} block, in which circumstance only the eval itself would return, not the entire function. The body of a try {} block may contain loop control expressions (redo, next, last) which will have their usual effect on any loops that the try {} block is contained by. The parsing rules for the set of statements (the try block and its associated catch and finally) are such that they are parsed as a self- contained statement. Because of this, there is no need to end with a terminating semicolon. Note (especially to users of Try::Tiny and similar) that the try {} block itself does not necessarily stop exceptions thrown inside it from propagating outside. It is the presence of a later catch {} block which causes this to happen. A try with only a finally and no catch will still propagate exceptions up to callers as normal. catch ... catch { STATEMENTS... } A catch statement provides a block of code to the preceding try statement that will be invoked in the case that the main block of code throws an exception. The catch block can inspect the raised exception by looking in $@ in the usual way. Presence of this catch statement causes any exception thrown by the preceding try block to be non-fatal to the surrounding code. If the catch block wishes to optionally handle some exceptions but not others, it can re-raise it (or another exception) by calling die in the usual manner. As with try, the body of a catch {} block may also contain a return expression, which as before, has its usual meaning, causing the entire containing function to return with the given value. The body may also contain loop control expressions (redo, next or last) which also have their usual effect. If a catch statement is not given, then any exceptions raised by the try block are raised to the caller in the usual way. finally ... finally { STATEMENTS... } A finally statement provides a block of code to the preceding try statement (or try/catch pair) which is executed afterwards, both in the case of a normal execution or a thrown exception. This code block may be used to provide whatever clean-up operations might be required by preceding code. Because it is executed during a stack cleanup operation, a finally {} block may not cause the containing function to return, or to alter the return value of it. It also cannot see the containing function's @_ arguments array (though as it is block scoped within the function, it will continue to share any normal lexical variables declared up until that point). It is protected from disturbing the value of $@. If the finally {} block code throws an exception, this will be printed as a warning and discarded, leaving $@ containing the original exception, if one existed. VALUE SEMANTICS Warning: the feature described in this section is experimental. This experiment may be stablised in a later version, or may be altered or removed without further notice. It is present here for testing and evaluation purposes. Additionally, on perl versions 5.18 and later, it will produce a warning in the experimental category. The syntax provided by this module may be used as a value-yielding expression. Because this syntax is new, experimental, and somewhat surprising, it must be specifically requested by name try_value: use Syntax::Keyword::Try qw( try try_value ); my $result = try do { ... } catch { ... }; Also, on Perl versions 5.24 and later: my $result = try do { ... } finally { ... }; my $result = try do { ... } catch { ... } finally { ... }; Specifically, note that the expression must be spelled as try do { ... } so that the syntax is distinct from that used by control-flow statements. The interposed do keyword reminds the reader, and instructs the syntax parser, that this will be an expression, not a statement. It is not necessary to similarly notate the catch or finally blocks. In this case, the syntax behaves syntactically like an expression, and may appear anywhere a normal expression is allowed. It follows similar semantics to the purely control-flow case; if the code in the try block does not throw an exception, then the expression as a whole yields whatever value the try expression did. If it fails, then the catch block is executed and the expression yields its resulting value instead. A finally block, if present, will be evaluated for side-effects before the rest of the expression returns. Remember that, as in the control-flow case, the return keyword will cause the entire containing function to return, not just the try block. OTHER MODULES There are already quite a number of modules on CPAN that provide a try/catch-like syntax for Perl. * Try * TryCatch * Try::Tiny * Syntax::Feature::Try They are compared here, by feature: True syntax plugin Like Try and Syntax::Feature::Try, this module is implemented as a true syntax plugin, allowing it to provide new parsing rules not available to simple functions. Most notably here it means that the resulting combination does not need to end in a semicolon. In comparison, Try::Tiny is plain perl and provides its functionality using regular perl functions; as such its syntax requires the trailing semicolon. TryCatch is a hybrid that uses Devel::Declare to parse the syntax tree. @_ in a try or catch block Because the try and catch block code is contained in a true block rather than an entire anonymous subroutine, invoking it does not interfere with the @_ arguments array. Code inside these blocks can interact with the containing function's array as before. This feature is unique among these modules; none of the others listed have this ability. return in a try or catch block Like TryCatch and Syntax::Feature::Try, the return statement has its usual effect within a subroutine containing syntax provided by this module. Namely, it causes the containing sub itself to return. In comparison, using Try or Try::Tiny mean that a return statement will only exit from the try block. next/last/redo in a try or catch block The loop control keywords of next, last and redo have their usual effect on dynamically contained loops. Syntax::Feature::Try documents that these do not work there. The other modules make no statement either way. Value Semantics Like Try and Syntax::Feature::Try, the syntax provided by this module only works as a syntax-level statement and not an expression when the experimental try_value feature described above has not been enabled. You cannot assign from the result of a try block. Additionally, final-expression value semantics do not work, so it cannot be contained by a do block to yield this value. In comparison, the behaviour implemented by Try::Tiny can be used as a valued expression, such as assigned to a variable or returned to the caller of its containing function. Such ability is provided by this module if the experimental try_value feature is enabled, though it must be spelled differently as try do { ... }. try without catch Like Syntax::Feature::Try, the syntax provided by this module allows a try block to be followed by only a finally block, with no catch. In this case, exceptions thrown by code contained by the try are not suppressed, instead they propagate as normal to callers. This matches the behaviour familiar to Java or C++ programmers. In comparison, the code provided by Try and Try::Tiny always suppress exception propagation even without an actual catch block. The TryCatch module does not allow a try block not followed by catch. Typed catch Like Try and Try::Tiny, this module makes no attempt to perform any kind of typed dispatch to distinguish kinds of exception caught by catch blocks. TryCatch and Syntax::Feature::Try both attempt to provide a kind of typed dispatch where different classes of exception are caught by different blocks of code, or propagated up entirely to callers. The author considers the lack of such ability in this module to be a feature. That kind of dispatch on type matching of a controlling expression is too useful a behaviour to be constrained to exception catching. If the language is to provide such a facility, it should be more universally applicable as a stand-alone independent ability. WITH OTHER MODULES Future::AsyncAwait As of Future::AsyncAwait version 0.10 and Syntax::Keyword::Try version 0.07, cross-module integration tests assert that basic try/catch blocks inside an async sub work correctly, including those that attempt to return from inside try. use Future::AsyncAwait; use Syntax::Keyword::Try; async sub attempt { try { await func(); return "success"; } catch { return "failed"; } } KNOWN BUGS Thread-safety at load time cannot be assured before perl 5.16 On perl versions 5.16 and above this module is thread-safe. On perl version 5.14 this module is thread-safe provided that it is used before any additional threads are created. However, when using 5.14 there is a race condition if this module is loaded late in the program startup, after additional threads have been created. This leads to the potential for it to be started up multiple times concurrently, which creates data races when modifying internal structures and likely leads to a segmentation fault, either during load or soon after when more code is compiled. As a workaround, for any such program that creates multiple threads, loads additional code (such as dynamically-discovered plugins), and has to run on 5.14, it should make sure to use Syntax::Keyword::Try; early on in startup, before it spins out any additional threads. (See also https://rt.cpan.org/Public/Bug/Display.html?id=123547) $@ is not local'ised by try do before perl 5.24 On perl versions 5.24 and above, or when using only control-flow statement syntax, $@ is always correctly localised. However, when using the experimental value-yielding expression version try do {...} on perl versions 5.22 or older, the localisation of $@ does not correctly apply around the expression. After such an expression, the value of $@ will leak out if a failure happened and the catch block was invoked, overwriting any previous value that was visible there. (See also https://rt.cpan.org/Public/Bug/Display.html?id=124366) ACKNOWLEDGEMENTS With thanks to Zefram, ilmari and others from irc.perl.org/#p5p for assisting with trickier bits of XS logic. AUTHOR Paul Evans Syntax-Keyword-Try-0.11/lib000755001750001750 013534573717 14425 5ustar00leoleo000000000000Syntax-Keyword-Try-0.11/lib/Syntax000755001750001750 013534573717 15713 5ustar00leoleo000000000000Syntax-Keyword-Try-0.11/lib/Syntax/Keyword000755001750001750 013534573717 17337 5ustar00leoleo000000000000Syntax-Keyword-Try-0.11/lib/Syntax/Keyword/Try.pm000444001750001750 3230113534573717 20627 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, 2016-2019 -- leonerd@leonerd.org.uk package Syntax::Keyword::Try; use strict; use warnings; our $VERSION = '0.11'; use Carp; require XSLoader; XSLoader::load( __PACKAGE__, $VERSION ); =head1 NAME C - a C syntax for perl =head1 SYNOPSIS use Syntax::Keyword::Try; sub foo { try { attempt_a_thing(); return "success"; } catch { warn "It failed - $@"; return "failure"; } } =head1 DESCRIPTION This module provides a syntax plugin that implements exception-handling semantics in a form familiar to users of other languages, being built on a block labeled with the C keyword, followed by at least one of a C or C block. As well as providing a handy syntax for this useful behaviour, this module also serves to contain a number of code examples for how to implement parser plugins and manipulate optrees to provide new syntax and behaviours for perl code. =cut =head1 KEYWORDS =head2 try try { STATEMENTS... } ... A C statement provides the main body of code that will be invoked, and must be followed by either a C statement, a C statement, or both. Execution of the C statement itself begins from the block given to the statement and continues until either it throws an exception, or completes successfully by reaching the end of the block. What will happen next depends on the presence of a C or C statement immediately following it. The body of a C block may contain a C expression. If executed, such an expression will cause the entire containing function to return with the value provided. This is different from a plain C block, in which circumstance only the C itself would return, not the entire function. The body of a C block may contain loop control expressions (C, C, C) which will have their usual effect on any loops that the C block is contained by. The parsing rules for the set of statements (the C block and its associated C and C) are such that they are parsed as a self- contained statement. Because of this, there is no need to end with a terminating semicolon. Note (especially to users of L and similar) that the C block itself does not necessarily stop exceptions thrown inside it from propagating outside. It is the presence of a later C block which causes this to happen. A C with only a C and no C will still propagate exceptions up to callers as normal. =head2 catch ... catch { STATEMENTS... } A C statement provides a block of code to the preceding C statement that will be invoked in the case that the main block of code throws an exception. The C block can inspect the raised exception by looking in C<$@> in the usual way. Presence of this C statement causes any exception thrown by the preceding C block to be non-fatal to the surrounding code. If the C block wishes to optionally handle some exceptions but not others, it can re-raise it (or another exception) by calling C in the usual manner. As with C, the body of a C block may also contain a C expression, which as before, has its usual meaning, causing the entire containing function to return with the given value. The body may also contain loop control expressions (C, C or C) which also have their usual effect. If a C statement is not given, then any exceptions raised by the C block are raised to the caller in the usual way. =head2 finally ... finally { STATEMENTS... } A C statement provides a block of code to the preceding C statement (or C pair) which is executed afterwards, both in the case of a normal execution or a thrown exception. This code block may be used to provide whatever clean-up operations might be required by preceding code. Because it is executed during a stack cleanup operation, a C block may not cause the containing function to return, or to alter the return value of it. It also cannot see the containing function's C<@_> arguments array (though as it is block scoped within the function, it will continue to share any normal lexical variables declared up until that point). It is protected from disturbing the value of C<$@>. If the C block code throws an exception, this will be printed as a warning and discarded, leaving C<$@> containing the original exception, if one existed. =head1 VALUE SEMANTICS =over 4 B the feature described in this section is experimental. This experiment may be stablised in a later version, or may be altered or removed without further notice. It is present here for testing and evaluation purposes. Additionally, on I versions 5.18 and later, it will produce a warning in the C category. =back The syntax provided by this module may be used as a value-yielding expression. Because this syntax is new, experimental, and somewhat surprising, it must be specifically requested by name C: use Syntax::Keyword::Try qw( try try_value ); my $result = try do { ... } catch { ... }; Also, on Perl versions 5.24 and later: my $result = try do { ... } finally { ... }; my $result = try do { ... } catch { ... } finally { ... }; Specifically, note that the expression must be spelled as C so that the syntax is distinct from that used by control-flow statements. The interposed C keyword reminds the reader, and instructs the syntax parser, that this will be an expression, not a statement. It is not necessary to similarly notate the C or C blocks. In this case, the syntax behaves syntactically like an expression, and may appear anywhere a normal expression is allowed. It follows similar semantics to the purely control-flow case; if the code in the C block does not throw an exception, then the expression as a whole yields whatever value the C expression did. If it fails, then the C block is executed and the expression yields its resulting value instead. A C block, if present, will be evaluated for side-effects before the rest of the expression returns. Remember that, as in the control-flow case, the C keyword will cause the entire containing function to return, not just the C block. =cut =head1 OTHER MODULES There are already quite a number of modules on CPAN that provide a C-like syntax for Perl. =over 2 =item * L =item * L =item * L =item * L =back They are compared here, by feature: =head2 True syntax plugin Like L and L, this module is implemented as a true syntax plugin, allowing it to provide new parsing rules not available to simple functions. Most notably here it means that the resulting combination does not need to end in a semicolon. In comparison, L is plain perl and provides its functionality using regular perl functions; as such its syntax requires the trailing semicolon. L is a hybrid that uses L to parse the syntax tree. =head2 C<@_> in a try or catch block Because the C and C block code is contained in a true block rather than an entire anonymous subroutine, invoking it does not interfere with the C<@_> arguments array. Code inside these blocks can interact with the containing function's array as before. This feature is unique among these modules; none of the others listed have this ability. =head2 C in a try or catch block Like L and L, the C statement has its usual effect within a subroutine containing syntax provided by this module. Namely, it causes the containing C itself to return. In comparison, using L or L mean that a C statement will only exit from the C block. =head2 C/C/C in a try or catch block The loop control keywords of C, C and C have their usual effect on dynamically contained loops. L documents that these do not work there. The other modules make no statement either way. =head2 Value Semantics Like L and L, the syntax provided by this module only works as a syntax-level statement and not an expression when the experimental C feature described above has not been enabled. You cannot assign from the result of a C block. Additionally, final-expression value semantics do not work, so it cannot be contained by a C block to yield this value. In comparison, the behaviour implemented by L can be used as a valued expression, such as assigned to a variable or returned to the caller of its containing function. Such ability is provided by this module if the experimental C feature is enabled, though it must be spelled differently as C. =head2 C without C Like L, the syntax provided by this module allows a C block to be followed by only a C block, with no C. In this case, exceptions thrown by code contained by the C are not suppressed, instead they propagate as normal to callers. This matches the behaviour familiar to Java or C++ programmers. In comparison, the code provided by L and L always suppress exception propagation even without an actual C block. The L module does not allow a C block not followed by C. =head2 Typed C Like L and L, this module makes no attempt to perform any kind of typed dispatch to distinguish kinds of exception caught by C blocks. L and L both attempt to provide a kind of typed dispatch where different classes of exception are caught by different blocks of code, or propagated up entirely to callers. The author considers the lack of such ability in this module to be a feature. That kind of dispatch on type matching of a controlling expression is too useful a behaviour to be constrained to exception catching. If the language is to provide such a facility, it should be more universally applicable as a stand-alone independent ability. =cut sub import { my $class = shift; my $caller = caller; $class->import_into( $caller, @_ ); } sub import_into { my $class = shift; my ( $caller, @syms ) = @_; @syms or @syms = qw( try ); my %syms = map { $_ => 1 } @syms; $^H{"Syntax::Keyword::Try/try"}++ if delete $syms{try}; $^H{"Syntax::Keyword::Try/try_value"}++ if delete $syms{try_value}; # Ignore requests for these, as they come automatically with `try` delete @syms{qw( catch finally )}; croak "Unrecognised import symbols @{[ keys %syms ]}" if keys %syms; } =head1 WITH OTHER MODULES =head2 Future::AsyncAwait As of C version 0.10 and L version 0.07, cross-module integration tests assert that basic C blocks inside an C work correctly, including those that attempt to C from inside C. use Future::AsyncAwait; use Syntax::Keyword::Try; async sub attempt { try { await func(); return "success"; } catch { return "failed"; } } =head1 KNOWN BUGS =head2 Thread-safety at load time cannot be assured before perl 5.16 On F versions 5.16 and above this module is thread-safe. On F version 5.14 this module is thread-safe provided that it is Cd before any additional threads are created. However, when using 5.14 there is a race condition if this module is loaded late in the program startup, after additional threads have been created. This leads to the potential for it to be started up multiple times concurrently, which creates data races when modifying internal structures and likely leads to a segmentation fault, either during load or soon after when more code is compiled. As a workaround, for any such program that creates multiple threads, loads additional code (such as dynamically-discovered plugins), and has to run on 5.14, it should make sure to use Syntax::Keyword::Try; early on in startup, before it spins out any additional threads. (See also L) =head2 $@ is not local'ised by C before perl 5.24 On F versions 5.24 and above, or when using only control-flow statement syntax, C<$@> is always correctly Cised. However, when using the experimental value-yielding expression version C on perl versions 5.22 or older, the Cisation of C<$@> does not correctly apply around the expression. After such an expression, the value of C<$@> will leak out if a failure happened and the C block was invoked, overwriting any previous value that was visible there. (See also L) =head1 ACKNOWLEDGEMENTS With thanks to C, C and others from C for assisting with trickier bits of XS logic. =head1 AUTHOR Paul Evans =cut 0x55AA; Syntax-Keyword-Try-0.11/lib/Syntax/Keyword/Try.xs000444001750001750 3275013534573717 20655 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, 2016-2018 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" /* Before perl 5.22 these were not visible */ #ifndef cv_clone #define cv_clone(a) Perl_cv_clone(aTHX_ a) #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 OpSIBLING #define OpSIBLING(op) (op->op_sibling) #endif #ifndef OpMORESIB_set #define OpMORESIB_set(op,sib) ((op)->op_sibling = (sib)) #endif /* borrowed from ZEFRAM/Scope-Escape-0.005/lib/Scope/Escape.xs */ #define PERL_VERSION_DECIMAL(r,v,s) (r*1000000 + v*1000 + s) #define PERL_DECIMAL_VERSION \ PERL_VERSION_DECIMAL(PERL_REVISION,PERL_VERSION,PERL_SUBVERSION) #define PERL_VERSION_GE(r,v,s) \ (PERL_DECIMAL_VERSION >= PERL_VERSION_DECIMAL(r,v,s)) #if PERL_VERSION_GE(5,26,0) # define HAVE_OP_SIBPARENT #endif #if PERL_VERSION_GE(5,19,4) typedef SSize_t array_ix_t; #else /* <5.19.4 */ typedef I32 array_ix_t; #endif /* <5.19.4 */ #ifndef wrap_keyword_plugin # ifndef OP_CHECK_MUTEX_LOCK /* < 5.15.8 */ # define OP_CHECK_MUTEX_LOCK ((void)0) # define OP_CHECK_MUTEX_UNLOCK ((void)0) # endif # define wrap_keyword_plugin(func, var) S_wrap_keyword_plugin(aTHX_ func, var) static void S_wrap_keyword_plugin(pTHX_ Perl_keyword_plugin_t func, Perl_keyword_plugin_t *var) { /* BOOT can potentially race with other threads (RT123547) */ /* Perl doesn't really provide us a nice mutex for doing this so this is the * best we can find. See also * https://rt.perl.org/Public/Bug/Display.html?id=132413 */ if(*var) return; OP_CHECK_MUTEX_LOCK; if(!*var) { *var = PL_keyword_plugin; PL_keyword_plugin = func; } OP_CHECK_MUTEX_UNLOCK; } #endif static OP *pp_entertrycatch(pTHX); static OP *pp_catch(pTHX); /* * A variant of dounwind() which preserves the topmost scalar or list value on * the stack in non-void context */ #define dounwind_keeping_stack(cxix) MY_dounwind_keeping_stack(aTHX_ cxix) static void MY_dounwind_keeping_stack(pTHX_ I32 cxix) { I32 gimme; SV *retval; /* chunks of this code inspired by * ZEFRAM/Scope-Escape-0.005/lib/Scope/Escape.xs */ switch(gimme = cxstack[cxix].blk_gimme) { case G_VOID: break; case G_SCALAR: { dSP; retval = TOPs; SvREFCNT_inc(retval); sv_2mortal(retval); break; } case G_ARRAY: { dSP; dMARK; SV **retvals = MARK+1; array_ix_t retcount = SP-MARK; array_ix_t i; AV *retav = newAV(); retval = (SV *)retav; sv_2mortal(retval); av_fill(retav, retcount-1); Copy(retvals, AvARRAY(retav), retcount, SV *); for(i = 0; i < retcount; i++) SvREFCNT_inc(retvals[i]); break; } } dounwind(cxix); /* Now put the value back */ switch(gimme) { case G_VOID: break; case G_SCALAR: { dSP; XPUSHs(retval); PUTBACK; break; } case G_ARRAY: { dSP; PUSHMARK(SP); AV *retav = (AV *)retval; array_ix_t retcount = av_len(retav) + 1; /* because av_len means top index */ EXTEND(SP, retcount); Copy(AvARRAY(retav), SP+1, retcount, SV *); SP += retcount; PUTBACK; break; } } } /* * A modified version of pp_return for returning from inside a try block. * To do this, we unwind the context stack to just past the CXt_EVAL and then * chain to the regular OP_RETURN func */ static OP *pp_returnintry(pTHX) { I32 cxix; for (cxix = cxstack_ix; cxix; cxix--) { if(CxTYPE(&cxstack[cxix]) == CXt_SUB) break; if(CxTYPE(&cxstack[cxix]) == CXt_EVAL && CxTRYBLOCK(&cxstack[cxix])) { /* If this CXt_EVAL frame came from our own ENTERTRYCATCH, then the * retop should point at an OP_CUSTOM and its first grand-child will be * our custom modified ENTERTRY. We can skip over it and continue in * this case. */ OP *retop = cxstack[cxix].blk_eval.retop; OP *leave, *enter; if(retop->op_type == OP_CUSTOM && retop->op_ppaddr == &pp_catch && (leave = cLOGOPx(retop)->op_first) && leave->op_type == OP_LEAVETRY && (enter = cLOGOPx(leave)->op_first) && enter->op_type == OP_ENTERTRY && enter->op_ppaddr == &pp_entertrycatch) { continue; } /* We have to stop at any other kind of CXt_EVAL */ break; } } if(!cxix) croak("Unable to find an CXt_SUB to pop back to"); dounwind_keeping_stack(cxix); return PL_ppaddr[OP_RETURN](aTHX); } /* * A custom SVOP that takes a CV and arranges for it to be invoked on scope * leave */ static XOP xop_pushfinally; static void invoke_finally(pTHX_ void *arg) { CV *finally = arg; dSP; PUSHMARK(SP); call_sv((SV *)finally, G_DISCARD|G_EVAL|G_KEEPERR); SvREFCNT_dec(finally); } static OP *pp_pushfinally(pTHX) { CV *finally = (CV *)cSVOP->op_sv; /* finally is a closure protosub; we have to clone it into a real sub. * If we do this now then captured lexicals still work even around * Future::AsyncAwait (see RT122796) * */ SAVEDESTRUCTOR_X(&invoke_finally, (SV *)cv_clone(finally)); return PL_op->op_next; } #define newPUSHFINALLYOP(finally) MY_newPUSHFINALLYOP(aTHX_ finally) static OP *MY_newPUSHFINALLYOP(pTHX_ CV *finally) { OP *op = newSVOP(OP_CUSTOM, 0, (SV *)finally); op->op_ppaddr = &pp_pushfinally; return op; } #define newLOCALISEOP(gv) MY_newLOCALISEOP(aTHX_ gv) static OP *MY_newLOCALISEOP(pTHX_ GV *gv) { OP *op = newGVOP(OP_GVSV, 0, gv); op->op_private |= OPpLVAL_INTRO; return op; } #define lex_consume(s) MY_lex_consume(aTHX_ s) static int MY_lex_consume(pTHX_ char *s) { /* I want strprefix() */ size_t i; for(i = 0; s[i]; i++) { if(s[i] != PL_parser->bufptr[i]) return 0; } lex_read_to(PL_parser->bufptr + i); return i; } #define newSTATEOP_nowarnings() MY_newSTATEOP_nowarnings(aTHX) static OP *MY_newSTATEOP_nowarnings(pTHX) { OP *op = newSTATEOP(0, NULL, NULL); STRLEN *warnings = ((COP *)op)->cop_warnings; char *warning_bits; if(warnings == pWARN_NONE) return op; if(warnings == pWARN_STD) /* TODO: understand what STD vs ALL means */ warning_bits = WARN_ALLstring; else if(warnings == pWARN_ALL) warning_bits = WARN_ALLstring; else warning_bits = (char *)(warnings + 1); warnings = Perl_new_warnings_bitfield(aTHX_ warnings, warning_bits, WARNsize); ((COP *)op)->cop_warnings = warnings; warning_bits = (char *)(warnings + 1); warning_bits[Off(2*WARN_EXITING)] &= ~Bit(2*WARN_EXITING); return op; } #define parse_scoped_block(flags) MY_parse_scoped_block(aTHX_ flags) static OP *MY_parse_scoped_block(pTHX_ int flags) { OP *ret; I32 save_ix = block_start(TRUE); ret = parse_block(flags); return block_end(save_ix, ret); } static void rethread_op(OP *op, OP *old, OP *new) { if(op->op_next == old) op->op_next = new; switch(OP_CLASS(op)) { case OA_LOGOP: if(cLOGOPx(op)->op_other == old) cLOGOPx(op)->op_other = new; break; case OA_LISTOP: if(cLISTOPx(op)->op_last == old) cLISTOPx(op)->op_last = new; break; } if(op->op_flags & OPf_KIDS) { OP *kid; for(kid = cUNOPx(op)->op_first; kid; kid = OpSIBLING(kid)) rethread_op(kid, old, new); } } #define walk_optree_try_in_eval(op_ptr, root) MY_walk_optree_try_in_eval(aTHX_ op_ptr, root) static void MY_walk_optree_try_in_eval(pTHX_ OP **op_ptr, OP *root); static void MY_walk_optree_try_in_eval(pTHX_ OP **op_ptr, OP *root) { OP *op = *op_ptr; switch(op->op_type) { /* Fix 'return' to unwind the CXt_EVAL block that implements try{} first */ case OP_RETURN: op->op_ppaddr = &pp_returnintry; break; /* wrap no warnings 'exiting' around loop controls */ case OP_NEXT: case OP_LAST: case OP_REDO: { #ifdef HAVE_OP_SIBPARENT OP *parent = OpHAS_SIBLING(op) ? NULL : op->op_sibparent; #endif OP *stateop = newSTATEOP_nowarnings(); OP *scope = newLISTOP(OP_SCOPE, 0, stateop, op); #ifdef HAVE_OP_SIBPARENT if(parent) OpLASTSIB_set(scope, parent); else OpLASTSIB_set(scope, NULL); #else op->op_sibling = NULL; #endif /* Rethread */ scope->op_next = stateop; stateop->op_next = op; *op_ptr = scope; } break; /* Don't enter inside nested eval{} blocks */ case OP_LEAVETRY: return; } if(op->op_flags & OPf_KIDS) { OP *kid, *next, *prev = NULL; for(kid = cUNOPx(op)->op_first; kid; kid = next) { OP *newkid = kid; next = OpSIBLING(kid); walk_optree_try_in_eval(&newkid, root); if(newkid != kid) { rethread_op(root, kid, newkid); if(prev) { OpMORESIB_set(prev, newkid); } else cUNOPx(op)->op_first = newkid; if(next) OpMORESIB_set(newkid, next); } prev = kid; } } } static OP *pp_entertrycatch(pTHX) { /* Localise the errgv */ save_scalar(PL_errgv); return PL_ppaddr[OP_ENTERTRY](aTHX); } static XOP xop_catch; static OP *pp_catch(pTHX) { /* If an error didn't happen, then ERRSV will be both not true and not a * reference. If it's a reference, then an error definitely happened */ if(SvROK(ERRSV) || SvTRUE(ERRSV)) return cLOGOP->op_other; else return cLOGOP->op_next; } /* A variant of OP_LEAVE which keeps the values on the stack */ static OP *pp_leave_keeping_stack(pTHX) { dounwind_keeping_stack(cxstack_ix - 1); return cUNOP->op_next; } #define newENTERTRYCATCHOP(try, catch) MY_newENTERTRYCATCHOP(aTHX_ try, catch) static OP *MY_newENTERTRYCATCHOP(pTHX_ OP *try, OP *catch) { OP *enter, *ret; /* Walk the block for OP_RETURN ops, so we can apply a hack to them to * make * try { return } * return from the containing sub, not just the eval block */ walk_optree_try_in_eval(&try, try); enter = newUNOP(OP_ENTERTRY, 0, try); /* despite calling newUNOP(OP_ENTERTRY,...) the returned root node is the * OP_LEAVETRY, whose first child is the ENTERTRY we wanted */ ((UNOP *)enter)->op_first->op_ppaddr = &pp_entertrycatch; ret = newLOGOP(OP_CUSTOM, 0, enter, newLISTOP(OP_SCOPE, 0, catch, NULL) ); /* the returned op is actually an UNOP that's either NULL or NOT; the real * logop is the op_next of it */ cUNOPx(ret)->op_first->op_ppaddr = &pp_catch; return ret; } static int try_keyword(pTHX_ OP **op) { OP *try = NULL, *catch = NULL; CV *finally = NULL; OP *ret = NULL; bool is_value = FALSE; HV *hints = GvHV(PL_hintgv); lex_read_space(0); if(hints && hv_fetchs(hints, "Syntax::Keyword::Try/try_value", 0) && lex_consume("do")) { lex_read_space(0); is_value = TRUE; #ifdef WARN_EXPERIMENTAL Perl_ck_warner(aTHX_ packWARN(WARN_EXPERIMENTAL), "'try do' syntax is experimental and may be changed or removed without notice"); #endif } if(lex_peek_unichar(0) != '{') croak("Expected try to be followed by '{'"); try = parse_scoped_block(0); lex_read_space(0); if(lex_consume("catch")) { lex_read_space(0); catch = parse_scoped_block(0); lex_read_space(0); } if(lex_consume("finally")) { I32 floor_ix, save_ix; OP *body; #if !PERL_VERSION_GE(5,24,0) if(is_value) croak("try do {} finally {} is not supported on this version of perl"); #endif lex_read_space(0); floor_ix = start_subparse(FALSE, CVf_ANON); SAVEFREESV(PL_compcv); save_ix = block_start(0); body = parse_block(0); SvREFCNT_inc(PL_compcv); body = block_end(save_ix, body); finally = newATTRSUB(floor_ix, NULL, NULL, NULL, body); lex_read_space(0); } if(!catch && !finally) { op_free(try); croak("Expected try {} to be followed by either catch {} or finally {}"); } ret = try; if(catch) { ret = newENTERTRYCATCHOP(try, catch); } /* If there's a finally, make * $RET = OP_PUSHFINALLY($FINALLY); $RET */ if(finally) { ret = op_prepend_elem(OP_LINESEQ, newPUSHFINALLYOP(finally), ret); } ret = op_append_list(OP_LEAVE, newOP(OP_ENTER, 0), ret); if(is_value) ret->op_ppaddr = &pp_leave_keeping_stack; *op = ret; return is_value ? KEYWORD_PLUGIN_EXPR : KEYWORD_PLUGIN_STMT; } static int (*next_keyword_plugin)(pTHX_ char *, STRLEN, OP **); static int my_keyword_plugin(pTHX_ char *kw, STRLEN kwlen, OP **op) { HV *hints; if(PL_parser && PL_parser->error_count) return (*next_keyword_plugin)(aTHX_ kw, kwlen, op); if(!(hints = GvHV(PL_hintgv))) return (*next_keyword_plugin)(aTHX_ kw, kwlen, op); if(kwlen == 3 && strEQ(kw, "try") && hv_fetchs(hints, "Syntax::Keyword::Try/try", 0)) return try_keyword(aTHX_ op); return (*next_keyword_plugin)(aTHX_ kw, kwlen, op); } MODULE = Syntax::Keyword::Try PACKAGE = Syntax::Keyword::Try BOOT: XopENTRY_set(&xop_catch, xop_name, "catch"); XopENTRY_set(&xop_catch, xop_desc, "optionally invoke the catch block if required"); XopENTRY_set(&xop_catch, xop_class, OA_LOGOP); Perl_custom_op_register(aTHX_ &pp_catch, &xop_catch); XopENTRY_set(&xop_pushfinally, xop_name, "pushfinally"); XopENTRY_set(&xop_pushfinally, xop_desc, "arrange for a CV to be invoked at scope exit"); XopENTRY_set(&xop_pushfinally, xop_class, OA_SVOP); Perl_custom_op_register(aTHX_ &pp_pushfinally, &xop_pushfinally); wrap_keyword_plugin(&my_keyword_plugin, &next_keyword_plugin); Syntax-Keyword-Try-0.11/t000755001750001750 013534573717 14122 5ustar00leoleo000000000000Syntax-Keyword-Try-0.11/t/00use.t000444001750001750 15613534573717 15362 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( "Syntax::Keyword::Try" ); done_testing; Syntax-Keyword-Try-0.11/t/01trycatch.t000444001750001750 243413534573717 16431 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try success { my $s; try { $s = 1; } catch { $s = 2; } is( $s, 1, 'sucessful try{} runs' ); } # try catches { my $s; ok( eval { try { die "oopsie"; } catch { } $s = 3; "ok"; }, 'try { die } is not fatal' ); is( $s, 3, 'code after try{} runs' ); } # exceptions that are false { my $caught; try { die FALSE->new; } catch { $caught++; } ok( $caught, 'catch{} sees a false exception' ); { package FALSE; use overload 'bool' => sub { 0 }; sub new { bless [], shift } } } # catch sees $@ { my $e; try { die "oopsie"; } catch { $e = $@; } like( $e, qr/^oopsie at /, 'catch{} sees $@' ); } # catch block executes { my $s; try { die "oopsie"; } catch { $s = 4; } is( $s, 4, 'catch{} of failed try{} runs' ); } # catch can rethrow { my $caught; ok( !eval { try { die "oopsie"; } catch { $caught = $@; die $@ } }, 'die in catch{} is fatal' ); my $e = $@; like( $e, qr/^oopsie at /, 'exception is thrown' ); like( $caught, qr/^oopsie at /, 'exception was seen by catch{}' ); } done_testing; Syntax-Keyword-Try-0.11/t/02tryfinally.t000444001750001750 222713534573717 17006 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try success { my $s; try { $s = 1; } finally { $s = 2; } is( $s, 2, 'sucessful try{} runs finally{}' ); } # try failure { my $s; my $e; ok( !eval { try { die "oopsie"; } finally { $e = $@; $s = 3; } }, 'failed try{} throws' ); my $dollarat = $@; is( $s, 3, 'failed try{} runs finally{}' ); like( $e, qr/^oopsie at /, 'finally{} sees $@' ); like( $dollarat, qr/^oopsie at /, 'try/finally leaves $@ intact' ); } # finally runs on 'return' { my $final; ( sub { try { return; } finally { $final++; } } )->(); ok( $final, 'finally{} runs after return' ); } # finally runs on 'goto' { my $final; try { goto after; } finally { $final++; } after: ok( $final, 'finally{} runs after goto' ); } # finally runs on 'last' { my $final; LOOP: { try { last LOOP; } finally { $final++; } } ok( $final, 'finally{} runs after last' ); } done_testing; Syntax-Keyword-Try-0.11/t/03trycatchfinally.t000444001750001750 72213534573717 17770 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try success { my $s; try { $s = 1; # overwritten } catch { die "FAIL"; } finally { $s = 2; } is( $s, 2, 't/c/f runs finally' ); } # try failure { my $s; try { die "oopsie"; } catch { $s = 3; } finally { $s++; } is( $s, 4, 't/c/f runs catch{} and finally{} on failure' ); } done_testing; Syntax-Keyword-Try-0.11/t/10snail.t000444001750001750 70213534573717 15672 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try gets @_ { my @args; ( sub { try { @args = @_ } catch {} } )->( 1, 2, 3 ); is_deeply( \@args, [ 1, 2, 3 ], 'try{} sees surrounding @_' ); } # catch sees @_ { my @args; ( sub { try { die "oopsie" } catch { @args = @_ } } )->( 4, 5, 6 ); is_deeply( \@args, [ 4, 5, 6 ], 'catch{} sees @_' ); } done_testing; Syntax-Keyword-Try-0.11/t/11loop.t000444001750001750 164413534573717 15564 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try can apply loop controls { my $count = 0; LOOP: { try { $count++; redo LOOP if $count < 2; } catch { } } is( $count, 2, 'try{redo} works' ); $count = 0; my $after = 0; LOOP2: { try { last LOOP2; $after++; # just to put a statement after 'last' } catch { } $count++; } is( $count, 0, 'try{last} works' ); } # catch can apply loop controls { my $count = 0; LOOP: { try { die "oopsie"; } catch { $count++; redo LOOP if $count < 2; } } is( $count, 2, 'catch{redo} works' ); $count = 0; LOOP2: { try { die "oopsie"; } catch { last LOOP2; } $count++; } is( $count, 0, 'catch{last} works' ); } done_testing; Syntax-Keyword-Try-0.11/t/12return.t000444001750001750 332613534573717 16132 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # return from try { my $after; is( ( sub { try { return "result" } catch {} $after++; return "nope"; } )->(), "result", 'return in try leaves containing function' ); ok( !$after, 'code after try{return} is not invoked' ); } # return LIST from try { is_deeply( [ sub { try { return qw( A B C ) } catch {} }->() ], [qw( A B C )], 'return LIST in try yields correct values' ); } # return from two nested try{}s { my $after; is( ( sub { try { try { return "result" } catch {} } catch {} $after++; return "nope"; } )->(), "result", 'return in try{try{}} leaves containing function' ); ok( !$after, 'code after try{try{return}} is not invoked' ); } # return inside eval{} inside try{} { is( ( sub { my $two; try { my $one = eval { return 1 }; $two = $one + 1; } catch {} return $two; } )->(), 2, 'return in eval{} inside try{} behaves as expected' ); } # return inside try{} inside eval{} { is( ( sub { my $ret = eval { try { return "part"; } catch {} }; return "($ret)"; } )->(), "(part)", 'return in try{} inside eval{}' ); } # return from catch { is( ( sub { try { die "oopsie" } catch { return "result" } return "nope"; } )->(), "result", 'return in catch leaves containing function' ); } done_testing; Syntax-Keyword-Try-0.11/t/13die-in-finally.t000444001750001750 64513534573717 17376 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # finally does not disturb $@ { local $SIG{__WARN__} = sub {}; ok( !eval { try { die "oopsie"; } finally { die "double oops"; } 1; }, 'die in both try{} and finally{} is still fatal' ); like( $@, qr/^oopsie at /, 'die in finally{} does not corrupt $@' ); } done_testing; Syntax-Keyword-Try-0.11/t/14try-localises.t000444001750001750 50213534573717 17360 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; # try/catch localises $@ (RT118415) { eval { die "oopsie" }; like( $@, qr/^oopsie at /, '$@ before try/catch' ); try { die "another failure" } catch {} like( $@, qr/^oopsie at /, '$@ after try/catch' ); } done_testing; Syntax-Keyword-Try-0.11/t/20try-do.t000444001750001750 330013534573717 16020 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use constant HAVE_WARN_EXPERIMENTAL => $] >= 5.018; no if HAVE_WARN_EXPERIMENTAL, warnings => 'experimental'; use Syntax::Keyword::Try qw( try try_value ); # try do { } yields result { is( try do { "result" } catch {}, "result", 'try do { } yields result' ); } # try do { } failure returns catch { is( try do { die "oops\n" } catch { "failure" }, "failure", 'try do { } yields catch result on failure' ); } # stack discipline { my @v = ( 1, [ 2, try do { 3 } catch {}, 4 ], 5 ); is_deeply( \@v, [ 1, [ 2 .. 4 ], 5 ], 'try do { } preserves stack discipline' ) or diag "Got ", explain \@v; } # list context { local $TODO = "list context"; no warnings 'void'; my @v = try do { 1, 2, 3 } catch {}; is_deeply( \@v, [ 1 .. 3 ], 'try do can yield lists' ); } # $@ localising SKIP: { # RT124366 skip "perls before 5.24 fail to lexicalise \$@ properly (RT124366)", 1 unless $] >= 5.024; eval { die "oopsie" }; my $ret = try do { die "another failure" } catch {}; like( $@, qr/^oopsie at /, '$@ after try do/catch' ); } # Non-try do { ... } unaffected { is( do { 1 + 2 }, 3, 'Plain do { ... } unaffected' ); } # try do syntax produces experimental warnings SKIP: { use if HAVE_WARN_EXPERIMENTAL, warnings => 'experimental'; skip "No 'experimental' warnings category", 1 unless HAVE_WARN_EXPERIMENTAL; my $warnings = ""; local $SIG{__WARN__} = sub { $warnings .= join "", @_ }; eval "try do { 1 } catch { 2 }" or die $@; like( $warnings, qr/^'try do' syntax is experimental/, 'try do syntax produces experimental warnings' ); } done_testing; Syntax-Keyword-Try-0.11/t/21try-do-finally.t000444001750001750 165213534573717 17465 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; BEGIN { # Before 5.24 this code won't even compile plan skip_all => "try do { } finally { } is not supported before perl 5.24" if $] < 5.024; } use constant HAVE_WARN_EXPERIMENTAL => $] >= 5.018; no if HAVE_WARN_EXPERIMENTAL, warnings => 'experimental'; use Syntax::Keyword::Try qw( try try_value ); # try do { } finally { } { my $x; my $result = try do { $x .= 1; "result" } finally { $x .= 2 }, $x .= 3; is( $result, "result", 'try do { } finally yields result' ); is( $x, "123", 'try do {} finally has finally side-effect' ); } # try do { } catch { } finally { } { my $x; my $result = try do { $x .= 4; die "oops" } catch { $x .= 5; "failure" } finally { $x .= 6 }; is( $result, "failure", 'try do {} catch finally catches exception' ); is( $x, "456", 'try do {} catch finally has finally side-effect' ); } done_testing; Syntax-Keyword-Try-0.11/t/80await+try.t000444001750001750 417713534573717 16544 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; BEGIN { plan skip_all => "Future is not available" unless eval { require Future }; plan skip_all => "Future::AsyncAwait >= 0.10 is not available" unless eval { require Future::AsyncAwait; Future::AsyncAwait->VERSION( '0.10' ) }; plan skip_all => "Syntax::Keyword::Try >= 0.07 is not available" unless eval { require Syntax::Keyword::Try; Syntax::Keyword::Try->VERSION( '0.07' ) }; Future::AsyncAwait->import; Syntax::Keyword::Try->import; diag( "Future::AsyncAwait $Future::AsyncAwait::VERSION, " . "Syntax::Keyword::Try $Syntax::Keyword::Try::VERSION" ); } # await in try/catch { async sub with_trycatch { my $f = shift; my $ret; try { await $f; $ret = "result"; } catch { $ret = "oopsie"; } return $ret; } my $f1 = Future->new; my $fdone = with_trycatch( $f1 ); $f1->done; is( scalar $fdone->get, "result", '$fdone for successful await in try/catch' ); my $f2 = Future->new; my $ffail = with_trycatch( $f2 ); $f2->fail( "fail" ); is( scalar $ffail->get, "oopsie", '$ffail for failed await in try/catch' ); } # await in try/catch with return { my $fellthrough; async sub with_trycatch_return { my $f = shift; try { await $f; return "result"; } catch {} $fellthrough++; return "fallthrough"; } my $f1 = Future->new; my $fdone = with_trycatch_return( $f1 ); $f1->done; is( scalar $fdone->get, "result", '$fdone for successful await in try/catch with return' ); ok( !$fellthrough, 'fallthrough after try{return} did not happen' ); } # await in try/finally { async sub with_tryfinally { my $f = shift; my $ret = ""; try { await $f; $ret .= "T"; } finally { $ret .= "F"; } return $ret; } my $f1 = Future->new; my $fret = with_tryfinally( $f1 ); $f1->done; is( scalar $fret->get, "TF", '$fret for await in try/finally' ); } done_testing; Syntax-Keyword-Try-0.11/t/90rt123547.t000444001750001750 176313534573717 15737 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; # RT123547 observes that if S:K:T is loaded late after multiple threads # are actually started, it will crash BEGIN { eval { require threads; threads->import; 1 } or plan skip_all => "threads are not supported"; } # Start two threads doing the same thing concurrently and hope we get # to the end my @threads = map { threads->create( sub { my $x; # We have to late-load the module and then demonstrate that it works # Because of late loading we couldn't have written normal code here, so # we'll string-eval it eval <<'EOPERL' use Syntax::Keyword::Try; try { $x = "a"; die "oops"; } catch { $x .= "b"; } finally { $x .= "c"; } 1; EOPERL or die "Failed - $@"; return $x; } ); } 1 .. 2; is( $_->join, "abc", 'try/catch/finally correct result' ) for @threads; pass "Did not crash"; done_testing; Syntax-Keyword-Try-0.11/t/90rt125971.t000444001750001750 134513534573717 15736 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use Syntax::Keyword::Try; sub inner { my $canary = Canary->new; # if this line is commented, nothing happens try { return 123; } catch { die "Something terrible happened: $@"; } } sub outer { my @result; try { @result = (1, scalar inner()); # scalar or void context is mandatory 1; # or catch will be triggered } catch { die "Something terrible happened: $@"; } return @result; } is_deeply [ outer() ], [ 1, 123 ], "No extra data in return"; done_testing; package Canary; sub new { bless {}, shift; } sub DESTROY { my $x; # Destructor MUST be nonempty $@ = "oops"; # Assigning to $@ is optional } Syntax-Keyword-Try-0.11/t/99pod.t000444001750001750 25713534573717 15374 0ustar00leoleo000000000000#!/usr/bin/perl use strict; 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();