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