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