Initial Commit

This commit is contained in:
Riley Schneider
2025-12-03 16:38:10 +01:00
parent c5e26bf594
commit b732d8d4b5
17680 changed files with 5977495 additions and 2 deletions

View File

@@ -0,0 +1,113 @@
package Package::Constants;
use if $] >= 5.019006, 'deprecate';
use 5.006;
use strict;
use warnings;
our $VERSION = '0.06';
our $DEBUG = 0;
=head1 NAME
Package::Constants - List all constants declared in a package
=head1 SYNOPSIS
use Package::Constants;
### list the names of all constants in a given package;
@const = Package::Constants->list( __PACKAGE__ );
@const = Package::Constants->list( 'main' );
### enable debugging output
$Package::Constants::DEBUG = 1;
=head1 DESCRIPTION
C<Package::Constants> lists all the constants defined in a certain
package. This can be useful for, among others, setting up an
autogenerated C<@EXPORT/@EXPORT_OK> for a Constants.pm file.
=head1 CLASS METHODS
=head2 @const = Package::Constants->list( PACKAGE_NAME );
Lists the names of all the constants defined in the provided package.
=cut
sub list {
my $class = shift;
my $pkg = shift;
return unless defined $pkg; # some joker might use '0' as a pkg...
_debug("Inspecting package '$pkg'");
my @rv;
{ no strict 'refs';
my $stash = $pkg . '::';
for my $name (sort keys %$stash ) {
_debug( " Checking stash entry '$name'" );
### is it a subentry?
my $sub = $pkg->can( $name );
next unless defined $sub;
_debug( " '$name' is a coderef" );
next unless defined prototype($sub) and
not length prototype($sub);
_debug( " '$name' is a constant" );
push @rv, $name;
}
}
return sort @rv;
}
=head1 GLOBAL VARIABLES
=head2 $Package::Constants::DEBUG
When set to true, prints out debug information to STDERR about the
package it is inspecting. Helps to identify issues when the results
are not as you expect.
Defaults to false.
=cut
sub _debug { warn "@_\n" if $DEBUG; }
1;
=head1 SEE ALSO
L<Module::Functions> - get a list of all the public functions defined in a package.
=head1 BUG REPORTS
Please report bugs or other issues to E<lt>bug-package-constants@rt.cpan.org<gt>.
=head1 AUTHOR
This module by Jos Boumans E<lt>kane@cpan.orgE<gt>.
=head1 COPYRIGHT
This library is free software; you may redistribute and/or modify it
under the same terms as Perl itself.
=cut
# Local variables:
# c-indentation-style: bsd
# c-basic-offset: 4
# indent-tabs-mode: nil
# End:
# vim: expandtab shiftwidth=4:

View File

