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