stop autovivifying on get
[gitmo/Package-Stash-PP.git] / lib / Package / Stash.pm
1 package Package::Stash;
2 use strict;
3 use warnings;
4
5 use Carp qw(confess);
6 use Scalar::Util qw(reftype);
7
8 =head1 NAME
9
10 Package::Stash - routines for manipulating stashes
11
12 =head1 SYNOPSIS
13
14   my $stash = Package::Stash->new('Foo');
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}
20
21 =head1 DESCRIPTION
22
23 Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
24 incredibly messy, and easy to get wrong. This module hides all of that behind a
25 simple API.
26
27 NOTE: Most methods in this class require a variable specification that includes
28 a sigil. If this sigil is absent, it is assumed to represent the IO slot.
29
30 =head1 METHODS
31
32 =cut
33
34 =head2 new $package_name
35
36 Creates a new C<Package::Stash> object, for the package given as the only
37 argument.
38
39 =cut
40
41 sub new {
42     my $class = shift;
43     my ($namespace) = @_;
44     return bless { 'package' => $namespace }, $class;
45 }
46
47 =head2 name
48
49 Returns the name of the package that this object represents.
50
51 =cut
52
53 sub name {
54     return $_[0]->{package};
55 }
56
57 =head2 namespace
58
59 Returns the raw stash itself.
60
61 =cut
62
63 sub 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',
81         ''  => 'IO',
82     );
83
84     sub _deconstruct_variable_name {
85         my ($self, $variable) = @_;
86
87         (defined $variable && length $variable)
88             || confess "You must pass a variable name";
89
90         my $sigil = substr($variable, 0, 1, '');
91
92         if (exists $SIGIL_MAP{$sigil}) {
93             return ($variable, $sigil, $SIGIL_MAP{$sigil});
94         }
95         else {
96             return ("${sigil}${variable}", '', $SIGIL_MAP{''});
97         }
98     }
99 }
100
101 =head2 add_package_symbol $variable $value %opts
102
103 Adds a new package symbol, for the symbol given as C<$variable>, and optionally
104 gives it an initial value of C<$value>. C<$variable> should be the name of
105 variable including the sigil, so
106
107   Package::Stash->new('Foo')->add_package_symbol('%foo')
108
109 will create C<%Foo::foo>.
110
111 Valid options (all optional) are C<filename>, C<first_line_num>, and
112 C<last_line_num>.
113
114 C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
115 be used to indicate where the symbol should be regarded as having been defined.
116 Currently these values are only used if the symbol is a subroutine ('C<&>'
117 sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
118 hash is updated to record the values of C<filename>, C<first_line_num>, and
119 C<last_line_num> for the subroutine. If these are not passed, their values are
120 inferred (as much as possible) from C<caller> information.
121
122 This is especially useful for debuggers and profilers, which use C<%DB::sub> to
123 determine where the source code for a subroutine can be found.  See
124 L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
125 information about C<%DB::sub>.
126
127 =cut
128
129 sub _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
142 sub add_package_symbol {
143     my ($self, $variable, $initial_value, %opts) = @_;
144
145     my ($name, $sigil, $type) = ref $variable eq 'HASH'
146         ? @{$variable}{qw[name sigil type]}
147         : $self->_deconstruct_variable_name($variable);
148
149     my $pkg = $self->name;
150
151     if (@_ > 2) {
152         $self->_valid_for_type($initial_value, $type)
153             || confess "$initial_value is not of type $type";
154
155         # cheap fail-fast check for PERLDBf_SUBLINE and '&'
156         if ($^P and $^P & 0x10 && $sigil eq '&') {
157             my $filename = $opts{filename};
158             my $first_line_num = $opts{first_line_num};
159
160             (undef, $filename, $first_line_num) = caller
161                 if not defined $filename;
162
163             my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
164
165             # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
166             $DB::sub{$pkg . '::' . $name} = "$filename:$first_line_num-$last_line_num";
167         }
168     }
169
170     no strict 'refs';
171     no warnings 'redefine', 'misc', 'prototype';
172     *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
173 }
174
175 =head2 remove_package_glob $name
176
177 Removes all package variables with the given name, regardless of sigil.
178
179 =cut
180
181 sub 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
189 =head2 has_package_symbol $variable
190
191 Returns whether or not the given package variable (including sigil) exists.
192
193 =cut
194
195 sub 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
222 =head2 get_package_symbol $variable
223
224 Returns the value of the given package variable (including sigil).
225
226 =cut
227
228 sub get_package_symbol {
229     my ($self, $variable) = @_;
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
237     if (!exists $namespace->{$name}) {
238         $self->add_package_symbol($variable)
239     }
240
241     my $entry_ref = \$namespace->{$name};
242
243     if (ref($entry_ref) eq 'GLOB') {
244         return *{$entry_ref}{$type};
245     }
246     else {
247         if ($type eq 'CODE') {
248             no strict 'refs';
249             return \&{ $self->name . '::' . $name };
250         }
251         else {
252             return undef;
253         }
254     }
255 }
256
257 =head2 remove_package_symbol $variable
258
259 Removes the package variable described by C<$variable> (which includes the
260 sigil); other variables with the same name but different sigils will be
261 untouched.
262
263 =cut
264
265 sub remove_package_symbol {
266     my ($self, $variable) = @_;
267
268     my ($name, $sigil, $type) = ref $variable eq 'HASH'
269         ? @{$variable}{qw[name sigil type]}
270         : $self->_deconstruct_variable_name($variable);
271
272     # FIXME:
273     # no doubt this is grossly inefficient and 
274     # could be done much easier and faster in XS
275
276     my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
277         { sigil => '$', type => 'SCALAR', name => $name },
278         { sigil => '@', type => 'ARRAY',  name => $name },
279         { sigil => '%', type => 'HASH',   name => $name },
280         { sigil => '&', type => 'CODE',   name => $name },
281         { sigil => '',  type => 'IO',     name => $name },
282     );
283
284     my ($scalar, $array, $hash, $code, $io);
285     if ($type eq 'SCALAR') {
286         $array  = $self->get_package_symbol($array_desc)  if $self->has_package_symbol($array_desc);
287         $hash   = $self->get_package_symbol($hash_desc)   if $self->has_package_symbol($hash_desc);
288         $code   = $self->get_package_symbol($code_desc)   if $self->has_package_symbol($code_desc);
289         $io     = $self->get_package_symbol($io_desc)     if $self->has_package_symbol($io_desc);
290     }
291     elsif ($type eq 'ARRAY') {
292         $scalar = $self->get_package_symbol($scalar_desc);
293         $hash   = $self->get_package_symbol($hash_desc)   if $self->has_package_symbol($hash_desc);
294         $code   = $self->get_package_symbol($code_desc)   if $self->has_package_symbol($code_desc);
295         $io     = $self->get_package_symbol($io_desc)     if $self->has_package_symbol($io_desc);
296     }
297     elsif ($type eq 'HASH') {
298         $scalar = $self->get_package_symbol($scalar_desc);
299         $array  = $self->get_package_symbol($array_desc)  if $self->has_package_symbol($array_desc);
300         $code   = $self->get_package_symbol($code_desc)   if $self->has_package_symbol($code_desc);
301         $io     = $self->get_package_symbol($io_desc)     if $self->has_package_symbol($io_desc);
302     }
303     elsif ($type eq 'CODE') {
304         $scalar = $self->get_package_symbol($scalar_desc);
305         $array  = $self->get_package_symbol($array_desc)  if $self->has_package_symbol($array_desc);
306         $hash   = $self->get_package_symbol($hash_desc)   if $self->has_package_symbol($hash_desc);
307         $io     = $self->get_package_symbol($io_desc)     if $self->has_package_symbol($io_desc);
308     }
309     elsif ($type eq 'IO') {
310         $scalar = $self->get_package_symbol($scalar_desc);
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);
314     }
315     else {
316         confess "This should never ever ever happen";
317     }
318
319     $self->remove_package_glob($name);
320
321     $self->add_package_symbol($scalar_desc => $scalar);
322     $self->add_package_symbol($array_desc  => $array)  if defined $array;
323     $self->add_package_symbol($hash_desc   => $hash)   if defined $hash;
324     $self->add_package_symbol($code_desc   => $code)   if defined $code;
325     $self->add_package_symbol($io_desc     => $io)     if defined $io;
326 }
327
328 =head2 list_all_package_symbols $type_filter
329
330 Returns a list of package variable names in the package, without sigils. If a
331 C<type_filter> is passed, it is used to select package variables of a given
332 type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
333 etc).
334
335 =cut
336
337 sub list_all_package_symbols {
338     my ($self, $type_filter) = @_;
339
340     my $namespace = $self->namespace;
341     return keys %{$namespace} unless defined $type_filter;
342
343     # NOTE:
344     # or we can filter based on 
345     # type (SCALAR|ARRAY|HASH|CODE)
346     if ($type_filter eq 'CODE') {
347         return grep {
348             (ref($namespace->{$_})
349                 ? (ref($namespace->{$_}) eq 'SCALAR')
350                 : (ref(\$namespace->{$_}) eq 'GLOB'
351                    && defined(*{$namespace->{$_}}{CODE})));
352         } keys %{$namespace};
353     } else {
354         return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
355     }
356 }
357
358 =head1 BUGS
359
360 No known bugs.
361
362 Please report any bugs through RT: email
363 C<bug-package-stash at rt.cpan.org>, or browse to
364 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
365
366 =head1 SEE ALSO
367
368 L<Class::MOP::Package> - this module is a factoring out of code that used to
369 live here
370
371 =head1 SUPPORT
372
373 You can find this documentation for this module with the perldoc command.
374
375     perldoc Package::Stash
376
377 You can also look for information at:
378
379 =over 4
380
381 =item * AnnoCPAN: Annotated CPAN documentation
382
383 L<http://annocpan.org/dist/Package-Stash>
384
385 =item * CPAN Ratings
386
387 L<http://cpanratings.perl.org/d/Package-Stash>
388
389 =item * RT: CPAN's request tracker
390
391 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
392
393 =item * Search CPAN
394
395 L<http://search.cpan.org/dist/Package-Stash>
396
397 =back
398
399 =head1 AUTHOR
400
401   Jesse Luehrs <doy at tozt dot net>
402
403 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
404 Moose Cabal.
405
406 =head1 COPYRIGHT AND LICENSE
407
408 This software is copyright (c) 2010 by Jesse Luehrs.
409
410 This is free software; you can redistribute it and/or modify it under
411 the same terms as perl itself.
412
413 =cut
414
415 1;