better diagnostics for get_symbol issues on bare anon stashes
[gitmo/Package-Stash.git] / lib / Package / Stash / PP.pm
1 package Package::Stash::PP;
2 use strict;
3 use warnings;
4 # ABSTRACT: pure perl implementation of the Package::Stash API
5
6 use B;
7 use Carp qw(confess);
8 use Scalar::Util qw(blessed reftype weaken);
9 use Symbol;
10 # before 5.12, assigning to the ISA glob would make it lose its magical ->isa
11 # powers
12 use constant BROKEN_ISA_ASSIGNMENT => ($] < 5.012);
13 # before 5.10, stashes don't ever seem to drop to a refcount of zero, so
14 # weakening them isn't helpful
15 use constant BROKEN_WEAK_STASH     => ($] < 5.010);
16 # before 5.10, the scalar slot was always treated as existing if the
17 # glob existed
18 use constant BROKEN_SCALAR_INITIALIZATION => ($] < 5.010);
19 # add_method on anon stashes triggers rt.perl #1804 otherwise
20 # fixed in perl commit v5.13.3-70-g0fe688f
21 use constant BROKEN_GLOB_ASSIGNMENT => ($] < 5.013004);
22
23 =head1 SYNOPSIS
24
25   use Package::Stash;
26
27 =head1 DESCRIPTION
28
29 This is a backend for L<Package::Stash> implemented in pure perl, for those without a compiler or who would like to use this inline in scripts.
30
31 =cut
32
33 sub new {
34     my $class = shift;
35     my ($package) = @_;
36
37     if (!defined($package) || (ref($package) && reftype($package) ne 'HASH')) {
38         confess "Package::Stash->new must be passed the name of the "
39               . "package to access";
40     }
41     elsif (ref($package) && reftype($package) eq 'HASH') {
42         confess "The PP implementation of Package::Stash does not support "
43               . "anonymous stashes before perl 5.14"
44             if BROKEN_GLOB_ASSIGNMENT;
45
46         return bless {
47             'namespace' => $package,
48         }, $class;
49     }
50     elsif ($package =~ /\A[0-9A-Z_a-z]+(?:::[0-9A-Z_a-z]+)*\z/) {
51         return bless {
52             'package' => $package,
53         }, $class;
54     }
55     else {
56         confess "$package is not a module name";
57     }
58
59 }
60
61 sub name {
62     confess "Can't call name as a class method"
63         unless blessed($_[0]);
64     confess "Can't get the name of an anonymous package"
65         unless defined($_[0]->{package});
66     return $_[0]->{package};
67 }
68
69 sub namespace {
70     confess "Can't call namespace as a class method"
71         unless blessed($_[0]);
72
73     if (BROKEN_WEAK_STASH) {
74         no strict 'refs';
75         return \%{$_[0]->name . '::'};
76     }
77     else {
78         return $_[0]->{namespace} if defined $_[0]->{namespace};
79
80         {
81             no strict 'refs';
82             $_[0]->{namespace} = \%{$_[0]->name . '::'};
83         }
84
85         weaken($_[0]->{namespace});
86
87         return $_[0]->{namespace};
88     }
89 }
90
91 sub _is_anon {
92     return !defined $_[0]->{package};
93 }
94
95 {
96     my %SIGIL_MAP = (
97         '$' => 'SCALAR',
98         '@' => 'ARRAY',
99         '%' => 'HASH',
100         '&' => 'CODE',
101         ''  => 'IO',
102     );
103
104     sub _deconstruct_variable_name {
105         my ($self, $variable) = @_;
106
107         my @ret;
108         if (ref($variable) eq 'HASH') {
109             @ret = @{$variable}{qw[name sigil type]};
110         }
111         else {
112             (defined $variable && length $variable)
113                 || confess "You must pass a variable name";
114
115             my $sigil = substr($variable, 0, 1, '');
116
117             if (exists $SIGIL_MAP{$sigil}) {
118                 @ret = ($variable, $sigil, $SIGIL_MAP{$sigil});
119             }
120             else {
121                 @ret = ("${sigil}${variable}", '', $SIGIL_MAP{''});
122             }
123         }
124
125         # XXX in pure perl, this will access things in inner packages,
126         # in xs, this will segfault - probably look more into this at
127         # some point
128         ($ret[0] !~ /::/)
129             || confess "Variable names may not contain ::";
130
131         return @ret;
132     }
133 }
134
135 sub _valid_for_type {
136     my $self = shift;
137     my ($value, $type) = @_;
138     if ($type eq 'HASH' || $type eq 'ARRAY'
139      || $type eq 'IO'   || $type eq 'CODE') {
140         return reftype($value) eq $type;
141     }
142     else {
143         my $ref = reftype($value);
144         return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE' || $ref eq 'REGEXP' || $ref eq 'VSTRING';
145     }
146 }
147
148 sub add_symbol {
149     my ($self, $variable, $initial_value, %opts) = @_;
150
151     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
152
153     if (@_ > 2) {
154         $self->_valid_for_type($initial_value, $type)
155             || confess "$initial_value is not of type $type";
156
157         # cheap fail-fast check for PERLDBf_SUBLINE and '&'
158         if ($^P and $^P & 0x10 && $sigil eq '&') {
159             my $filename = $opts{filename};
160             my $first_line_num = $opts{first_line_num};
161
162             (undef, $filename, $first_line_num) = caller
163                 if not defined $filename;
164
165             my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
166
167             # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
168             $DB::sub{$self->name . '::' . $name} = "$filename:$first_line_num-$last_line_num";
169         }
170     }
171
172     if (BROKEN_GLOB_ASSIGNMENT) {
173         if (@_ > 2) {
174             no strict 'refs';
175             *{ $self->name . '::' . $name } = ref $initial_value
176                 ? $initial_value : \$initial_value;
177         }
178         else {
179             no strict 'refs';
180             *{ $self->name . '::' . $name };
181         }
182     }
183     else {
184         my $namespace = $self->namespace;
185         $namespace->{$name} ||= *{ Symbol::gensym() };
186
187         if (@_ > 2) {
188             *{ $namespace->{$name} } = ref $initial_value
189                 ? $initial_value : \$initial_value;
190         }
191     }
192 }
193
194 sub remove_glob {
195     my ($self, $name) = @_;
196     delete $self->namespace->{$name};
197 }
198
199 sub has_symbol {
200     my ($self, $variable) = @_;
201
202     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
203
204     my $namespace = $self->namespace;
205
206     return unless exists $namespace->{$name};
207
208     my $entry_ref = \$namespace->{$name};
209     if (reftype($entry_ref) eq 'GLOB') {
210         if ($type eq 'SCALAR') {
211             if (BROKEN_SCALAR_INITIALIZATION) {
212                 return defined ${ *{$entry_ref}{$type} };
213             }
214             else {
215                 return B::svref_2object($entry_ref)->SV->isa('B::SV');
216             }
217         }
218         else {
219             return defined *{$entry_ref}{$type};
220         }
221     }
222     else {
223         # a symbol table entry can be -1 (stub), string (stub with prototype),
224         # or reference (constant)
225         return $type eq 'CODE';
226     }
227 }
228
229 sub get_symbol {
230     my ($self, $variable, %opts) = @_;
231
232     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
233
234     my $namespace = $self->namespace;
235
236     if (!exists $namespace->{$name}) {
237         if ($opts{vivify}) {
238             if ($type eq 'ARRAY') {
239                 if (BROKEN_ISA_ASSIGNMENT) {
240                     $self->add_symbol(
241                         $variable,
242                         $name eq 'ISA' ? () : ([])
243                     );
244                 }
245                 else {
246                     $self->add_symbol($variable, []);
247                 }
248             }
249             elsif ($type eq 'HASH') {
250                 $self->add_symbol($variable, {});
251             }
252             elsif ($type eq 'SCALAR') {
253                 $self->add_symbol($variable);
254             }
255             elsif ($type eq 'IO') {
256                 $self->add_symbol($variable, Symbol::geniosym);
257             }
258             elsif ($type eq 'CODE') {
259                 confess "Don't know how to vivify CODE variables";
260             }
261             else {
262                 confess "Unknown type $type in vivication";
263             }
264         }
265         else {
266             return undef;
267         }
268     }
269
270     my $entry_ref = \$namespace->{$name};
271
272     if (ref($entry_ref) eq 'GLOB') {
273         return *{$entry_ref}{$type};
274     }
275     else {
276         if ($type eq 'CODE') {
277             if (BROKEN_GLOB_ASSIGNMENT || !$self->_is_anon) {
278                 no strict 'refs';
279                 return \&{ $self->name . '::' . $name };
280             }
281
282             # XXX we should really be able to support arbitrary anonymous
283             # stashes here... (not just via Package::Anon)
284             if (blessed($namespace) && $namespace->isa('Package::Anon')) {
285                 # ->can will call gv_init for us, which inflates the glob
286                 # don't know how to do this in general
287                 $namespace->bless(\(my $foo))->can($name);
288             }
289             else {
290                 confess "Don't know how to inflate a " . ref($entry_ref)
291                       . " into a full coderef (perhaps you could use"
292                       . " Package::Anon instead of a bare stash?)"
293             }
294
295             return *{ $namespace->{$name} }{CODE};
296         }
297         else {
298             return undef;
299         }
300     }
301 }
302
303 sub get_or_add_symbol {
304     my $self = shift;
305     $self->get_symbol(@_, vivify => 1);
306 }
307
308 sub remove_symbol {
309     my ($self, $variable) = @_;
310
311     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
312
313     # FIXME:
314     # no doubt this is grossly inefficient and
315     # could be done much easier and faster in XS
316
317     my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
318         { sigil => '$', type => 'SCALAR', name => $name },
319         { sigil => '@', type => 'ARRAY',  name => $name },
320         { sigil => '%', type => 'HASH',   name => $name },
321         { sigil => '&', type => 'CODE',   name => $name },
322         { sigil => '',  type => 'IO',     name => $name },
323     );
324
325     my ($scalar, $array, $hash, $code, $io);
326     if ($type eq 'SCALAR') {
327         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
328         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
329         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
330         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
331     }
332     elsif ($type eq 'ARRAY') {
333         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
334         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
335         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
336         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
337     }
338     elsif ($type eq 'HASH') {
339         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
340         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
341         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
342         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
343     }
344     elsif ($type eq 'CODE') {
345         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
346         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
347         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
348         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
349     }
350     elsif ($type eq 'IO') {
351         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
352         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
353         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
354         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
355     }
356     else {
357         confess "This should never ever ever happen";
358     }
359
360     $self->remove_glob($name);
361
362     $self->add_symbol($scalar_desc => $scalar) if defined $scalar;
363     $self->add_symbol($array_desc  => $array)  if defined $array;
364     $self->add_symbol($hash_desc   => $hash)   if defined $hash;
365     $self->add_symbol($code_desc   => $code)   if defined $code;
366     $self->add_symbol($io_desc     => $io)     if defined $io;
367 }
368
369 sub list_all_symbols {
370     my ($self, $type_filter) = @_;
371
372     my $namespace = $self->namespace;
373     return keys %{$namespace} unless defined $type_filter;
374
375     # NOTE:
376     # or we can filter based on
377     # type (SCALAR|ARRAY|HASH|CODE)
378     if ($type_filter eq 'CODE') {
379         return grep {
380             # any non-typeglob in the symbol table is a constant or stub
381             ref(\$namespace->{$_}) ne 'GLOB'
382                 # regular subs are stored in the CODE slot of the typeglob
383                 || defined(*{$namespace->{$_}}{CODE})
384         } keys %{$namespace};
385     }
386     elsif ($type_filter eq 'SCALAR') {
387         return grep {
388             BROKEN_SCALAR_INITIALIZATION
389                 ? (ref(\$namespace->{$_}) eq 'GLOB'
390                       && defined(${*{$namespace->{$_}}{'SCALAR'}}))
391                 : (do {
392                       my $entry = \$namespace->{$_};
393                       ref($entry) eq 'GLOB'
394                           && B::svref_2object($entry)->SV->isa('B::SV')
395                   })
396         } keys %{$namespace};
397     }
398     else {
399         return grep {
400             ref(\$namespace->{$_}) eq 'GLOB'
401                 && defined(*{$namespace->{$_}}{$type_filter})
402         } keys %{$namespace};
403     }
404 }
405
406 sub get_all_symbols {
407     my ($self, $type_filter) = @_;
408
409     my $namespace = $self->namespace;
410     return { %{$namespace} } unless defined $type_filter;
411
412     return {
413         map { $_ => $self->get_symbol({name => $_, type => $type_filter}) }
414             $self->list_all_symbols($type_filter)
415     }
416 }
417
418 =head1 BUGS
419
420 =over 4
421
422 =item * remove_symbol also replaces the associated typeglob
423
424 This can cause unexpected behavior when doing manipulation at compile time -
425 removing subroutines will still allow them to be called from within the package
426 as subroutines (although they will not be available as methods). This can be
427 considered a feature in some cases (this is how L<namespace::clean> works, for
428 instance), but should not be relied upon - use C<remove_glob> directly if you
429 want this behavior.
430
431 =item * Some minor memory leaks
432
433 The pure perl implementation has a couple minor memory leaks (see the TODO
434 tests in t/20-leaks.t) that I'm having a hard time tracking down - these may be
435 core perl bugs, it's hard to tell.
436
437 =back
438
439 Please report any bugs through RT: email
440 C<bug-package-stash at rt.cpan.org>, or browse to
441 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
442
443 =head1 SEE ALSO
444
445 =over 4
446
447 =item * L<Class::MOP::Package>
448
449 This module is a factoring out of code that used to live here
450
451 =back
452
453 =head1 SUPPORT
454
455 You can find this documentation for this module with the perldoc command.
456
457     perldoc Package::Stash
458
459 You can also look for information at:
460
461 =over 4
462
463 =item * AnnoCPAN: Annotated CPAN documentation
464
465 L<http://annocpan.org/dist/Package-Stash>
466
467 =item * CPAN Ratings
468
469 L<http://cpanratings.perl.org/d/Package-Stash>
470
471 =item * RT: CPAN's request tracker
472
473 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
474
475 =item * Search CPAN
476
477 L<http://search.cpan.org/dist/Package-Stash>
478
479 =back
480
481 =head1 AUTHOR
482
483 Jesse Luehrs <doy at tozt dot net>
484
485 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
486 Moose Cabal.
487
488 =begin Pod::Coverage
489
490 BROKEN_ISA_ASSIGNMENT
491 add_symbol
492 get_all_symbols
493 get_or_add_symbol
494 get_symbol
495 has_symbol
496 list_all_symbols
497 name
498 namespace
499 new
500 remove_glob
501
502 =end Pod::Coverage
503
504 =cut
505
506 1;