Source

p5-moox-late / lib / MooX / late.pm

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package MooX::late;

use 5.008;
use strict;
use warnings;
use Moo              qw( );
use Carp             qw( carp croak );
use Scalar::Util     qw( blessed );
use Module::Runtime  qw( is_module_name );

BEGIN {
	$MooX::late::AUTHORITY = 'cpan:TOBYINK';
	$MooX::late::VERSION   = '0.003';
}

sub import
{
	my $me = shift;
	my $caller = caller;
	
	my $install_tracked;
	{
		no warnings;
		if ($Moo::MAKERS{$caller})
		{
			$install_tracked = \&Moo::_install_tracked;
		}
		elsif ($Moo::Role::INFO{$caller})
		{
			$install_tracked = \&Moo::Role::_install_tracked;
		}
		else
		{
			croak "MooX::late applied to a non-Moo package"
				. "(need: use Moo or use Moo::Role)";
		}
	}
	
	my $orig = $caller->can('has')
		or croak "Could not locate 'has' function to alter";
	
	$install_tracked->(
		$caller, has => sub
		{
			my ($name, %spec) = @_;
			
			$me->_process_isa($name, \%spec)
				if exists $spec{isa} && !ref $spec{isa};
			
			$me->_process_default($name, \%spec)
				if exists $spec{default} && !ref $spec{default};
			
			$me->_process_lazy_build($name, \%spec)
				if exists $spec{lazy_build} && $spec{lazy_build};
			
			return $orig->($name, %spec);
		},
	);
	
	$install_tracked->($caller, blessed => \&Scalar::Util::blessed);
	$install_tracked->($caller, confess => \&Carp::confess);
}

sub _process_isa
{
	my ($me, $name, $spec) = @_;
	$spec->{isa} = _fatal_type_constraint($spec->{isa});
	return;
}

sub _process_default
{
	my ($me, $name, $spec) = @_;
	my $value = $spec->{default};
	$spec->{default} = sub { $value };
	return;
}

sub _process_lazy_build
{
	my ($me, $name, $spec) = @_;
	delete $spec->{lazy_build};
	
	$spec->{is}      ||= "ro";
	$spec->{lazy}    ||= 1;
	$spec->{builder} ||= "_build_$name";
	
	if ($name =~ /^_/)
	{
		$spec->{clearer}   ||= "_clear$name";
		$spec->{predicate} ||= "_has$name";
	}
	else
	{
		$spec->{clearer}   ||= "clear_$name";
		$spec->{predicate} ||= "has_$name";
	}
	
	return;
}

