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