@@ -0,0 +1,361 @@
package Package::DeprecationManager;
use strict;
use warnings;
our $VERSION = '0.17';
use Carp qw( croak );
use List::Util 1.33 qw( any );
use Package::Stash;
use Params::Util qw( _HASH0 );
use Sub::Install;
use Sub::Name qw( subname );
sub import {
shift;
my %args = @_;
croak
'You must provide a hash reference -deprecations parameter when importing Package::DeprecationManager'
unless $args{-deprecations} && _HASH0( $args{-deprecations} );
my %registry;
my $caller = caller();
my $orig_import = $caller->can('import');
my $import = _build_import( \%registry, $orig_import );
my $warn
= _build_warn( \%registry, $args{-deprecations}, $args{-ignore} );
# We need to remove this to prevent a 'subroutine redefined' warning.
if ($orig_import) {
Package::Stash->new($caller)->remove_symbol('&import');
}
Sub::Install::install_sub(
{
code => subname( $caller . '::import', $import ),
into => $caller,
as => 'import',
}
);
Sub::Install::install_sub(
{
code => subname( $caller . '::deprecated', $warn ),
into => $caller,
as => 'deprecated',
}
);
return;
}
sub _build_import {
my $registry = shift;
my $orig_import = shift;
return sub {
my $class = shift;
my @args;
my $api_version;
## no critic (ControlStructures::ProhibitCStyleForLoops)
for ( my $i = 0; $i < @_; $i++ ) {
if ( $_[$i] eq '-api_version' || $_[$i] eq '-compatible' ) {
$api_version = $_[ ++$i ];
}
else {
push @args, $_[$i];
}
}
## use critic
my $caller = caller();
$registry->{$caller} = $api_version
if defined $api_version;
if ($orig_import) {
@_ = ( $class, @args );
goto &{$orig_import};
}
return;
};
}
sub _build_warn {
my $registry = shift;
my $deprecated_at = shift;
my $ignore = shift;
my %ignore = map { $_ => 1 } grep { !ref } @{ $ignore || [] };
my @ignore_res = grep {ref} @{ $ignore || [] };
my %warned;
return sub {
my %args = @_ < 2 ? ( message => shift ) : @_;
my ( $package, undef, undef, $sub ) = caller(1);
my $skipped = 1;
if ( @ignore_res || keys %ignore ) {
while ( defined $package
&& ( $ignore{$package} || any { $package =~ $_ } @ignore_res )
) {
$package = caller( $skipped++ );
}
}
$package = 'unknown package' unless defined $package;
unless ( defined $args{feature} ) {
$args{feature} = $sub;
}
my $compat_version = $registry->{$package};
my $at = $deprecated_at->{ $args{feature} };
return
if defined $compat_version
&& defined $deprecated_at
&& $compat_version lt $at;
my $msg;
if ( defined $args{message} ) {
$msg = $args{message};
}
else {
$msg = "$args{feature} has been deprecated";
$msg .= " since version $at"
if defined $at;
}
return if $warned{$package}{ $args{feature} }{$msg};
$warned{$package}{ $args{feature} }{$msg} = 1;
# We skip at least two levels. One for this anon sub, and one for the
# sub calling it.
local $Carp::CarpLevel = $Carp::CarpLevel + $skipped;
Carp::cluck($msg);
};
}
1;
# ABSTRACT: Manage deprecation warnings for your distribution
__END__
=pod
=encoding UTF-8
=head1 NAME
Package::DeprecationManager - Manage deprecation warnings for your distribution
=head1 VERSION
version 0.17
=head1 SYNOPSIS
package My::Class;
use Package::DeprecationManager -deprecations => {
'My::Class::foo' => '0.02',
'My::Class::bar' => '0.05',
'feature-X' => '0.07',
};
sub foo {
deprecated( 'Do not call foo!' );
...
}
sub bar {
deprecated();
...
}
sub baz {
my %args = @_;
if ( $args{foo} ) {
deprecated(
message => ...,
feature => 'feature-X',
);
}
}
package Other::Class;
use My::Class -api_version => '0.04';
My::Class->new()->foo(); # warns
My::Class->new()->bar(); # does not warn
My::Class->new()->bar(); # does not warn again
=head1 DESCRIPTION
This module allows you to manage a set of deprecations for one or more modules.
When you import C<Package::DeprecationManager>, you must provide a set of
C<-deprecations> as a hash ref. The keys are "feature" names, and the values
are the version when that feature was deprecated.
In many cases, you can simply use the fully qualified name of a subroutine or
method as the feature name. This works for cases where the whole subroutine is
deprecated. However, the feature names can be any string. This is useful if
you don't want to deprecate an entire subroutine, just a certain usage.
You can also provide an optional array reference in the C<-ignore>
parameter.
The values to be ignored can be package names or regular expressions (made
with C<qr//>). Use this to ignore packages in your distribution that can
appear on the call stack when a deprecated feature is used.
As part of the import process, C<Package::DeprecationManager> will export two
subroutines into its caller. It provides an C<import()> sub for the caller and a
C<deprecated()> sub.
The C<import()> sub allows callers of I<your> class to specify an C<-api_version>
parameter. If this is supplied, then deprecation warnings are only issued for
deprecations with API versions earlier than the one specified.
You must call the C<deprecated()> sub in each deprecated subroutine. When
called, it will issue a warning using C<Carp::cluck()>.
The C<deprecated()> sub can be called in several ways. If you do not pass any
arguments, it will generate an appropriate warning message. If you pass a
single argument, this is used as the warning message.
Finally, you can call it with named arguments. Currently, the only allowed
names are C<message> and C<feature>. The C<feature> argument should correspond
to the feature name passed in the C<-deprecations> hash.
If you don't explicitly specify a feature, the C<deprecated()> sub uses
C<caller()> to identify its caller, using its fully qualified subroutine name.
A given deprecation warning is only issued once for a given package. This
module tracks this based on both the feature name I<and> the error message
itself. This means that if you provide several different error messages for
the same feature, all of those errors will appear.
=head2 Other import() subs
This module works by installing an C<import> sub in any package that uses
it. If that package I<already> has an C<import> sub, then that C<import> will
be called after any arguments passed for C<Package::DeprecationManager> are
stripped out. You need to define your C<import> sub before you C<use
Package::DeprecationManager> to make this work:
package HasExporter;
use Exporter qw( import );
use Package::DeprecationManager -deprecations => {
'HasExporter::foo' => '0.02',
};
our @EXPORT_OK = qw( some_sub another_sub );
=head1 DONATIONS
If you'd like to thank me for the work I've done on this module, please
consider making a "donation" to me via PayPal. I spend a lot of free time
creating free software, and would appreciate any support you'd care to offer.
Please note that B<I am not suggesting that you must do this> in order
for me to continue working on this particular software. I will
continue to do so, inasmuch as I have in the past, for as long as it
interests me.
Similarly, a donation made in this way will probably not make me work on this
software much more, unless I get so many donations that I can consider working
on free software full time, which seems unlikely at best.
To donate, log into PayPal and send money to autarch@urth.org or use the
button on this page: L<http://www.urth.org/~autarch/fs-donation.html>
=head1 CREDITS
The idea for this functionality and some of its implementation was originally
created as L<Class::MOP::Deprecated> by Goro Fuji.
=head1 BUGS
Please report any bugs or feature requests to
C<bug-package-deprecationmanager@rt.cpan.org>, or through the web interface at
L<http://rt.cpan.org>. I will be notified, and then you'll automatically be
notified of progress on your bug as I make changes.
Bugs may be submitted through L<the RT bug tracker|http://rt.cpan.org/Public/Dist/Display.html?Name=Package-DeprecationManager>
(or L<bug-package-deprecationmanager@rt.cpan.org|mailto:bug-package-deprecationmanager@rt.cpan.org>).
I am also usually active on IRC as 'drolsky' on C<irc://irc.perl.org>.
=head1 DONATIONS
If you'd like to thank me for the work I've done on this module, please
consider making a "donation" to me via PayPal. I spend a lot of free time
creating free software, and would appreciate any support you'd care to offer.
Please note that B<I am not suggesting that you must do this> in order for me
to continue working on this particular software. I will continue to do so,
inasmuch as I have in the past, for as long as it interests me.
Similarly, a donation made in this way will probably not make me work on this
software much more, unless I get so many donations that I can consider working
on free software full time (let's all have a chuckle at that together).
To donate, log into PayPal and send money to autarch@urth.org, or use the
button at L<http://www.urth.org/~autarch/fs-donation.html>.
=head1 AUTHOR
Dave Rolsky <autarch@urth.org>
=head1 CONTRIBUTORS
=for stopwords Jesse Luehrs Karen Etheridge Tomas Doran
=over 4
=item *
Jesse Luehrs <doy@tozt.net>
=item *
Karen Etheridge <ether@cpan.org>
=item *
Tomas Doran <bobtfish@bobtfish.net>
=back
=head1 COPYRIGHT AND LICENCE
This software is Copyright (c) 2016 by Dave Rolsky.
This is free software, licensed under:
The Artistic License 2.0 (GPL Compatible)
=cut

View File

@@ -0,0 +1,306 @@
package Package::Stash; # git description: v0.38-23-gce01289
use strict;
use warnings;
use 5.008001;
# ABSTRACT: Routines for manipulating stashes
our $VERSION = '0.39';
our $IMPLEMENTATION;
use Module::Implementation 0.06;
BEGIN {
local $ENV{PACKAGE_STASH_IMPLEMENTATION} = $IMPLEMENTATION
if ( $IMPLEMENTATION and not $ENV{PACKAGE_STASH_IMPLEMENTATION} );
Module::Implementation::build_loader_sub(
implementations => [ 'XS', 'PP' ],
symbols => [qw(
new
name
namespace
add_symbol
remove_glob
has_symbol
get_symbol
get_or_add_symbol
remove_symbol
list_all_symbols
get_all_symbols
)],
)->();
$IMPLEMENTATION = Module::Implementation::implementation_for(__PACKAGE__);
}
__END__
=pod
=encoding UTF-8
=head1 NAME
Package::Stash - Routines for manipulating stashes
=head1 VERSION
version 0.39
=head1 SYNOPSIS
my $stash = Package::Stash->new('Foo');
$stash->add_symbol('%foo', {bar => 1});
# $Foo::foo{bar} == 1
$stash->has_symbol('$foo') # false
my $namespace = $stash->namespace;
*{ $namespace->{foo} }{HASH} # {bar => 1}
=head1 DESCRIPTION
Manipulating stashes (Perl's symbol tables) is occasionally necessary, but
incredibly messy, and easy to get wrong. This module hides all of that behind a
simple API.
NOTE: Most methods in this class require a variable specification that includes
a sigil. If this sigil is absent, it is assumed to represent the IO slot.
Due to limitations in the typeglob API available to perl code, and to typeglob
manipulation in perl being quite slow, this module provides two
implementations - one in pure perl, and one using XS. The XS implementation is
to be preferred for most usages; the pure perl one is provided for cases where
XS modules are not a possibility. The current implementation in use can be set
by setting C<$ENV{PACKAGE_STASH_IMPLEMENTATION}> or
C<$Package::Stash::IMPLEMENTATION> before loading Package::Stash (with the
environment variable taking precedence), otherwise, it will use the XS
implementation if possible, falling back to the pure perl one.
=head1 METHODS
=head2 new $package_name
Creates a new C<Package::Stash> object, for the package given as the only
argument.
=head2 name
Returns the name of the package that this object represents.
=head2 namespace
Returns the raw stash itself.
=head2 add_symbol $variable $value %opts
Adds a new package symbol, for the symbol given as C<$variable>, and optionally
gives it an initial value of C<$value>. C<$variable> should be the name of
variable including the sigil, so
Package::Stash->new('Foo')->add_symbol('%foo')
will create C<%Foo::foo>.
Valid options (all optional) are C<filename>, C<first_line_num>, and
C<last_line_num>.
C<$opts{filename}>, C<$opts{first_line_num}>, and C<$opts{last_line_num}> can
be used to indicate where the symbol should be regarded as having been defined.
Currently these values are only used if the symbol is a subroutine ('C<&>'
sigil) and only if C<$^P & 0x10> is true, in which case the special C<%DB::sub>
hash is updated to record the values of C<filename>, C<first_line_num>, and
C<last_line_num> for the subroutine. If these are not passed, their values are
inferred (as much as possible) from C<caller> information.
=head2 remove_glob $name
Removes all package variables with the given name, regardless of sigil.
=head2 has_symbol $variable
Returns whether or not the given package variable (including sigil) exists.
=head2 get_symbol $variable
Returns the value of the given package variable (including sigil).
=head2 get_or_add_symbol $variable
Like C<get_symbol>, except that it will return an empty hashref or
arrayref if the variable doesn't exist.
=head2 remove_symbol $variable
Removes the package variable described by C<$variable> (which includes the
sigil); other variables with the same name but different sigils will be
untouched.
=head2 list_all_symbols $type_filter
Returns a list of package variable names in the package, without sigils. If a
C<type_filter> is passed, it is used to select package variables of a given
type, where valid types are the slots of a typeglob ('SCALAR', 'CODE', 'HASH',
etc). Note that if the package contained any C<BEGIN> blocks, perl will leave
an empty typeglob in the C<BEGIN> slot, so this will show up if no filter is
used (and similarly for C<INIT>, C<END>, etc).
=head2 get_all_symbols $type_filter
Returns a hashref, keyed by the variable names in the package. If
C<$type_filter> is passed, the hash will contain every variable of that type in
the package as values, otherwise, it will contain the typeglobs corresponding
to the variable names (basically, a clone of the stash).
=for stopwords profilers
This is especially useful for debuggers and profilers, which use C<%DB::sub> to
determine where the source code for a subroutine can be found. See
L<http://perldoc.perl.org/perldebguts.html#Debugger-Internals> for more
information about C<%DB::sub>.
=head1 WORKING WITH VARIABLES
It is important to note, that when working with scalar variables, the default
behavior is to B<copy> values.
my $stash = Package::Stash->new('Some::Namespace');
my $variable = 1;
# $Some::Namespace::name is a copy of $variable
$stash->add_symbol('$name', $variable);
$variable++
# $Some::Namespace::name == 1 , $variable == 2
This will likely confuse people who expect it to work the same as typeglob
assignment, which simply creates new references to existing variables.
my $variable = 1;
{
no strict 'refs';
# assign $Package::Stash::name = $variable
*{'Package::Stash::name'} = \$variable;
}
$variable++ # affects both names
If this behaviour is desired when working with Package::Stash, simply pass
Package::Stash a scalar ref:
my $stash = Package::Stash->new('Some::Namespace');
my $variable = 1;
# $Some::Namespace::name is now $variable
$stash->add_symbol('$name', \$variable);
$variable++
# $Some::Namespace::name == 2 , $variable == 2
This will be what you want as well if you're ever working with L<Readonly>
variables:
use Readonly;
Readonly my $value, 'hello';
$stash->add_symbol('$name', \$value); # reference
print $Some::Namespace::name; # hello
# Tries to modify the read-only 'hello' and dies.
$Some::Namespace::name .= " world";
$stash->add_symbol('$name', $value); # copy
print $Some::Namespace::name; # hello
# No problem, modifying a copy, not the original
$Some::Namespace::name .= " world";
=head1 SEE ALSO
=over 4
=item * L<Class::MOP::Package>
This module is a factoring out of code that used to live here
=back
=head1 HISTORY
Based on code from L<Class::MOP::Package>, by Stevan Little and the Moose
Cabal.
=head1 BUGS / CAVEATS
=over 4
=item * Prior to perl 5.10, scalar slots are only considered to exist if they are defined
This is due to a shortcoming within perl itself. See
L<perlref/Making References> point 7 for more information.
=item * GLOB and FORMAT variables are not (yet) accessible through this module.
=item * Also, see the BUGS section for the specific backends (L<Package::Stash::XS> and L<Package::Stash::PP>)
=back
Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Package-Stash>
(or L<bug-Package-Stash@rt.cpan.org|mailto:bug-Package-Stash@rt.cpan.org>).
=head1 AUTHORS
=over 4
=item *
Stevan Little <stevan.little@iinteractive.com>
=item *
Jesse Luehrs <doy@tozt.net>
=back
=head1 CONTRIBUTORS
=for stopwords Karen Etheridge Carlos Lima Dave Rolsky Justin Hunter Christian Walde Kent Fredric Niko Tyni Renee Tim Bunce
=over 4
=item *
Karen Etheridge <ether@cpan.org>
=item *
Carlos Lima <carlos@multi>
=item *
Dave Rolsky <autarch@urth.org>
=item *
Justin Hunter <justin.d.hunter@gmail.com>
=item *
Christian Walde <walde.christian@googlemail.com>
=item *
Kent Fredric <kentfredric@gmail.com>
=item *
Niko Tyni <ntyni@debian.org>
=item *
Renee <reb@perl-services.de>
=item *
Tim Bunce <Tim.Bunce@pobox.com>
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2020 by Jesse Luehrs.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut

View File

@@ -0,0 +1,35 @@
package # hide from PAUSE
Package::Stash::Conflicts;
use strict;
use warnings;
# this module was generated with Dist::Zilla::Plugin::Conflicts 0.19
use Dist::CheckConflicts
-dist => 'Package::Stash',
-conflicts => {
'Class::MOP' => '1.08',
'MooseX::Method::Signatures' => '0.36',
'MooseX::Role::WithOverloading' => '0.08',
'namespace::clean' => '0.18',
},
-also => [ qw(
B
Carp
Dist::CheckConflicts
Getopt::Long
Module::Implementation
Scalar::Util
Symbol
constant
strict
warnings
) ],
;
1;
# ABSTRACT: Provide information on conflicts for Package::Stash
# Dist::Zilla: -PodWeaver

View File

@@ -0,0 +1,501 @@
package Package::Stash::PP;
use strict;
use warnings;
# ABSTRACT: Pure perl implementation of the Package::Stash API
our $VERSION = '0.39';
use B;
use Carp qw(confess);
use Scalar::Util qw(blessed reftype weaken);
use Symbol;
# before 5.12, assigning to the ISA glob would make it lose its magical ->isa
# powers
use constant BROKEN_ISA_ASSIGNMENT => ($] < 5.012);
# before 5.10, stashes don't ever seem to drop to a refcount of zero, so
# weakening them isn't helpful
use constant BROKEN_WEAK_STASH => ($] < 5.010);
# before 5.10, the scalar slot was always treated as existing if the
# glob existed
use constant BROKEN_SCALAR_INITIALIZATION => ($] < 5.010);
# add_method on anon stashes triggers rt.perl #1804 otherwise
# fixed in perl commit v5.13.3-70-g0fe688f
use constant BROKEN_GLOB_ASSIGNMENT => ($] < 5.013004);
# pre-5.10, ->isa lookups were cached in the ::ISA::CACHE:: slot
use constant HAS_ISA_CACHE => ($] < 5.010);
#pod =head1 SYNOPSIS
#pod
#pod use Package::Stash;
#pod
#pod =head1 DESCRIPTION
#pod
#pod 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.
#pod
#pod =cut
sub new {
my $class = shift;
my ($package) = @_;
if (!defined($package) || (ref($package) && reftype($package) ne 'HASH')) {
confess "Package::Stash->new must be passed the name of the "
. "package to access";
}
elsif (ref($package) && reftype($package) eq 'HASH') {
confess "The PP implementation of Package::Stash does not support "
. "anonymous stashes before perl 5.14"
if BROKEN_GLOB_ASSIGNMENT;
return bless {
'namespace' => $package,
}, $class;
}
elsif ($package =~ /\A[0-9A-Z_a-z]+(?:::[0-9A-Z_a-z]+)*\z/) {
return bless {
'package' => $package,
}, $class;
}
else {
confess "$package is not a module name";
}
}
sub name {
confess "Can't call name as a class method"
unless blessed($_[0]);
confess "Can't get the name of an anonymous package"
unless defined($_[0]->{package});
return $_[0]->{package};
}
sub namespace {
confess "Can't call namespace as a class method"
unless blessed($_[0]);
if (BROKEN_WEAK_STASH) {
no strict 'refs';
return \%{$_[0]->name . '::'};
}
else {
return $_[0]->{namespace} if defined $_[0]->{namespace};
{
no strict 'refs';
$_[0]->{namespace} = \%{$_[0]->name . '::'};
}
weaken($_[0]->{namespace});
return $_[0]->{namespace};
}
}
{
my %SIGIL_MAP = (
'$' => 'SCALAR',
'@' => 'ARRAY',
'%' => 'HASH',
'&' => 'CODE',
'' => 'IO',
);
sub _deconstruct_variable_name {
my ($variable) = @_;
my @ret;
if (ref($variable) eq 'HASH') {
@ret = @{$variable}{qw[name sigil type]};
}
else {
(defined $variable && length $variable)
|| confess "You must pass a variable name";
my $sigil = substr($variable, 0, 1, '');
if (exists $SIGIL_MAP{$sigil}) {
@ret = ($variable, $sigil, $SIGIL_MAP{$sigil});
}
else {
@ret = ("${sigil}${variable}", '', $SIGIL_MAP{''});
}
}
# XXX in pure perl, this will access things in inner packages,
# in xs, this will segfault - probably look more into this at
# some point
($ret[0] !~ /::/)
|| confess "Variable names may not contain ::";
return @ret;
}
}
sub _valid_for_type {
my ($value, $type) = @_;
if ($type eq 'HASH' || $type eq 'ARRAY'
|| $type eq 'IO' || $type eq 'CODE') {
return reftype($value) eq $type;
}
else {
my $ref = reftype($value);
return !defined($ref) || $ref eq 'SCALAR' || $ref eq 'REF' || $ref eq 'LVALUE' || $ref eq 'REGEXP' || $ref eq 'VSTRING';
}
}
sub add_symbol {
my ($self, $variable, $initial_value, %opts) = @_;
my ($name, $sigil, $type) = _deconstruct_variable_name($variable);
if (@_ > 2) {
_valid_for_type($initial_value, $type)
|| confess "$initial_value is not of type $type";
# cheap fail-fast check for PERLDBf_SUBLINE and '&'
if ($^P and $^P & 0x10 && $sigil eq '&') {
my $filename = $opts{filename};
my $first_line_num = $opts{first_line_num};
(undef, $filename, $first_line_num) = caller
if not defined $filename;
my $last_line_num = $opts{last_line_num} || ($first_line_num ||= 0);
# http://perldoc.perl.org/perldebguts.html#Debugger-Internals
$DB::sub{$self->name . '::' . $name} = "$filename:$first_line_num-$last_line_num";
}
}
if (BROKEN_GLOB_ASSIGNMENT) {
if (@_ > 2) {
no strict 'refs';
no warnings 'redefine';
*{ $self->name . '::' . $name } = ref $initial_value
? $initial_value : \$initial_value;
}
else {
no strict 'refs';
if (BROKEN_ISA_ASSIGNMENT && $name eq 'ISA') {
*{ $self->name . '::' . $name };
}
else {
my $undef = _undef_ref_for_type($type);
*{ $self->name . '::' . $name } = $undef;
}
}
}
else {
my $namespace = $self->namespace;
{
# using glob aliasing instead of Symbol::gensym, because otherwise,
# magic doesn't get applied properly.
# see <20120710063744.19360.qmail@lists-nntp.develooper.com> on p5p
local *__ANON__:: = $namespace;
no strict 'refs';
no warnings 'void';
no warnings 'once';
*{"__ANON__::$name"};
}
if (@_ > 2) {
no warnings 'redefine';
*{ $namespace->{$name} } = ref $initial_value
? $initial_value : \$initial_value;
}
else {
return if BROKEN_ISA_ASSIGNMENT && $name eq 'ISA';
*{ $namespace->{$name} } = _undef_ref_for_type($type);
}
}
}
sub _undef_ref_for_type {
my ($type) = @_;
if ($type eq 'ARRAY') {
return [];
}
elsif ($type eq 'HASH') {
return {};
}
elsif ($type eq 'SCALAR') {
return \undef;
}
elsif ($type eq 'IO') {
return Symbol::geniosym;
}
elsif ($type eq 'CODE') {
confess "Don't know how to vivify CODE variables";
}
else {
confess "Unknown type $type in vivication";
}
}
sub remove_glob {
my ($self, $name) = @_;
delete $self->namespace->{$name};
}
sub has_symbol {
my ($self, $variable) = @_;
my ($name, $sigil, $type) = _deconstruct_variable_name($variable);
my $namespace = $self->namespace;
return unless exists $namespace->{$name};
my $entry_ref = \$namespace->{$name};
if (reftype($entry_ref) eq 'GLOB') {
if ($type eq 'SCALAR') {
if (BROKEN_SCALAR_INITIALIZATION) {
return defined ${ *{$entry_ref}{$type} };
}
else {
my $sv = B::svref_2object($entry_ref)->SV;
return $sv->isa('B::SV')
|| ($sv->isa('B::SPECIAL')
&& $B::specialsv_name[$$sv] ne 'Nullsv');
}
}
else {
return defined *{$entry_ref}{$type};
}
}
else {
# a symbol table entry can be -1 (stub), string (stub with prototype),
# or reference (constant)
return $type eq 'CODE';
}
}
sub get_symbol {
my ($self, $variable, %opts) = @_;
my ($name, $sigil, $type) = _deconstruct_variable_name($variable);
my $namespace = $self->namespace;
if (!exists $namespace->{$name}) {
if ($opts{vivify}) {
$self->add_symbol($variable);
}
else {
return undef;
}
}
my $entry_ref = \$namespace->{$name};
if (ref($entry_ref) eq 'GLOB') {
return *{$entry_ref}{$type};
}
else {
if ($type eq 'CODE') {
if (BROKEN_GLOB_ASSIGNMENT || defined($self->{package})) {
no strict 'refs';
return \&{ $self->name . '::' . $name };
}
# XXX we should really be able to support arbitrary anonymous
# stashes here... (not just via Package::Anon)
if (blessed($namespace) && $namespace->isa('Package::Anon')) {
# ->can will call gv_init for us, which inflates the glob
# don't know how to do this in general
$namespace->bless(\(my $foo))->can($name);
}
else {
confess "Don't know how to inflate a " . ref($entry_ref)
. " into a full coderef (perhaps you could use"
. " Package::Anon instead of a bare stash?)"
}
return *{ $namespace->{$name} }{CODE};
}
else {
return undef;
}
}
}
sub get_or_add_symbol {
my $self = shift;
$self->get_symbol(@_, vivify => 1);
}
sub remove_symbol {
my ($self, $variable) = @_;
my ($name, $sigil, $type) = _deconstruct_variable_name($variable);
# FIXME:
# no doubt this is grossly inefficient and
# could be done much easier and faster in XS
my %desc = (
SCALAR => { sigil => '$', type => 'SCALAR', name => $name },
ARRAY => { sigil => '@', type => 'ARRAY', name => $name },
HASH => { sigil => '%', type => 'HASH', name => $name },
CODE => { sigil => '&', type => 'CODE', name => $name },
IO => { sigil => '', type => 'IO', name => $name },
);
confess "This should never ever ever happen" if !$desc{$type};
my @types_to_store = grep { $type ne $_ && $self->has_symbol($desc{$_}) }
keys %desc;
my %values = map { $_, $self->get_symbol($desc{$_}) } @types_to_store;
$values{SCALAR} = $self->get_symbol($desc{SCALAR})
if !defined $values{SCALAR}
&& $type ne 'SCALAR'
&& BROKEN_SCALAR_INITIALIZATION;
$self->remove_glob($name);
$self->add_symbol($desc{$_} => $values{$_})
for grep { defined $values{$_} } keys %values;
}
sub list_all_symbols {
my ($self, $type_filter) = @_;
my $namespace = $self->namespace;
if (HAS_ISA_CACHE) {
return grep { $_ ne '::ISA::CACHE::' } keys %{$namespace}
unless defined $type_filter;
}
else {
return keys %{$namespace}
unless defined $type_filter;
}
# NOTE:
# or we can filter based on
# type (SCALAR|ARRAY|HASH|CODE)
if ($type_filter eq 'CODE') {
return grep {
# any non-typeglob in the symbol table is a constant or stub
ref(\$namespace->{$_}) ne 'GLOB'
# regular subs are stored in the CODE slot of the typeglob
|| defined(*{$namespace->{$_}}{CODE})
} keys %{$namespace};
}
elsif ($type_filter eq 'SCALAR') {
return grep {
!(HAS_ISA_CACHE && $_ eq '::ISA::CACHE::') &&
(BROKEN_SCALAR_INITIALIZATION
? (ref(\$namespace->{$_}) eq 'GLOB'
&& defined(${*{$namespace->{$_}}{'SCALAR'}}))
: (do {
my $entry = \$namespace->{$_};
ref($entry) eq 'GLOB'
&& B::svref_2object($entry)->SV->isa('B::SV')
}))
} keys %{$namespace};
}
else {
return grep {
ref(\$namespace->{$_}) eq 'GLOB'
&& defined(*{$namespace->{$_}}{$type_filter})
} keys %{$namespace};
}
}
sub get_all_symbols {
my ($self, $type_filter) = @_;
my $namespace = $self->namespace;
return { %{$namespace} } unless defined $type_filter;
return {
map { $_ => $self->get_symbol({name => $_, type => $type_filter}) }
$self->list_all_symbols($type_filter)
}
}
__END__
=pod
=encoding UTF-8
=head1 NAME
Package::Stash::PP - Pure perl implementation of the Package::Stash API
=head1 VERSION
version 0.39
=head1 SYNOPSIS
use Package::Stash;
=head1 DESCRIPTION
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.
=for stopwords TODO
=over 4
=item * remove_symbol also replaces the associated typeglob
This can cause unexpected behavior when doing manipulation at compile time -
removing subroutines will still allow them to be called from within the package
as subroutines (although they will not be available as methods). This can be
considered a feature in some cases (this is how L<namespace::clean> works, for
instance), but should not be relied upon - use C<remove_glob> directly if you
want this behavior.
=item * Some minor memory leaks
The pure perl implementation has a couple minor memory leaks (see the TODO
tests in t/20-leaks.t) that I'm having a hard time tracking down - these may be
core perl bugs, it's hard to tell.
=back
=head1 SEE ALSO
=over 4
=item * L<Class::MOP::Package>
This module is a factoring out of code that used to live here
=back
=for Pod::Coverage BROKEN_ISA_ASSIGNMENT
add_symbol
get_all_symbols
get_or_add_symbol
get_symbol
has_symbol
list_all_symbols
name
namespace
new
remove_glob
=head1 BUGS
Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Package-Stash>
(or L<bug-Package-Stash@rt.cpan.org|mailto:bug-Package-Stash@rt.cpan.org>).
=head1 AUTHOR
Mostly copied from code from L<Class::MOP::Package>, by Stevan Little and the
Moose Cabal.
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2020 by Jesse Luehrs.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut

