9aaa51ae26ec1bfe026e19e9c27bcf9379e39c6c
[p5sagit/namespace-clean.git] / lib / namespace / clean.pm
1 package namespace::clean;
2
3 =head1 NAME
4
5 namespace::clean - Keep imports and functions out of your namespace
6
7 =cut
8
9 use warnings;
10 use strict;
11
12 use vars        qw( $VERSION $STORAGE_VAR $SCOPE_HOOK_KEY );
13 use Symbol      qw( qualify_to_ref );
14 use Scope::Guard;
15
16 =head1 VERSION
17
18 0.07
19
20 =cut
21
22 $VERSION        = 0.07;
23 $STORAGE_VAR    = '__NAMESPACE_CLEAN_STORAGE';
24 $SCOPE_HOOK_KEY = 'namespace_clean_SCOPING';
25
26 =head1 SYNOPSIS
27
28   package Foo;
29   use warnings;
30   use strict;
31
32   use Carp qw(croak);   # 'croak' will be removed
33
34   sub bar { 23 }        # 'bar' will be removed
35
36   # remove all previously defined functions
37   use namespace::clean;
38
39   sub baz { bar() }     # 'baz' still defined, 'bar' still bound
40
41   # begin to collection function names from here again
42   no namespace::clean;
43
44   sub quux { baz() }    # 'quux' will be removed
45
46   # remove all functions defined after the 'no' unimport
47   use namespace::clean;
48
49   # Will print: 'No', 'No', 'Yes' and 'No'
50   print +(__PACKAGE__->can('croak') ? 'Yes' : 'No'), "\n";
51   print +(__PACKAGE__->can('bar')   ? 'Yes' : 'No'), "\n";
52   print +(__PACKAGE__->can('baz')   ? 'Yes' : 'No'), "\n";
53   print +(__PACKAGE__->can('quux')  ? 'Yes' : 'No'), "\n";
54
55   1;
56
57 =head1 DESCRIPTION
58
59 When you define a function, or import one, into a Perl package, it will
60 naturally also be available as a method. This does not per se cause
61 problems, but it can complicate subclassing and, for example, plugin
62 classes that are included via multiple inheritance by loading them as 
63 base classes.
64
65 The C<namespace::clean> pragma will remove all previously declared or
66 imported symbols at the end of the current package's compile cycle.
67 Functions called in the package itself will still be bound by their
68 name, but they won't show up as methods on your class or instances.
69
70 By unimporting via C<no> you can tell C<namespace::clean> to start
71 collecting functions for the next C<use namespace::clean;> specification.
72
73 You can use the C<-except> flag to tell C<namespace::clean> that you
74 don't want it to remove a certain function or method. A common use would
75 be a module exporting an C<import> method along with some functions:
76
77   use ModuleExportingImport;
78   use namespace::clean -except => [qw( import )];
79
80 If you just want to C<-except> a single sub, you can pass it directly.
81 For more than one value you have to use an array reference.
82
83 =head2 Moose
84
85 When using C<namespace::clean> together with L<Moose> you want to keep
86 the installed C<meta> method. So your classes should look like:
87
88   package Foo;
89   use Moose;
90   use namespace::clean -except => 'meta';
91   ...
92
93 Same goes for L<Moose::Role>.
94
95 =head1 METHODS
96
97 You shouldn't need to call any of these. Just C<use> the package at the
98 appropriate place.
99
100 =cut
101
102 =head2 import
103
104 Makes a snapshot of the current defined functions and installs a 
105 L<Scope::Guard> in the current scope to invoke the cleanups.
106
107 =cut
108
109 sub import {
110     my ($pragma, %args) = @_;
111
112     # calling class, all current functions and our storage
113     my $cleanee   = caller;
114     my $functions = $pragma->get_functions($cleanee);
115     my $store     = $pragma->get_class_store($cleanee);
116
117     # except parameter can be array ref or single value
118     my %except = map {( $_ => 1 )} (
119         $args{ -except }
120         ? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
121         : ()
122     );
123
124     # register symbols for removal, if they have a CODE entry
125     for my $f (keys %$functions) {
126         next if     $except{ $f };
127         next unless    $functions->{ $f } 
128                 and *{ $functions->{ $f } }{CODE};
129         $store->{remove}{ $f } = 1;
130     }
131
132     # register EOF handler on first call to import
133     unless ($store->{handler_is_installed}) {
134         $^H |= 0x120000;
135         $^H{ $SCOPE_HOOK_KEY } = Scope::Guard->new(sub {
136           SYMBOL:
137             for my $f (keys %{ $store->{remove} }) {
138
139                 # ignore already removed symbols
140                 next SYMBOL if $store->{exclude}{ $f };
141                 no strict 'refs';
142
143                 # keep original value to restore non-code slots
144                 {   no warnings 'uninitialized';    # fix possible unimports
145                     local *__tmp = *{ ${ "${cleanee}::" }{ $f } };
146                     delete ${ "${cleanee}::" }{ $f };
147                 }
148
149               SLOT:
150                 # restore non-code slots to symbol
151                 for my $t (qw( SCALAR ARRAY HASH IO FORMAT )) {
152                     next SLOT unless defined *__tmp{ $t };
153                     *{ "${cleanee}::$f" } = *__tmp{ $t };
154                 }
155             }
156         });
157         $store->{handler_is_installed} = 1;
158     }
159
160     return 1;
161 }
162
163 =head2 unimport
164
165 This method will be called when you do a
166
167   no namespace::clean;
168
169 It will start a new section of code that defines functions to clean up.
170
171 =cut
172
173 sub unimport {
174     my ($pragma) = @_;
175
176     # the calling class, the current functions and our storage
177     my $cleanee   = caller;
178     my $functions = $pragma->get_functions($cleanee);
179     my $store     = $pragma->get_class_store($cleanee);
180
181     # register all unknown previous functions as excluded
182     for my $f (keys %$functions) {
183         next if $store->{remove}{ $f }
184              or $store->{exclude}{ $f };
185         $store->{exclude}{ $f } = 1;
186     }
187
188     return 1;
189 }
190
191 =head2 get_class_store
192
193 This returns a reference to a hash in a passed package containing 
194 information about function names included and excluded from removal.
195
196 =cut
197
198 sub get_class_store {
199     my ($pragma, $class) = @_;
200     no strict 'refs';
201     return \%{ "${class}::${STORAGE_VAR}" };
202 }
203
204 =head2 get_functions
205
206 Takes a class as argument and returns all currently defined functions
207 in it as a hash reference with the function name as key and a typeglob
208 reference to the symbol as value.
209
210 =cut
211
212 sub get_functions {
213     my ($pragma, $class) = @_;
214
215     return {
216         map  { @$_ }                                        # key => value
217         grep { *{ $_->[1] }{CODE} }                         # only functions
218         map  { [$_, qualify_to_ref( $_, $class )] }         # get globref
219         grep { $_ !~ /::$/ }                                # no packages
220         do   { no strict 'refs'; keys %{ "${class}::" } }   # symbol entries
221     };
222 }
223
224 =head1 IMPLEMENTATION DETAILS
225
226 This module works through the effect that a 
227
228   delete $SomePackage::{foo};
229
230 will remove the C<foo> symbol from C<$SomePackage> for run time lookups
231 (e.g., method calls) but will leave the entry alive to be called by
232 already resolved names in the package itself. C<namespace::clean> will
233 restore and therefor in effect keep all glob slots that aren't C<CODE>.
234
235 A test file has been added to the perl core to ensure that this behaviour
236 will be stable in future releases.
237
238 Just for completeness sake, if you want to remove the symbol completely,
239 use C<undef> instead.
240
241 =head1 SEE ALSO
242
243 L<Scope::Guard>
244
245 =head1 AUTHOR AND COPYRIGHT
246
247 Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
248 Matt S Trout for the inspiration on the whole idea.
249
250 =head1 LICENSE
251
252 This program is free software; you can redistribute it and/or modify 
253 it under the same terms as perl itself.
254
255 =cut
256
257 1;