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