implement list_all_package_symbols
[gitmo/Package-Stash-XS.git] / lib / Package / Stash.pm
CommitLineData
e94260da 1package Package::Stash;
f10f6217 2use strict;
3use warnings;
988beb41 4# ABSTRACT: routines for manipulating stashes
f10f6217 5
6use Carp qw(confess);
7use Scalar::Util qw(reftype);
dc378b60 8use Symbol;
59017825 9
10use XSLoader;
11XSLoader::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
dc378b60 21# before 5.12, assigning to the ISA glob would make it lose its magical ->isa
22# powers
23use constant BROKEN_ISA_ASSIGNMENT => ($] < 5.012);
f4979588 24
f4979588 25=head1 SYNOPSIS
26
e94260da 27 my $stash = Package::Stash->new('Foo');
683542f5 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}
f4979588 33
34=head1 DESCRIPTION
35
683542f5 36Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
37incredibly messy, and easy to get wrong. This module hides all of that behind a
38simple API.
39
56a29840 40NOTE: Most methods in this class require a variable specification that includes
41a sigil. If this sigil is absent, it is assumed to represent the IO slot.
42
988beb41 43=method new $package_name
683542f5 44
e94260da 45Creates a new C<Package::Stash> object, for the package given as the only
683542f5 46argument.
f4979588 47
988beb41 48=method name
683542f5 49
50Returns the name of the package that this object represents.
51
988beb41 52=method namespace
683542f5 53
54Returns the raw stash itself.
55
56=cut
57
f10f6217 58{
59 my %SIGIL_MAP = (
60 '$' => 'SCALAR',
61 '@' => 'ARRAY',
62 '%' => 'HASH',
63 '&' => 'CODE',
56a29840 64 '' => 'IO',
f10f6217 65 );
66
67 sub _deconstruct_variable_name {
68 my ($self, $variable) = @_;
69
56a29840 70 (defined $variable && length $variable)
f10f6217 71 || confess "You must pass a variable name";
72
73 my $sigil = substr($variable, 0, 1, '');
74
56a29840 75 if (exists $SIGIL_MAP{$sigil}) {
76 return ($variable, $sigil, $SIGIL_MAP{$sigil});
77 }
78 else {
79 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
80 }
f10f6217 81 }
82}
83
988beb41 84=method add_package_symbol $variable $value %opts
683542f5 85
86Adds a new package symbol, for the symbol given as C<$variable>, and optionally
87gives it an initial value of C<$value>. C<$variable> should be the name of
88variable including the sigil, so
89
e94260da 90 Package::Stash->new('Foo')->add_package_symbol('%foo')
683542f5 91
92will create C<%Foo::foo>.
93
c61010aa 94Valid options (all optional) are C<filename>, C<first_line_num>, and
95C<last_line_num>.
96
97C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
98be used to indicate where the symbol should be regarded as having been defined.
4ada57e0 99Currently these values are only used if the symbol is a subroutine ('C<&>'
c61010aa 100sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
101hash is updated to record the values of C<filename>, C<first_line_num>, and
102C<last_line_num> for the subroutine. If these are not passed, their values are
103inferred (as much as possible) from C<caller> information.
4ada57e0 104
105This is especially useful for debuggers and profilers, which use C<%DB::sub> to
106determine where the source code for a subroutine can be found. See
107L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
108information about C<%DB::sub>.
109
683542f5 110=cut
111
3634ce60 112sub _valid_for_type {
113 my $self = shift;
114 my ($value, $type) = @_;
115 if ($type eq 'HASH' || $type eq 'ARRAY'
116 || $type eq 'IO' || $type eq 'CODE') {
117 return reftype($value) eq $type;
118 }
119 else {
120 my $ref = reftype($value);
121 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
122 }
123}
124
f10f6217 125sub add_package_symbol {
640de369 126 my ($self, $variable, $initial_value, %opts) = @_;
f10f6217 127
128 my ($name, $sigil, $type) = ref $variable eq 'HASH'
129 ? @{$variable}{qw[name sigil type]}
130 : $self->_deconstruct_variable_name($variable);
131
4ada57e0 132 my $pkg = $self->name;
133
3634ce60 134 if (@_ > 2) {
135 $self->_valid_for_type($initial_value, $type)
136 || confess "$initial_value is not of type $type";
3634ce60 137
4ada57e0 138 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
139 if ($^P and $^P & 0x10 && $sigil eq '&') {
640de369 140 my $filename = $opts{filename};
141 my $first_line_num = $opts{first_line_num};
4ada57e0 142
640de369 143 (undef, $filename, $first_line_num) = caller
4ada57e0 144 if not defined $filename;
640de369 145
146 my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
4ada57e0 147
148 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
640de369 149 $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
4ada57e0 150 }
151 }
f10f6217 152
153 no strict 'refs';
154 no warnings 'redefine', 'misc', 'prototype';
155 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
156}
157
988beb41 158=method remove_package_glob $name
683542f5 159
160Removes all package variables with the given name, regardless of sigil.
161
988beb41 162=method has_package_symbol $variable
683542f5 163
164Returns whether or not the given package variable (including sigil) exists.
165
166=cut
167
f10f6217 168sub has_package_symbol {
169 my ($self, $variable) = @_;
170
171 my ($name, $sigil, $type) = ref $variable eq 'HASH'
172 ? @{$variable}{qw[name sigil type]}
173 : $self->_deconstruct_variable_name($variable);
174
175 my $namespace = $self->namespace;
176
177 return unless exists $namespace->{$name};
178
179 my $entry_ref = \$namespace->{$name};
180 if (reftype($entry_ref) eq 'GLOB') {
f7543739 181 # XXX: assigning to any typeglob slot also initializes the SCALAR slot,
182 # and saying that an undef scalar variable doesn't exist is probably
183 # vaguely less surprising than a scalar variable popping into existence
184 # without anyone defining it
185 if ($type eq 'SCALAR') {
186 return defined ${ *{$entry_ref}{$type} };
187 }
188 else {
189 return defined *{$entry_ref}{$type};
190 }
f10f6217 191 }
192 else {
193 # a symbol table entry can be -1 (stub), string (stub with prototype),
194 # or reference (constant)
195 return $type eq 'CODE';
196 }
197}
198
988beb41 199=method get_package_symbol $variable
683542f5 200
201Returns the value of the given package variable (including sigil).
202
203=cut
204
f10f6217 205sub get_package_symbol {
e55803fc 206 my ($self, $variable, %opts) = @_;
f10f6217 207
208 my ($name, $sigil, $type) = ref $variable eq 'HASH'
209 ? @{$variable}{qw[name sigil type]}
210 : $self->_deconstruct_variable_name($variable);
211
212 my $namespace = $self->namespace;
213
7486ccf3 214 if (!exists $namespace->{$name}) {
dc378b60 215 if ($opts{vivify}) {
216 if ($type eq 'ARRAY') {
217 if (BROKEN_ISA_ASSIGNMENT) {
218 $self->add_package_symbol(
219 $variable,
220 $name eq 'ISA' ? () : ([])
221 );
222 }
223 else {
224 $self->add_package_symbol($variable, []);
225 }
226 }
227 elsif ($type eq 'HASH') {
228 $self->add_package_symbol($variable, {});
229 }
230 elsif ($type eq 'SCALAR') {
231 $self->add_package_symbol($variable);
232 }
233 elsif ($type eq 'IO') {
234 $self->add_package_symbol($variable, Symbol::geniosym);
235 }
236 elsif ($type eq 'CODE') {
237 confess "Don't know how to vivify CODE variables";
238 }
239 else {
240 confess "Unknown type $type in vivication";
241 }
5d3589c8 242 }
e55803fc 243 else {
dc378b60 244 if ($type eq 'CODE') {
245 # this effectively "de-vivifies" the code slot. if we don't do
246 # this, referencing the coderef at the end of this function
247 # will cause perl to auto-vivify a stub coderef in the slot,
248 # which isn't what we want
249 $self->add_package_symbol($variable);
250 }
e55803fc 251 }
30d1a098 252 }
f10f6217 253
254 my $entry_ref = \$namespace->{$name};
255
256 if (ref($entry_ref) eq 'GLOB') {
257 return *{$entry_ref}{$type};
258 }
259 else {
260 if ($type eq 'CODE') {
261 no strict 'refs';
262 return \&{ $self->name . '::' . $name };
263 }
264 else {
265 return undef;
266 }
267 }
268}
269
988beb41 270=method get_or_add_package_symbol $variable
e55803fc 271
272Like C<get_package_symbol>, except that it will return an empty hashref or
273arrayref if the variable doesn't exist.
274
275=cut
276
277sub get_or_add_package_symbol {
278 my $self = shift;
279 $self->get_package_symbol(@_, vivify => 1);
280}
281
988beb41 282=method remove_package_symbol $variable
683542f5 283
284Removes the package variable described by C<$variable> (which includes the
285sigil); other variables with the same name but different sigils will be
286untouched.
287
288=cut
289
f10f6217 290sub remove_package_symbol {
291 my ($self, $variable) = @_;
292
293 my ($name, $sigil, $type) = ref $variable eq 'HASH'
294 ? @{$variable}{qw[name sigil type]}
295 : $self->_deconstruct_variable_name($variable);
296
297 # FIXME:
9a3d1390 298 # no doubt this is grossly inefficient and
f10f6217 299 # could be done much easier and faster in XS
300
b1a00d0e 301 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
f10f6217 302 { sigil => '$', type => 'SCALAR', name => $name },
303 { sigil => '@', type => 'ARRAY', name => $name },
304 { sigil => '%', type => 'HASH', name => $name },
305 { sigil => '&', type => 'CODE', name => $name },
b1a00d0e 306 { sigil => '', type => 'IO', name => $name },
f10f6217 307 );
308
b1a00d0e 309 my ($scalar, $array, $hash, $code, $io);
f10f6217 310 if ($type eq 'SCALAR') {
311 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
312 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
313 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 314 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 315 }
316 elsif ($type eq 'ARRAY') {
42fa5cfc 317 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 318 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
319 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 320 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 321 }
322 elsif ($type eq 'HASH') {
42fa5cfc 323 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 324 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
325 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 326 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 327 }
328 elsif ($type eq 'CODE') {
42fa5cfc 329 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 330 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
331 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
b1a00d0e 332 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
333 }
334 elsif ($type eq 'IO') {
42fa5cfc 335 $scalar = $self->get_package_symbol($scalar_desc);
b1a00d0e 336 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
337 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
338 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
f10f6217 339 }
340 else {
341 confess "This should never ever ever happen";
342 }
343
344 $self->remove_package_glob($name);
345
42fa5cfc 346 $self->add_package_symbol($scalar_desc => $scalar);
f10f6217 347 $self->add_package_symbol($array_desc => $array) if defined $array;
348 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
349 $self->add_package_symbol($code_desc => $code) if defined $code;
b1a00d0e 350 $self->add_package_symbol($io_desc => $io) if defined $io;
f10f6217 351}
352
988beb41 353=method list_all_package_symbols $type_filter
683542f5 354
355Returns a list of package variable names in the package, without sigils. If a
356C<type_filter> is passed, it is used to select package variables of a given
357type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
d1f721b3 358etc). Note that if the package contained any C<BEGIN> blocks, perl will leave
359an empty typeglob in the C<BEGIN> slot, so this will show up if no filter is
360used (and similarly for C<INIT>, C<END>, etc).
683542f5 361
0992f4ec 362=head1 BUGS
363
364No known bugs.
365
366Please report any bugs through RT: email
367C<bug-package-stash at rt.cpan.org>, or browse to
368L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
369
f4979588 370=head1 SEE ALSO
371
f4979588 372=over 4
373
988beb41 374=item * L<Class::MOP::Package>
f4979588 375
988beb41 376This module is a factoring out of code that used to live here
f4979588 377
378=back
379
0992f4ec 380=head1 SUPPORT
381
382You can find this documentation for this module with the perldoc command.
383
384 perldoc Package::Stash
385
386You can also look for information at:
387
388=over 4
389
390=item * AnnoCPAN: Annotated CPAN documentation
391
392L<http://annocpan.org/dist/Package-Stash>
393
394=item * CPAN Ratings
395
396L<http://cpanratings.perl.org/d/Package-Stash>
397
398=item * RT: CPAN's request tracker
399
400L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
401
402=item * Search CPAN
403
404L<http://search.cpan.org/dist/Package-Stash>
405
406=back
407
408=head1 AUTHOR
409
410Jesse Luehrs <doy at tozt dot net>
411
412Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
413Moose Cabal.
414
f4979588 415=cut
416
4171;