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