switched to Sub::Exporter
[gitmo/MooseX-Types.git] / lib / MooseX / Types.pm
1 package MooseX::Types;
2 use Moose;
3
4 =head1 NAME
5
6 MooseX::Types - Organise your Moose types in libraries
7
8 =cut
9
10 #use warnings;
11 #use strict;
12
13 use Moose::Util::TypeConstraints;
14 use MooseX::Types::Base             ();
15 use MooseX::Types::Util             qw( filter_tags );
16 use MooseX::Types::UndefinedType;
17 use Carp::Clan                      qw( ^MooseX::Types );
18
19 use namespace::clean -except => [qw( meta )];
20
21 our $VERSION = 0.05;
22
23 my $UndefMsg = q{Action for type '%s' not yet defined in library '%s'};
24
25 =head1 SYNOPSIS
26
27 =head2 Library Definition
28
29   package MyLibrary;
30
31   # predeclare our own types
32   use MooseX::Types 
33       -declare => [qw( PositiveInt NegativeInt )];
34
35   # import builtin types
36   use MooseX::Types::Moose 'Int';
37
38   # type definition
39   subtype PositiveInt, 
40       as Int, 
41       where { $_ > 0 },
42       message { "Int is not larger than 0" };
43   
44   subtype NegativeInt,
45       as Int,
46       where { $_ < 0 },
47       message { "Int is not smaller than 0" };
48
49   # type coercion
50   coerce PositiveInt,
51       from Int,
52           via { 1 };
53
54   1;
55
56 =head2 Usage
57
58   package Foo;
59   use Moose;
60   use MyLibrary qw( PositiveInt NegativeInt );
61
62   # use the exported constants as type names
63   has 'bar',
64       isa    => PositiveInt,
65       is     => 'rw';
66   has 'baz',
67       isa    => NegativeInt,
68       is     => 'rw';
69
70   sub quux {
71       my ($self, $value);
72
73       # test the value
74       print "positive\n" if is_PositiveInt($value);
75       print "negative\n" if is_NegativeInt($value);
76
77       # coerce the value, NegativeInt doesn't have a coercion
78       # helper, since it didn't define any coercions.
79       $value = to_PositiveInt($value) or die "Cannot coerce";
80   }
81
82   1;
83
84 =head1 DESCRIPTION
85
86 The types provided with L<Moose> are by design global. This package helps
87 you to organise and selectively import your own and the built-in types in
88 libraries. As a nice side effect, it catches typos at compile-time too.
89
90 However, the main reason for this module is to provide an easy way to not
91 have conflicts with your type names, since the internal fully qualified
92 names of the types will be prefixed with the library's name.
93
94 This module will also provide you with some helper functions to make it 
95 easier to use Moose types in your code.
96
97 =head1 TYPE HANDLER FUNCTIONS
98
99 =head2 $type
100
101 A constant with the name of your type. It contains the type's fully
102 qualified name. Takes no value, as all constants.
103
104 =head2 is_$type
105
106 This handler takes a value and tests if it is a valid value for this
107 C<$type>. It will return true or false.
108
109 =head2 to_$type
110
111 A handler that will take a value and coerce it into the C<$type>. It will
112 return a false value if the type could not be coerced.
113
114 B<Important Note>: This handler will only be exported for types that can
115 do type coercion. This has the advantage that a coercion to a type that
116 cannot hasn't defined any coercions will lead to a compile-time error.
117
118 =head1 LIBRARY DEFINITION
119
120 A MooseX::Types is just a normal Perl module. Unlike Moose 
121 itself, it does not install C<use strict> and C<use warnings> in your
122 class by default, so this is up to you.
123
124 The only thing a library is required to do is
125
126   use MooseX::Types -declare => \@types;
127
128 with C<@types> being a list of types you wish to define in this library.
129 This line will install a proper base class in your package as well as the
130 full set of L<handlers|/"TYPE HANDLER FUNCTIONS"> for your declared 
131 types. It will then hand control over to L<Moose::Util::TypeConstraints>'
132 C<import> method to export the functions you will need to declare your
133 types.
134
135 If you want to use Moose' built-in types (e.g. for subtyping) you will 
136 want to 
137
138   use MooseX::Types::Moose @types;
139
140 to import the helpers from the shipped L<MooseX::Types::Moose>
141 library which can export all types that come with Moose.
142
143 You will have to define coercions for your types or your library won't
144 export a L</to_$type> coercion helper for it.
145
146 Note that you currently cannot define types containing C<::>, since 
147 exporting would be a problem.
148
149 You also don't need to use C<warnings> and C<strict>, since the
150 definition of a library automatically exports those.
151
152 =head1 LIBRARY USAGE
153
154 You can import the L<"type helpers"|/"TYPE HANDLER FUNCTIONS"> of a
155 library by C<use>ing it with a list of types to import as arguments. If
156 you want all of them, use the C<:all> tag. For example:
157
158   use MyLibrary      ':all';
159   use MyOtherLibrary qw( TypeA TypeB );
160
161 MooseX::Types comes with a library of Moose' built-in types called
162 L<MooseX::Types::Moose>.
163
164 The exporting mechanism is, since version 0.5, implemented via a wrapper
165 around L<Sub::Exporter>. This means you can do something like this:
166
167   use MyLibrary TypeA => { -as => 'MyTypeA' },
168                 TypeB => { -as => 'MyTypeB' };
169
170 =head1 WRAPPING A LIBRARY
171
172 You can define your own wrapper subclasses to manipulate the behaviour
173 of a set of library exports. Here is an example:
174
175   package MyWrapper;
176   use strict;
177   use Class::C3;
178   use base 'MooseX::Types::Wrapper';
179
180   sub coercion_export_generator {
181       my $class = shift;
182       my $code = $class->next::method(@_);
183       return sub {
184           my $value = $code->(@_);
185           warn "Coercion returned undef!"
186               unless defined $value;
187           return $value;
188       };
189   }
190
191   1;
192
193 This class wraps the coercion generator (e.g., C<to_Int()>) and warns
194 if a coercion returned an undefined value. You can wrap any library
195 with this:
196
197   package Foo;
198   use strict;
199   use MyWrapper MyLibrary => [qw( Foo Bar )],
200                 Moose     => [qw( Str Int )];
201
202   ...
203   1;
204
205 The C<Moose> library name is a special shortcut for 
206 L<MooseX::Types::Moose>.
207
208 =head2 Generator methods you can overload
209
210 =over 4
211
212 =item type_export_generator( $short, $full )
213
214 Creates a closure returning the type's L<Moose::Meta::TypeConstraint> 
215 object. 
216
217 =item check_export_generator( $short, $full, $undef_message )
218
219 This creates the closure used to test if a value is valid for this type.
220
221 =item coercion_export_generator( $short, $full, $undef_message )
222
223 This is the closure that's doing coercions.
224
225 =back
226
227 =head2 Provided Parameters
228
229 =over 4
230
231 =item $short
232
233 The short, exported name of the type.
234
235 =item $full
236
237 The fully qualified name of this type as L<Moose> knows it.
238
239 =item $undef_message
240
241 A message that will be thrown when type functionality is used but the
242 type does not yet exist.
243
244 =back
245
246 =head1 METHODS
247
248 =head2 import
249
250 Installs the L<MooseX::Types::Base> class into the caller and 
251 exports types according to the specification described in 
252 L</"LIBRARY DEFINITION">. This will continue to 
253 L<Moose::Util::TypeConstraints>' C<import> method to export helper
254 functions you will need to declare your types.
255
256 =cut
257
258 sub import {
259     my ($class, %args) = @_;
260     my  $callee = caller;
261
262     # everyone should want this
263     strict->import;
264     warnings->import;
265
266     # inject base class into new library
267     {   no strict 'refs';
268         unshift @{ $callee . '::ISA' }, 'MooseX::Types::Base';
269     }
270
271     # generate predeclared type helpers
272     if (my @orig_declare = @{ $args{ -declare } || [] }) {
273         my ($tags, $declare) = filter_tags @orig_declare;
274         my @to_export;
275
276         for my $type (@$declare) {
277
278             croak "Cannot create a type containing '::' ($type) at the moment"
279                 if $type =~ /::/;
280
281             # add type to library and remember to export
282             $callee->add_type($type);
283             push @to_export, $type;
284         }
285
286         $callee->import({ -full => 1, -into => $callee }, @to_export);
287     }
288
289     # run type constraints import
290     return Moose::Util::TypeConstraints->import({ into => $callee });
291 }
292
293 =head2 type_export_generator
294
295 Generate a type export, e.g. C<Int()>. This will return either a
296 L<Moose::Meta::TypeConstraint> object, or alternatively a
297 L<MooseX::Types::UndefinedType> object if the type was not
298 yet defined.
299
300 =cut
301
302 sub type_export_generator {
303     my ($class, $type, $full) = @_;
304     return sub { 
305         return find_type_constraint($full)
306             || MooseX::Types::UndefinedType->new($full);
307     };
308 }
309
310 =head2 coercion_export_generator
311
312 This generates a coercion handler function, e.g. C<to_Int($value)>. 
313
314 =cut
315
316 sub coercion_export_generator {
317     my ($class, $type, $full, $undef_msg) = @_;
318     return sub {
319         my ($value) = @_;
320
321         # we need a type object
322         my $tobj = find_type_constraint($full) or croak $undef_msg;
323         my $return = $tobj->coerce($value);
324
325         # non-successful coercion returns false
326         return unless $tobj->check($return);
327
328         return $return;
329     }
330 }
331
332 =head2 check_export_generator
333
334 Generates a constraint check closure, e.g. C<is_Int($value)>.
335
336 =cut
337
338 sub check_export_generator {
339     my ($class, $type, $full, $undef_msg) = @_;
340     return sub {
341         my ($value) = @_;
342
343         # we need a type object
344         my $tobj = find_type_constraint($full) or croak $undef_msg;
345
346         return $tobj->check($value);
347     }
348 }
349
350 =head1 CAVEATS
351
352 A library makes the types quasi-unique by prefixing their names with (by
353 default) the library package name. If you're only using the type handler
354 functions provided by MooseX::Types, you shouldn't ever have to use
355 a type's actual full name.
356
357 =head1 SEE ALSO
358
359 L<Moose>, 
360 L<Moose::Util::TypeConstraints>, 
361 L<MooseX::Types::Moose>,
362 L<Sub::Exporter>
363
364 =head1 AUTHOR AND COPYRIGHT
365
366 Robert 'phaylon' Sedlacek C<E<lt>rs@474.atE<gt>>, with many thanks to
367 the C<#moose> cabal on C<irc.perl.org>.
368
369 =head1 LICENSE
370
371 This program is free software; you can redistribute it and/or modify
372 it under the same terms as perl itself.
373
374 =cut
375
376 1;