1=head1 NAME
2
3Lexical::Import - clean imports from package-exporting modules
4
5=head1 SYNOPSIS
6
7	use Lexical::Import "Carp";
8
9	use Lexical::Import qw(Time::HiRes time sleep);
10
11	use Lexical::Import qw(Fcntl-1.01 :flock);
12
13	use Lexical::Import (
14		["Carp"],
15		[qw(Time::HiRes time sleep)],
16		[qw(Fcntl-1.01 :flock)],
17	);
18
19=head1 DESCRIPTION
20
21This module allows functions and other items, from a separate
22module, to be imported into the lexical namespace (as implemented by
23L<Lexical::Var>), when the exporting module exports non-lexically to
24a package in the traditional manner.  This is a translation layer,
25to help code written in the new way to use modules written in the old way.
26
27A lexically-imported item takes effect from the end of the definition
28statement up to the end of the immediately enclosing block, except
29where it is shadowed within a nested block.  This is the same lexical
30scoping that the C<my>, C<our>, and C<state> keywords supply.  Within its
31scope, any use of the single-part name of the item (e.g., "C<$foo>")
32refers directly to that item, regardless of what is in any package.
33Explicitly package-qualified names (e.g., "C<$main::foo>") still refer
34to the package.  There is no conflict between a lexical name definition
35and the same name in any package.
36
37This mechanism only works on Perl 5.11.2 and later.  Prior to that,
38it is impossible for lexical subroutine imports to work for bareword
39subroutine calls.  (See L<Lexical::Var/BUGS> for details.)  Other kinds
40of lexical importing are possible on earlier Perls, but because this is
41such a critical kind of usage in most code, this module will ensure that
42it works, for convenience.  If the limited lexical importing is desired
43on earlier Perls, use L<Lexical::Var> directly.
44
45=cut
46
47package Lexical::Import;
48
49{ use 5.011002; }
50use warnings;
51use strict;
52
53use Carp qw(croak);
54use Lexical::Var 0.006 ();
55use Module::Runtime 0.011 qw($module_name_rx require_module);
56use Params::Classify 0.000 qw(is_string is_ref);
57use version 0.81 ();
58
59our $VERSION = "0.002";
60
61require XSLoader;
62XSLoader::load(__PACKAGE__, $VERSION);
63
64=head1 PACKAGE METHODS
65
66These methods are meant to be invoked on the C<Lexical::Import> package.
67
68=over
69
70=item Lexical::Import->import(MODULE_NAME, ARGS ...)
71
72I<MODULE_NAME> must be a Perl module name, in bareword syntax with C<::>
73separators.  The named module is loaded, and its C<import> method is
74called with the supplied I<ARGS>.  It is expected to insert some set of
75functions and other items to the package from which its C<import> method
76was called.  Whatever scalars, arrays, hashes, and subroutines it thus
77exported are added to the lexical environment that is currently compiling.
78
79The overall effect, when this is performed at compile time (usually via
80C<use>), is that a C<use> is performed on the I<MODULE_NAME> and I<ARGS>,
81with all of the module's package-based exporting being turned into
82lexical exporting.  If the exporting module does some lexical exporting
83of its own, that will still work correctly when done by this indirect
84mechanism, but there is no point to the indirection if the exporting
85module uses lexical exporting exclusively.
86
87Optionally, I<MODULE_NAME> may be suffixed with a version number,
88separated from the module name by a "C<->".  The version number must
89conform to the "strict" syntax (see L<version::Internals>).  If this
90is done, then after loading the module it will be checked that what was
91loaded is at least the specified version.  For example, "C<Fcntl-1.01>"
92requests the C<Fcntl> module, version 1.01 or later.  This check is
93actually performed by calling the C<VERSION> method of the module, so the
94module can redefine it to have effects other than version checking, which
95some modules do even though it shows poor taste.  Any items exported by
96C<VERSION> into the calling package will be picked up and added to the
97lexical environment, just as if they had been exported by C<import>.
98
99Optionally, I<MODULE_NAME> may be prefixed with a "C<->", in which
100case the module's C<unimport> method is called instead of C<import>.
101This effectively performs a C<no> instead of a C<use>.  This is meant
102to handle the few modules which, in poor taste, switch the conventional
103meanings of C<use> and C<no>.
104
105=item Lexical::Import->import(IMPORT_LIST, ...)
106
107There must be one or more I<IMPORT_LIST>, each of which is a reference
108to an array containing a I<MODULE_NAME> and I<ARGS> as described for
109the preceding form of C<import>.  Each such list is processed in turn
110for importing.  This is a shorthand for where several invocations of
111this module would otherwise be required.
112
113=cut
114
115sub Lexical::Import::__DELETE_STAGE::DESTROY {
116	no strict "refs";
117	delete $Lexical::Import::{$_[0]->{name}."::"};
118}
119
120my $next_stagenum = 0;
121
122sub import {
123	my $class = shift;
124	croak "$class does no default importation" if @_ == 0;
125	foreach my $arglist (is_ref($_[0], "ARRAY") ? @_ : (\@_)) {
126		croak "non-array in $class multi-import list"
127			unless is_ref($arglist, "ARRAY");
128		croak "$class needs the name of a module to import from"
129			unless is_string($arglist->[0]);
130		my($no, $mname, $reqver) =
131			($arglist->[0] =~
132			 /\A(-)?($module_name_rx)(?:-($version::STRICT))?\z/o);
133		croak "malformed module name `@{[$arglist->[0]]}'"
134			unless defined $mname;
135		require_module($mname);
136		my $stagename = "__STAGE".($next_stagenum++);
137		my $stagepkg = "Lexical::Import::".$stagename;
138		my $cleanup_stage = bless({name=>$stagename},
139					"Lexical::Import::__DELETE_STAGE");
140		no strict "refs";
141		%{$stagepkg."::"} = ();
142		eval(qq{
143			package $stagepkg;
144			sub {
145				my \$mname = shift;
146				my \$reqver = shift;
147				my \$import = shift;
148				\$mname->VERSION(\$reqver) if defined \$reqver;
149				\$mname->\$import(\@_);
150			}
151		})->(
152			$mname, $reqver, $no ? "unimport" : "import",
153			@{$arglist}[1..$#$arglist],
154		);
155		my @imports;
156		foreach my $name (keys %{$stagepkg."::"}) {
157			next unless $name =~ /\A[A-Z_a-z][0-9A-Z_a-z]*\z/;
158			my $glob = \*{$stagepkg."::".$name};
159			push @imports, "\$".$name, *{$glob}{SCALAR}
160				if _glob_has_scalar($glob);
161			push @imports, "\@".$name, *{$glob}{ARRAY}
162				if defined *{$glob}{ARRAY};
163			push @imports, "%".$name, *{$glob}{HASH}
164				if defined *{$glob}{HASH};
165			push @imports, "&".$name, *{$glob}{CODE}
166				if defined *{$glob}{CODE};
167		}
168		Lexical::Var->import(@imports) if @imports;
169	}
170}
171
172=item Lexical::Import->unimport
173
174Unimportation is not supported by this module, so this method just
175C<die>s.
176
177=cut
178
179sub unimport { croak "$_[0] does not support unimportation" }
180
181=back
182
183=head1 BUGS
184
185Only scalars, arrays, hashes, and subroutines can be translated from the
186package namespace to the lexical namespace.  If a module exports more
187exotic items, such as bareword I/O handles or formats, they will be lost.
188
189If an exporting module does anything more complex than just inserting
190items into the calling package, this is liable to fail.  For example, if
191it records the name of the calling package for some functional purpose
192then this won't work as intended: it will get the name of a temporary
193package that doesn't exist once the importing is complete.
194
195If an exporting module tries to read a variable in the calling package,
196this will fail in two ways.  Firstly, because it sees a temporary
197package, it won't pick up any variable from the real caller.  Secondly,
198it is liable to bring the variable into existence (with an empty value),
199which looks like it exported the variable, so the empty variable will
200be lexically imported by the real caller.
201
202Subroutine calls, to lexically-imported subroutines, that have neither
203sigil nor parentheses (around the argument list) are subject to an
204ambiguity with indirect object syntax.  If the first argument expression
205begins with a bareword or a scalar variable reference then the Perl
206parser is liable to interpret the call as an indirect method call.
207Normally this syntax would be interpreted as a subroutine call if the
208subroutine exists, but the parser doesn't look at lexically-defined
209subroutines for this purpose.  The call interpretation can be forced by
210prefixing the first argument expression with a C<+>, or by wrapping the
211whole argument list in parentheses.
212
213If this package's C<import> method is called from inside a string
214C<eval> inside a C<BEGIN> block, it does not have proper access to the
215compiling environment, and will complain that it is being invoked outside
216compilation.  Calling from the body of a C<require>d or C<do>ed file
217causes the same problem.  Other kinds of indirection within a C<BEGIN>
218block, such as calling via a normal function, do not cause this problem.
219Ultimately this is a problem with the Perl core, and may change in a
220future version.
221
222=head1 SEE ALSO
223
224L<Lexical::Var>,
225L<Sub::Import>
226
227=head1 AUTHOR
228
229Andrew Main (Zefram) <zefram@fysh.org>
230
231=head1 COPYRIGHT
232
233Copyright (C) 2010, 2011 Andrew Main (Zefram) <zefram@fysh.org>
234
235=head1 LICENSE
236
237This module is free software; you can redistribute it and/or modify it
238under the same terms as Perl itself.
239
240=cut
241
2421;
243