Stop relying on stash entries always being upgraded into real GVs.
[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 );
07fbef3d 13use Symbol qw( qualify_to_ref gensym );
aa2aafae 14use B::Hooks::EndOfScope;
07fbef3d 15use Sub::Identify qw(sub_fullname);
16use Sub::Name qw(subname);
40aef9d6 17
18=head1 VERSION
19
fcfe7810 200.11
40aef9d6 21
22=cut
23
fcfe7810 24$VERSION = '0.11';
de673bbf 25$STORAGE_VAR = '__NAMESPACE_CLEAN_STORAGE';
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
fcfe7810 119=head2 Cleaning other packages
120
121You can tell C<namespace::clean> that you want to clean up another package
122instead of the one importing. To do this you have to pass in the C<-cleanee>
123option like this:
124
125 package My::MooseX::namespace::clean;
126 use strict;
127
128 use namespace::clean (); # no cleanup, just load
129
130 sub import {
131 namespace::clean->import(
132 -cleanee => scalar(caller),
133 -except => 'meta',
134 );
135 }
136
137If you don't care about C<namespace::clean>s discover-and-C<-except> logic, and
138just want to remove subroutines, try L</clean_subroutines>.
139
40aef9d6 140=head1 METHODS
141
142You shouldn't need to call any of these. Just C<use> the package at the
143appropriate place.
144
6c0ece9b 145=cut
146
fcfe7810 147=head2 clean_subroutines
40aef9d6 148
fcfe7810 149This exposes the actual subroutine-removal logic.
150
151 namespace::clean->clean_subroutines($cleanee, qw( subA subB ));
152
153will remove C<subA> and C<subB> from C<$cleanee>. Note that this will remove the
154subroutines B<immediately> and not wait for scope end. If you want to have this
155effect at a specific time (e.g. C<namespace::clean> acts on scope compile end)
156it is your responsibility to make sure it runs at that time.
40aef9d6 157
158=cut
159
de673bbf 160my $RemoveSubs = sub {
fcfe7810 161
de673bbf 162 my $cleanee = shift;
163 my $store = shift;
164 SYMBOL:
165 for my $f (@_) {
07fbef3d 166 my $fq = "${cleanee}::$f";
de673bbf 167
168 # ignore already removed symbols
169 next SYMBOL if $store->{exclude}{ $f };
170 no strict 'refs';
171
226432f6 172 next SYMBOL unless exists ${ "${cleanee}::" }{ $f };
173
174 if (ref(\${ "${cleanee}::" }{ $f }) eq 'GLOB') {
175 # convince the Perl debugger to work
176 # it assumes that sub_fullname($sub) can always be used to find the CV again
177 # since we are deleting the glob where the subroutine was originally
178 # defined, that assumption no longer holds, so we need to move it
179 # elsewhere and point the CV's name to the new glob.
180 my $sub = \&$fq;
181 if ( sub_fullname($sub) eq $fq ) {
182 my $new_fq = "namespace::clean::deleted::$fq";
183 subname($new_fq, $sub);
184 *{$new_fq} = $sub;
185 }
186
187 local *__tmp;
188
189 # keep original value to restore non-code slots
190 { no warnings 'uninitialized'; # fix possible unimports
191 *__tmp = *{ ${ "${cleanee}::" }{ $f } };
192 delete ${ "${cleanee}::" }{ $f };
193 }
194
195 SLOT:
196 # restore non-code slots to symbol.
197 # omit the FORMAT slot, since perl erroneously puts it into the
198 # SCALAR slot of the new glob.
199 for my $t (qw( SCALAR ARRAY HASH IO )) {
200 next SLOT unless defined *__tmp{ $t };
201 *{ "${cleanee}::$f" } = *__tmp{ $t };
202 }
07fbef3d 203 }
226432f6 204 else {
205 # A non-glob in the stash is assumed to stand for some kind
206 # of function. So far they all do, but the core might change
207 # this some day. Watch perl5-porters.
de673bbf 208 delete ${ "${cleanee}::" }{ $f };
209 }
de673bbf 210 }
211};
53e92ec5 212
fcfe7810 213sub clean_subroutines {
214 my ($nc, $cleanee, @subs) = @_;
215 $RemoveSubs->($cleanee, {}, @subs);
216}
217
218=head2 import
219
220Makes a snapshot of the current defined functions and installs a
221L<B::Hooks::EndOfScope> hook in the current scope to invoke the cleanups.
222
223=cut
224
de673bbf 225sub import {
226 my ($pragma, @args) = @_;
53e92ec5 227
de673bbf 228 my (%args, $is_explicit);
fcfe7810 229
230 ARG:
231 while (@args) {
232
233 if ($args[0] =~ /^\-/) {
234 my $key = shift @args;
235 my $value = shift @args;
236 $args{ $key } = $value;
237 }
238 else {
239 $is_explicit++;
240 last ARG;
241 }
9b680ffe 242 }
243
fcfe7810 244 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
de673bbf 245 if ($is_explicit) {
aa2aafae 246 on_scope_end {
de673bbf 247 $RemoveSubs->($cleanee, {}, @args);
aa2aafae 248 };
9b680ffe 249 }
de673bbf 250 else {
251
252 # calling class, all current functions and our storage
253 my $functions = $pragma->get_functions($cleanee);
254 my $store = $pragma->get_class_store($cleanee);
255
256 # except parameter can be array ref or single value
257 my %except = map {( $_ => 1 )} (
258 $args{ -except }
259 ? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
260 : ()
261 );
262
263 # register symbols for removal, if they have a CODE entry
264 for my $f (keys %$functions) {
265 next if $except{ $f };
266 next unless $functions->{ $f }
267 and *{ $functions->{ $f } }{CODE};
268 $store->{remove}{ $f } = 1;
269 }
270
271 # register EOF handler on first call to import
272 unless ($store->{handler_is_installed}) {
aa2aafae 273 on_scope_end {
de673bbf 274 $RemoveSubs->($cleanee, $store, keys %{ $store->{remove} });
aa2aafae 275 };
de673bbf 276 $store->{handler_is_installed} = 1;
277 }
278
279 return 1;
280 }
9b680ffe 281}
282
283=head2 unimport
284
285This method will be called when you do a
286
287 no namespace::clean;
288
289It will start a new section of code that defines functions to clean up.
290
291=cut
292
293sub unimport {
fcfe7810 294 my ($pragma, %args) = @_;
9b680ffe 295
6c0ece9b 296 # the calling class, the current functions and our storage
fcfe7810 297 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
9b680ffe 298 my $functions = $pragma->get_functions($cleanee);
299 my $store = $pragma->get_class_store($cleanee);
300
6c0ece9b 301 # register all unknown previous functions as excluded
9b680ffe 302 for my $f (keys %$functions) {
303 next if $store->{remove}{ $f }
304 or $store->{exclude}{ $f };
305 $store->{exclude}{ $f } = 1;
306 }
307
308 return 1;
309}
310
311=head2 get_class_store
312
6c0ece9b 313This returns a reference to a hash in a passed package containing
314information about function names included and excluded from removal.
9b680ffe 315
316=cut
317
318sub get_class_store {
319 my ($pragma, $class) = @_;
320 no strict 'refs';
321 return \%{ "${class}::${STORAGE_VAR}" };
40aef9d6 322}
323
324=head2 get_functions
325
326Takes a class as argument and returns all currently defined functions
327in it as a hash reference with the function name as key and a typeglob
328reference to the symbol as value.
329
330=cut
331
332sub get_functions {
333 my ($pragma, $class) = @_;
334
335 return {
6c0ece9b 336 map { @$_ } # key => value
337 grep { *{ $_->[1] }{CODE} } # only functions
338 map { [$_, qualify_to_ref( $_, $class )] } # get globref
339 grep { $_ !~ /::$/ } # no packages
340 do { no strict 'refs'; keys %{ "${class}::" } } # symbol entries
40aef9d6 341 };
342}
343
61c4bce7 344=head1 BUGS
345
346C<namespace::clean> will clobber any formats that have the same name as
347a deleted sub. This is due to a bug in perl that makes it impossible to
348re-assign the FORMAT ref into a new glob.
349
6c0ece9b 350=head1 IMPLEMENTATION DETAILS
351
352This module works through the effect that a
353
354 delete $SomePackage::{foo};
355
356will remove the C<foo> symbol from C<$SomePackage> for run time lookups
357(e.g., method calls) but will leave the entry alive to be called by
472d4b1e 358already resolved names in the package itself. C<namespace::clean> will
359restore and therefor in effect keep all glob slots that aren't C<CODE>.
6c0ece9b 360
361A test file has been added to the perl core to ensure that this behaviour
362will be stable in future releases.
363
364Just for completeness sake, if you want to remove the symbol completely,
365use C<undef> instead.
366
40aef9d6 367=head1 SEE ALSO
368
705fe1b1 369L<B::Hooks::EndOfScope>
40aef9d6 370
371=head1 AUTHOR AND COPYRIGHT
372
373Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
374Matt S Trout for the inspiration on the whole idea.
375
376=head1 LICENSE
377
378This program is free software; you can redistribute it and/or modify
379it under the same terms as perl itself.
380
381=cut
382
de673bbf 383no warnings;
384'Danger! Laws of Thermodynamics may not apply.'