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