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