Mouse::Util::does_role() respects $thing->does() method
[gitmo/Mouse.git] / lib / Mouse / Exporter.pm
1 package Mouse::Exporter;
2 use strict;
3 use warnings;
4 use Carp ();
5
6 my %SPEC;
7
8 my $strict_bits;
9 my $warnings_extra_bits;
10 BEGIN{
11     $strict_bits         = strict::bits(qw(subs refs vars));
12     $warnings_extra_bits = warnings::bits(FATAL => 'recursion');
13 }
14
15 # it must be "require", because Mouse::Util depends on Mouse::Exporter,
16 # which depends on Mouse::Util::import()
17 require Mouse::Util;
18
19 sub import{
20     # strict->import;
21     $^H              |= $strict_bits;
22     # warnings->import('all', FATAL => 'recursion');
23     ${^WARNING_BITS} |= $warnings::Bits{all};
24     ${^WARNING_BITS} |= $warnings_extra_bits;
25     return;
26 }
27
28
29 sub setup_import_methods{
30     my($class, %args) = @_;
31
32     my $exporting_package = $args{exporting_package} ||= caller();
33
34     my($import, $unimport) = $class->build_import_methods(%args);
35
36     Mouse::Util::install_subroutines($exporting_package,
37         import   => $import,
38         unimport => $unimport,
39
40         export_to_level => sub {
41             my($package, $level, undef, @args) = @_; # the third argument is redundant
42             $package->import({ into_level => $level + 1 }, @args);
43         },
44         export => sub {
45             my($package, $into, @args) = @_;
46             $package->import({ into => $into }, @args);
47         },
48     );
49     return;
50 }
51
52 sub build_import_methods{
53     my($self, %args) = @_;
54
55     my $exporting_package = $args{exporting_package} ||= caller();
56
57     $SPEC{$exporting_package} = \%args;
58
59     # canonicalize args
60     my @export_from;
61     if($args{also}){
62         my %seen;
63         my @stack = ($exporting_package);
64
65         while(my $current = shift @stack){
66             push @export_from, $current;
67
68             my $also = $SPEC{$current}{also} or next;
69             push @stack, grep{ !$seen{$_}++ } ref($also) ? @{ $also } : $also;
70         }
71     }
72     else{
73         @export_from = ($exporting_package);
74     }
75
76     my %exports;
77     my @removables;
78     my @all;
79
80     my @init_meta_methods;
81
82     foreach my $package(@export_from){
83         my $spec = $SPEC{$package} or next;
84
85         if(my $as_is = $spec->{as_is}){
86             foreach my $thingy (@{$as_is}){
87                 my($code_package, $code_name, $code);
88
89                 if(ref($thingy)){
90                     $code = $thingy;
91                     ($code_package, $code_name) = Mouse::Util::get_code_info($code);
92                 }
93                 else{
94                     $code_package = $package;
95                     $code_name    = $thingy;
96                     no strict 'refs';
97                     $code         = \&{ $code_package . '::' . $code_name };
98                }
99
100                 push @all, $code_name;
101                 $exports{$code_name} = $code;
102                 if($code_package eq $package){
103                     push @removables, $code_name;
104                 }
105             }
106         }
107
108         if(my $init_meta = $package->can('init_meta')){
109             if(!grep{ $_ == $init_meta } @init_meta_methods){
110                 push @init_meta_methods, $init_meta;
111             }
112         }
113     }
114     $args{EXPORTS}    = \%exports;
115     $args{REMOVABLES} = \@removables;
116
117     $args{groups}{all} ||= \@all;
118
119     if(my $default_list = $args{groups}{default}){
120         my %default;
121         foreach my $keyword(@{$default_list}){
122             $default{$keyword} = $exports{$keyword}
123                 || Carp::confess(qq{The $exporting_package package does not export "$keyword"});
124         }
125         $args{DEFAULT} = \%default;
126     }
127     else{
128         $args{groups}{default} ||= \@all;
129         $args{DEFAULT}           = $args{EXPORTS};
130     }
131
132     if(@init_meta_methods){
133         $args{INIT_META} = \@init_meta_methods;
134     }
135
136     return (\&do_import, \&do_unimport);
137 }
138
139 # the entity of general import()
140 sub do_import {
141     my($package, @args) = @_;
142
143     my $spec = $SPEC{$package}
144         || Carp::confess("The package $package package does not use Mouse::Exporter");
145
146     my $into = _get_caller_package(ref($args[0]) ? shift @args : undef);
147
148     my @exports;
149     my @traits;
150
151     while(@args){
152         my $arg = shift @args;
153         if($arg =~ s/^-//){
154             if($arg eq 'traits'){
155                 push @traits, ref($args[0]) ? @{shift(@args)} : shift(@args);
156             }
157             else {
158                 Mouse::Util::not_supported("-$arg");
159             }
160         }
161         elsif($arg =~ s/^://){
162             my $group = $spec->{groups}{$arg}
163                 || Carp::confess(qq{The $package package does not export the group "$arg"});
164             push @exports, @{$group};
165         }
166         else{
167             push @exports, $arg;
168         }
169     }
170
171     # strict->import;
172     $^H              |= $strict_bits;
173     # warnings->import('all', FATAL => 'recursion');
174     ${^WARNING_BITS} |= $warnings::Bits{all};
175     ${^WARNING_BITS} |= $warnings_extra_bits;
176
177     if($spec->{INIT_META}){
178         my $meta;
179         foreach my $init_meta(@{$spec->{INIT_META}}){
180             $meta = $package->$init_meta(for_class => $into);
181         }
182
183         if(@traits){
184             my $type = (split /::/, ref $meta)[-1]; # e.g. "Class" for "My::Meta::Class"
185             @traits = map{
186               ref($_)
187                 ? $_
188                 : Mouse::Util::resolve_metaclass_alias($type => $_, trait => 1)
189             } @traits;
190
191             require Mouse::Util::MetaRole;
192             Mouse::Util::MetaRole::apply_metaroles(
193                 for => $into,
194                 Mouse::Util::is_a_metarole($into->meta)
195                     ? (role_metaroles  => { role  => \@traits })
196                     : (class_metaroles => { class => \@traits }),
197             );
198         }
199     }
200     elsif(@traits){
201         Carp::confess("Cannot provide traits when $package does not have an init_meta() method");
202     }
203
204     if(@exports){
205         my @export_table;
206         foreach my $keyword(@exports){
207             push @export_table,
208                 $keyword => ($spec->{EXPORTS}{$keyword}
209                     || Carp::confess(qq{The $package package does not export "$keyword"})
210                 );
211         }
212         Mouse::Util::install_subroutines($into, @export_table);
213     }
214     else{
215         Mouse::Util::install_subroutines($into, %{$spec->{DEFAULT}});
216     }
217     return;
218 }
219
220 # the entity of general unimport()
221 sub do_unimport {
222     my($package, $arg) = @_;
223
224     my $spec = $SPEC{$package}
225         || Carp::confess("The package $package does not use Mouse::Exporter");
226
227     my $from = _get_caller_package($arg);
228
229     my $stash = do{
230         no strict 'refs';
231         \%{$from . '::'}
232     };
233
234     for my $keyword (@{ $spec->{REMOVABLES} }) {
235         next if !exists $stash->{$keyword};
236         my $gv = \$stash->{$keyword};
237
238         # remove what is from us
239         if(ref($gv) eq 'GLOB' && *{$gv}{CODE} == $spec->{EXPORTS}{$keyword}){
240             delete $stash->{$keyword};
241         }
242     }
243     return;
244 }
245
246 sub _get_caller_package {
247     my($arg) = @_;
248
249     # We need one extra level because it's called by import so there's a layer
250     # of indirection
251     if(ref $arg){
252         return defined($arg->{into})       ? $arg->{into}
253              : defined($arg->{into_level}) ? scalar caller(1 + $arg->{into_level})
254              :                               scalar caller(1);
255     }
256     else{
257         return scalar caller(1);
258     }
259 }
260
261 1;
262 __END__
263
264 =head1 NAME
265
266 Mouse::Exporter - make an import() and unimport() just like Mouse.pm
267
268 =head1 VERSION
269
270 This document describes Mouse version 0.95
271
272 =head1 SYNOPSIS
273
274     package MyApp::Mouse;
275
276     use Mouse ();
277     use Mouse::Exporter;
278
279     Mouse::Exporter->setup_import_methods(
280       as_is => [ 'has_rw', 'other_sugar', \&Some::Random::thing ],
281       also  => 'Mouse',
282     );
283
284     sub has_rw {
285         my $meta = caller->meta;
286         my ( $name, %options ) = @_;
287         $meta->add_attribute(
288           $name,
289           is => 'rw',
290           %options,
291         );
292     }
293
294     # then later ...
295     package MyApp::User;
296
297     use MyApp::Mouse;
298
299     has 'name';
300     has_rw 'size';
301     thing;
302
303     no MyApp::Mouse;
304
305 =head1 DESCRIPTION
306
307 This module encapsulates the exporting of sugar functions in a
308 C<Mouse.pm>-like manner. It does this by building custom C<import>,
309 C<unimport> methods for your module, based on a spec you provide.
310
311 Note that C<Mouse::Exporter> does not provide the C<with_meta> option,
312 but you can easily get the metaclass by C<< caller->meta >> as L</SYNOPSIS> shows.
313
314 =head1 METHODS
315
316 =head2 C<< setup_import_methods( ARGS ) >>
317
318 =head2 C<< build_import_methods( ARGS ) -> (\&import, \&unimport) >>
319
320 =head1 SEE ALSO
321
322 L<Moose::Exporter>
323
324 =cut
325