=pod

=head1 NAME

Package::Autoloader - modular wrapper for 'AUTOLOAD' with dynamic export


=head1 SYNOPSIS

The following basic example demonstrates how subroutine generation is done and how packages can facilitate the potential.

	package Synopsis;
	use Package::Autoloader sub{eval shift}, sub {
		my $generator = q{
			my $greet = substr($sub_name, 6); #magic
	 		return(qq{print 'Hello $greet\n'});
		};
		$_[0]->register_rule($generator, '+::*', 'greet_');
	};

	
	package Synopsis::Desc1;
	use Package::Autoloader sub{eval shift};
	
	greet_mundo();

	
	package sisponyS::Desc2;
	our @ISA = ('Synopsis');
	use Package::Autoloader sub{eval shift};
	
	my $obj = bless( \(my $o = 0), 'sisponyS::Desc2');
	$obj->greet_monde();


All examples in this document can be found as separate perl files in
the examples directory.

The dynamically generated subroutines greet_mundo and greet_monde print Hello plus the second part of their name to the screen. The example makes maximum use of convenience features.

The package sisponyS::Desc2 should remind you that 'can', 'defined' and 'exists' are not aware of AUTOLOAD. However, there are two subroutines potentially_can, and potentially_defined, which are aware of Package::Autoloader. Details below.


=head1 WARNING

This is an experimental module. It hasn't been thoroughly tested, making the probability of fatal bugs quiet high. The goal of the release is to document the current development.


=head1 DESCRIPTION

Package::Autoloader supplies packages with subroutine definitions on the fly. It requires individual activation with the sub-eval-shift like shown in the synopsis. This module complements L<Package::Transporter>.

Once a missing subroutine is encountered, Perl's autoload mechanism forwards the request to an autoloader object and a tree of rules is checked for a matching generator. If one is found, the generator should bring the requested subroutine into existence.

Rules are searched hierarchically through he components of the package name. For the package A::B::C the name hierarchy is A::B::C, A::B::, A::, and ''. Any rule found on the way to the top is checked and if the check is successful, the search stops.

From a practical point of view, Package::Autoloader enables you to specify autoloading in terms of modular rules instead of a monolithic AUTOLOAD subroutine. The rules are normally activated during compile time.

The following lines, added to the synopsis, should print the words No, No, Yes to the screen. The method greet_monde springs into existence as a subroutine in a parent class. The reverse name sisponyS should stress that the search goes along @ISA (using whatever MRO is in effect).

	sub print_yn($) { print STDOUT (($_[0]) ? 'Yes' : 'No'), "\n"; }
	print_yn(defined(&sisponyS::Desc2::greet_monde));
	print_yn(defined(&Synopsis::Desc1::greet_monde));
	print_yn(defined(&Synopsis::greet_monde));


=head2 Convenience Functions

The method register_rule has a convenience mode, where it accepts three-argument rule shortcuts. The first argument is a generator, the second is a wildcard and the third is the matching subroutine pattern.

Minimally the generator is the textual body of a subroutine, which should at least generate textual bodies of other subroutines.

The wildcard is one of the following four symbols:

=over 8

=item a single plus '+' means the rule applies to the package itself only, although the generated subroutines follow inheritance;

=item a double colon followed by an asterisk '::*' means the rule applies to package names deeper in the hierarchy, so that the rules defined in Synopis applies to Synopsis::Desc1;

=item combination of the above symbols '+::*' is a combination of the functions; and

=item a single asterisk '*' means the rule applies globally other packages, including itself;

=back

