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