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