=pod

=head1 NAME

Package::Autoloader - a modular and OO-aware interface to AUTOLOAD

=head1 SYNOPSIS

The following code registers two rules for use by AUTOLOAD. It demonstrates the tasks you can address with Package::Autoloader: consume rules and define rules for automatic subroutine generation. All yes-no-tests are written to print 'Yes'.


	package Synopsis;
	use Package::Autoloader sub{eval shift}, sub {
		$_[0]->register_rule('::Export', '::*', ['hello_world']);
		$_[0]->register_rule('::Hello_Anything', '=', 'salut_');
	};
	
	sub hello_world { print "Hello World.\n"; }
	
	
	package Synopsis::Desc1;
	use Package::Autoloader sub{eval shift};
	
	yn(!defined(&hello_world));
	yn(potentially_defined('hello_world'));
	
	hello_world(); # first rule
	
	yn(defined(&hello_world));
	
	
	package sisponyS::Desc2;
	our @ISA = ('Synopsis');
	use Package::Autoloader sub{eval shift};
	
	my $obj = bless( \(my $o = 0), 'sisponyS::Desc2');
	
	yn(!potentially_defined('hello_world')); # name is sisponyS::
	yn(!defined(&salut_monde));
	yn(!potentially_defined('salut_monde'));
	yn($obj->potentially_can('salut_monde')); # no autovivification
	yn($obj->can('salut_monde')); # with autovivification
	
	$obj->salut_monde(); # second rule
	
	yn(!defined(&sisponyS::Desc2::salut_monde));
	yn(!defined(&Synopsis::Desc1::salut_monde));
	yn(defined(&Synopsis::salut_monde));
	
	package main;
	use Package::Autoloader sub{eval shift}, sub {
		my $yn = q{
	 		return(q{print STDOUT ($_[0] ? 'Yes' : 'No'), "\n";});
		};
		$_[0]->register_rule($yn, '*', 'yn');
	};
	
	exit(0);


Code examples in this document can be found as separate Perl files in the examples directory.

The dynamically generated subroutine salut_monde print Hello plus the second part of its name to the screen. (The impartial translation is intentional to stress what is happening - this package is not about localisation.) The synopsis makes maximum use of convenience features, which hide the full flexibility of the interface. For more details on what happens above, see the tests for definedness in L<Package::Autoloader::Generator::Hello_Anything>.


=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.

Another warning. This package allows you to facilitate different origins for subroutine definitions, which are then passed to eval(). Control over an origin - file system or data base - means control over your program. Keep that in mind to avoid unpleasant surprises.


=head1 DESCRIPTION

Package::Autoloader makes AUTOLOAD a two-line subroutine, which forwards all requests into a rule-based dispatch. Thus allowing more than one feature to be based on AUTOLOAD. Actual generation of subroutines is done by generator classes.

Simple rules allow generators to be attached to requests for missing subroutines. This way generators can be kept generic. Wildcards for package names and subroutine names are supported. A pre-selection tree ensures that only relevant rules are considered.

The $_[0] from the synopsis is a package object, which gives access to a package via a visit point. The object is monadic on a per-package basis, meaning that in the package Synopsis it is always the same $pkg and the 'new' is a 'new only if no old exists'. Execution of arbitrary code is done like this:

	$pkg = Package::Autoloader->new(sub{eval shift});
	$pkg->transport(\$code, $argument1, ...);

Although the above is a more complicated way to say "eval $code", the $pkg object can be passed around and is available in the generator. Actually two $pkg objects are avaialble there, the one of the defining package ($defining_pkg) and the one of the consuming package ($pkg). The $arguments to transport enable exchange of living data structures between packages without serialisation into the string $code.

Package::Autoloader affects only packages which use it. Consumption requires individual activation with the sub-eval-shift like shown in the synopsis. This module complements L<Package::Transporter>.

The implementation should be straightforward and involves at least five method calls to respond to an AUTOLOAD request. Some informal code might illustrate what happens. Each step uses the results of the former step; details are omitted here.

	AUTOLOAD(...)
		$pkg->autoload(...)
			$RULES->lookup(...)
				$rule->check(...)
				$rule->check(...) # eventually
				...
			$generator->run(...)
		$pkg->transport(...)
	goto &$autloaded_sub

