actually, this isn't our fault, this is just generic 5.8 brokenness
[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             no warnings 'redefine';
189             *{ $namespace->{$name} } = ref $initial_value
190                 ? $initial_value : \$initial_value;
191         }
192     }
193 }
194
195 sub remove_glob {
196     my ($self, $name) = @_;
197     delete $self->namespace->{$name};
198 }
199
200 sub has_symbol {
201     my ($self, $variable) = @_;
202
203     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
204
205     my $namespace = $self->namespace;
206
207     return unless exists $namespace->{$name};
208
209     my $entry_ref = \$namespace->{$name};
210     if (reftype($entry_ref) eq 'GLOB') {
211         if ($type eq 'SCALAR') {
212             if (BROKEN_SCALAR_INITIALIZATION) {
213                 return defined ${ *{$entry_ref}{$type} };
214             }
215             else {
216                 return B::svref_2object($entry_ref)->SV->isa('B::SV');
217             }
218         }
219         else {
220             return defined *{$entry_ref}{$type};
221         }
222     }
223     else {
224         # a symbol table entry can be -1 (stub), string (stub with prototype),
225         # or reference (constant)
226         return $type eq 'CODE';
227     }
228 }
229
230 sub get_symbol {
231     my ($self, $variable, %opts) = @_;
232
233     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
234
235     my $namespace = $self->namespace;
236
237     if (!exists $namespace->{$name}) {
238         if ($opts{vivify}) {
239             if ($type eq 'ARRAY') {
240                 if (BROKEN_ISA_ASSIGNMENT) {
241                     $self->add_symbol(
242                         $variable,
243                         $name eq 'ISA' ? () : ([])
244                     );
245                 }
246                 else {
247                     $self->add_symbol($variable, []);
248                 }
249             }
250             elsif ($type eq 'HASH') {
251                 $self->add_symbol($variable, {});
252             }
253             elsif ($type eq 'SCALAR') {
254                 $self->add_symbol($variable);
255             }
256             elsif ($type eq 'IO') {
257                 $self->add_symbol($variable, Symbol::geniosym);
258             }
259             elsif ($type eq 'CODE') {
260                 confess "Don't know how to vivify CODE variables";
261             }
262             else {
263                 confess "Unknown type $type in vivication";
264             }
265         }
266         else {
267             return undef;
268         }
269     }
270
271     my $entry_ref = \$namespace->{$name};
272
273     if (ref($entry_ref) eq 'GLOB') {
274         return *{$entry_ref}{$type};
275     }
276     else {
277         if ($type eq 'CODE') {
278             if (BROKEN_GLOB_ASSIGNMENT || !$self->_is_anon) {
279                 no strict 'refs';
280                 return \&{ $self->name . '::' . $name };
281             }
282
283             # XXX we should really be able to support arbitrary anonymous
284             # stashes here... (not just via Package::Anon)
285             if (blessed($namespace) && $namespace->isa('Package::Anon')) {
286                 # ->can will call gv_init for us, which inflates the glob
287                 # don't know how to do this in general
288                 $namespace->bless(\(my $foo))->can($name);
289             }
290             else {
291                 confess "Don't know how to inflate a " . ref($entry_ref)
292                       . " into a full coderef (perhaps you could use"
293                       . " Package::Anon instead of a bare stash?)"
294             }
295
296             return *{ $namespace->{$name} }{CODE};
297         }
298         else {
299             return undef;
300         }
301     }
302 }
303
304 sub get_or_add_symbol {
305     my $self = shift;
306     $self->get_symbol(@_, vivify => 1);
307 }
308
309 sub remove_symbol {
310     my ($self, $variable) = @_;
311
312     my ($name, $sigil, $type) = $self->_deconstruct_variable_name($variable);
313
314     # FIXME:
315     # no doubt this is grossly inefficient and
316     # could be done much easier and faster in XS
317
318     my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
319         { sigil => '$', type => 'SCALAR', name => $name },
320         { sigil => '@', type => 'ARRAY',  name => $name },
321         { sigil => '%', type => 'HASH',   name => $name },
322         { sigil => '&', type => 'CODE',   name => $name },
323         { sigil => '',  type => 'IO',     name => $name },
324     );
325
326     my ($scalar, $array, $hash, $code, $io);
327     if ($type eq 'SCALAR') {
328         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
329         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
330         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
331         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
332     }
333     elsif ($type eq 'ARRAY') {
334         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
335         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
336         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
337         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
338     }
339     elsif ($type eq 'HASH') {
340         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
341         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
342         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
343         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
344     }
345     elsif ($type eq 'CODE') {
346         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
347         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
348         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
349         $io     = $self->get_symbol($io_desc)     if $self->has_symbol($io_desc);
350     }
351     elsif ($type eq 'IO') {
352         $scalar = $self->get_symbol($scalar_desc) if $self->has_symbol($scalar_desc) || BROKEN_SCALAR_INITIALIZATION;
353         $array  = $self->get_symbol($array_desc)  if $self->has_symbol($array_desc);
354         $hash   = $self->get_symbol($hash_desc)   if $self->has_symbol($hash_desc);
355         $code   = $self->get_symbol($code_desc)   if $self->has_symbol($code_desc);
356     }
357     else {
358         confess "This should never ever ever happen";
359     }
360
361     $self->remove_glob($name);
362
363     $self->add_symbol($scalar_desc => $scalar) if defined $scalar;
364     $self->add_symbol($array_desc  => $array)  if defined $array;
365     $self->add_symbol($hash_desc   => $hash)   if defined $hash;
366     $self->add_symbol($code_desc   => $code)   if defined $code;
367     $self->add_symbol($io_desc     => $io)     if defined $io;
368 }
369
370 sub list_all_symbols {
371     my ($self, $type_filter) = @_;
372
373     my $namespace = $self->namespace;
374     return keys %{$namespace} unless defined $type_filter;
375
376     # NOTE:
377     # or we can filter based on
378     # type (SCALAR|ARRAY|HASH|CODE)
379     if ($type_filter eq 'CODE') {
380         return grep {
381             # any non-typeglob in the symbol table is a constant or stub
382             ref(\$namespace->{$_}) ne 'GLOB'
383                 # regular subs are stored in the CODE slot of the typeglob
384                 || defined(*{$namespace->{$_}}{CODE})
385         } keys %{$namespace};
386     }
387     elsif ($type_filter eq 'SCALAR') {
388         return grep {
389             BROKEN_SCALAR_INITIALIZATION
390                 ? (ref(\$namespace->{$_}) eq 'GLOB'
391                       && defined(${*{$namespace->{$_}}{'SCALAR'}}))
392                 : (do {
393                       my $entry = \$namespace->{$_};
394                       ref($entry) eq 'GLOB'
395                           && B::svref_2object($entry)->SV->isa('B::SV')
396                   })
397         } keys %{$namespace};
398     }
399     else {
400         return grep {
401             ref(\$namespace->{$_}) eq 'GLOB'
402                 && defined(*{$namespace->{$_}}{$type_filter})
403         } keys %{$namespace};
404     }
405 }
406
407 sub get_all_symbols {
408     my ($self, $type_filter) = @_;
409
410     my $namespace = $self->namespace;
411     return { %{$namespace} } unless defined $type_filter;
412
413     return {
414         map { $_ => $self->get_symbol({name => $_, type => $type_filter}) }
415             $self->list_all_symbols($type_filter)
416     }
417 }
418
419 =head1 BUGS
420
421 =over 4
422
423 =item * remove_symbol also replaces the associated typeglob
424
425 This can cause unexpected behavior when doing manipulation at compile time -
426 removing subroutines will still allow them to be called from within the package
427 as subroutines (although they will not be available as methods). This can be
428 considered a feature in some cases (this is how L<namespace::clean> works, for
429 instance), but should not be relied upon - use C<remove_glob> directly if you
430 want this behavior.
431
432 =item * Some minor memory leaks
433
434 The pure perl implementation has a couple minor memory leaks (see the TODO
435 tests in t/20-leaks.t) that I'm having a hard time tracking down - these may be
436 core perl bugs, it's hard to tell.
437
438 =back
439
440 Please report any bugs through RT: email
441 C<bug-package-stash at rt.cpan.org>, or browse to
442 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
443
444 =head1 SEE ALSO
445
446 =over 4
447
448 =item * L<Class::MOP::Package>
449
450 This module is a factoring out of code that used to live here
451
452 =back
453
454 =head1 SUPPORT
455
456 You can find this documentation for this module with the perldoc command.
457
458     perldoc Package::Stash
459
460 You can also look for information at:
461
462 =over 4
463
464 =item * AnnoCPAN: Annotated CPAN documentation
465
466 L<http://annocpan.org/dist/Package-Stash>
467
468 =item * CPAN Ratings
469
470 L<http://cpanratings.perl.org/d/Package-Stash>
471
472 =item * RT: CPAN's request tracker
473
474 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
475
476 =item * Search CPAN
477
478 L<http://search.cpan.org/dist/Package-Stash>
479
480 =back
481
482 =head1 AUTHOR
483
484 Jesse Luehrs <doy at tozt dot net>
485
486 Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
487 Moose Cabal.
488
489 =begin Pod::Coverage
490
491 BROKEN_ISA_ASSIGNMENT
492 add_symbol
493 get_all_symbols
494 get_or_add_symbol
495 get_symbol
496 has_symbol
497 list_all_symbols
498 name
499 namespace
500 new
501 remove_glob
502
503 =end Pod::Coverage
504
505 =cut
506
507 1;