Turn *_for_cv into classmethods.
[p5sagit/Devel-BeginLift.git] / lib / Devel / BeginLift.pm
CommitLineData
0395308e 1package Devel::BeginLift;
2
3use strict;
4use warnings;
1594b447 5use 5.008001;
0395308e 6
79eec0c9 7our $VERSION = 0.001000;
0395308e 8
1594b447 9use vars qw(%lift);
10use base qw(DynaLoader);
5e5bdebb 11use B::Hooks::OP::Check::EntersubForCV;
0395308e 12
1594b447 13bootstrap Devel::BeginLift;
0395308e 14
15sub import {
16 my ($class, @args) = @_;
17 my $target = caller;
18 $class->setup_for($target => \@args);
19}
20
21sub unimport {
22 my ($class) = @_;
23 my $target = caller;
24 $class->teardown_for($target);
25}
26
27sub setup_for {
28 my ($class, $target, $args) = @_;
5e5bdebb 29 $lift{$target} ||= [];
30 push @{ $lift{$target} }, map {
eeee00df 31 $class->setup_for_cv($_);
5e5bdebb 32 } map {
33 ref $_ eq 'CODE'
34 ? $_
35 : \&{ "${target}::${_}" }
36 } @{ $args };
0395308e 37}
38
39sub teardown_for {
40 my ($class, $target) = @_;
eeee00df 41 $class->teardown_for_cv($_) for @{ $lift{$target} };
0395308e 42 delete $lift{$target};
0395308e 43}
44
79eec0c9 45=head1 NAME
46
47Devel::BeginLift - make selected sub calls evaluate at compile time
48
49=head1 SYNOPSIS
50
51 use Devel::BeginLift qw(foo baz);
52
53 use vars qw($i);
54
55 BEGIN { $i = 0 }
56
57 sub foo { "foo: $_[0]\n"; }
58
59 sub bar { "bar: $_[0]\n"; }
60
61 for (1 .. 3) {
62 print foo($i++);
63 print bar($i++);
64 }
65
66 no Devel::BeginLift;
67
68 print foo($i++);
69
70outputs -
71
72foo: 0
73bar: 1
74foo: 0
75bar: 2
76foo: 0
77bar: 3
78foo: 4
79
80=head1 DESCRIPTION
81
82Devel::BeginLift 'lifts' arbitrary sub calls to running at compile time
83- sort of a souped up version of "use constant". It does this via some
84slightly insane perlguts magic.
85
86=head2 import
87
88 use Devel::BeginLift qw(list of subs);
89
90Calls Devel::BeginLift->setup_for(__PACKAGE__ => \@list_of_subs);
91
92=head2 unimport
93
94 no Devel::BeginLift;
95
96Calls Devel::BeginLift->teardown_for(__PACKAGE__);
97
98=head2 setup_for
99
100 Devel::BeginLift->setup_for($package => \@subnames);
101
102Installs begin lifting magic (unless already installed) and registers
103"${package}::$name" for each member of @subnames to be executed when parsed
104and replaced with its output rather than left for runtime.
105
106=head2 teardown_for
107
108 Devel::BeginLift->teardown_for($package);
109
110Deregisters all subs currently registered for $package and uninstalls begin
111lifting magic is number of teardown_for calls matches number of setup_for
112calls.
113
114=head1 AUTHOR
115
116Matt S Trout - <mst@shadowcatsystems.co.uk>
117
118Company: http://www.shadowcatsystems.co.uk/
119Blog: http://chainsawblues.vox.com/
120
121=head1 LICENSE
122
123This library is free software under the same terms as perl itself
124
125=cut
126
0395308e 1271;