The third argument can be either a single subroutine name, an array reference of full names, a partial name ending in underscore or a textual regular expression (not the result of qr//).


=head2 Subroutine Potential

Whether a package has potential for a subroutine can be tested with the utility functions potentially_(can|defined). They can be explicitely activated (e.g. in a parent class). Either globally by setting Package::Autoloader::Package::CANDEFINED=1 or individually by using the following technique:

	package Synopsis::Desc1;
	use Package::Autoloader sub{eval shift}, sub{
		$_[0]->potentially_candefinded;
	};

The dynamic functions take the name of a subroutine (meaning a string) as an argument and return true or false. That makes their use consistent, but different from from their static counterparts 'can' and 'defined'.

	if(potentially_defined('turbo_mode')) ...
	if($obj->potentially_can('turbo_mode')) ...

potentially_can does not return a subroutine reference, because it is about potential and thus it does not do autovivification. Beside that, potentially_can is potentially expensive. Remember Perl supports multiple inheritance, so that a search for rules has to go through the tree of parent classes (linearised though) and through the name hierarchy of each class. A lot of each to ensure that the method name in question springs into existence in the right defining parent class.

There is no potentially_exists, because the rule system in Package::Autoloader doesn't distinguish between defined and exists, because AUTOLOAD doesn't tell whether a prototype is requested or a full subroutine definition. It would be useful to automatically generate prototypes, which would solve the problem described in in the BUGS section below. Background: 'exists' considers even prototypes and names treated with undef (crazy, eh?), while 'defined' only considers (fully) defined subroutines. You probably want to use the combination of can and defined for most practical purposes.


=head2 Visit Points

By default a missing subroutine is defined inside a package via an eval. The eval is passed around through the anonymous subroutine reference sub{eval shift}. This construct is called a visit point for the purpose of this documentation.

It is actually a fast solution, easy to understand, and with straightforward results, bearing only a few surprises. Direct symbol table manipulations can't achieve the same, so its futile to discuss whether they are faster or slower with regards to the overall effort.

Every package using Package::Autoloader gets an individual AUTOLOAD subroutine. That appeared to be the most robust approach and allows for a 'use strict' without exceptions.


=head1 RULES

The two rules from the synopsis conveniently hide the full interface for rules. You can specify rules in three ways

=over 8

=item * by giving B<a generator, a wildcard and a subroutine specification> - a minimal rule object will be created;

=item * by giving B<an array holding parameters for new()> - a rule object will be instantiated accordingly;

=item * by giving B<a ready-make rule object> - will be taken as-is.

=back


=head2 Rule Details

A rule is a check whether a generator applies to a missing subroutine. Example: a call for Ex::Ample::no_such_thing(7, [8, 9]) will cause these style of checks to occur internally:

	$rule->check('Ex::Ample', 'no_such_thing', 1, 7, [8, 9]);

Included in Package::Autoloader is the general-purpose rule class Package::Autoloader::Rule. To create a rule object for the above example, use it as follows:

	use Package::Autoloader::Rule;
	my $rule = Package::Autoloader::Rule->new
		($generator, 'Ex::Ample', 'no_such_thing', 1, '', 'ARRAY');

However, it is not required to specify all details; normally the last item in rule creation is the subroutine name. Note that the standard rule class does not check the values of arguments, but rather the result of ref().

In order to minimize the number of rules to evaluate, they are organized by purpose, package name, and subroutine name. Internally the above rule will be stored in the pre-selection tree under

	'Ex::Ample' => {'no_' => [$rule]}

This detail only needs to be considered when you write your own rules class. See the pre_select attribute in the standard class.

To widen the scope of a hierarchy search rule, shorten the names. Ex:: applies to all package names starting with Ex:: (no wildcard required), Ex::(A|B|C) is recognized as a regular expression and an empty package name applies to all packages. Alternatively you can specify a list of complete names (meaning these won't undergo wildcard interpretation) as an array reference.

Similarly for subroutine names (any kind of search). Specify no_ to match a name starting with no_ (partial subroutine name ending in underscore but no wildcard required), no_(parking|money) is recognized as a regular expression and an empty subroutine name applies to all subroutines. Alternatively you can specify a list of complete names (meaning these won't undergo wildcard interpretation) as an array reference.


=head2 Generators

A generator is an anonymous subroutine, which is called with all information its rule check got plus a package object. Valid return values are:

=over 8

=item * B<a string not looking like a complete subroutine definition> - surroundings are added automatically.

=item * B<a string starting with 'sub '> - taken as a complete definition of the missing subroutine and submitted to the eval(). Note that the string should include a return statement for a reference to the subroutine after the definition. 

=item * B<a CODE reference> - assuming the generator already did all necessary steps, the reference is passed to the upper layers, where it will eventually hit the goto &$reference in the autoloader.

=back


The first parameter to the generator call is a package object. The generator can use the package object to submit code to the package via ->transport(). While you have access to lexical variables declared before the visit point, you can't create them. Because eval behaves like a block, not like an inline instruction.

There is no general-purpose generator shipped with Package::Autoloader, because that function is covered by Package::Transporter. Autoloader is about demand, Transporter is about supply; they complement each other. Keep in mind that you can't autoload constant functions in Perl. 

A manual crafted generator looks like the following:

	my $generator = sub { 
		my ($pkg, $sub_name, $argc) = (shift, shift, shift);

		#... do something to create the $sub_ref

		return($sub_ref);
	};


=head1 PUBLIC INTERFACE REFERENCE

The following methods belong to the  public interface of Package::Autoloader::Package.

=over 8

=item B<potentially_candefined>

Activates the two subroutines potentially_can and potentially_defined for the current package.

=item B<$Package::Autoloader::Package::CANDEFINDED>

A package global to activate potentially_candefined for all packages. Please note you have to set it in a BEGIN block.

=item B<register_rule>

Trigger the convenience function as described above.

=item B<export>

Trigger the export function as described below. It is actually a rule registration with a pre-defined generator suitable for export of existing subroutines.

=back


=head1 EXAMPLES

The following example demonstrates the use of the on-demand export function.

	package Synopsis;
	use Package::Autoloader sub{eval shift}, sub {
		$_[0]->export('::*', ['hello_world']);
	};
	
	sub hello_world() { print "Hello World.\n"; };
	
	package Synopsis::Ex1;
	use Package::Autoloader sub{eval shift};
	
	print STDOUT (defined(&hello_world) ? 'Can':'Cannot'),"\n";
	print STDOUT (potentially_defined('hello_world') ? 'Can':'Cannot'),"\n";
	
	hello_world();

The following example is one of those tempting idea which turn out to be a bug farm. The example enables set-style accessors for objects globally. You will probably prefer to use Package::Transporter for this purpose.

	use Package::Autoloader sub{eval shift}, sub {
		my $generator = q{
			my $name = substr($sub_name, 4);
			my $sub_text = sprintf(q{
				my $self = shift;
				$self->{%s} = shift;
			}, $name);
	 		return($sub_text);
		};
		$_[0]->register_rule($generator, '*', 'set_');
	};
	my $obj = bless( {}, 'main');
	$obj->set_world(1);

Closures are a fancy application for Autoloader. The following example creates subroutine names, which carry one argument in their name.

	use Package::Autoloader sub{eval shift}, sub {
		my $calc_generic = sub { return($_[1] * $_[0]/100 + $_[2]); };
		my $generator = sub {
			my ($pkg, $sub_name, $argc) = (shift, shift, shift);
			my $argument = substr($sub_name, 5) || 100;
			my $sub_text = sprintf(q{
	my ($calc_generic, $arg1) = (shift(@_), shift(@_));
	sub %s { return($calc_generic->($arg1, @_)); };
	return(\&%s);
			}, $sub_name, $sub_name);
	
			my $sub_ref = $pkg->transport(\$sub_text,
				$calc_generic, $argument);
	 		return($sub_ref);
		};
		$_[0]->register_rule($generator, '*', 'calc_');
	};
	
	print calc_5(7, 8); # same as $calc_generic->(5, 7, 8);
	exit(0);

However, don't believe that closures are closed - you can hijack anything in Perl 5.

=head1 BUGS AND LIMITATIONS

Please report unknown bugs via the "CPAN Request Tracker", which is the default way of managing such reports. If that is too much of hassle, then just drop me a note to the e-mail address below.

http://rt.cpan.org/NoAuth/Bugs.html?Dist=Package-Autoloader

This is an early public release. Also see the Todo file.

=head2 Prototypes

Imagine the following situation, where subroutine A calls B and vice versa (so that you can't simply change the order):

	sub A($) { ... B(2, 8); ... }
	sub B($) { ... A(7); ... }

Perl should complain that it can't verify the arguments for the call to B(2), because B is not defined, yet. The solution are subroutine prototypes (forward declarations). AUTOLOAD does not indicate whether a prototype definition is sufficient, so you can only solve the above situation by manually supplying prototypes, which renders AUTOLOAD nearly useless.

=head1 AUTHOR

Winfried Trumper E<lt>pub+perl(a)wt.tuxomania.netE<gt>


=head1 COPYRIGHT

Copyright (C) 2010 Winfried Trumper

This module is free software; you can redistribute it and/or modify it
under the same terms as Perl itself.


=head1 SEE ALSO

L<Package::Transporter> complements Package::Autoloader in various ways.

=head2 Relations

Some of the exporter modules create subroutines on the fly, most notably Sub::Exporter and Class::Exporter. The compatibility of 'AUTOLOAD' and 'can' is addressed by L<Class::AutoloadCAN>.


=cut
