Extend add_package_symbol to set %DB::sub if appropriate.
[gitmo/Package-Stash.git] / lib / Package / Stash.pm
CommitLineData
e94260da 1package Package::Stash;
f10f6217 2use strict;
3use warnings;
4
5use Carp qw(confess);
6use Scalar::Util qw(reftype);
f4979588 7
8=head1 NAME
9
e94260da 10Package::Stash - routines for manipulating stashes
f4979588 11
12=head1 SYNOPSIS
13
e94260da 14 my $stash = Package::Stash->new('Foo');
683542f5 15 $stash->add_package_symbol('%foo', {bar => 1});
16 # $Foo::foo{bar} == 1
17 $stash->has_package_symbol('$foo') # false
18 my $namespace = $stash->namespace;
19 *{ $namespace->{foo} }{HASH} # {bar => 1}
f4979588 20
21=head1 DESCRIPTION
22
683542f5 23Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
24incredibly messy, and easy to get wrong. This module hides all of that behind a
25simple API.
26
56a29840 27NOTE: Most methods in this class require a variable specification that includes
28a sigil. If this sigil is absent, it is assumed to represent the IO slot.
29
683542f5 30=head1 METHODS
31
32=cut
33
34=head2 new $package_name
35
e94260da 36Creates a new C<Package::Stash> object, for the package given as the only
683542f5 37argument.
f4979588 38
39=cut
40
f10f6217 41sub new {
42 my $class = shift;
43 my ($namespace) = @_;
60146e1c 44 return bless { 'package' => $namespace }, $class;
f10f6217 45}
46
683542f5 47=head2 name
48
49Returns the name of the package that this object represents.
50
51=cut
52
f10f6217 53sub name {
54 return $_[0]->{package};
55}
56
683542f5 57=head2 namespace
58
59Returns the raw stash itself.
60
61=cut
62
f10f6217 63sub namespace {
64 # NOTE:
65 # because of issues with the Perl API
66 # to the typeglob in some versions, we
67 # need to just always grab a new
68 # reference to the hash here. Ideally
69 # we could just store a ref and it would
70 # Just Work, but oh well :\
71 no strict 'refs';
72 return \%{$_[0]->name . '::'};
73}
74
75{
76 my %SIGIL_MAP = (
77 '$' => 'SCALAR',
78 '@' => 'ARRAY',
79 '%' => 'HASH',
80 '&' => 'CODE',
56a29840 81 '' => 'IO',
f10f6217 82 );
83
84 sub _deconstruct_variable_name {
85 my ($self, $variable) = @_;
86
56a29840 87 (defined $variable && length $variable)
f10f6217 88 || confess "You must pass a variable name";
89
90 my $sigil = substr($variable, 0, 1, '');
91
56a29840 92 if (exists $SIGIL_MAP{$sigil}) {
93 return ($variable, $sigil, $SIGIL_MAP{$sigil});
94 }
95 else {
96 return ("${sigil}${variable}", '', $SIGIL_MAP{''});
97 }
f10f6217 98 }
99}
100
4ada57e0 101=head2 add_package_symbol $variable $value $filename $firstlinenum $lastlinenum
683542f5 102
103Adds a new package symbol, for the symbol given as C<$variable>, and optionally
104gives it an initial value of C<$value>. C<$variable> should be the name of
105variable including the sigil, so
106
e94260da 107 Package::Stash->new('Foo')->add_package_symbol('%foo')
683542f5 108
109will create C<%Foo::foo>.
110
4ada57e0 111The optional $filename, $firstlinenum, and $lastlinenum arguments can be used
112to indicate where the symbol should be regarded as having been defined.
113Currently these values are only used if the symbol is a subroutine ('C<&>'
114sigil) and only if C<$^P & 0x10> is true. In which case the special
115C<%DB::sub> hash is updated to record the values of $filename, $firstlinenum,
116and $lastlinenum for the subroutine.
117
118This is especially useful for debuggers and profilers, which use C<%DB::sub> to
119determine where the source code for a subroutine can be found. See
120L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
121information about C<%DB::sub>.
122
683542f5 123=cut
124
3634ce60 125sub _valid_for_type {
126 my $self = shift;
127 my ($value, $type) = @_;
128 if ($type eq 'HASH' || $type eq 'ARRAY'
129 || $type eq 'IO' || $type eq 'CODE') {
130 return reftype($value) eq $type;
131 }
132 else {
133 my $ref = reftype($value);
134 return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE';
135 }
136}
137
f10f6217 138sub add_package_symbol {
4ada57e0 139 my ($self, $variable, $initial_value) = @_; # extra args unpacked below
f10f6217 140
141 my ($name, $sigil, $type) = ref $variable eq 'HASH'
142 ? @{$variable}{qw[name sigil type]}
143 : $self->_deconstruct_variable_name($variable);
144
4ada57e0 145 my $pkg = $self->name;
146
3634ce60 147 if (@_ > 2) {
148 $self->_valid_for_type($initial_value, $type)
149 || confess "$initial_value is not of type $type";
3634ce60 150
4ada57e0 151 # cheap fail-fast check for PERLDBf_SUBLINE and '&'
152 if ($^P and $^P & 0x10 && $sigil eq '&') {
153 my (undef, undef, undef, $filename, $firstlinenum, $lastlinenum) = @_;
154
155 (undef, $filename, $firstlinenum) = caller
156 if not defined $filename;
157 $lastlinenum = $firstlinenum ||= 0
158 if not defined $lastlinenum;
159
160 # http://perldoc.perl.org/perldebguts.html#Debugger-Internals
161 $DB::sub{$pkg . '::' . $name} = "$filename:$firstlinenum-$lastlinenum";
162 }
163 }
f10f6217 164
165 no strict 'refs';
166 no warnings 'redefine', 'misc', 'prototype';
167 *{$pkg . '::' . $name} = ref $initial_value ? $initial_value : \$initial_value;
168}
169
683542f5 170=head2 remove_package_glob $name
171
172Removes all package variables with the given name, regardless of sigil.
173
174=cut
175
f10f6217 176sub remove_package_glob {
177 my ($self, $name) = @_;
178 no strict 'refs';
179 delete ${$self->name . '::'}{$name};
180}
181
182# ... these functions deal with stuff on the namespace level
183
683542f5 184=head2 has_package_symbol $variable
185
186Returns whether or not the given package variable (including sigil) exists.
187
188=cut
189
f10f6217 190sub has_package_symbol {
191 my ($self, $variable) = @_;
192
193 my ($name, $sigil, $type) = ref $variable eq 'HASH'
194 ? @{$variable}{qw[name sigil type]}
195 : $self->_deconstruct_variable_name($variable);
196
197 my $namespace = $self->namespace;
198
199 return unless exists $namespace->{$name};
200
201 my $entry_ref = \$namespace->{$name};
202 if (reftype($entry_ref) eq 'GLOB') {
203 if ( $type eq 'SCALAR' ) {
204 return defined ${ *{$entry_ref}{SCALAR} };
205 }
206 else {
207 return defined *{$entry_ref}{$type};
208 }
209 }
210 else {
211 # a symbol table entry can be -1 (stub), string (stub with prototype),
212 # or reference (constant)
213 return $type eq 'CODE';
214 }
215}
216
683542f5 217=head2 get_package_symbol $variable
218
219Returns the value of the given package variable (including sigil).
220
221=cut
222
f10f6217 223sub get_package_symbol {
224 my ($self, $variable) = @_;
225
226 my ($name, $sigil, $type) = ref $variable eq 'HASH'
227 ? @{$variable}{qw[name sigil type]}
228 : $self->_deconstruct_variable_name($variable);
229
230 my $namespace = $self->namespace;
231
30d1a098 232 if (!exists $namespace->{$name}) {
b746972e 233 # assigning to the result of this function like
234 # @{$stash->get_package_symbol('@ISA')} = @new_ISA
235 # makes the result not visible until the variable is explicitly
236 # accessed... in the case of @ISA, this might never happen
237 # for instance, assigning like that and then calling $obj->isa
238 # will fail. see t/005-isa.t
239 if ($type eq 'ARRAY' && $name ne 'ISA') {
a2a2164a 240 $self->add_package_symbol($variable, []);
241 }
242 elsif ($type eq 'HASH') {
243 $self->add_package_symbol($variable, {});
244 }
245 else {
246 # FIXME
247 $self->add_package_symbol($variable)
248 }
30d1a098 249 }
f10f6217 250
251 my $entry_ref = \$namespace->{$name};
252
253 if (ref($entry_ref) eq 'GLOB') {
254 return *{$entry_ref}{$type};
255 }
256 else {
257 if ($type eq 'CODE') {
258 no strict 'refs';
259 return \&{ $self->name . '::' . $name };
260 }
261 else {
262 return undef;
263 }
264 }
265}
266
683542f5 267=head2 remove_package_symbol $variable
268
269Removes the package variable described by C<$variable> (which includes the
270sigil); other variables with the same name but different sigils will be
271untouched.
272
273=cut
274
f10f6217 275sub remove_package_symbol {
276 my ($self, $variable) = @_;
277
278 my ($name, $sigil, $type) = ref $variable eq 'HASH'
279 ? @{$variable}{qw[name sigil type]}
280 : $self->_deconstruct_variable_name($variable);
281
282 # FIXME:
283 # no doubt this is grossly inefficient and
284 # could be done much easier and faster in XS
285
b1a00d0e 286 my ($scalar_desc, $array_desc, $hash_desc, $code_desc, $io_desc) = (
f10f6217 287 { sigil => '$', type => 'SCALAR', name => $name },
288 { sigil => '@', type => 'ARRAY', name => $name },
289 { sigil => '%', type => 'HASH', name => $name },
290 { sigil => '&', type => 'CODE', name => $name },
b1a00d0e 291 { sigil => '', type => 'IO', name => $name },
f10f6217 292 );
293
b1a00d0e 294 my ($scalar, $array, $hash, $code, $io);
f10f6217 295 if ($type eq 'SCALAR') {
296 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
297 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
298 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 299 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 300 }
301 elsif ($type eq 'ARRAY') {
42fa5cfc 302 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 303 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
304 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 305 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 306 }
307 elsif ($type eq 'HASH') {
42fa5cfc 308 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 309 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
310 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
b1a00d0e 311 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
f10f6217 312 }
313 elsif ($type eq 'CODE') {
42fa5cfc 314 $scalar = $self->get_package_symbol($scalar_desc);
f10f6217 315 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
316 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
b1a00d0e 317 $io = $self->get_package_symbol($io_desc) if $self->has_package_symbol($io_desc);
318 }
319 elsif ($type eq 'IO') {
42fa5cfc 320 $scalar = $self->get_package_symbol($scalar_desc);
b1a00d0e 321 $array = $self->get_package_symbol($array_desc) if $self->has_package_symbol($array_desc);
322 $hash = $self->get_package_symbol($hash_desc) if $self->has_package_symbol($hash_desc);
323 $code = $self->get_package_symbol($code_desc) if $self->has_package_symbol($code_desc);
f10f6217 324 }
325 else {
326 confess "This should never ever ever happen";
327 }
328
329 $self->remove_package_glob($name);
330
42fa5cfc 331 $self->add_package_symbol($scalar_desc => $scalar);
f10f6217 332 $self->add_package_symbol($array_desc => $array) if defined $array;
333 $self->add_package_symbol($hash_desc => $hash) if defined $hash;
334 $self->add_package_symbol($code_desc => $code) if defined $code;
b1a00d0e 335 $self->add_package_symbol($io_desc => $io) if defined $io;
f10f6217 336}
337
683542f5 338=head2 list_all_package_symbols $type_filter
339
340Returns a list of package variable names in the package, without sigils. If a
341C<type_filter> is passed, it is used to select package variables of a given
342type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
343etc).
344
345=cut
346
f10f6217 347sub list_all_package_symbols {
348 my ($self, $type_filter) = @_;
349
350 my $namespace = $self->namespace;
351 return keys %{$namespace} unless defined $type_filter;
352
353 # NOTE:
354 # or we can filter based on
355 # type (SCALAR|ARRAY|HASH|CODE)
356 if ($type_filter eq 'CODE') {
357 return grep {
358 (ref($namespace->{$_})
359 ? (ref($namespace->{$_}) eq 'SCALAR')
360 : (ref(\$namespace->{$_}) eq 'GLOB'
361 && defined(*{$namespace->{$_}}{CODE})));
362 } keys %{$namespace};
363 } else {
364 return grep { *{$namespace->{$_}}{$type_filter} } keys %{$namespace};
365 }
366}
f4979588 367
368=head1 BUGS
369
370No known bugs.
371
372Please report any bugs through RT: email
e94260da 373C<bug-package-stash at rt.cpan.org>, or browse to
374L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Package-Stash>.
f4979588 375
376=head1 SEE ALSO
377
683542f5 378L<Class::MOP::Package> - this module is a factoring out of code that used to
379live here
f4979588 380
381=head1 SUPPORT
382
383You can find this documentation for this module with the perldoc command.
384
e94260da 385 perldoc Package::Stash
f4979588 386
387You can also look for information at:
388
389=over 4
390
391=item * AnnoCPAN: Annotated CPAN documentation
392
e94260da 393L<http://annocpan.org/dist/Package-Stash>
f4979588 394
395=item * CPAN Ratings
396
e94260da 397L<http://cpanratings.perl.org/d/Package-Stash>
f4979588 398
399=item * RT: CPAN's request tracker
400
e94260da 401L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash>
f4979588 402
403=item * Search CPAN
404
e94260da 405L<http://search.cpan.org/dist/Package-Stash>
f4979588 406
407=back
408
409=head1 AUTHOR
410
411 Jesse Luehrs <doy at tozt dot net>
412
683542f5 413Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
414Moose Cabal.
415
f4979588 416=head1 COPYRIGHT AND LICENSE
417
418This software is copyright (c) 2010 by Jesse Luehrs.
419
420This is free software; you can redistribute it and/or modify it under
421the same terms as perl itself.
422
423=cut
424
4251;