=head2 Motivation and Background

In Perl5 subroutines are brought into existence on demand via AUTOLOAD. It's a monolithic subroutine and handles exactly one package. Although AUTOLOAD is simple to use for trivial cases, it immediately looses its simplicity when doing OO programming. AUTOLOAD is subject to be overridden by other AUTOLOAD routines as part of OO. As a consequence, one has to find the parent AUTOLOADs with SUPER:: or mro::next::method and write them all in a specific way. Simplicity has already gone by then. That it the whole point.

Package::Autoloader can be seen as an AUTOLOAD object, which hides the complexity of AUTOLOAD in non-trivial cases.

Another problem is the drain of Exporter. Autoloaded subroutines spring into existence when exported. In general that is more problematic than it sounds. Consider these two concepts of AUTOLOAD:

#1 Unlimited potential, which is tapped only when the missing subroutine is called. Export is about neither, because it requires full names in advance.

#2 Auto-vivification is conflict-free. AUTOLOAD never creates a subroutine with the same name of an existing subroutine. But export does that.

Again, in the general case one would like to see the potential being exported, not the drain. Package::Autoloader provides that.

Last but not least, the functions can, exists and defined are not aware of AUTOLOAD. That is a good thing, because it allows for differentiated views. But one would like to test for potential, too. Package::Autoloader adds new functions, which are called potentially_can and potentially_defined. They report potential without vivification of the subroutine. There is no potentially_exists, because it is a subtle distinction from defined, which can't be made with the information in AUTOLOAD.


=head2 Consumption via Search Paths

The search path is a list of package names, which are searched for rules. Rules decide autonomously whether they actually apply to a missing subroutine or not. There is no need to set the search path explicitly, but the default one has to be explained.

By default the search path consists of the 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. You can modify the search path with the search proxy methods as follows.

For method lookup a full hierarchical search is started in each parent class. The last three lines from the synopsis, should remind you that the method salut_monde springs into existence as a subroutine in a parent class, because it is defined there only.


=head2 Convenience Function

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. Alternatively you can give a reference to a subroutine, a generator object or the (partial) name of a generator class. ('::Hello_Anything' will be interpreted as 'Package::Autoloader::Generator::Hello_Anything').

The wildcard is one of the following four symbols:

=over 8

=item * B<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 * a combination of the above symbols '+::*'

means a combination of their 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 are automatically created upon use. The 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 PUBLIC INTERFACE REFERENCE

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

=over 8

=item B<register_rule>

Trigger the convenience function as described above.


=back


=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. The documentation can't keep up with the development speed at the moment.

=head2 Common Pitfalls

The statement 'use Package::Autoloader' is executed during compile time. Some things are not available then. Like the DATA file handle or lexical variables. You can use Package::Autoloader->new, see sql_table.pl and DATA_section.pl.

Matching subroutine names with '' means that you promise to generate anything. It's most likely not what you want. Example:

	$_[0]->register_rule('Some_Generator_Class', '=', '');

=head2 Prototypes

See the generator 'SQL_Table' for an attempt to have prototypes with AUTOLOAD. Keep in mind AUTOLOAD ignores prototypes (for unknown reasons), so it's more an egg in a chicken-and-egg dilemma.

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

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

Perl can't verify the arguments for the call to B(2, 8), 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.

=head2 Constant Functions

Constant Functions are inlined at compile time, when AUTOLOAD isn't considered, yet. Therefore you can't define constant functions via AUTOLOAD at the moment (Perl 5.10/5.11).

=head2 CORE::defined and UNIVERSAL::can

Both are left unmodified, because any re-definition could not be limited in scope. Meaning that a re-definition would cause any package to be unconditionally affected by a 'use Package::Autoloader'. Absolutely not desirable, even if it sounds convenient. Individual AUTOLOAD routines and can methods might appear as unnecessary effort on the first sight, but they're the proper way of doing it.

Beside that, in a modified 'defined' you won't easily get the name of the subroutine it was called with. Example: defined(&some_routine) won't lead to 'some_routine' directly. 


=head1 AUTHOR

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

=head2 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
