get_package_symbol, without the vivify bits yet
[gitmo/Package-Stash-XS.git] / lib / Package / Stash.pm
1 package Package::Stash;
2 use strict;
3 use warnings;
4 # ABSTRACT: routines for manipulating stashes
5
6 use Carp qw(confess);
7 use Scalar::Util qw(reftype);
8 use Symbol;
9
10 use XSLoader;
11 XSLoader::load(
12     __PACKAGE__,
13     # we need to be careful not to touch $VERSION at compile time, otherwise
14     # DynaLoader will assume it's set and check against it, which will cause
15     # fail when being run in the checkout without dzil having set the actual
16     # $VERSION
17     exists $Package::Stash::{VERSION}
18         ? ${ $Package::Stash::{VERSION} } : (),
19 );
20
21 # before 5.12, assigning to the ISA glob would make it lose its magical ->isa
22 # powers
23 use constant BROKEN_ISA_ASSIGNMENT => ($] < 5.012);
24
25 =head1 SYNOPSIS
26
27   my $stash = Package::Stash->new('Foo');
28   $stash->add_package_symbol('%foo', {bar => 1});
29   # $Foo::foo{bar} == 1
30   $stash->has_package_symbol('$foo') # false
31   my $namespace = $stash->namespace;
32   *{ $namespace->{foo} }{HASH} # {bar => 1}
33
34 =head1 DESCRIPTION
35
36 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
37 incredibly messy, and easy to get wrong. This module hides all of that behind a
38 simple API.
39
40 NOTE: Most methods in this class require a variable specification that includes
41 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
42
43 =method new $package_name
44
45 Creates a new C<Package::Stash> object, for the package given as the only
46 argument.
47
48 =method name
49
50 Returns the name of the package that this object represents.
51
52 =method namespace
53
54 Returns the raw stash itself.
55
56 =cut
57
58 =pod
59
60 {
61     my %SIGIL_MAP = (
62         '$' => 'SCALAR',
63         '@' => 'ARRAY',
64         '%' => 'HASH',
65         '&' => 'CODE',
66         ''  => 'IO',
67     );
68
69     sub _deconstruct_variable_name {
70         my ($self, $variable) = @_;
71
72         (defined $variable && length $variable)
73             || confess "You must pass a variable name";
74
75         my $sigil = substr($variable, 0, 1, '');
76
77         if (exists $SIGIL_MAP{$sigil}) {
78             return ($variable, $sigil, $SIGIL_MAP{$sigil});
79         }
80         else {
81             return ("${sigil}${variable}", '', $SIGIL_MAP{''});
82         }
83     }
84 }
85
86 =cut
87
88 =method add_package_symbol $variable $value %opts
89
90 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
91 gives it an initial value of C<$value>. C<$variable> should be the name of
92 variable including the sigil, so
93
94   Package::Stash->new('Foo')->add_package_symbol('%foo')
95
96 will create C<%Foo::foo>.
97
98 Valid options (all optional) are C<filename>, C<first_line_num>, and
99 C<last_line_num>.
100
101 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
102 be used to indicate where the symbol should be regarded as having been defined.
103 Currently these values are only used if the symbol is a subroutine ('C<&>'
104 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
105 hash is updated to record the values of C<filename>, C<first_line_num>, and
106 C<last_line_num> for the subroutine. If these are not passed, their values are
107 inferred (as much as possible) from C<caller> information.
108
109 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
110 determine where the source code for a subroutine can be found.  See
111 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
112 information about C<%DB::sub>.
113
114 =method remove_package_glob $name
115
116 Removes all package variables with the given name, regardless of sigil.
117
118 =method has_package_symbol $variable
119
120 Returns whether or not the given package variable (including sigil) exists.
121
122 =method get_package_symbol $variable
123
124 Returns the value of the given package variable (including sigil).
125
126 =cut
127
128 =pod
129
130 sub get_package_symbol {
131     my ($self, $variable, %opts) = @_;
132
133     my ($name, $sigil, $type) = ref $variable eq 'HASH'
134         ? @{$variable}{qw[name sigil type]}
135         : $self->_deconstruct_variable_name($variable);
136
137     my $namespace = $self->namespace;
138
139     if (!exists $namespace->{$name}) {
140         if ($opts{vivify}) {
141             if ($type eq 'ARRAY') {
142                 if (BROKEN_ISA_ASSIGNMENT) {
143                     $self->add_package_symbol(
144                         $variable,
145                         $name eq 'ISA' ? () : ([])
146                     );
147                 }
148                 else {
149                     $self->add_package_symbol($variable, []);
150                 }
151             }
152             elsif ($type eq 'HASH') {
153                 $self->add_package_symbol($variable, {});
154             }
155             elsif ($type eq 'SCALAR') {
156                 $self->add_package_symbol($variable);
157             }
158             elsif ($type eq 'IO') {
159                 $self->add_package_symbol($variable, Symbol::geniosym);
160             }
161             elsif ($type eq 'CODE') {
162                 confess "Don't know how to vivify CODE variables";
163             }
164             else {
165                 confess "Unknown type $type in vivication";
166             }
167         }
168         else {
169             if ($type eq 'CODE') {
170                 # this effectively "de-vivifies" the code slot. if we don't do
171                 # this, referencing the coderef at the end of this function
172                 # will cause perl to auto-vivify a stub coderef in the slot,
173                 # which isn't what we want
174                 $self->add_package_symbol($variable);
175             }
176         }
177     }
178
179     my $entry_ref = \$namespace->{$name};
180
181     if (ref($entry_ref) eq 'GLOB') {
182         return *{$entry_ref}{$type};
183     }
184     else {
185         if ($type eq 'CODE') {
186             no strict 'refs';
187             return \&{ $self->name . '::' . $name };
188         }
189         else {
190             return undef;
191         }
192     }
193 }
194
195 =cut
196
197 =method get_or_add_package_symbol $variable
198
199 Like C<get_package_symbol>, except that it will return an empty hashref or
200 arrayref if the variable doesn't exist.
201
202 =cut
203
204 sub get_or_add_package_symbol {
205     my $self = shift;
206     $self->get_package_symbol(@_, vivify => 1);
207 }
208
209 =method remove_package_symbol $variable
210
211 Removes the package variable described by C<$variable> (which includes the
212 sigil); other variables with the same name but different sigils will be
213 untouched.
214
215 =method list_all_package_symbols $type_filter
216
217 Returns a list of package variable names in the package, without sigils. If a
218 C<type_filter> is passed, it is used to select package variables of a given
219 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
220 etc). Note that if the package contained any C<BEGIN> blocks, perl will leave
221 an empty typeglob in the C<BEGIN> slot, so this will show up if no filter is
222 used (and similarly for C<INIT>, C<END>, etc).
223
224 =head1 BUGS
225
226 No known bugs.
227
228 Please report any bugs through RT: email
229 C<bug-package-stash at rt.cpan.org>, or browse to
230 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
231
232 =head1 SEE ALSO
233
234 =over 4
235
236 =item * L<Class::MOP::Package>
237
238 This module is a factoring out of code that used to live here
239
240 =back
241
242 =head1 SUPPORT
243
244 You can find this documentation for this module with the perldoc command.
245
246     perldoc Package::Stash
247
248 You can also look for information at:
249
250 =over 4
251
252 =item * AnnoCPAN: Annotated CPAN documentation
253
254 L<http://annocpan.org/dist/Package-Stash>
255
256 =item * CPAN Ratings
257
258 L<http://cpanratings.perl.org/d/Package-Stash>
259
260 =item * RT: CPAN's request tracker
261
262 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
263
264 =item * Search CPAN
265
266 L<http://search.cpan.org/dist/Package-Stash>
267
268 =back
269
270 =head1 AUTHOR
271
272 Jesse Luehrs <doy at tozt dot net>
273
274 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
275 Moose Cabal.
276
277 =cut
278
279 1;