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