# A bunch of stuff stolen from Moose::Util::TypeConstraints...
{
	my $valid_chars = qr{[\w:\.]};
	my $type_atom   = qr{ (?>$valid_chars+) }x;
	my $ws          = qr{ (?>\s*) }x;
	my $op_union    = qr{ $ws \| $ws }x;
	my ($type, $type_capture_parts, $type_with_parameter, $union, $any);
	if ($] >= 5.010)
	{
		my $type_pattern    = q{  (?&type_atom)  (?: \[ (?&ws)  (?&any)  (?&ws) \] )? };
		my $type_capture_parts_pattern   = q{ ((?&type_atom)) (?: \[ (?&ws) ((?&any)) (?&ws) \] )? };
		my $type_with_parameter_pattern  = q{  (?&type_atom)      \[ (?&ws)  (?&any)  (?&ws) \]    };
		my $union_pattern   = q{ (?&type) (?> (?: (?&op_union) (?&type) )+ ) };
		my $any_pattern     = q{ (?&type) | (?&union) };
		
		my $defines = qr{(?(DEFINE)
			(?<valid_chars>         $valid_chars)
			(?<type_atom>           $type_atom)
			(?<ws>                  $ws)
			(?<op_union>            $op_union)
			(?<type>                $type_pattern)
			(?<type_capture_parts>  $type_capture_parts_pattern)
			(?<type_with_parameter> $type_with_parameter_pattern)
			(?<union>               $union_pattern)
			(?<any>                 $any_pattern)
		)}x;
		
		$type                = qr{ $type_pattern                $defines }x;
		$type_capture_parts  = qr{ $type_capture_parts_pattern  $defines }x;
		$type_with_parameter = qr{ $type_with_parameter_pattern $defines }x;
		$union               = qr{ $union_pattern               $defines }x;
		$any                 = qr{ $any_pattern                 $defines }x;
	}
	else
	{
		use re 'eval';
		
		$type                = qr{  $type_atom  (?: \[ $ws  (??{$any})  $ws \] )? }x;
		$type_capture_parts  = qr{ ($type_atom) (?: \[ $ws ((??{$any})) $ws \] )? }x;
		$type_with_parameter = qr{  $type_atom      \[ $ws  (??{$any})  $ws \]    }x;
		$union               = qr{ $type (?> (?: $op_union $type )+ ) }x;
		$any                 = qr{ $type | $union }x;
	}
	
	sub _parse_parameterized_type_constraint {
		{ no warnings 'void'; $any; }  # force capture of interpolated lexical
		$_[0] =~ m{ $type_capture_parts }x;
		return ( $1, $2 );
	}
	
	sub _detect_parameterized_type_constraint {
		{ no warnings 'void'; $any; }  # force capture of interpolated lexical
		$_[0] =~ m{ ^ $type_with_parameter $ }x;
	}
	
	sub _parse_type_constraint_union {
		{ no warnings 'void'; $any; }  # force capture of interpolated lexical
		my $given = shift;
		my @rv;
		while ( $given =~ m{ \G (?: $op_union )? ($type) }gcx ) {
			push @rv => $1;
		}
		( pos($given) eq length($given) )
		|| __PACKAGE__->_throw_error( "'$given' didn't parse (parse-pos="
			. pos($given)
			. " and str-length="
			. length($given)
			. ")" );
		@rv;
	}
	
	sub _detect_type_constraint_union {
		{ no warnings 'void'; $any; }  # force capture of interpolated lexical
		$_[0] =~ m{^ $type $op_union $type ( $op_union .* )? $}x;
	}
	
	my $warned = 0;
	sub _get_simple_type_constraint
	{
		no strict 'refs';
		
		eval { require MooX::Types::MooseLike::Base }
		or do {
			carp "Use of isa => STRING requires MooX::Types::MooseLike::Base"
				unless $warned++;
			return sub { 1 };
		};
		
		my $tc = shift;
		return {
			ClassName => sub { is_module_name($_[0]) },
			RoleName  => sub { is_module_name($_[0]) },
			map {
				$_ => \&{"MooX::Types::MooseLike::Base::is_$_"};
			}
			qw {
				Any Item Undef Defined Value Bool Str Num Int
				CodeRef RegexpRef GlobRef FileHandle Object
				ArrayRef HashRef ScalarRef
			}
		}->{$tc} or sub { 1 };
	}

	sub _get_type_constraint_union
	{
		my @tc =
			grep defined,
			map { _type_constraint($_) }
			_parse_type_constraint_union($_[0]);
		
		return sub {
			my $value = shift;
			foreach my $x (@tc) {
				return 1 if eval { $x->($value) };
			}
			return;
		};
	}
	
	sub _get_parameterized_type_constraint
	{
		my ($outer, $inner) = _parse_parameterized_type_constraint($_[0]);
		$inner = _type_constraint($inner);
		
		if ($outer eq 'Maybe')
		{
			return sub { !defined($_[0]) or $inner->($_[0]) };
		}
		
		if ($outer eq 'ScalarRef')
		{
			return sub {
				return unless ref $_[0] eq 'SCALAR';
				$inner->(${$_[0]});
			};
		}
		
		if ($outer eq 'ArrayRef')
		{
			return sub {
				return unless ref $_[0] eq 'ARRAY';
				foreach my $e (@{$_[0]}) {
					$inner->($e) or return;
				}
				return 1;
			};
		}
		
		if ($outer eq 'HashRef')
		{
			return sub {
				return unless ref $_[0] eq 'HASH';
				foreach my $e (values %{$_[0]}) {
					return unless $inner->($e);
				}
				return 1;
			};
		}
		
		return sub { 1 };
	}

	sub _type_constraint
	{
		my $tc = shift;
		$tc =~ s/(^\s+|\s+$)//g;
		
		$tc =~ /^(
			Any|Item|Bool|Undef|Defined|Value|Str|Num|Int|
			Ref|CodeRef|RegexpRef|GlobRef|FileHandle|Object|
			ScalarRef|ArrayRef|HashRef|ClassName|RoleName
		)$/x
			and return _get_simple_type_constraint($1);
		
		_detect_type_constraint_union($tc)
			and return _get_type_constraint_union($tc);
		
		_detect_parameterized_type_constraint($tc)
			and return _get_parameterized_type_constraint($tc);
		
		is_module_name($tc)
			and return sub { blessed($_[0]) and $_[0]->isa($tc) };
		
		return sub { 1 };
	}
	
	my %Cache;
	sub _fatal_type_constraint
	{
		my $tc    = _type_constraint(my $tc_name = shift);
		
		my $fatal = (
			$Cache{$tc_name} ||= sub {
				$tc->($_[0]) or
				croak "value '$_[0]' is not a $tc_name"
			}
		);
		
		# For inflation
		$Moo::HandleMoose::TYPE_MAP{$fatal} = sub {
			Moose::Util::TypeConstraints::find_or_parse_type_constraint $tc_name
		};
		
		return $fatal;
	}
}