View File

@@ -0,0 +1,137 @@
package Package::Stash::XS; # git description: 4627d81
use strict;
use warnings;
use 5.008001;
# ABSTRACT: faster and more correct implementation of the Package::Stash API
our $VERSION = '0.29';
use XSLoader;
XSLoader::load(
__PACKAGE__,
# we need to be careful not to touch $VERSION at compile time, otherwise
# DynaLoader will assume it's set and check against it, which will cause
# fail when being run in the checkout without dzil having set the actual
# $VERSION
exists $Package::Stash::XS::{VERSION}
? ${ $Package::Stash::XS::{VERSION} } : (),
);
1;
__END__
=pod
=encoding UTF-8
=head1 NAME
Package::Stash::XS - faster and more correct implementation of the Package::Stash API
=head1 VERSION
version 0.29
=head1 SYNOPSIS
use Package::Stash;
=head1 DESCRIPTION
This is a backend for L<Package::Stash>, which provides the functionality in a
way that's less buggy and much faster. It will be used by default if it's
installed, and should be preferred in all environments with a compiler.
=head1 SEE ALSO
L<Package::Stash>
=head1 SUPPORT
You can find this documentation for this module with the perldoc command.
perldoc Package::Stash::XS
You can also look for information at:
=over 4
=item * MetaCPAN
L<https://metacpan.org/release/Package-Stash-XS>
=item * Github
L<https://github.com/moose/Package-Stash-XS>
=item * RT: CPAN's request tracker
L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Stash-XS>
=item * CPAN Ratings
L<http://cpanratings.perl.org/d/Package-Stash-XS>
=back
=for Pod::Coverage add_symbol
get_all_symbols
get_or_add_symbol
get_symbol
has_symbol
list_all_symbols
name
namespace
new
remove_glob
remove_symbol
=head1 BUGS
No known bugs (but see the BUGS section in L<Package::Stash>).
Bugs may be submitted through L<the RT bug tracker|https://rt.cpan.org/Public/Dist/Display.html?Name=Package-Stash-XS>
(or L<bug-Package-Stash-XS@rt.cpan.org|mailto:bug-Package-Stash-XS@rt.cpan.org>).
=head1 AUTHOR
Jesse Luehrs <doy@tozt.net>
=head1 CONTRIBUTORS
=for stopwords Florian Ragwitz Karen Etheridge Dave Rolsky Justin Hunter Tim Bunce
=over 4
=item *
Florian Ragwitz <rafl@debian.org>
=item *
Karen Etheridge <ether@cpan.org>
=item *
Dave Rolsky <autarch@urth.org>
=item *
Justin Hunter <justin.d.hunter@gmail.com>
=item *
Tim Bunce <Tim.Bunce@pobox.com>
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2018 by Jesse Luehrs.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut