]> Dogcows Code - chaz/p5-Return-Type-Lexical/blob - lib/Return/Type/Lexical.pm
add code comment
[chaz/p5-Return-Type-Lexical] / lib / Return / Type / Lexical.pm
1 package Return::Type::Lexical;
2 # ABSTRACT: Same thing as Return::Type, but lexical
3
4 use 5.008;
5 use warnings;
6 use strict;
7
8 use parent 'Return::Type';
9
10 our $VERSION = '999.999'; # VERSION
11
12 sub import {
13 my ($class, %args) = @_;
14 $^H{'Return::Type::Lexical/in_effect'} = exists $args{check} && !$args{check} ? 0 : 1;
15 }
16
17 sub unimport {
18 $^H{'Return::Type::Lexical/in_effect'} = 0;
19 }
20
21 sub _in_effect {
22 my ($level) = @_;
23 $level = 0 if !defined $level;
24 my $hinthash = (caller($level))[10];
25 my $in_effect = $hinthash->{'Return::Type::Lexical/in_effect'};
26 return !defined $in_effect || $in_effect;
27 }
28
29 # XXX This is kind of janky. It relies upon Return::Type using Attribute::Handlers, and it assumes
30 # some internal Attribute::Handlers behavior. If it proves to be too fragile, we may need to copy
31 # the Return::Type code to here. Or make Return::Type lexical if that can be done without breaking
32 # backward-compatibility.
33 my $handler;
34 BEGIN {
35 $handler = $UNIVERSAL::{ReturnType};
36 delete $UNIVERSAL::{ReturnType};
37 delete $UNIVERSAL::{_ATTR_CODE_ReturnType};
38 }
39 sub UNIVERSAL::ReturnType :ATTR(CODE,BEGIN) {
40 my $in_effect = _in_effect(4);
41 return if !$in_effect;
42
43 return $handler->(@_);
44 }
45
46 1;
47 __END__
48
49 =head1 SYNOPSIS
50
51 use Return::Type::Lexical;
52 use Types::Standard qw(Int);
53
54 sub foo :ReturnType(Int) { return "not an int" }
55
56 {
57 no Return::Type::Lexical;
58 sub bar :ReturnType(Int) { return "not an int" }
59 }
60
61 my $foo = foo(); # throws an error
62 my $bar = bar(); # returns "not an int"
63
64 # Can also be used with Devel::StrictMode to only perform
65 # type checks in strict mode:
66
67 use Devel::StrictMode;
68 use Return::Type::Lexical check => STRICT;
69
70 =head1 DESCRIPTION
71
72 This module works just like L<Return::Type>, but type-checking can be enabled and disabled within
73 lexical scopes.
74
75 There is no runtime penalty when type-checking is disabled.
76
77 =method import
78
79 The C<check> attribute can be used to set whether or not types are checked.
80
81 =cut
This page took 0.039456 seconds and 4 git commands to generate.