Lexical-Failure-0.001001/000755 000765 000024 00000000000 14451122416 015275 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/tlib/000755 000765 000024 00000000000 14451122416 016227 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/Changes000644 000765 000024 00000003173 14451122415 016573 0ustar00damianstaff000000 000000 Revision history for Lexical-Failure 0.000001 Fri Feb 1 16:02:07 2013 Initial release. 0.000002 Mon Jul 29 07:32:42 2013 No changes logged 0.000003 Mon Jul 29 07:41:50 2013 - Reformatted test modules to make them invisible to CPAN indexer 0.000004 Fri Aug 2 18:49:10 2013 - Fixed 'make test' bug (Many thanks, Doran and Vincent!) 0.000005 Mon Dec 30 08:23:01 2013 - Fixed POD linking bugs (thanks, Darin!) - Undid workarounds for out-by-one line-number errors in Keyword::Simple v0.01 (now require v0.02) 0.000006 Sat May 3 10:59:58 2014 - Fixed documentation typos (thanks, Laurent) - Coded around mysterious problems with Test::Effects under 5.19+ (thanks Slaven!) 0.000007 Thu Nov 13 16:09:17 2014 - Simplified and sharpened t/inner_scalar.t which also removed the requirement for PadWalker (thanks Father C!) 0.001000 Tue Jul 4 17:54:22 2023 - [POTENTIALLY INCOMPATIBLE CHANGE] As it makes no sense to use fail() for error-signalling in non-API-level subroutines, fail() now always fails at the API level (i.e. at the level of the call stack where control leaves the current package). In other words, calling fail() in a nested subroutine within a package, fails the subroutine where we first entered the package. See the documentation for details. (Many thanks, Konrad!) - Removed all use of smartmatching and given/when for 5.38 compatibility 0.001001 Wed Jul 5 09:02:37 2023 - Shrouded new internal 'package Carp' declarations from CPAN (Sorry, Neil. Sorry, Andreas.) Lexical-Failure-0.001001/MANIFEST000644 000765 000024 00000000774 14451122416 016436 0ustar00damianstaff000000 000000 Changes lib/Lexical/Failure.pm lib/Lexical/Failure/Objects.pm Makefile.PL MANIFEST README t/00.load.t t/aliased.t t/context.t t/default.t t/error_runtime_setter.t t/extras.t t/implicit_croak.t t/inner_scalar.t t/simple.t tlib/AliasModule.pm tlib/DefaultModule.pm tlib/ExtrasModule.pm tlib/SetterErrorModule.pm tlib/TestModule.pm t/nested.t META.yml Module YAML meta-data (added by MakeMaker) META.json Module JSON meta-data (added by MakeMaker) Lexical-Failure-0.001001/t/000755 000765 000024 00000000000 14451122416 015540 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/README000644 000765 000024 00000003730 14451122415 016157 0ustar00damianstaff000000 000000 Lexical::Failure version 0.001001 This module sets up two new keywords: C and C, with which you can quickly create modules whose failure signaling is lexcially scoped, under the control of client code. Normally, modules specify some fixed mechanism for error handling and require client code to adapt to that policy. One module may signal errors by returning C, or perhaps some special "error object". Another may C or C on failure. A third may set a flag variable. A fourth may require the client code to set up a callback, which is executed on failure. If you are using all four modules, your own code now has to check for failure in four different ways, depending on where the failing component originated. If you would rather that I components throw exceptions, or all return C, you will probably have to write wrappers around 3/4 of them, to convert from their "native" failure mechanism to your preferred one. Lexical::Failure offers an alternative: a simple mechanism with which module authors can generically specify "fail here with this message" (using the C keyword), but then allow each block of client code to decide how that failure is reported to it within its own lexical scope (using the C keyword). Module authors can still provide a default failure signaling mechanism, for when client code does not specify how errors are to be reported. This is handy for ensuring backwards compatibility in existing modules that are converted to this new failure signaling approach. INSTALLATION To install this module, run the following commands: perl Makefile.PL make make test make install Alternatively, to install with Module::Build, you can use the following commands: perl Build.PL ./Build ./Build test ./Build install DEPENDENCIES None. COPYRIGHT AND LICENCE Copyright (C) 2013, Damian Conway This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself. Lexical-Failure-0.001001/META.yml000644 000765 000024 00000001277 14451122416 016555 0ustar00damianstaff000000 000000 --- abstract: 'User-selectable lexically-scoped failure signaling' author: - 'Damian Conway ' build_requires: ExtUtils::MakeMaker: '0' configure_requires: ExtUtils::MakeMaker: '0' dynamic_config: 1 generated_by: 'ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010' license: artistic_2 meta-spec: url: http://module-build.sourceforge.net/META-spec-v1.4.html version: '1.4' name: Lexical-Failure no_index: directory: - t - inc requires: Hash::Util::FieldHash: '0' Keyword::Simple: '0.02' Scope::Upper: '0' Test::Effects: '0' Test::More: '0' perl: '5.014' version: '0.001001' x_serialization_backend: 'CPAN::Meta::YAML version 0.018' Lexical-Failure-0.001001/lib/000755 000765 000024 00000000000 14451122416 016043 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/Makefile.PL000644 000765 000024 00000001352 14451122217 017247 0ustar00damianstaff000000 000000 use strict; use warnings; use ExtUtils::MakeMaker; WriteMakefile( NAME => 'Lexical::Failure', AUTHOR => 'Damian Conway ', VERSION_FROM => 'lib/Lexical/Failure.pm', ABSTRACT_FROM => 'lib/Lexical/Failure.pm', PL_FILES => {}, LICENSE => 'artistic2', MIN_PERL_VERSION => 5.014, PREREQ_PM => { 'Test::More' => 0, 'Test::Effects' => 0, 'Scope::Upper' => 0, 'Keyword::Simple' => 0.02, 'Hash::Util::FieldHash' => 0, }, dist => { COMPRESS => 'gzip -9f', SUFFIX => 'gz', }, clean => { FILES => 'Lexical-Failure-*' }, ); Lexical-Failure-0.001001/META.json000644 000765 000024 00000002171 14451122416 016717 0ustar00damianstaff000000 000000 { "abstract" : "User-selectable lexically-scoped failure signaling", "author" : [ "Damian Conway " ], "dynamic_config" : 1, "generated_by" : "ExtUtils::MakeMaker version 7.64, CPAN::Meta::Converter version 2.150010", "license" : [ "artistic_2" ], "meta-spec" : { "url" : "http://search.cpan.org/perldoc?CPAN::Meta::Spec", "version" : 2 }, "name" : "Lexical-Failure", "no_index" : { "directory" : [ "t", "inc" ] }, "prereqs" : { "build" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "configure" : { "requires" : { "ExtUtils::MakeMaker" : "0" } }, "runtime" : { "requires" : { "Hash::Util::FieldHash" : "0", "Keyword::Simple" : "0.02", "Scope::Upper" : "0", "Test::Effects" : "0", "Test::More" : "0", "perl" : "5.014" } } }, "release_status" : "stable", "version" : "0.001001", "x_serialization_backend" : "JSON::PP version 4.10" } Lexical-Failure-0.001001/lib/Lexical/000755 000765 000024 00000000000 14451122416 017424 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/lib/Lexical/Failure.pm000644 000765 000024 00000073073 14451122415 021362 0ustar00damianstaff000000 000000 package Lexical::Failure; use 5.014; use warnings; no if $] >= 5.018, 'warnings', "experimental"; use Scope::Upper qw< want_at unwind uplevel CALLER UP SUB >; use Carp qw< carp croak confess cluck >; use Keyword::Simple; use Attribute::Handlers; use Lexical::Failure::Objects; our $VERSION = '0.001001'; # Be invisible to Carp... our @CARP_NOT = __PACKAGE__; # Lexical hints are always at index 10 of caller()... my $HINTS = 10; # How to fail... my %STD_FAILURE_HANDLERS = ( 'die' => sub { _uplevel_die(@_); }, 'croak' => sub { package # Hide this from CPAN indexer Carp; uplevel { croak(@_) } @_, CALLER($Lexical::Failure::uplevel); }, 'confess' => sub { package # Hide this from CPAN indexer Carp; uplevel { confess(@_) } @_, CALLER($Lexical::Failure::uplevel); }, 'null' => sub { return; }, 'undef' => sub { return undef; }, 'failobj' => sub { uplevel { croak(@_) } @_, CALLER($Lexical::Failure::uplevel) if !defined wantarray; return Lexical::Failure::Objects->new( msg => (@_==1 ? $_[0] : "@_"), context => [caller $Lexical::Failure::uplevel], ); }, ); # Track handlers for lexical installations of fail() my @ACTIVE_FAILURE_HANDLER_FOR_SCOPE; my @VALID_FAILURE_HANDLERS_FOR_SCOPE; # # 'croak' is the universal default failure handler... my $DEF_NAMED_HANDLER = 'croak'; my $DEFAULT_SCOPE_ID = 0; $ACTIVE_FAILURE_HANDLER_FOR_SCOPE[$DEFAULT_SCOPE_ID] = $STD_FAILURE_HANDLERS{$DEF_NAMED_HANDLER}; # Load the module... sub import { my ($fail, $ON_FAILURE, $default, $handlers) = _process_import_args(@_); # Export API... Keyword::Simple::define $ON_FAILURE, _replace_keyword_with('Lexical::Failure::ON_FAILURE'); Keyword::Simple::define $fail, _replace_keyword_with('Lexical::Failure::fail'); # Install specified failure handlers for the caller's scope... my $handlers_scope_ID = scalar @VALID_FAILURE_HANDLERS_FOR_SCOPE; $^H{'Lexical::Failure::handlers_scope_ID'} = $handlers_scope_ID; push @VALID_FAILURE_HANDLERS_FOR_SCOPE, { %STD_FAILURE_HANDLERS, %{$handlers} }; # Install default failure handler for the caller's scope... if (ref($default) ne 'CODE') { croak "Unknown default failure handler: '$default'" if !exists $VALID_FAILURE_HANDLERS_FOR_SCOPE[-1]{$default}; $default = $VALID_FAILURE_HANDLERS_FOR_SCOPE[-1]{$default}; } my $default_scope_ID = scalar @ACTIVE_FAILURE_HANDLER_FOR_SCOPE; $^H{'Lexical::Failure::default_scope_ID'} = $default_scope_ID; push @ACTIVE_FAILURE_HANDLER_FOR_SCOPE, $default; return; } sub _process_import_args { my $package = shift; # What we're looking for (and their values if we don't find them)... my $fail = 'fail'; my $ON_FAILURE = 'ON_FAILURE'; my $default = 'croak'; my $handlers = {}; # Trawl through the argument list... while (defined( my $next_arg = shift @_)) { if ($next_arg eq 'fail') { $fail = shift(@_) or croak "Missing rename for 'fail' in use $package"; croak "Value for 'fail' option must be a string" if ref $fail; } elsif ($next_arg eq 'ON_FAILURE') { $ON_FAILURE = shift(@_) or croak "Missing rename for 'fail_width' in use $package"; croak "Value for 'ON_FAILURE' option must be a string" if ref $fail; } elsif ($next_arg eq 'default') { $default = shift(@_) or croak "Missing specification for 'default' in use $package"; croak "Value for 'default' option must be a string or subroutine reference" if ref $fail && ref $fail ne 'CODE'; } elsif ($next_arg eq 'handlers') { $handlers = shift(@_) or croak "Missing specification for 'handlers' in use $package"; croak "Value for 'handlers' option must be a hash reference" if !ref $handlers || ref $handlers ne 'HASH'; croak "Handlers in 'handlers' hash must all be code references" if grep { ref($_) ne 'CODE' } values %{$handlers}; } else { croak "Unexpected argument ($next_arg) in use $package" } } return ($fail, $ON_FAILURE, $default, $handlers); } sub _replace_keyword_with { my $replacement = shift; return sub { my ($src_ref) = @_; substr(${$src_ref}, 0, 0) = $replacement; } } sub ON_FAILURE { my $handler = shift; # No arg or undef arg --> no-op... return if !defined $handler; # Can't be called at runtime... if (${^GLOBAL_PHASE} ne 'START') { croak "Can't call ON_FAILURE after compilation" } # Can't be called outside a subroutine... if ((caller 1)[3] eq '(eval)') { croak "Can't call ON_FAILURE outside a subroutine" } # Can only be called with certain types of arguments... my $handler_type = ref $handler; croak "Invalid handler type ($handler_type ref) in call to ON_FAILURE" if $handler_type !~ m{\A (?: CODE | SCALAR | ARRAY | HASH | (?#STRING) ) \z}xms; # Which package is setting this handler??? my $owner = caller; # Locate valid failure handlers... my $handlers_scope_ID = (caller 0)[$HINTS]{'Lexical::Failure::handlers_scope_ID'}; my $valid_handlers_ref = $VALID_FAILURE_HANDLERS_FOR_SCOPE[$handlers_scope_ID]; # Translate failure handlers (if necessary)... for my $type (ref $handler) { # Find handler for symbolic failure modes ('die', 'confess', etc.)... if ($type eq q{}) { croak "Unknown failure handler: '$handler'" if !exists $valid_handlers_ref->{$handler}; $handler = $valid_handlers_ref->{$handler}; last; } my $target_var = $handler; # _check_scoping_of($target_var); # Experimentally removed (may not be necessary) # Scalars are simply assigned to... if ($type eq 'SCALAR') { $handler = sub { ${$target_var} = [@_]; return; }; last; } # Arrays are simply pushed onto... if ($type eq 'ARRAY') { $handler = sub { push @{$target_var}, [@_]; return; }; last; } # Hashes are simply added to... if ($type eq 'HASH') { $handler = sub { my $caller_sub = (caller 2)[3]; $target_var->{$caller_sub} = [@_]; return; }; last; } } # Install failure handler for the scope... my $scope_ID = scalar @ACTIVE_FAILURE_HANDLER_FOR_SCOPE; $^H{"Lexical::Failure::scope_ID::$owner"} = $scope_ID; push @ACTIVE_FAILURE_HANDLER_FOR_SCOPE, $handler; return; } # Fail by calling the appropriate handler... sub fail { my (@msg) = @_; # Find the requested lexical handler... my $caller = caller; my ($fail_handler, $uplevel) = _find_callers_handler($caller); # Determine original context of sub that's failing... my $context = want_at(CALLER($uplevel-1)); # Ignore this code when croaking/carping from a handler package Carp; # Hide this from CPAN indexer use Scope::Upper qw< unwind CALLER UP SUB>; # Simulate a return... unwind +( do { local $Lexical::Failure::uplevel = $uplevel; !defined $context ? do{ $fail_handler->(@msg); undef; } : ! $context ? scalar $fail_handler->(@msg) : $fail_handler->(@msg) } ) => CALLER($uplevel-1); } # Locate hints hash of first scope outside caller (if any)... sub _find_callers_handler { my ($immediate_caller_package) = @_; # Scope ID for default handler... my $default_scope_ID = (caller 1)[$HINTS]{'Lexical::Failure::default_scope_ID'} // $DEFAULT_SCOPE_ID; # Search upwards for first namespace different from $caller... LEVEL: for my $uplevel (2..10000) { my @uplevel_caller = caller($uplevel); # Give up if no higher contexts... last LEVEL if !@uplevel_caller; # Return handler for first different namespace (or else default handler)... if ($uplevel_caller[0] ne $immediate_caller_package) { my $target_scope_ID = $uplevel_caller[10]{"Lexical::Failure::scope_ID::$immediate_caller_package"} // $default_scope_ID; return $ACTIVE_FAILURE_HANDLER_FOR_SCOPE[ $target_scope_ID ], $uplevel; } } # If no such uplevel context, return a "null" hints hash... return $ACTIVE_FAILURE_HANDLER_FOR_SCOPE[ $default_scope_ID ], 0; } # Simulate a die() called at 2 levels higher up the stack... sub _uplevel_die { my $exception = @_ ? join(q{},@_) : $@ ? qq{$@\t...propagated} : q{Died}; die $exception if ref $exception; if (!ref $exception && substr($exception, -1) ne "\n") { my (undef, $file, $line) = caller(2); $exception .= " at $file line $line\n"; } die $exception; } 1; # Magic true value required at end of module __END__ =head1 NAME Lexical::Failure - User-selectable lexically-scoped failure signaling =head1 VERSION This document describes Lexical::Failure version 0.001001 =head1 SYNOPSIS package Your::Module; # Set up this module for lexical failure handling... use Lexical::Failure; # Each time module is imported, set up failure handler... sub import { my ($package, %named_arg) = @_; ON_FAILURE( $named_arg{'fail'} ); } # Then, in the module's subs/methods, call fail() to fail... sub inverse_square { my ($n) = @_; if ($n == 0) { fail "Can't invert zero"; } return 1/$n**2; } sub load_file { my ($filename) = @_; fail 'No such file: ', $filename if ! -r $filename; local (@ARGV, $/) = $filename; return readline; } =head1 DESCRIPTION This module sets up two new keywords: C and C, with which you can quickly create modules whose failure signaling is lexicially scoped, under the control of client code. Normally, modules specify some fixed mechanism for error handling and require client code to adapt to that policy. One module may signal errors by returning C, or perhaps some special "error object". Another may C or C on failure. A third may set a flag variable. A fourth may require the client code to set up a callback, which is executed on failure. If you are using all four modules, your own code now has to check for failure in four different ways, depending on where the failing component originated. If you would rather that I components throw exceptions, or all return C, you will probably have to write wrappers around 3/4 of them, to convert from their "native" failure mechanism to your preferred one. Lexical::Failure offers an alternative: a simple mechanism with which module authors can generically specify "fail here with this message" (using the C keyword), but then allow each block of client code to decide how that failure is reported to it within its own lexical scope (using the C keyword). Module authors can still provide a default failure signaling mechanism, for when client code does not specify how errors are to be reported. This is handy for ensuring backwards compatibility in existing modules that are converted to this new failure signaling approach. =head1 INTERFACE =head2 Accessing the API To install the new C and C keywords, simple load the module: use Lexical::Failure; =head3 Changing the names of the API keywords To avoid name conflicts, you can change the name of either (or both) of the keywords that the module sets up, by passing a named argument when loading the module. The name of the argument should be the standard name of the keyword you want to rename, and the value of the argument should be a string containing the new name. For example: use Lexical::Failure ( fail => 'return_error', ON_FAILURE => 'set_error_handler', ); sub import { my ($package, %named_arg) = @_; set_error_handler( $named_arg{'fail'} ); } sub inverse_square { my ($n) = @_; return_error "Can't invert zero" if $n == 0; return 1/$n**2; } =head2 Signaling failure with C Once the module is loaded, you simply use the C keyword in place of C, C, C, C, C, or any other mechanism by which you would normally indicate failure. You can call C with any number of arguments, including none, and these will be passed to whichever failure handler the client code eventually selects (see below). Note that C is a keyword, not a subroutine (that is, it's like C itself, and not something you can call as part of a larger expression). Note too that, as failure handlers operate at the interface level of a module, calling C in a nested call within the package signals the failure from the package boundary (i.e. like C and C do). =head2 Specifying a lexically scoped failure handler with C You set up a failure-signaling interface for client code by placing the C keyword in your module's C subroutine (or in a subroutine called from your C). The keyword expects one argument, which specifies how failures in the module are to be handled in the lexical scope where your module was loaded. The single argument can be: =over =item * a string containing the name of a named failure handler =item * a reference to a variable, into which failure signals will be stored =item * a reference to a subroutine, which will be used as a callback and invoked whenever a failure is to be signalled =item * C (or no argument at all), in which case C does nothing. This means you don't need to bother checking whether a failure specifier was passed in to your C. Just pass in the resulting C value...and it's ignored. =back Typically, then, you have your C subroutine accept an argument through which client code indicates its desired failure mode: package Your::Module; sub import { my ($package, %named_arg) = @_; ON_FAILURE $named_arg{'fail'}; } Then the client code can specify different reporting strategies in different lexical scopes: # Hereafter, report failures by returning undef... use Your::Module fail => 'undef'; { # But in this block, make errors fatal... use Your::Module fail => 'croak'; { # And in here, set a flag... my $nested_error_flag; use Your::Module fail => \$nested_error_flag; { # And in here, any error is quietly loggged... use Your::Module fail => sub { $logger->error(@_) }; } } # Back to croaking errors here } # Back to returning undef here Each C invokes C, whereupon the call to C installs the specified failure handler into the lexical scope in which C occurred. The installed handler is specific to Your::Module, so if two or more modules are each using Lexical::Failure, client code can set failure-signaling policies for each module independently in the same scope. =head3 Named failure handlers If C is passed a string, that string is treated as the name of a predefined failure handler. Lexical::Failure provides six standard named handlers: =over =item C Specifies that each C should act like: return; That is: return C in scalar context or return an empty list in list context. Note that, this context-sensitive behaviour can occasionally lead to subtle errors. For example, if these three subroutines are using C failure signaling: my %personal_data = ( name => get_name(), age => get_age(), status => get_status(), ); then if any of them fails, it will return an empty list, messing up the initialization of the hash. In such cases, C is a better alternative. =item C Specifies that each C should act like: return undef; Note that to get this behaviour, the argument needs to be C<'undef'> (a five letter string), not C (the special undefined value). Note too that, when this handler is selected, C returns an C even in list context. This can be problematical, as an C is (to many people's surprise) I in list context. For example, if C returns C on failure, the conditional test of this C will still be true: if (my @results = get_results($data)) { .... } because C<@results> will then contain one element (the C), and a non-empty array always evaluates true in boolean context. For this reason it's usually better to use C instead. =item C Specifies that each C should act like: die @args; =item C Specifies that each C should act like: Carp::croak(@args); =item C Specifies that each C should act like: Carp::confess(@args); =item C Specifies that each C should act like: return Lexical::Failure::Objects->new( msg => ( @args == 1 ? $args[0] : "@args" ), context => [caller 1] ); In other words, C causes C to return a special object encapsulating the arguments passed to C and the call context in which the C occurred. See the documentation of L for more details on this alternative. =back You can also set up other named failure handlers of your own devising (see L<"Specifying additional named failure handlers">). =head3 Variables as failure handlers If C is passed a reference to a scalar, array, or hash, that variable becomes the "receiver" of subsequent failure reports, as follows: =over =item C Specifies that C should act like: $scalar = [@args]; return undef; =item C Specifies that C should act like: push @array, [@args]; return undef; =item C Specifies that C should act like: $hash{ $CURRENT_SUBNAME } = [@args]; return undef; =back =head3 Subroutines as failure handlers C can also be passed a reference to a subroutine, which then acts like a callback when failures are signalled. In other words: ON_FAILURE $subroutine_ref; causes C to act like: return $subroutine_ref->(@args); The availability of this alternative means that client code can create entirely new failure-signaling behaviours whenever needed. For example: # Signal failure by logging an error and returning negatively... use Your::Module fail => sub { $logger->error(@_); return -1; }; # Signal failure by returning undef/empty list, # except in one critical case... use Your::Module fail => sub { my $msg = "@_"; croak $msg if $msg =~ /dangerous/; return; }; # The very first failure is instantly (and unluckily) fatal... use Your::Module fail => sub { carp(@_); exit(13) }; =head3 Restricting how client code can signal failure Because the call to C must occur in your module's C subroutine, you always have ultimate control over what types of failure signaling the client code may request from your module. For example, to prevent client code from requesting C behaviours: sub import { my ($package, %named_arg) = @_; croak "Can't specify 'undef' as a failure handler" if $named_arg{'fail'} eq 'undef'; ON_FAILURE $named_arg{'fail'}; } or to quietly convert 'die' behaviours into (much more useful) 'croak' behaviours: sub import { my ($package, %named_arg) = @_; $named_arg{'fail'} =~ s/^die$/croak/; ON_FAILURE $named_arg{'fail'}; } =head3 Specifying a module's default failure handler In any scope where no explicit failure signaling behaviour has been specified, Lexical::Failure defaults to its standard C<'croak'> behaviour (see L<"Named failure handlers">). However, you can also specify a different default for your module, by adding a named argument when you load Lexical::Failure: # Default to full confession on failure... use Lexical::Failure default => 'confess'; # Default to 'return undef or empty list' on failure... use Lexical::Failure default => 'null'; # Default to instant fatality on failure... use Lexical::Failure default => sub { carp(@_); exit() }; The values allowed for the C<'default'> option are somewhat more restrictive than those which can be passed directly to C; you can specify only standard named handlers (see L<"Named failure handlers">) or a subroutine reference. If you need your default to be a non-standard named handler (see L<"Specifying additional named failure handlers">) or a reference to a variable, you must arrange that in your C instead. For example: sub import { my ($package, %named_arg) = @_; # Install failure signaling, if specified... if (defined $named_arg{'fail'}) { ON_FAILURE $named_arg{'fail'}; } # Otherwise, default to pushing errors onto a package variable # (yeah, this is a HORRIBLE idea, but it's what our boss decided!) else { ON_FAILURE \@Your::Module::errors; } } =head3 Specifying additional named failure handlers The six standard L provide convenient declarative shortcuts for client code. That is, instead of constantly having to create messy subroutines like: use Your::Module fail => sub { return Lexical::Failure::Objects->new( msg => (@_ == 1 ? $_[0] : "@_"), context => [caller 1], ); }; client code can just request: use Your::Module fail => 'failobj'; However, you may wish to offer a similar declarative interface for other failure-signaling behaviours that your client code is likely to need. For example: use Your::Module fail => 'logged'; use Your::Module fail => 'exit'; use Your::Module fail => 'loud undef'; Lexical::Failure provides a simple way to set up extra named handlers like these. You just specify the name and associated callback for each when loading the module: package Your::Module; use Lexical::Failure handlers => { 'logged' => sub { $logger->error(@_); }, 'exit' => sub { say @_; exit; }, 'loud undef' => sub { carp(@_); return undef; }, }; The C<'handlers'> option expects a reference to a hash, in which each key is the name of a new named failure handler, and each corresponding value is a reference to a subroutine implementing the behaviour of that named handler. Once specified, any of the new handler names may be passed to C to specify that C should use the corresponding callback to signal failures. Note that any extra named handlers defined in this way are only available from the module in which they are defined. =head1 DIAGNOSTICS =over =item C<< Unknown failure handler: %s >> You called C with a string as the handler specification. However, that string was not one of the standard named handlers (C<'confess'>, C<'croak'>, C<'die'>, C<'failobj'>, C<'undef'>, or C<'null'>), nor any of the extra handlers you may have specified with a C<'handlers'> option when loading Lexical::Failure. Did you perhaps misspell the handler name? =item C<< Unknown default failure handler: %s >> When loading Lexical::Failure, you specified a default handler for all scopes like so: use Lexical::Failure default => 'SOME_STRING'; However, the string you specified did not match the name of any of the standard handlers (C<'confess'>, C<'croak'>, C<'die'>, C<'failobj'>, C<'undef'>, or C<'null'>) nor the name of any handler you had specified yourself using the C<'handlers'> option. Did you perhaps misspell the handler name? =item C<< Can't call ON_FAILURE after compilation >> Lexical failure handlers must be specified at compile-time (usually in your module's C subroutine). However, you called C at runtime. Move the call into your module's C, or into some other subroutine that C calls. =item C<< Can't call ON_FAILURE outside a subroutine >> You probably attempted to set up a lexical handler at the top level of your module's source code. For example: package Your::Module; use Lexical::Failure; ON_FAILURE('die'); The lexical hinting mechanism that Lexical::Failure uses only works when C is called from within your module's C subroutine (or from a subroutine that C itself calls). To achieve the "set a default handler for my module" effect intended in the previous example, rewrite it either as: package Your::Module; use Lexical::Failure; sub import { ON_FAILURE('die'); } or simply: package Your::Module; use Lexical::Failure default => 'die'; =item C<< Missing rename for %s >> You tried to rename either C or C as part of your C call, but forgot to include the new name for the subroutine (i.e. you left out the argument expected after C<'fail'> or C<'ON_FAILURE'>). =item C<< Missing specification for %s >> You tried to specify either the C<'default'> or C<'handlers'> option as part of your C call, but forgot to include the corresponding default value or handlers hash (i.e. you left out the argument expected after C<'default'> or C<'handlers'>). =item C<< Value for %s option must be a %s >> You passed a I C<< => >> I pair to C, but the value was of the wrong type for that particular keyword. See L<"Changing the names of the API keywords"> or L<"Specifying a module's default failure handler"> or L<"Specifying additional named failure handlers"> for the correct usage. =item C<< Handlers in 'handlers' hash must all be code references >> The C<'handlers'> option to C expects a reference to a hash in which each value is a code reference. At least one of the values in the hash you passed was something else. =item C<< Unexpected argument (%s) >> C accepts only four arguments: use Lexical::Failure ( fail => $NEW_NAME, ON_FAILURE => $NEW_NAME, default => $HANDLER_NAME, handlers => \%HANDLER_HASH, ); You attempted to pass it something else. Or perhaps you misspelled one of the above keywords? =item C<< Invalid handler type (%s) in call to ON_FAILURE >> The argument passed to C must be either a string (i.e. the name of a named handler) or a reference to a subroutine (i.e. the handler itself) or a reference to a variable (i.e. the lvalue into which error messages are to be assigned). You passed it something else (probably a regex or a reference to a reference). =back =head1 CONFIGURATION AND ENVIRONMENT Lexical::Failure requires no configuration files or environment variables. =head1 DEPENDENCIES Requires the modules: L, L, and L. Also requires the L helper module included in its distribution. =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to C, or through the web interface at L. =head1 AUTHOR Damian Conway C<< >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2013, Damian Conway C<< >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "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 SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. 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 SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (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 SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Lexical-Failure-0.001001/lib/Lexical/Failure/000755 000765 000024 00000000000 14451122416 021013 5ustar00damianstaff000000 000000 Lexical-Failure-0.001001/lib/Lexical/Failure/Objects.pm000644 000765 000024 00000030502 14155010543 022740 0ustar00damianstaff000000 000000 package Lexical::Failure::Objects; use 5.014; use warnings; use Hash::Util::FieldHash 'fieldhash'; our $VERSION = '0.000001'; # Be invisible to Carp... our @CARP_NOT = __PACKAGE__; # Attribute storage... fieldhash my %msg_for; fieldhash my %context_for; fieldhash my %checked_for; # Constructor... sub new { my ($class, %option) = @_; my $newobj = bless do{ \my $impl }, $class; $msg_for{$newobj} = $option{msg}; $context_for{$newobj} = $option{context}; return $newobj; } # Utilities for error generation... sub _croak { require Carp; Carp::croak(@_); } sub _cant_use { my ($obj, $as) = @_; $as //= q{}; my (undef, $file, $line, $subname) = @{$context_for{$obj}}; $checked_for{$obj} = 1; _croak("$msg_for{$obj} at $file line $line\nAttempt to use failure returned by $subname" . $as); } # How failure objects behave... use overload ( # Fail when used as a boolean... bool => sub { my ($self) = @_; $checked_for{$self} = 1; return; }, q[!] => sub { my ($self) = @_; $checked_for{$self} = 1; return 1; }, # Croak when used any other way... q[neg] => sub { my ($self) = @_; _cant_use($self, " as negative value"); }, q[~] => sub { my ($self) = @_; _cant_use($self, " in bitwise complement"); }, q[""] => sub { my ($self) = @_; _cant_use($self, " as string"); }, q[0+] => sub { my ($self) = @_; _cant_use($self, " as number"); }, q[qr] => sub { my ($self) = @_; _cant_use($self, " as regex"); }, q[++] => sub { my ($self) = @_; _cant_use($self, " in increment"); }, q[--] => sub { my ($self) = @_; _cant_use($self, " in decrement"); }, q[atan2] => sub { my ($self) = @_; _cant_use($self, " as argument to atan2"); }, q[cos] => sub { my ($self) = @_; _cant_use($self, " as argument to cos"); }, q[sin] => sub { my ($self) = @_; _cant_use($self, " as argument to sin"); }, q[exp] => sub { my ($self) = @_; _cant_use($self, " as argument to exp"); }, q[abs] => sub { my ($self) = @_; _cant_use($self, " as argument to abs"); }, q[log] => sub { my ($self) = @_; _cant_use($self, " as argument to log"); }, q[sqrt] => sub { my ($self) = @_; _cant_use($self, " as argument to sqrt"); }, q[int] => sub { my ($self) = @_; _cant_use($self, " as argument to int"); }, q[+] => sub { my ($self) = @_; _cant_use($self, " in addition"); }, q[-] => sub { my ($self) = @_; _cant_use($self, " in subtraction"); }, q[*] => sub { my ($self) = @_; _cant_use($self, " in multiplication"); }, q[/] => sub { my ($self) = @_; _cant_use($self, " in division"); }, q[%] => sub { my ($self) = @_; _cant_use($self, " in modulo"); }, q[**] => sub { my ($self) = @_; _cant_use($self, " in exponentiation"); }, q[<<] => sub { my ($self) = @_; _cant_use($self, " in left shift"); }, q[>>] => sub { my ($self) = @_; _cant_use($self, " in right shift"); }, q[x] => sub { my ($self) = @_; _cant_use($self, " in repetition"); }, q[.] => sub { my ($self) = @_; _cant_use($self, " in string concatenation"); }, q[<>] => sub { my ($self) = @_; _cant_use($self, " in <> iterator"); }, q[-X] => sub { my ($self) = @_; _cant_use($self, " in filetest"); }, q[${}] => sub { my ($self) = @_; _cant_use($self, " as scalar reference"); }, q[@{}] => sub { my ($self) = @_; _cant_use($self, " as array reference"); }, q[%{}] => sub { my ($self) = @_; _cant_use($self, " as hash reference"); }, q[&{}] => sub { my ($self) = @_; _cant_use($self, " as subroutine reference"); }, q[*{}] => sub { my ($self) = @_; _cant_use($self, " as typeglob reference"); }, q[+=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[-=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[*=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[/=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[%=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[**=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[<<=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[>>=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[x=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[.=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[&=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[|=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[^=] => sub { my ($self) = @_; _cant_use($self, " in assignment"); }, q[<] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[<=] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[>] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[>=] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[==] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[!=] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[<=>] => sub { my ($self) = @_; _cant_use($self, " in numeric comparison"); }, q[cmp] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[lt] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[le] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[gt] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[ge] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[eq] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[ne] => sub { my ($self) = @_; _cant_use($self, " in string comparison"); }, q[&] => sub { my ($self) = @_; _cant_use($self, " in bitwise and"); }, q[|] => sub { my ($self) = @_; _cant_use($self, " in bitwise or"); }, q[^] => sub { my ($self) = @_; _cant_use($self, " in bitwise xor"); }, q[~~] => sub { my ($self) = @_; _cant_use($self, " in smartmatch"); }, ); # Throw an exception if still unchecked upon destruction... sub DESTROY { my ($self) = @_; if (!$checked_for{$self}) { $checked_for{$self} = 1; say {*STDERR} "$msg_for{$self} at $context_for{$self}[1] line $context_for{$self}[2]\n"; exit(); } } # Context-enquiry interface... sub subname { my ($self) = @_; return $context_for{$self}[3]; } sub line { my ($self) = @_; return $context_for{$self}[2]; } sub file { my ($self) = @_; return $context_for{$self}[1]; } sub context { my ($self) = @_; my ($subname, $file, $line) = @{$context_for{$self}}[3,1,2]; return "call to $subname at $file line $line"; } 1; # Magic true value required at end of module __END__ =head1 NAME Lexical::Failure::Objects - Special failure objects for Lexical::Failure =head1 VERSION This document describes Lexical::Failure::Objects version 0.000001 =head1 DESCRIPTION This module implements the "failure objects" returned by the optional C<'failobj'> mechanism of the C module. When C is in effect, any call to C will return one of these objects, which simulates a special out-of-band value that you can either explicitly test for failure or else simply ignore and automatically get an exception. For example, given the subroutine: package Math; use Lexical::Failure; sub inverse_square { my ($n) = @_; if ($n == 0) { fail "Can't invert zero"; } return 1/$n**2; } when C<'failobj'> is the selected failure signalling strategy: use Math (fail => 'failobj') then failure can either be tested for explicitly: # This block skipped if $n == 0... if (my $inv_sq = Math::inverse_square($n) { print $inv_sq; } or else simply ignored, in which case an exception will automatically be thrown: print inverse_square($n); # ...throw exception if $n == 0 =head1 INTERFACE If it is used as a boolean, a failure object evaluates false (i.e. it acts as if C had been in effect). If it is used as a value in I other way (as a string, as a reference, as a regex, as a filehandle, etc., etc.), or if it's ignored and allowed to go out of scope without being evaluated at all, then a failure object throws an exception (i.e. it acts as if C had been in effect). =head2 Constructor (C) The class's constructor expects two named arguments: $failure_obj = Lexical::Failure::Objects->new( msg => $MESSAGE_STR_OR_OBJ, context => [$PACKAGE, $FILE, $LINE, $SUBNAME], ); You should never normally need to construct failure objects directly; it's better to let C craete them automatically via its C<'failobj'> mechanism. =head2 Methods C also provides four methods with which you can query the location of the failure that they represent. None of these methods takes any arguments. =over =item C<< $failobj->subname() >> Returns the name of the subroutine in which the failure was signaled. That is, the equivalent of S>. =item C<< $failobj->file() >> Returns the name of the file containing the subroutine call from which failure was signaled. That is, the equivalent of S>. =item C<< $failobj->line() >> Returns the line number of the subroutine call from which failure was signaled. That is, the equivalent of S>. =item C<< $failobj->context() >> Returns a string summarizing the information provided by the previous three methods, in the form: "call to at line " =back =head1 DIAGNOSTICS None of their own. If they throw an exception (when misused or ignored), it will be the exception that C would otherwise have thrown. =head1 CONFIGURATION AND ENVIRONMENT Lexical::Failure::Objects requires no configuration files or environment variables. =head1 DEPENDENCIES Requires the Hash::Util::FieldHash module. =head1 INCOMPATIBILITIES None reported. =head1 BUGS AND LIMITATIONS No bugs have been reported. Please report any bugs or feature requests to C, or through the web interface at L. =head1 AUTHOR Damian Conway C<< >> =head1 LICENCE AND COPYRIGHT Copyright (c) 2013, Damian Conway C<< >>. All rights reserved. This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See L. =head1 DISCLAIMER OF WARRANTY BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE SOFTWARE, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE SOFTWARE "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 SOFTWARE IS WITH YOU. SHOULD THE SOFTWARE PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR, OR CORRECTION. 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 SOFTWARE AS PERMITTED BY THE ABOVE LICENCE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE (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 SOFTWARE TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Lexical-Failure-0.001001/t/nested.t000644 000765 000024 00000004742 14155010543 017214 0ustar00damianstaff000000 000000 use Test::More; plan tests => 6; my $DIE_LINE; package Foo { use Test::More; use Lexical::Failure fail => 'error'; sub import { my ($package, $fail_mode) = @_; ON_FAILURE($fail_mode); } sub public { if (private_level_1()) { diag "private_level_1() returned true"; } else { diag "private_level_1() returned false"; } fail 'Should not return from call to private_level_1()'; return 1; } sub private_level_1 { private_level_2(); } sub private_level_2 { $DIE_LINE = __LINE__ + 1; error 'failed'; } } use Test::Effects; subtest 'null mode' => sub { BEGIN { Foo->import('null') } effects_ok { Foo::public() } { #VERBOSE => 1, return => undef, } => 'scalar context'; effects_ok { Foo::public() } { #VERBOSE => 1, return => [], } => 'list context'; }; subtest 'undef mode' => sub { BEGIN { Foo->import('undef') } effects_ok { Foo::public() } { #VERBOSE => 1, return => undef, }; }; subtest 'failobj mode' => sub { BEGIN { Foo->import('failobj') } my $CROAK_LINE = __LINE__+1; my $result = Foo::public(); effects_ok { !!$result } { #VERBOSE => 1, return => q{}, } => 'failobj checked'; my $USE_LINE = __LINE__+1; effects_ok { $result+0 } { #VERBOSE => 1, die => qr/\Qfailed at \E\S+\Q line $CROAK_LINE\E\n\QAttempt to use failure returned by Foo::public in addition at \E\S+\Q line \E$USE_LINE/, } => 'failobj used'; }; subtest 'die mode' => sub { BEGIN { Foo->import('die') } effects_ok { Foo::public() } { #VERBOSE => 1, die => qr/\Qfailed at \E\S+\Q line $DIE_LINE/, }; }; subtest 'croak mode' => sub { BEGIN { Foo->import('croak') } my $CROAK_LINE = __LINE__+1; eval { Foo::public() }; like $@, qr/\Qfailed at \E\S+\Q line $CROAK_LINE\E/; }; subtest 'croak mode' => sub { BEGIN { Foo->import('confess') } my $CROAK_LINE = __LINE__+1; eval { Foo::public() }; my $error = $@; like $error, qr/line $CROAK_LINE/ => 'croak line reported'; like $error, qr/\Qfailed at \E\S+\Q line $DIE_LINE/ => 'die line reported'; }; done_testing(); Lexical-Failure-0.001001/t/simple.t000644 000765 000024 00000014263 14155010543 017222 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; plan tests => 14; use lib 'tlib'; { my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval{ TestModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'fail --> default'; # effects_ok { TestModule::dont_succeed() } # { die => qr{\A \QDidn't succeed at $CROAK_LINE\E }xms } # => 'fail --> default'; }; { use TestModule errors => undef; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval{ TestModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'fail --> no arg == no change'; # effects_ok { TestModule::dont_succeed() } # { die => qr{\A \QDidn't succeed at $CROAK_LINE\E }xms } # => 'fail --> no arg == no change'; }; { use TestModule errors => 'croak'; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval{ TestModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'fail --> croak'; # effects_ok { TestModule::dont_succeed() } # { die => qr{\A \QDidn't succeed at $CROAK_LINE\E }xms } # => 'fail --> croak'; }; { use TestModule errors => 'confess'; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval{ TestModule::dont_succeed() }; like $@, qr{\QTestModule::dont_succeed() called at $CROAK_LINE\E}xms => 'fail --> confess'; # effects_ok { TestModule::dont_succeed() } # { die => qr{\QTestModule::dont_succeed() called at $CROAK_LINE\E}xms } # => 'fail --> confess'; }; { use TestModule errors => 'die'; effects_ok { TestModule::dont_succeed() } { die => qr{\A \QDidn't succeed at $TestModule::DIE_LINE\E }xms } => 'fail --> die'; }; { use TestModule errors => 'null'; effects_ok { TestModule::dont_succeed() } { scalar_return => undef } => 'fail --> null'; effects_ok { TestModule::dont_succeed() } { list_return => [] } => 'fail --> [null]'; }; { use TestModule errors => 'undef'; effects_ok { TestModule::dont_succeed() } { scalar_return => undef } => 'fail --> undef'; effects_ok { TestModule::dont_succeed() } { list_return => [undef] } => 'fail --> [undef]'; }; subtest 'fail --> failobj', sub { plan tests => 9; use TestModule errors => 'failobj'; my $FAIL_LINE = __LINE__ + 3; my $CROAK_LINE = __FILE__ . ' line ' . $FAIL_LINE; my $FAIL_CONTEXT = "call to TestModule::dont_succeed at $CROAK_LINE"; my $result = TestModule::dont_succeed(); is ref($result), 'Lexical::Failure::Objects' => 'Correct return type'; ok !$result => 'Correct boolean value'; is $result->line, $FAIL_LINE => 'Correct context line'; is $result->file, (__FILE__) => 'Correct context file'; is $result->subname, 'TestModule::dont_succeed' => 'Correct context sub'; is $result->context, $FAIL_CONTEXT => 'Correct context string'; my $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { 1 + $result } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed in addition at $TRIGGER_LINE\E }xms } => 'Correct death when misused as number'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { "$result" } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed as string at $TRIGGER_LINE\E }xms } => 'Correct death when misused as string'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { %{$result} } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed as hash reference at $TRIGGER_LINE\E }xms } => 'Correct death when misused as hashref'; }; { my $errmsg; subtest 'fail --> func', sub { plan tests => 2; use TestModule errors => sub { $errmsg = "@_"; return; }; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { TestModule::dont_succeed() } { return => undef } => 'fail --> func'; is $errmsg, "Didn't succeed" => 'Correct error message'; }; } { my $errmsg; subtest 'fail --> inner scalar', sub { plan tests => 2; use TestModule errors => \$errmsg; effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is_deeply $errmsg, ["Didn't succeed"] => 'Correct error message'; }; } { my @errmsgs; subtest 'fail --> array', sub { plan tests => 7; use TestModule errors => \@errmsgs; effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; ok @errmsgs == 1 => 'Correct number of pushes'; is_deeply $errmsgs[0], ["Didn't succeed"] => 'Correct error message'; $errmsgs[0] = undef; effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects again'; ok @errmsgs == 2 => 'Correct number of pushes again'; is $errmsgs[0], undef() => 'Correct slot pushed'; is_deeply $errmsgs[1], ["Didn't succeed"] => 'Correct error message again'; }; } { my %errmsg_from; subtest 'fail --> hash', sub { plan tests => 4; use TestModule errors => \%errmsg_from; effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; ok keys %errmsg_from == 1 => 'Correct number of entries'; ok exists $errmsg_from{'TestModule::dont_succeed'} => 'Correct key'; is_deeply $errmsg_from{'TestModule::dont_succeed'}, ["Didn't succeed"] => 'Correct value'; }; } Lexical-Failure-0.001001/t/extras.t000644 000765 000024 00000001472 14155010543 017235 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; plan tests => 2; use lib 'tlib'; subtest 'fail --> extra handler used', sub { use ExtrasModule errors => 'squawk'; effects_ok { ExtrasModule::dont_succeed() } VERBOSE { return => 'squawk!', warn => qr{\A \QSquawked as expected\E }xms, } => 'Extra handler installed and called'; }; subtest 'fail --> extra handler unused', sub { use ExtrasModule; eval { ExtrasModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed\E }xms => 'Extra handler installed and called'; # effects_ok { ExtrasModule::dont_succeed() } # VERBOSE { # die => qr{\A \QDidn't succeed\E }xms, # } # => 'Extra handler installed and called'; }; Lexical-Failure-0.001001/t/context.t000644 000765 000024 00000001343 14155010543 017410 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; use Carp; plan tests => 3; use lib 'tlib'; use TestModule errors => sub { if (!defined wantarray) { croak "@_"; } elsif (!wantarray) { return undef; } else { return 'FAIL'; } }; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { ; TestModule::dont_succeed() } { die => qr{\QDidn't succeed at $CROAK_LINE\E} } => 'void context should croak'; effects_ok { scalar TestModule::dont_succeed() } { scalar_return => undef } => 'scalar context should return undef'; effects_ok { TestModule::dont_succeed() } { list_return => ['FAIL'] } => 'list context should return one-element list'; Lexical-Failure-0.001001/t/aliased.t000644 000765 000024 00000013476 14155010543 017340 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; plan tests => 13; use lib 'tlib'; { use AliasModule; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval { AliasModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'fail --> default'; # effects_ok { AliasModule::dont_succeed() } # { die => qr{\A \QDidn't succeed at $CROAK_LINE\E }xms } # => 'fail --> default'; }; { use AliasModule errors => 'croak'; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval { AliasModule::dont_succeed() }; like $@, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'fail --> croak'; # effects_ok { AliasModule::dont_succeed() } # { die => qr{\A \QDidn't succeed at $CROAK_LINE\E }xms } # => 'fail --> croak'; }; { use AliasModule errors => 'confess'; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); eval { AliasModule::dont_succeed() }; like $@, qr{\QAliasModule::dont_succeed() called at $CROAK_LINE\E}xms => 'fail --> confess'; # effects_ok { AliasModule::dont_succeed() } # { die => qr{\QAliasModule::dont_succeed() called at $CROAK_LINE\E}xms } # => 'fail --> confess'; }; { use AliasModule errors => 'die'; effects_ok { AliasModule::dont_succeed() } { die => qr{\A \QDidn't succeed at $AliasModule::DIE_LINE\E }xms } => 'fail --> die'; }; { use AliasModule errors => 'null'; effects_ok { AliasModule::dont_succeed() } { scalar_return => undef } => 'fail --> null'; effects_ok { AliasModule::dont_succeed() } { list_return => [] } => 'fail --> [null]'; }; { use AliasModule errors => 'undef'; effects_ok { AliasModule::dont_succeed() } { scalar_return => undef } => 'fail --> undef'; effects_ok { AliasModule::dont_succeed() } { list_return => [undef] } => 'fail --> [undef]'; }; subtest 'fail --> failobj', sub { plan tests => 9; use AliasModule errors => 'failobj'; my $FAIL_LINE = __LINE__ + 3; my $CROAK_LINE = __FILE__ . ' line ' . $FAIL_LINE; my $FAIL_CONTEXT = "call to AliasModule::dont_succeed at $CROAK_LINE"; my $result = AliasModule::dont_succeed(); is ref($result), 'Lexical::Failure::Objects' => 'Correct return type'; ok !$result => 'Correct boolean value'; is $result->line, $FAIL_LINE => 'Correct context line'; is $result->file, (__FILE__) => 'Correct context file'; is $result->subname, 'AliasModule::dont_succeed' => 'Correct context sub'; is $result->context, $FAIL_CONTEXT => 'Correct context string'; my $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { 1 + $result } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by AliasModule::dont_succeed in addition at $TRIGGER_LINE\E }xms } => 'Correct death when misused as number'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { "$result" } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by AliasModule::dont_succeed as string at $TRIGGER_LINE\E }xms } => 'Correct death when misused as string'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { %{$result} } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by AliasModule::dont_succeed as hash reference at $TRIGGER_LINE\E }xms } => 'Correct death when misused as hashref'; }; { my $errmsg; subtest 'fail --> func', sub { plan tests => 2; use AliasModule errors => sub { $errmsg = "@_"; return; }; my $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { AliasModule::dont_succeed() } { return => undef } => 'fail --> func'; is $errmsg, "Didn't succeed" => 'Correct error message'; }; } { my $errmsg; subtest 'fail --> scalar', sub { plan tests => 2; use AliasModule errors => \$errmsg; effects_ok { AliasModule::dont_succeed() } { return => undef } => 'Correct effects'; is $errmsg->[0], "Didn't succeed" => 'Correct error message'; }; } { my @errmsgs; subtest 'fail --> array', sub { plan tests => 7; use AliasModule errors => \@errmsgs; effects_ok { AliasModule::dont_succeed() } { return => undef } => 'Correct effects'; ok @errmsgs == 1 => 'Correct number of pushes'; is $errmsgs[0][0], "Didn't succeed" => 'Correct error message'; $errmsgs[0] = undef; effects_ok { AliasModule::dont_succeed() } { return => undef } => 'Correct effects again'; ok @errmsgs == 2 => 'Correct number of pushes again'; is $errmsgs[0], undef() => 'Correct slot pushed'; is $errmsgs[1][0], "Didn't succeed" => 'Correct error message again'; }; } { my %errmsg_from; subtest 'fail --> hash', sub { plan tests => 4; use AliasModule errors => \%errmsg_from; effects_ok { AliasModule::dont_succeed() } { return => undef } => 'Correct effects'; ok keys %errmsg_from == 1 => 'Correct number of entries'; ok exists $errmsg_from{'AliasModule::dont_succeed'} => 'Correct key'; is $errmsg_from{'AliasModule::dont_succeed'}[0], "Didn't succeed" => 'Correct value'; }; } Lexical-Failure-0.001001/t/implicit_croak.t000644 000765 000024 00000002132 14155010543 020712 0ustar00damianstaff000000 000000 use 5.014; use warnings; use Test::More; plan tests => 3; # Where the fail() comes from... use lib 'tlib'; use TestModule errors => 'failobj'; # Track line from which failure should be reported... my $CROAK_LINE; my $CROAK_LINE2; # Try to fail in void context... my $died; for (1..1) { local $SIG{__DIE__} = sub { like shift, qr{\A \QDidn't succeed at $CROAK_LINE\E }xms => 'Correct exception message 1'; $died = 1; close *STDERR; }; BEGIN { $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 1); } eval { TestModule::dont_succeed() }; ok $died => 'This should be test 2'; } fail 'Should have croaked from unchecked failure' if !$died; # Try to fail in non-void context... undef $died; for (1..1) { local $SIG{__DIE__} = sub { like shift, qr{\A \QDidn't succeed at $CROAK_LINE2\E }xms => 'Correct exception message 2'; $died = 1; close *STDERR; }; BEGIN { $CROAK_LINE2 = __FILE__ . ' line ' . (__LINE__ + 1); } my $result = TestModule::dont_succeed(); ok !$died => 'This should be test 3'; } Lexical-Failure-0.001001/t/error_runtime_setter.t000644 000765 000024 00000000471 14155010543 022207 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; plan tests => 1; use lib 'tlib'; { use SetterErrorModule; effects_ok { SetterErrorModule::dont_succeed() } { die => qr{\A \QCan't call ON_FAILURE after compilation at $SetterErrorModule::CROAK_LINE\E }xms } => 'runtime fail_width() sub'; }; Lexical-Failure-0.001001/t/inner_scalar.t000755 000765 000024 00000006343 14155010543 020374 0ustar00damianstaff000000 000000 use Test::Effects tests => 15; use warnings; use 5.014; use lib 'tlib'; my $warned; sub _check_warning { no warnings 'uninitialized'; my $warning = "@_" =~ qr{ \A (Variable \s \S+) \s \Qis not available\E }x; my $line = '???'; for my $upscope (0..100) { if (caller($upscope) eq 'main') { $line = (caller $upscope)[2]; last; } } ok $warning => "Warned ($+) as expected at line $line"; $warned = 1; } BEGIN { $SIG{__WARN__} = \&_check_warning; } { subtest 'fail --> my inner scalar', sub { plan tests => 2; my $errmsg; use TestModule errors => \$errmsg; BEGIN{ if (!$warned) { fail 'Did not warn as expected' } ok $warned => 'Warning given at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is $errmsg, undef() => 'Failed to bind, as expected'; }; } { subtest 'fail --> my inner hash', sub { plan tests => 2; my $errmsg; use TestModule errors => ($errmsg = {}); BEGIN{ if (!$warned) { fail 'Did not warn as expected' } ok $warned => 'Warning given at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; ok ref($errmsg) ne 'HASH' || !keys %$errmsg => 'Failed to bind, as expected'; }; } { subtest 'fail --> my inner array', sub { plan tests => 2; my @errmsg; use TestModule errors => \@errmsg; BEGIN{ if (!$warned) { fail 'Did not warn as expected' } ok $warned => 'Warning given at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is_deeply \@errmsg, [] => 'Failed to bind, as expected'; }; } my $outer_var; { subtest 'fail --> my outer scalar', sub { plan tests => 2; use TestModule errors => \$outer_var; BEGIN{ ok !$warned => 'No unexpected warning at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is_deeply $outer_var, ["Didn't succeed"] => 'Successfully bound, as expected'; }; } { subtest 'fail --> our package scalar', sub { plan tests => 2; our $error; use TestModule errors => \$error; BEGIN{ ok !$warned => 'No unexpected warning at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is_deeply $error, ["Didn't succeed"] => 'Successfully bound, as expected'; }; } { subtest 'fail --> qualified package scalar', sub { plan tests => 2; use TestModule errors => \$Other::var; BEGIN{ ok !$warned => 'No unexpected warning at line '.__LINE__; $warned = 0 } effects_ok { TestModule::dont_succeed() } { return => undef } => 'Correct effects'; is_deeply $Other::var, ["Didn't succeed"] => 'Successfully bound, as expected'; }; } done_testing(); Lexical-Failure-0.001001/t/00.load.t000644 000765 000024 00000000243 14155010543 017057 0ustar00damianstaff000000 000000 use Test::More tests => 1, import =>[qw< use_ok diag >]; BEGIN { use_ok( 'Lexical::Failure' ); } diag( "Testing Lexical::Failure $Lexical::Failure::VERSION" ); Lexical-Failure-0.001001/t/default.t000644 000765 000024 00000003404 14155010543 017350 0ustar00damianstaff000000 000000 use Test::Effects; use 5.014; plan tests => 1; use lib 'tlib'; subtest 'fail --> default failobj', sub { plan tests => 9; use DefaultModule; my $FAIL_LINE = __LINE__ + 3; my $CROAK_LINE = __FILE__ . ' line ' . $FAIL_LINE; my $FAIL_CONTEXT = "call to TestModule::dont_succeed at $CROAK_LINE"; my $result = TestModule::dont_succeed(); is ref($result), 'Lexical::Failure::Objects' => 'Correct return type'; ok !$result => 'Correct boolean value'; is $result->line, $FAIL_LINE => 'Correct context line'; is $result->file, (__FILE__) => 'Correct context file'; is $result->subname, 'TestModule::dont_succeed' => 'Correct context sub'; is $result->context, $FAIL_CONTEXT => 'Correct context string'; my $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { 1 + $result } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed in addition at $TRIGGER_LINE\E }xms } => 'Correct death when misused as number'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { "$result" } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed as string at $TRIGGER_LINE\E }xms } => 'Correct death when misused as string'; $TRIGGER_LINE = __FILE__ . ' line ' . (__LINE__ + 1); effects_ok { %{$result} } { die => qr{\A \QDidn't succeed at $CROAK_LINE\E \s* \QAttempt to use failure returned by TestModule::dont_succeed as hash reference at $TRIGGER_LINE\E }xms } => 'Correct death when misused as hashref'; }; Lexical-Failure-0.001001/tlib/ExtrasModule.pm000644 000765 000024 00000000644 14155010543 021203 0ustar00damianstaff000000 000000 package ExtrasModule; our $VERSION = '0.000001'; use 5.014; use warnings; use Carp; use Lexical::Failure handlers => { squawk => sub { carp 'Squawked as expected'; return 'squawk!' } }; sub import { my (undef, undef, $errors) = @_; ON_FAILURE($errors); } sub dont_succeed { fail "Didn't succeed"; return 'This value should not be returned'; } 1; # Magic true value required at end of module Lexical-Failure-0.001001/tlib/TestModule.pm000644 000765 000024 00000000656 14155010543 020657 0ustar00damianstaff000000 000000 package TestModule; our $VERSION = '0.000001'; use 5.014; use warnings; use Lexical::Failure; our $DIE_LINE = -1; sub import { my (undef, undef, $errors) = @_; ON_FAILURE($errors); } sub dont_succeed { $DIE_LINE = __FILE__ . ' line ' . (__LINE__ + 1); fail "Didn't succeed"; return 'This value should never be returned'; } # Module implementation here 1; # Magic true value required at end of module Lexical-Failure-0.001001/tlib/DefaultModule.pm000644 000765 000024 00000000566 14155010543 021324 0ustar00damianstaff000000 000000 package TestModule; our $VERSION = '0.000001'; use 5.014; use warnings; use Lexical::Failure default => 'failobj'; our $DIE_LINE = -1; sub dont_succeed { $DIE_LINE = __FILE__ . ' line ' . (__LINE__ + 1); fail "Didn't succeed"; return 'This value should never be returned'; } # Module implementation here 1; # Magic true value required at end of module Lexical-Failure-0.001001/tlib/AliasModule.pm000644 000765 000024 00000000770 14155010543 020766 0ustar00damianstaff000000 000000 package AliasModule; our $VERSION = '0.000001'; use 5.014; use warnings; use Lexical::Failure fail => 'error', ON_FAILURE => 'on_error'; our $DIE_LINE = -1; sub import { my (undef, undef, $errors) = @_; on_error($errors); } sub dont_succeed { $DIE_LINE = __FILE__ . ' line ' . (__LINE__ + 1); error "Didn't succeed"; return 'This value should never be returned'; } # Module implementation here 1; # Magic true value required at end of module Lexical-Failure-0.001001/tlib/SetterErrorModule.pm000644 000765 000024 00000000711 14155010543 022210 0ustar00damianstaff000000 000000 package SetterErrorModule; our $VERSION = '0.000001'; use 5.014; use warnings; use Lexical::Failure; sub import { my (undef, undef, $errors) = @_; ON_FAILURE($errors); } our $CROAK_LINE = __FILE__ . ' line ' . (__LINE__ + 2); sub dont_succeed { ON_FAILURE('carp'); fail "The fail should never happen"; return 'This value should never be returned'; } # Module implementation here 1; # Magic true value required at end of module