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