Syntax-Keyword-Try-0.09000755001750001750 013200613021 13633 5ustar00leoleo000000000000Syntax-Keyword-Try-0.09/Build.PL000444001750001750 106013200613021 15261 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.09/Changes000444001750001750 400613200613021 15263 0ustar00leoleo000000000000Revision history for Syntax-Keyword-Try 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.09/LICENSE000444001750001750 4376213200613021 15031 0ustar00leoleo000000000000This software is copyright (c) 2017 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) 2017 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) 2017 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.09/MANIFEST000444001750001750 47313200613021 15105 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/80await+try.t t/90rt123547.t t/99pod.t Syntax-Keyword-Try-0.09/META.json000444001750001750 225213200613021 15412 0ustar00leoleo000000000000{ "abstract" : "a C syntax for perl", "author" : [ "Paul Evans " ], "dynamic_config" : 1, "generated_by" : "Module::Build version 0.422", "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.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 2.94" } Syntax-Keyword-Try-0.09/META.yml000444001750001750 132413200613021 15241 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.422, 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.09' requires: 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-Try-0.09/README000444001750001750 2362013200613021 14673 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 preceeding 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 preceeding 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 preceeding 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 preceeding 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. TODO * Value semantics. It would be nice if a do {}-wrapped try set could yield a value, in the way other similar constructs can. For example my $x = do { try { attempt(); "success" } catch { "failure" } }; A workaround for this current lack is to wrap the try{} catch{} pair in an anonymous function which is then immediately executed: my $x = sub { try { attempt(); return "success" } catch { return "failure" } }->(); See also https://rt.cpan.org/Ticket/Display.html?id=121267. 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; 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. See above for a workaround involving an anonymous sub however. 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. 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. 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) 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.09/lib000755001750001750 013200613021 14401 5ustar00leoleo000000000000Syntax-Keyword-Try-0.09/lib/Syntax000755001750001750 013200613021 15667 5ustar00leoleo000000000000Syntax-Keyword-Try-0.09/lib/Syntax/Keyword000755001750001750 013200613021 17313 5ustar00leoleo000000000000Syntax-Keyword-Try-0.09/lib/Syntax/Keyword/Try.pm000444001750001750 2471113200613021 20611 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-2017 -- leonerd@leonerd.org.uk package Syntax::Keyword::Try; use strict; use warnings; our $VERSION = '0.09'; 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 preceeding 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 preceeding 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 preceeding 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 preceeding 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. =cut =head1 TODO =over 2 =item * Value semantics. It would be nice if a C-wrapped C set could yield a value, in the way other similar constructs can. For example my $x = do { try { attempt(); "success" } catch { "failure" } }; A workaround for this current lack is to wrap the C pair in an anonymous function which is then immediately executed: my $x = sub { try { attempt(); return "success" } catch { return "failure" } }->(); See also L. =back =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; 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. See above for a workaround involving an anonymous sub however. 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. =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}; croak "Unrecognised import symbols @{[ keys %syms ]}" if keys %syms; } =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) =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.09/lib/Syntax/Keyword/Try.xs000444001750001750 2731313200613021 20630 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-2017 -- leonerd@leonerd.org.uk */ #include "EXTERN.h" #include "perl.h" #include "XSUB.h" #ifndef OP_CHECK_MUTEX_LOCK /* < 5.15.8 */ #define OP_CHECK_MUTEX_LOCK ((void)0) #define OP_CHECK_MUTEX_UNLOCK ((void)0) #endif /* 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,19,4) typedef SSize_t array_ix_t; #else /* <5.19.4 */ typedef I32 array_ix_t; #endif /* <5.19.4 */ static OP *pp_entertrycatch(pTHX); /* * 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; I32 gimme; SV *retval; 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_OR 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_OR && (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"); /* Before we unwind the stack we must preserve the value(s) being returned */ /* 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; } } 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: { OP *stateop, *afterop = OpSIBLING(op); *op_ptr = newLISTOP(OP_SCOPE, 0, stateop = newSTATEOP_nowarnings(), op); (*op_ptr)->op_next = stateop; stateop->op_next = op; if(afterop) { OpMORESIB_set(op, NULL); OpMORESIB_set(*op_ptr, afterop); } } 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; OpMORESIB_set(newkid, next); } prev = kid; } } } /* We call this op entertrycatch to distinguish it from core perl's entertry. * It doesn't actually implement the catch behaviour */ static OP *pp_entertrycatch(pTHX) { return PL_ppaddr[OP_ENTERTRY](aTHX); } #define newENTERTRYCATCHOP(try, catch) MY_newENTERTRYCATCHOP(aTHX_ try, catch) static OP *MY_newENTERTRYCATCHOP(pTHX_ OP *try, OP *catch) { OP *enter; /* 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, op_append_elem(OP_LINESEQ, try, newSVOP(OP_CONST, 0, &PL_sv_yes) ) ); /* 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; return newLOGOP(OP_OR, 0, enter, newLISTOP(OP_SCOPE, 0, catch, NULL) ); } static int try_keyword(pTHX_ OP **op) { OP *try = NULL, *catch = NULL; CV *finally = NULL; OP *ret = NULL; lex_read_space(0); if(lex_peek_unichar(0) != '{') croak("Expected try 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; 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 there's a catch block, make * $RET = eval { $TRY; 1 } or do { $CATCH } */ if(catch) { ret = newENTERTRYCATCHOP(try, catch); /* localise $@ beforehand */ ret = op_prepend_elem(OP_LINESEQ, newLOCALISEOP(PL_errgv), ret); } /* If there's a finally, make * $RET = OP_PUSHFINALLY($FINALLY); $RET */ if(finally) { ret = op_prepend_elem(OP_LINESEQ, newPUSHFINALLYOP(finally), ret); } /* If there's either catch or finally, block-wrap the result */ if(catch || finally) { ret = newLISTOP(OP_LEAVE, 0, op_prepend_elem(OP_LINESEQ, newOP(OP_ENTER, 0), ret), NULL); } *op = ret; return 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: /* 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 */ OP_CHECK_MUTEX_LOCK; if(!next_keyword_plugin) { next_keyword_plugin = PL_keyword_plugin; PL_keyword_plugin = &my_keyword_plugin; 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); } OP_CHECK_MUTEX_UNLOCK; Syntax-Keyword-Try-0.09/t000755001750001750 013200613021 14076 5ustar00leoleo000000000000Syntax-Keyword-Try-0.09/t/00use.t000444001750001750 15613200613021 15336 0ustar00leoleo000000000000#!/usr/bin/perl use strict; use warnings; use Test::More; use_ok( "Syntax::Keyword::Try" ); done_testing; Syntax-Keyword-Try-0.09/t/01trycatch.t000444001750001750 243413200613021 16405 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.09/t/02tryfinally.t000444001750001750 222713200613021 16762 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.09/t/03trycatchfinally.t000444001750001750 72213200613021 17744 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.09/t/10snail.t000444001750001750 70213200613021 15646 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.09/t/11loop.t000444001750001750 164413200613021 15540 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.09/t/12return.t000444001750001750 332613200613021 16106 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.09/t/13die-in-finally.t000444001750001750 64513200613021 17352 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.09/t/14try-localises.t000444001750001750 50213200613021 17334 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.09/t/80await+try.t000444001750001750 377513200613021 16523 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; } # 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.09/t/90rt123547.t000444001750001750 176313200613021 15713 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.09/t/99pod.t000444001750001750 25713200613021 15350 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();