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