No idea why $DebuggerFixup was originally introduced - fold it back
[p5sagit/namespace-clean.git] / lib / namespace / clean.pm
CommitLineData
40aef9d6 1package namespace::clean;
40aef9d6 2
3use warnings;
4use strict;
5
62a21612 6our $VERSION = '0.25';
727a1a2f 7our $STORAGE_VAR = '__NAMESPACE_CLEAN_STORAGE';
fa84e425 8
727a1a2f 9use B::Hooks::EndOfScope 'on_scope_end';
9887772b 10
acb1d694 11# FIXME This is a crock of shit, needs to go away
12# currently here to work around https://rt.cpan.org/Ticket/Display.html?id=74151
13# kill with fire when PS::XS is *finally* fixed
14BEGIN {
15 my $provider;
16
17 if ( $] < 5.008007 ) {
18 require Package::Stash::PP;
19 $provider = 'Package::Stash::PP';
20 }
21 else {
22 require Package::Stash;
23 $provider = 'Package::Stash';
24 }
25 eval <<"EOS" or die $@;
26
27sub stash_for (\$) {
28 $provider->new(\$_[0]);
29}
30
311;
32
33EOS
34}
40aef9d6 35
df4cbc4e 36use namespace::clean::_Util qw( DEBUGGER_NEEDS_CV_RENAME DEBUGGER_NEEDS_CV_PIVOT );
80e4e267 37
1ae6a568 38# Built-in debugger CV-retrieval fixups necessary before perl 5.15.5:
80e4e267 39# since we are deleting the glob where the subroutine was originally
1ae6a568 40# defined, the assumptions below no longer hold.
80e4e267 41#
1ae6a568 42# In 5.8.9 ~ 5.13.5 (inclusive) the debugger assumes that a CV can
43# always be found under sub_fullname($sub)
44# Workaround: use sub naming to properly name the sub hidden in the package's
45# deleted-stash
46#
47# In the rest of the range ( ... ~ 5.8.8 and 5.13.6 ~ 5.15.4 ) the debugger
48# assumes the name of the glob passed to entersub can be used to find the CV
49# Workaround: realias the original glob to the deleted-stash slot
50#
51# Can not tie constants to the current value of $^P directly,
52# as the debugger can be enabled during runtime (kinda dubious)
80e4e267 53#
017bd598 54
55my $RemoveSubs = sub {
de673bbf 56 my $cleanee = shift;
57 my $store = shift;
acb1d694 58 my $cleanee_stash = stash_for($cleanee);
017bd598 59 my $deleted_stash;
60
de673bbf 61 SYMBOL:
62 for my $f (@_) {
017bd598 63
de673bbf 64 # ignore already removed symbols
65 next SYMBOL if $store->{exclude}{ $f };
de673bbf 66
017bd598 67 my $sub = $cleanee_stash->get_symbol("&$f")
68 or next SYMBOL;
226432f6 69
80e4e267 70 my $need_debugger_fixup =
df4cbc4e 71 ( DEBUGGER_NEEDS_CV_RENAME or DEBUGGER_NEEDS_CV_PIVOT )
64c1bcfc 72 &&
80e4e267 73 $^P
74 &&
75 ref(my $globref = \$cleanee_stash->namespace->{$f}) eq 'GLOB'
1ae6a568 76 &&
77 ( $deleted_stash ||= stash_for("namespace::clean::deleted::$cleanee") )
80e4e267 78 ;
79
1ae6a568 80 # convince the Perl debugger to work
81 # see the comment on top
82 if ( DEBUGGER_NEEDS_CV_RENAME and $need_debugger_fixup ) {
83 #
84 # Note - both get_subname and set_subname are only compiled when CV_RENAME
85 # is true ( the 5.8.9 ~ 5.12 range ). On other perls this entire block is
86 # constant folded away, and so are the definitions in ::_Util
87 #
88 # Do not be surprised that they are missing without DEBUGGER_NEEDS_CV_RENAME
89 #
90 namespace::clean::_Util::get_subname( $sub ) eq ( $cleanee_stash->name . "::$f" )
91 and
92 $deleted_stash->add_symbol(
93 "&$f",
94 namespace::clean::_Util::set_subname( $deleted_stash->name . "::$f", $sub ),
80e4e267 95 );
de673bbf 96 }
1ae6a568 97 elsif ( DEBUGGER_NEEDS_CV_PIVOT and $need_debugger_fixup ) {
98 $deleted_stash->add_symbol("&$f", $sub);
99 }
d6aecfbf 100
d64ad6f8 101 my @symbols = map {
102 my $name = $_ . $f;
103 my $def = $cleanee_stash->get_symbol($name);
104 defined($def) ? [$name, $def] : ()
ad4b1a60 105 } '$', '@', '%', '';
d64ad6f8 106
c86d6ae2 107 $cleanee_stash->remove_glob($f);
d64ad6f8 108
80e4e267 109 # if this perl needs no renaming trick we need to
110 # rename the original glob after the fact
1ae6a568 111 DEBUGGER_NEEDS_CV_PIVOT
112 and
113 $need_debugger_fixup
114 and
115 *$globref = $deleted_stash->namespace->{$f};
80e4e267 116
d64ad6f8 117 $cleanee_stash->add_symbol(@$_) for @symbols;
de673bbf 118 }
119};
53e92ec5 120
fcfe7810 121sub clean_subroutines {
122 my ($nc, $cleanee, @subs) = @_;
123 $RemoveSubs->($cleanee, {}, @subs);
124}
125
de673bbf 126sub import {
127 my ($pragma, @args) = @_;
53e92ec5 128
de673bbf 129 my (%args, $is_explicit);
fcfe7810 130
131 ARG:
132 while (@args) {
133
134 if ($args[0] =~ /^\-/) {
135 my $key = shift @args;
136 my $value = shift @args;
137 $args{ $key } = $value;
138 }
139 else {
140 $is_explicit++;
141 last ARG;
142 }
9b680ffe 143 }
144
fcfe7810 145 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
de673bbf 146 if ($is_explicit) {
aa2aafae 147 on_scope_end {
de673bbf 148 $RemoveSubs->($cleanee, {}, @args);
aa2aafae 149 };
9b680ffe 150 }
de673bbf 151 else {
152
153 # calling class, all current functions and our storage
154 my $functions = $pragma->get_functions($cleanee);
155 my $store = $pragma->get_class_store($cleanee);
acb1d694 156 my $stash = stash_for($cleanee);
de673bbf 157
158 # except parameter can be array ref or single value
159 my %except = map {( $_ => 1 )} (
160 $args{ -except }
161 ? ( ref $args{ -except } eq 'ARRAY' ? @{ $args{ -except } } : $args{ -except } )
162 : ()
163 );
164
165 # register symbols for removal, if they have a CODE entry
166 for my $f (keys %$functions) {
167 next if $except{ $f };
c86d6ae2 168 next unless $stash->has_symbol("&$f");
de673bbf 169 $store->{remove}{ $f } = 1;
170 }
171
172 # register EOF handler on first call to import
173 unless ($store->{handler_is_installed}) {
aa2aafae 174 on_scope_end {
de673bbf 175 $RemoveSubs->($cleanee, $store, keys %{ $store->{remove} });
aa2aafae 176 };
de673bbf 177 $store->{handler_is_installed} = 1;
178 }
179
180 return 1;
181 }
9b680ffe 182}
183
9b680ffe 184sub unimport {
fcfe7810 185 my ($pragma, %args) = @_;
9b680ffe 186
6c0ece9b 187 # the calling class, the current functions and our storage
fcfe7810 188 my $cleanee = exists $args{ -cleanee } ? $args{ -cleanee } : scalar caller;
9b680ffe 189 my $functions = $pragma->get_functions($cleanee);
190 my $store = $pragma->get_class_store($cleanee);
191
6c0ece9b 192 # register all unknown previous functions as excluded
9b680ffe 193 for my $f (keys %$functions) {
194 next if $store->{remove}{ $f }
195 or $store->{exclude}{ $f };
196 $store->{exclude}{ $f } = 1;
197 }
198
199 return 1;
200}
201
9b680ffe 202sub get_class_store {
203 my ($pragma, $class) = @_;
acb1d694 204 my $stash = stash_for($class);
5460fcfb 205 my $var = "%$STORAGE_VAR";
c86d6ae2 206 $stash->add_symbol($var, {})
207 unless $stash->has_symbol($var);
208 return $stash->get_symbol($var);
40aef9d6 209}
210
40aef9d6 211sub get_functions {
212 my ($pragma, $class) = @_;
213
acb1d694 214 my $stash = stash_for($class);
40aef9d6 215 return {
c86d6ae2 216 map { $_ => $stash->get_symbol("&$_") }
217 $stash->list_all_symbols('CODE')
40aef9d6 218 };
219}
220
b3b7a821 221'Danger! Laws of Thermodynamics may not apply.'
222
223__END__
224
225=head1 NAME
226
227namespace::clean - Keep imports and functions out of your namespace
228
229=head1 SYNOPSIS
230
231 package Foo;
232 use warnings;
233 use strict;
234
235 use Carp qw(croak); # 'croak' will be removed
236
237 sub bar { 23 } # 'bar' will be removed
238
239 # remove all previously defined functions
240 use namespace::clean;
241
242 sub baz { bar() } # 'baz' still defined, 'bar' still bound
243
244 # begin to collection function names from here again
245 no namespace::clean;
246
247 sub quux { baz() } # 'quux' will be removed
248
249 # remove all functions defined after the 'no' unimport
250 use namespace::clean;
251
252 # Will print: 'No', 'No', 'Yes' and 'No'
253 print +(__PACKAGE__->can('croak') ? 'Yes' : 'No'), "\n";
254 print +(__PACKAGE__->can('bar') ? 'Yes' : 'No'), "\n";
255 print +(__PACKAGE__->can('baz') ? 'Yes' : 'No'), "\n";
256 print +(__PACKAGE__->can('quux') ? 'Yes' : 'No'), "\n";
257
258 1;
259
260=head1 DESCRIPTION
261
262=head2 Keeping packages clean
263
264When you define a function, or import one, into a Perl package, it will
265naturally also be available as a method. This does not per se cause
266problems, but it can complicate subclassing and, for example, plugin
267classes that are included via multiple inheritance by loading them as
268base classes.
269
270The C<namespace::clean> pragma will remove all previously declared or
271imported symbols at the end of the current package's compile cycle.
272Functions called in the package itself will still be bound by their
273name, but they won't show up as methods on your class or instances.
274
275By unimporting via C<no> you can tell C<namespace::clean> to start
276collecting functions for the next C<use namespace::clean;> specification.
277
278You can use the C<-except> flag to tell C<namespace::clean> that you
279don't want it to remove a certain function or method. A common use would
280be a module exporting an C<import> method along with some functions:
281
282 use ModuleExportingImport;
283 use namespace::clean -except => [qw( import )];
284
285If you just want to C<-except> a single sub, you can pass it directly.
286For more than one value you have to use an array reference.
287
288=head2 Explicitly removing functions when your scope is compiled
289
290It is also possible to explicitly tell C<namespace::clean> what packages
291to remove when the surrounding scope has finished compiling. Here is an
292example:
293
294 package Foo;
295 use strict;
296
297 # blessed NOT available
298
299 sub my_class {
300 use Scalar::Util qw( blessed );
301 use namespace::clean qw( blessed );
302
303 # blessed available
304 return blessed shift;
305 }
306
307 # blessed NOT available
308
309=head2 Moose
310
311When using C<namespace::clean> together with L<Moose> you want to keep
312the installed C<meta> method. So your classes should look like:
313
314 package Foo;
315 use Moose;
316 use namespace::clean -except => 'meta';
317 ...
318
319Same goes for L<Moose::Role>.
320
321=head2 Cleaning other packages
322
323You can tell C<namespace::clean> that you want to clean up another package
324instead of the one importing. To do this you have to pass in the C<-cleanee>
325option like this:
326
327 package My::MooseX::namespace::clean;
328 use strict;
329
330 use namespace::clean (); # no cleanup, just load
331
332 sub import {
333 namespace::clean->import(
334 -cleanee => scalar(caller),
335 -except => 'meta',
336 );
337 }
338
339If you don't care about C<namespace::clean>s discover-and-C<-except> logic, and
340just want to remove subroutines, try L</clean_subroutines>.
341
342=head1 METHODS
343
344=head2 clean_subroutines
345
346This exposes the actual subroutine-removal logic.
347
348 namespace::clean->clean_subroutines($cleanee, qw( subA subB ));
349
350will remove C<subA> and C<subB> from C<$cleanee>. Note that this will remove the
351subroutines B<immediately> and not wait for scope end. If you want to have this
352effect at a specific time (e.g. C<namespace::clean> acts on scope compile end)
353it is your responsibility to make sure it runs at that time.
354
355=head2 import
356
357Makes a snapshot of the current defined functions and installs a
358L<B::Hooks::EndOfScope> hook in the current scope to invoke the cleanups.
359
360
361=head2 unimport
362
363This method will be called when you do a
364
365 no namespace::clean;
366
367It will start a new section of code that defines functions to clean up.
368
369=head2 get_class_store
370
371This returns a reference to a hash in a passed package containing
372information about function names included and excluded from removal.
373
374=head2 get_functions
375
376Takes a class as argument and returns all currently defined functions
377in it as a hash reference with the function name as key and a typeglob
378reference to the symbol as value.
379
6c0ece9b 380=head1 IMPLEMENTATION DETAILS
381
04312494 382This module works through the effect that a
6c0ece9b 383
384 delete $SomePackage::{foo};
385
386will remove the C<foo> symbol from C<$SomePackage> for run time lookups
387(e.g., method calls) but will leave the entry alive to be called by
472d4b1e 388already resolved names in the package itself. C<namespace::clean> will
389restore and therefor in effect keep all glob slots that aren't C<CODE>.
6c0ece9b 390
391A test file has been added to the perl core to ensure that this behaviour
392will be stable in future releases.
393
394Just for completeness sake, if you want to remove the symbol completely,
395use C<undef> instead.
396
40aef9d6 397=head1 SEE ALSO
398
705fe1b1 399L<B::Hooks::EndOfScope>
40aef9d6 400
04312494 401=head1 THANKS
40aef9d6 402
04312494 403Many thanks to Matt S Trout for the inspiration on the whole idea.
40aef9d6 404
fa84e425 405=head1 AUTHORS
406
407=over
408
409=item *
410
411Robert 'phaylon' Sedlacek <rs@474.at>
412
413=item *
414
415Florian Ragwitz <rafl@debian.org>
416
417=item *
418
419Jesse Luehrs <doy@tozt.net>
420
421=item *
422
423Peter Rabbitson <ribasushi@cpan.org>
424
b2e54862 425=item *
426
427Father Chrysostomos <sprout@cpan.org>
428
fa84e425 429=back
430
431=head1 COPYRIGHT AND LICENSE
432
b2e54862 433This software is copyright (c) 2011 by L</AUTHORS>
fa84e425 434
435This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.