1;

__END__

=head1 NAME

MooX::late - easily translate Moose code to Moo

=head1 SYNOPSIS

	package Foo;
	use MooX 'late';
	has bar => (is => 'ro', isa => 'Str');

or, without L<MooX>:

	package Foo;
	use Moo;
	use MooX::late;
	has bar => (is => 'ro', isa => 'Str');

=head1 DESCRIPTION

L<Moo> is a light-weight object oriented programming framework which aims
to be compatible with L<Moose>. It does this by detecting when Moose has
been loaded, and automatically "inflating" its classes and roles to full
Moose classes and roles. This way, Moo classes can consume Moose roles,
Moose classes can extend Moo classes, and so forth.

However, the surface syntax of Moo differs somewhat from Moose. For example
the C<isa> option when defining attributes in Moose must be either a string
or a blessed L<Moose::Meta::TypeConstraint> object; but in Moo must be a
coderef. These differences in surface syntax make porting code from Moose to
Moo potentially tricky. L<MooX::late> provides some assistance by enabling a
slightly more Moosey surface syntax.

MooX::late does the following:

=over

=item 1.

Allows C<< isa => $string >> to work when defining attributes for all
Moose's built-in type constraints (and assumes other strings are package
names).

This feature require L<MooX::Types::MooseLike::Base>. If you don't
have it, you'll get a warning message and all your C<isa> checks will be
no-ops.

=item 2.

Allows C<< default => $non_reference_value >> to work when defining
attributes.

=item 3.

Allows C<< lazy_build => 1 >> to work when defining attributes.

=item 4.

Exports C<blessed> and C<confess> functions to your namespace.

=back

Four features. It is not the aim of C<MooX::late> to make every aspect of
Moo behave exactly identically to Moose. It's just going after the low-hanging
fruit. So it does four things right now, and I promise that future versions
will never do more than seven.

=head1 BUGS

Please report any bugs to
L<http://rt.cpan.org/Dist/Display.html?Queue=MooX-late>.

=head1 SEE ALSO

C<MooX::late> uses L<MooX::Types::MooseLike::Base> to check many type
constraints. This is an optional dependency, but without it most type
constraints are ignored.

The following modules bring additional Moose functionality to Moo:

=over

=item *

L<MooX::Override> - support override/super

=item *

L<MooX::Augment> - support augment/inner

=back

If you have L<MooX> then you can import them all at once using:

	use MooX qw( late Override Augment );

=head1 AUTHOR

Toby Inkster E<lt>tobyink@cpan.orgE<gt>.

=head1 COPYRIGHT AND LICENCE

This software is copyright (c) 2012 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.

=head1 DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.