Remove pointless shebang in each module
[gitmo/Mouse.git] / lib / Mouse.pm
1 package Mouse;
2 use strict;
3 use warnings;
4 use 5.006;
5 use base 'Exporter';
6
7 our $VERSION = '0.13';
8 use 5.006;
9
10 BEGIN {
11     if ($ENV{MOUSE_DEBUG}) {
12         *DEBUG = sub (){ 1 };
13     } else {
14         *DEBUG = sub (){ 0 };
15     }
16 }
17
18 use Carp 'confess';
19 use Scalar::Util 'blessed';
20 use Mouse::Util;
21
22 use Mouse::Meta::Attribute;
23 use Mouse::Meta::Class;
24 use Mouse::Object;
25 use Mouse::TypeRegistry;
26
27 our @EXPORT = qw(extends has before after around blessed confess with);
28
29 sub extends { Mouse::Meta::Class->initialize(caller)->superclasses(@_) }
30
31 sub has {
32     my $meta = Mouse::Meta::Class->initialize(caller);
33
34     my $names = shift;
35     $names = [$names] if !ref($names);
36
37     for my $name (@$names) {
38         if ($name =~ s/^\+//) {
39             Mouse::Meta::Attribute->clone_parent($meta, $name, @_);
40         }
41         else {
42             Mouse::Meta::Attribute->create($meta, $name, @_);
43         }
44     }
45 }
46
47 sub before {
48     my $meta = Mouse::Meta::Class->initialize(caller);
49
50     my $code = pop;
51
52     for (@_) {
53         $meta->add_before_method_modifier($_ => $code);
54     }
55 }
56
57 sub after {
58     my $meta = Mouse::Meta::Class->initialize(caller);
59
60     my $code = pop;
61
62     for (@_) {
63         $meta->add_after_method_modifier($_ => $code);
64     }
65 }
66
67 sub around {
68     my $meta = Mouse::Meta::Class->initialize(caller);
69
70     my $code = pop;
71
72     for (@_) {
73         $meta->add_around_method_modifier($_ => $code);
74     }
75 }
76
77 sub with {
78     Mouse::Util::apply_all_roles((caller)[0], @_);
79 }
80
81 sub import {
82     my $class = shift;
83
84     strict->import;
85     warnings->import;
86
87     my $caller = caller;
88
89     my $meta = Mouse::Meta::Class->initialize($caller);
90     $meta->superclasses('Mouse::Object')
91         unless $meta->superclasses;
92
93     no strict 'refs';
94     no warnings 'redefine';
95     *{$caller.'::meta'} = sub { $meta };
96
97     if (@_) {
98         __PACKAGE__->export_to_level( 1, $class, @_);
99     } else {
100         # shortcut for the common case of no type character
101         no strict 'refs';
102         for my $keyword (@EXPORT) {
103             *{ $caller . '::' . $keyword } = *{__PACKAGE__ . '::' . $keyword};
104         }
105     }
106 }
107
108 sub unimport {
109     my $caller = caller;
110
111     no strict 'refs';
112     for my $keyword (@EXPORT) {
113         delete ${ $caller . '::' }{$keyword};
114     }
115 }
116
117 sub load_class {
118     my $class = shift;
119
120     if (ref($class) || !defined($class) || !length($class)) {
121         my $display = defined($class) ? $class : 'undef';
122         confess "Invalid class name ($display)";
123     }
124
125     return 1 if $class eq 'Mouse::Object';
126     return 1 if is_class_loaded($class);
127
128     (my $file = "$class.pm") =~ s{::}{/}g;
129
130     eval { CORE::require($file) };
131     confess "Could not load class ($class) because : $@" if $@;
132
133     return 1;
134 }
135
136 sub is_class_loaded {
137     my $class = shift;
138
139     return 0 if ref($class) || !defined($class) || !length($class);
140
141     # walk the symbol table tree to avoid autovififying
142     # \*{${main::}{"Foo::"}} == \*main::Foo::
143
144     my $pack = \*::;
145     foreach my $part (split('::', $class)) {
146         return 0 unless exists ${$$pack}{"${part}::"};
147         $pack = \*{${$$pack}{"${part}::"}};
148     }
149
150     # check for $VERSION or @ISA
151     return 1 if exists ${$$pack}{VERSION}
152              && defined *{${$$pack}{VERSION}}{SCALAR};
153     return 1 if exists ${$$pack}{ISA}
154              && defined *{${$$pack}{ISA}}{ARRAY};
155
156     # check for any method
157     foreach ( keys %{$$pack} ) {
158         next if substr($_, -2, 2) eq '::';
159         return 1 if defined *{${$$pack}{$_}}{CODE};
160     }
161
162     # fail
163     return 0;
164 }
165
166 1;
167
168 __END__
169
170 =head1 NAME
171
172 Mouse - Moose minus the antlers
173
174 =head1 SYNOPSIS
175
176     package Point;
177     use Mouse; # automatically turns on strict and warnings
178
179     has 'x' => (is => 'rw', isa => 'Int');
180     has 'y' => (is => 'rw', isa => 'Int');
181
182     sub clear {
183         my $self = shift;
184         $self->x(0);
185         $self->y(0);
186     }
187
188     package Point3D;
189     use Mouse;
190
191     extends 'Point';
192
193     has 'z' => (is => 'rw', isa => 'Int');
194
195     after 'clear' => sub {
196         my $self = shift;
197         $self->z(0);
198     };
199
200 =head1 DESCRIPTION
201
202 L<Moose> is wonderful.
203
204 Unfortunately, it's a little slow. Though significant progress has been made
205 over the years, the compile time penalty is a non-starter for some
206 applications.
207
208 Mouse aims to alleviate this by providing a subset of Moose's
209 functionality, faster. In particular, L<Moose/has> is missing only a few
210 expert-level features.
211
212 We're also going as light on dependencies as possible. Most functions we use
213 from L<Scalar::Util> are copied into this dist. L<Scalar::Util> is required if
214 you'd like weak references; there's simply no way to do it from pure Perl.
215 L<Class::Method::Modifiers> is required if you want support for L</before>,
216 L</after>, and L</around>.
217
218 =head2 MOOSE COMPAT
219
220 Compatibility with Moose has been the utmost concern. Fewer than 1% of the
221 tests fail when run against Moose instead of Mouse. Mouse code coverage is also
222 over 96%. Even the error messages are taken from Moose. The Mouse code just
223 runs the test suite 4x faster.
224
225 The idea is that, if you need the extra power, you should be able to run
226 C<s/Mouse/Moose/g> on your codebase and have nothing break. To that end,
227 nothingmuch has written L<Squirrel> (part of this distribution) which will act
228 as Mouse unless Moose is loaded, in which case it will act as Moose.
229
230 Mouse also has the blessings of Moose's author, stevan.
231
232 =head2 MISSING FEATURES
233
234 =head3 Roles
235
236 We're working on fixing this one! stevan has suggested an implementation
237 strategy. Mouse currently ignores methods, so that needs to be fixed next.
238 Roles that consist entirely of attributes may be usable in this very version.
239
240 =head3 Complex types
241
242 User-defined type constraints and parameterized types may be implemented. Type
243 coercions probably not (patches welcome).
244
245 =head3 Bootstrapped meta world
246
247 Very handy for extensions to the MOP. Not pressing, but would be nice to have.
248
249 =head3 Modification of attribute metaclass
250
251 When you declare an attribute with L</has>, you get the inlined accessors
252 installed immediately. Modifying the attribute metaclass, even if possible,
253 does nothing.
254
255 =head3 Lots more..
256
257 MouseX?
258
259 =head1 KEYWORDS
260
261 =head2 meta -> Mouse::Meta::Class
262
263 Returns this class' metaclass instance.
264
265 =head2 extends superclasses
266
267 Sets this class' superclasses.
268
269 =head2 before (method|methods) => Code
270
271 Installs a "before" method modifier. See L<Moose/before> or
272 L<Class::Method::Modifiers/before>.
273
274 Use of this feature requires L<Class::Method::Modifiers>!
275
276 =head2 after (method|methods) => Code
277
278 Installs an "after" method modifier. See L<Moose/after> or
279 L<Class::Method::Modifiers/after>.
280
281 Use of this feature requires L<Class::Method::Modifiers>!
282
283 =head2 around (method|methods) => Code
284
285 Installs an "around" method modifier. See L<Moose/around> or
286 L<Class::Method::Modifiers/around>.
287
288 Use of this feature requires L<Class::Method::Modifiers>!
289
290 =head2 has (name|names) => parameters
291
292 Adds an attribute (or if passed an arrayref of names, multiple attributes) to
293 this class. Options:
294
295 =over 4
296
297 =item is => ro|rw
298
299 If specified, inlines a read-only/read-write accessor with the same name as
300 the attribute.
301
302 =item isa => TypeConstraint
303
304 Provides basic type checking in the constructor and accessor. Basic types such
305 as C<Int>, C<ArrayRef>, C<Defined> are supported. Any unknown type is taken to
306 be a class check (e.g. isa => 'DateTime' would accept only L<DateTime>
307 objects).
308
309 =item required => 0|1
310
311 Whether this attribute is required to have a value. If the attribute is lazy or
312 has a builder, then providing a value for the attribute in the constructor is
313 optional.
314
315 =item init_arg => Str | Undef
316
317 Allows you to use a different key name in the constructor.  If undef, the
318 attribue can't be passed to the constructor.
319
320 =item default => Value | CodeRef
321
322 Sets the default value of the attribute. If the default is a coderef, it will
323 be invoked to get the default value. Due to quirks of Perl, any bare reference
324 is forbidden, you must wrap the reference in a coderef. Otherwise, all
325 instances will share the same reference.
326
327 =item lazy => 0|1
328
329 If specified, the default is calculated on demand instead of in the
330 constructor.
331
332 =item predicate => Str
333
334 Lets you specify a method name for installing a predicate method, which checks
335 that the attribute has a value. It will not invoke a lazy default or builder
336 method.
337
338 =item clearer => Str
339
340 Lets you specify a method name for installing a clearer method, which clears
341 the attribute's value from the instance. On the next read, lazy or builder will
342 be invoked.
343
344 =item handles => HashRef|ArrayRef
345
346 Lets you specify methods to delegate to the attribute. ArrayRef forwards the
347 given method names to method calls on the attribute. HashRef maps local method
348 names to remote method names called on the attribute. Other forms of
349 L</handles>, such as regular expression and coderef, are not yet supported.
350
351 =item weak_ref => 0|1
352
353 Lets you automatically weaken any reference stored in the attribute.
354
355 Use of this feature requires L<Scalar::Util>!
356
357 =item trigger => CodeRef
358
359 Any time the attribute's value is set (either through the accessor or the constructor), the trigger is called on it. The trigger receives as arguments the instance, the new value, and the attribute instance.
360
361 Mouse 0.05 supported more complex triggers, but this behavior is now removed.
362
363 =item builder => Str
364
365 Defines a method name to be called to provide the default value of the
366 attribute. C<< builder => 'build_foo' >> is mostly equivalent to
367 C<< default => sub { $_[0]->build_foo } >>.
368
369 =item auto_deref => 0|1
370
371 Allows you to automatically dereference ArrayRef and HashRef attributes in list
372 context. In scalar context, the reference is returned (NOT the list length or
373 bucket status). You must specify an appropriate type constraint to use
374 auto_deref.
375
376 =item lazy_build => 0|1
377
378 Automatically define lazy => 1 as well as builder => "_build_$attr", clearer =>
379 "clear_$attr', predicate => 'has_$attr' unless they are already defined.
380
381 =back
382
383 =head2 confess error -> BOOM
384
385 L<Carp/confess> for your convenience.
386
387 =head2 blessed value -> ClassName | undef
388
389 L<Scalar::Util/blessed> for your convenience.
390
391 =head1 MISC
392
393 =head2 import
394
395 Importing Mouse will default your class' superclass list to L<Mouse::Object>.
396 You may use L</extends> to replace the superclass list.
397
398 =head2 unimport
399
400 Please unimport Mouse (C<no Mouse>) so that if someone calls one of the
401 keywords (such as L</extends>) it will break loudly instead breaking subtly.
402
403 =head1 FUNCTIONS
404
405 =head2 load_class Class::Name
406
407 This will load a given C<Class::Name> (or die if it's not loadable).
408 This function can be used in place of tricks like
409 C<eval "use $module"> or using C<require>.
410
411 =head2 is_class_loaded Class::Name -> Bool
412
413 Returns whether this class is actually loaded or not. It uses a heuristic which
414 involves checking for the existence of C<$VERSION>, C<@ISA>, and any
415 locally-defined method.
416
417 =head1 AUTHOR
418
419 Shawn M Moore, C<< <sartak at gmail.com> >>
420
421 Yuval Kogman, C<< <nothingmuch at woobling.org> >>
422
423 with plenty of code borrowed from L<Class::MOP> and L<Moose>
424
425 =head1 BUGS
426
427 No known bugs.
428
429 Please report any bugs through RT: email
430 C<bug-mouse at rt.cpan.org>, or browse
431 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Mouse>.
432
433 =head1 COPYRIGHT AND LICENSE
434
435 Copyright 2008 Shawn M Moore.
436
437 This program is free software; you can redistribute it and/or modify it
438 under the same terms as Perl itself.
439
440 =cut
441