Type::Utils - utility functions to make defining and using type constraints a little easier |
Type::Utils - utility functions to make defining and using type constraints a little easier
package Types::Mine; use Type::Library -base; use Type::Utils -all; BEGIN { extends "Types::Standard" }; declare "AllCaps", as "Str", where { uc($_) eq $_ }, inline_as { my $varname = $_[1]; "uc($varname) eq $varname" }; coerce "AllCaps", from "Str", via { uc($_) };
This module is covered by the Type-Tiny stability policy.
This module provides utility functions to make defining and using type constraints a little easier.
Many of the following are similar to the similarly named functions described in the Moose::Util::TypeConstraints manpage.
declare $name, %options
declare %options
as
and where
to
specify the parent type (if any) and (possibly) refine its definition.
declare EvenInt, as Int, where { $_ % 2 == 0 };
my $EvenInt = declare as Int, where { $_ % 2 == 0 };
NOTE: > If the caller package inherits from the Type::Library manpage then any non-anonymous types declared in the package will be automatically installed into the library.
Hidden gem: if you're inheriting from a type constraint that includes some
coercions, you can include coercion => 1
in the %options
hash
to inherit the coercions.
subtype $name, %options
subtype %options
as
and where
to specify the parent
type and refine its definition.
Actually, you should use declare
instead; this is just an alias.
This function is not exported by default.
type $name, %options
type %options
where
to provide a coderef that
constrains values.
Actually, you should use declare
instead; this is just an alias.
This function is not exported by default.
as $parent
declare
to specify a parent type constraint:
declare EvenInt, as Int, where { $_ % 2 == 0 };
where { BLOCK }
declare
to provide the constraint coderef:
declare EvenInt, as Int, where { $_ % 2 == 0 };
The coderef operates on $_
, which is the value being tested.
message { BLOCK }
declare EvenInt, as Int, where { $_ % 2 == 0 }, message { Int->validate($_) or "$_ is not divisible by two"; };
Without a custom message, the messages generated by Type::Tiny are along the lines of Value ``33'' did not pass type constraint ``EvenInt'' >, which is usually reasonable.
inline_as { BLOCK }
declare EvenInt, as Int, where { $_ % 2 == 0 }, inline_as { my ($constraint, $varname) = @_; my $perlcode = $constraint->parent->inline_check($varname) . "&& ($varname % 2 == 0)"; return $perlcode; }; warn EvenInt->inline_check('$xxx'); # demonstration
Experimental: your inline_as
block can return a list, in which case
these will be smushed together with ``&&''. The first item on the list may
be undef, in which case the undef will be replaced by the inlined parent
type constraint. (And will throw an exception if there is no parent.)
declare EvenInt, as Int, where { $_ % 2 == 0 }, inline_as { return (undef, "($_ % 2 == 0)"); };
Returning a list like this is considered experimental, is not tested very much, and I offer no guarantees that it will necessarily work with Moose/Mouse/Moo.
class_type $name, { class => $package, %options }
class_type { class => $package, %options }
class_type $name
If $package
is omitted, is assumed to be the same as $name
.
If $name
contains ``::'' (which would be an invalid name as far as
the Type::Tiny manpage is concerned), this will be removed.
So for example, class_type("Foo::Bar")
declares a the Type::Tiny::Class manpage
type constraint named ``FooBar'' which constrains values to objects blessed
into the ``Foo::Bar'' package.
role_type $name, { role => $package, %options }
role_type { role => $package, %options }
role_type $name
If $package
is omitted, is assumed to be the same as $name
.
If $name
contains ``::'' (which would be an invalid name as far as
the Type::Tiny manpage is concerned), this will be removed.
duck_type $name, \@methods
duck_type \@methods
union $name, \@constraints
union \@constraints
enum $name, \@values
enum \@values
intersection $name, \@constraints
intersection \@constraints
Many of the following are similar to the similarly named functions described in the Moose::Util::TypeConstraints manpage.
coerce $target, @coercions
$_
.
from $source
coerce EvenInt, from Int, via { $_ * 2 }; # As a coderef... coerce EvenInt, from Int, q { $_ * 2 }; # or as a string!
via { BLOCK }
declare_coercion $name, \%opts, $type1, $code1, ...
declare_coercion \%opts, $type1, $code1, ...
declare_coercion "ArrayRefFromAny", from "Any", via { [$_] };
This coercion will be exportable from the library as a the Type::Coercion manpage object, but the ArrayRef type exported by the library won't automatically use it.
Coercions declared this way are immutable (frozen).
to_type $type
declare_coercion
to declare the target type constraint for
a coercion, but still without explicitly attaching the coercion to the
type constraint:
declare_coercion "ArrayRefFromAny", to_type "ArrayRef", from "Any", via { [$_] };
You should pretty much always use this when declaring an unattached
coercion because it's exceedingly useful for a type coercion to know what
it will coerce to - this allows it to skip coercion when no coercion is
needed (e.g. avoiding coercing []
to [ [] ]
) and allows
assert_coerce
to work properly.
extends @libraries
Should usually be executed in a BEGIN
block.
This is not exported by default because it's not fun to export it to Moo,
Moose or Mouse classes! use Type::Utils -all
can be used to import
it into your type library.
match_on_type $value => ($type => \&action, ..., \&default?)
switch
/case
or given
/when
construct. Dispatches
along different code paths depending on the type of the incoming value.
Example blatantly stolen from the Moose documentation:
sub to_json { my $value = shift; return match_on_type $value => ( HashRef() => sub { my $hash = shift; '{ ' . ( join ", " => map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) } sort keys %$hash ) . ' }'; }, ArrayRef() => sub { my $array = shift; '[ '.( join ", " => map { to_json($_) } @$array ).' ]'; }, Num() => q {$_}, Str() => q { '"' . $_ . '"' }, Undef() => q {'null'}, => sub { die "$_ is not acceptable json type" }, ); }
Note that unlike Moose, code can be specified as a string instead of a
coderef. (e.g. for Num
, Str
and Undef
above.)
For improved performance, try compile_match_on_type
.
This function is not exported by default.
my $coderef = compile_match_on_type($type => \&action, ..., \&default?)
match_on_type
block into a coderef. The following JSON
converter is about two orders of magnitude faster than the previous
example:
sub to_json; *to_json = compile_match_on_type( HashRef() => sub { my $hash = shift; '{ ' . ( join ", " => map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) } sort keys %$hash ) . ' }'; }, ArrayRef() => sub { my $array = shift; '[ '.( join ", " => map { to_json($_) } @$array ).' ]'; }, Num() => q {$_}, Str() => q { '"' . $_ . '"' }, Undef() => q {'null'}, => sub { die "$_ is not acceptable json type" }, );
Remember to store the coderef somewhere fairly permanent so that you
don't compile it over and over. state
variables (in Perl >= 5.10)
are good for this. (Same sort of idea as the Type::Params manpage.)
This function is not exported by default.
my $coderef = classifier(@types)
use feature qw( say ); use Type::Utils qw( classifier ); use Types::Standard qw( Int Num Str Any ); my $classifier = classifier(Str, Int, Num, Any); say $classifier->( "42" )->name; # Int say $classifier->( "4.2" )->name; # Num say $classifier->( [] )->name; # Any
Note that, for example, ``42'' satisfies Int, but it would satisfy the type constraints Num, Str, and Any as well. In this case, the classifier has picked the most specific type constraint that ``42'' satisfies.
If no type constraint is satisfied by the value, then the classifier will return undef.
dwim_type($string, %options)
It uses the syntax of the Type::Parser manpage. Firstly the the Type::Registry manpage for the caller package is consulted; if that doesn't have a match, the Types::Standard manpage is consulted for type constraint names; and if there's still no match, then if a type constraint looks like a class name, a new the Type::Tiny::Class manpage object is created for it.
Somewhere along the way, it also checks Moose/Mouse's type constraint registries if they are loaded.
You can specify an alternative for the caller using the for
option.
If you'd rather create a the Type::Tiny::Role manpage object, set the does
option to true.
# An arrayref of objects, each of which must do role Foo. my $type = dwim_type("ArrayRef[Foo]", does => 1); Type::Registry->for_me->add_types("-Standard"); Type::Registry->for_me->alias_type("Int" => "Foo"); # An arrayref of integers. my $type = dwim_type("ArrayRef[Foo]", does => 1);
While it's probably better overall to use the proper the Type::Registry manpage interface for resolving type constraint strings, this function often does what you want.
It should never die if it fails to find a type constraint (but may die if the type constraint string is syntactically malformed), preferring to return undef.
This function is not exported by default.
english_list(\$conjunction, @items)
english_list(qw/foo bar baz/); # "foo, bar, and baz" english_list(\"or", qw/quux quuux/); # "quux or quuux"
This function is not exported by default.
By default, all of the functions documented above are exported, except
subtype
and type
(prefer declare
instead), extends
, dwim_type
,
match_on_type
/compile_match_on_type
, classifier
, and
english_list
.
This module uses the Exporter::Tiny manpage; see the documentation of that module for tips and tricks importing from Type::Utils.
Please report any bugs to http://rt.cpan.org/Dist/Display.html.
the Type::Tiny::Manual manpage.
the Type::Tiny manpage, the Type::Library manpage, the Types::Standard manpage, the Type::Coercion manpage.
the Type::Tiny::Class manpage, the Type::Tiny::Role manpage, the Type::Tiny::Duck manpage, the Type::Tiny::Enum manpage, the Type::Tiny::Union manpage.
the Moose::Util::TypeConstraints manpage, the Mouse::Util::TypeConstraints manpage.
Toby Inkster <tobyink@cpan.org>.
This software is copyright (c) 2013-2014 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.
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.
Type::Utils - utility functions to make defining and using type constraints a little easier |