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