Type::Tiny(3) | User Contributed Perl Documentation | Type::Tiny(3) |
Type::Tiny - tiny, yet Moo(se)-compatible type constraint
use v5.12; use strict; use warnings; package Horse { use Moo; use Types::Standard qw( Str Int Enum ArrayRef Object ); use Type::Params qw( compile ); use namespace::autoclean; has name => ( is => 'ro', isa => Str, required => 1, ); has gender => ( is => 'ro', isa => Enum[qw( f m )], ); has age => ( is => 'rw', isa => Int->where( '$_ >= 0' ), ); has children => ( is => 'ro', isa => ArrayRef[Object], default => sub { return [] }, ); sub add_child { state $check = compile( Object, Object ); # method signature my ($self, $child) = $check->(@_); # unpack @_ push @{ $self->children }, $child; return $self; } } package main; my $boldruler = Horse->new( name => "Bold Ruler", gender => 'm', age => 16, ); my $secretariat = Horse->new( name => "Secretariat", gender => 'm', age => 0, ); $boldruler->add_child( $secretariat );
This module is covered by the Type-Tiny stability policy.
This documents the internals of the Type::Tiny class. Type::Tiny::Manual is a better starting place if you're new.
Type::Tiny is a small class for creating Moose-like type constraint objects which are compatible with Moo, Moose and Mouse.
use Scalar::Util qw(looks_like_number); use Type::Tiny; my $NUM = "Type::Tiny"->new( name => "Number", constraint => sub { looks_like_number($_) }, message => sub { "$_ ain't a number" }, ); package Ermintrude { use Moo; has favourite_number => (is => "ro", isa => $NUM); } package Bullwinkle { use Moose; has favourite_number => (is => "ro", isa => $NUM); } package Maisy { use Mouse; has favourite_number => (is => "ro", isa => $NUM); }
Maybe now we won't need to have separate MooseX, MouseX and MooX versions of everything? We can but hope...
Attributes are named values that may be passed to the constructor. For each attribute, there is a corresponding reader method. For example:
my $type = Type::Tiny->new( name => "Foo" ); print $type->name, "\n"; # says "Foo"
Important attributes
These are the attributes you are likely to be most interested in providing when creating your own type constraints, and most interested in reading when dealing with type constraint objects.
Alternatively, a string of Perl code checking $_ can be passed as a parameter to the constructor, and will be converted to a coderef.
Defaults to "sub { 1 }" - i.e. a coderef that passes all values.
If provided, must be a Type::Tiny object.
(The coderef will be called in list context and can actually return a list of strings which will be joined with "&&". If the first item on the list is undef, it will be substituted with the type's parent's inline check.)
If "constraint" (above) is a coderef generated via Sub::Quote, then Type::Tiny may be able to automatically generate "inlined" for you. If "constraint" (above) is a string, it will be able to.
Optional; if not supplied will be an anonymous type constraint.
Generally speaking this attribute should not be passed to the constructor; you should rely on the default lazily-built coercion object.
You may pass "coercion => 1" to the constructor to inherit coercions from the constraint's parent. (This requires the parent constraint to have a coercion.)
The idea is to allow for:
@sorted = Int->sort( 2, 1, 11 ); # => 1, 2, 11 @sorted = Str->sort( 2, 1, 11 ); # => 1, 11, 2
Attributes related to parameterizable and parameterized types
The following additional attributes are used for parameterizable (e.g. "ArrayRef") and parameterized (e.g. "ArrayRef[Int]") type constraints. Unlike Moose, these aren't handled by separate subclasses.
Note that for compatibility with the Moose API, the base type is not passed to the constraint generator, but can be found in the package variable $Type::Tiny::parameterize_type. The first parameter is also available as $_.
Types can be parameterized with an empty parameter list. For example, in Types::Standard, "Tuple" is just an alias for "ArrayRef" but "Tuple[]" will only allow zero-length arrayrefs to pass the constraint. If you wish "YourType" and "YourType[]" to mean the same thing, then do:
return $Type::Tiny::parameterize_type unless @_;
The constraint generator should generate and return a new constraint coderef based on the parameters. Alternatively, the constraint generator can return a fully-formed Type::Tiny object, in which case the "name_generator", "inline_generator", and "coercion_generator" attributes documented below are ignored.
Optional; providing a generator makes this type into a parameterizable type constraint. If there is no generator, attempting to parameterize the type constraint will throw an exception.
Optional; the default is reasonable.
Optional.
Optional.
Lazy generated attributes
The following attributes should not be usually passed to the constructor; unless you're doing something especially unusual, you should rely on the default lazily-built return values.
It should rarely be necessary to obtain a Moose::Meta::TypeConstraint object from Type::Tiny because the Type::Tiny object itself should be usable pretty much anywhere a Moose::Meta::TypeConstraint is expected.
Predicate methods
These methods return booleans indicating information about the type constraint. They are each tightly associated with a particular attribute. (See "Attributes".)
Validation and coercion
The following methods are used for coercing and validating values against a type constraint:
Yes, that's three very similar methods. Blame Moose::Meta::TypeConstraint whose API I'm attempting to emulate. :-)
This seems a more useful behaviour than "assert_valid($value)". I would have just changed "assert_valid($value)" to do this, except that there are edge cases where it could break Moose compatibility.
The $varname is an optional string like '$foo' indicating the name of the variable being checked.
Child type constraint creation and parameterization
These methods generate new type constraint objects that inherit from the constraint they are called upon:
HashRef & sub { exists($_->{name}) }
Like the "constraint" attribute, this will accept a string of Perl code:
HashRef->where('exists($_->{name})')
Type relationship introspection methods
These methods allow you to determine a type constraint's relationship to other type constraints in an organised hierarchy:
Note that these have a slightly DWIM side to them. If you create two Type::Tiny::Class objects which test the same class, they're considered equal. And:
my $subtype_of_Num = Types::Standard::Num->create_child_type; my $subtype_of_Int = Types::Standard::Int->create_child_type; $subtype_of_Int->is_subtype_of( $subtype_of_Num ); # true
my $subtype_of_Num = Types::Standard::Num->create_child_type; my $subtype_of_Int = Types::Standard::Int->create_child_type; $subtype_of_Int->is_strictly_subtype_of( $subtype_of_Num ); # false
Due to a historical misunderstanding, this differs from the Moose implementation of the "parents" method. In Moose, "parents" only returns the immediate parent type constraints, and because type constraints only have one immediate parent, this is effectively an alias for "parent". The extension module MooseX::Meta::TypeConstraint::Intersection is the only place where multiple type constraints are returned; and they are returned as an arrayref in violation of the base class' documentation. I'm keeping my behaviour as it seems more useful.
In list context also returns the number of type constraints which had been looped through before the matching constraint was found.
Equivalent to:
$type->find_parent(sub { not $_->_is_null_constraint })
( ArrayRef[Int] )->type_parameter; # returns Int ( ArrayRef[Int] )->parent; # returns ArrayRef
Note that parameterizable type constraints can perfectly legitimately take multiple parameters (several of the parameterizable type constraints in Types::Standard do). This method only returns the first such parameter. "Attributes related to parameterizable and parameterized types" documents the "parameters" attribute, which returns an arrayref of all the parameters.
Hint for people subclassing Type::Tiny: Since version 1.006000, the methods for determining subtype, supertype, and type equality should not be overridden in subclasses of Type::Tiny. This is because of the problem of diamond inheritance. If X and Y are both subclasses of Type::Tiny, they both need to be consulted to figure out how type constraints are related; not just one of them should be overriding these methods. See the source code for Type::Tiny::Enum for an example of how subclasses can give hints about type relationships to Type::Tiny. Summary: push a coderef onto @Type::Tiny::CMP. This coderef will be passed two type constraints. It should then return one of the constants Type::Tiny::CMP_SUBTYPE (first type is a subtype of second type), Type::Tiny::CMP_SUPERTYPE (second type is a subtype of first type), Type::Tiny::CMP_EQUAL (the two types are exactly the same), Type::Tiny::CMP_EQUIVALENT (the two types are effectively the same), or Type::Tiny::CMP_UNKNOWN (your coderef couldn't establish any relationship).
Type relationship introspection function
This function will return one of the constants: Type::Tiny::CMP_SUBTYPE (first type is a subtype of second type), Type::Tiny::CMP_SUPERTYPE (second type is a subtype of first type), Type::Tiny::CMP_EQUAL (the two types are exactly the same), Type::Tiny::CMP_EQUIVALENT (the two types are effectively the same), or Type::Tiny::CMP_UNKNOWN (couldn't establish any relationship). In numeric contexts, these evaluate to -1, 1, 0, 0, and 0, making it potentially usable with "sort" (though you may need to silence warnings about treating the empty string as a numeric value).
List processing methods
@integers = Int->grep(@list);
$first_lady = Woman->first(@people);
@truths = Bool->map(@list);
@sorted_numbers = Num->sort( Num->grep(@list) );
if ( Int->any(@numbers) ) { say "there was at least one integer"; }
if ( Int->all(@numbers) ) { say "they were all integers"; }
Inlining methods
The following methods are used to generate strings of Perl code which may be pasted into stringy "eval"uated subs to perform type checks:
print( Types::Standard::Num->inline_check('$foo') );
prints the following output:
(!ref($foo) && Scalar::Util::looks_like_number($foo))
For Moose-compat, there is an alias "_inline_check" for this method.
... or die ...;
Can also be called line "inline_assert($varname, $typevarname, %extras)". In this case, it will generate a string of code that may include $typevarname which is supposed to be the name of a variable holding the type itself. (This is kinda complicated, but it allows a useful string to still be produced if the type is not inlineable.) The %extras are additional options to be passed to Error::TypeTiny::Assertion's constructor and must be key-value pairs of strings only, no references or undefs.
Other methods
If Mouse is loaded, then "isa" mocks Mouse::Meta::TypeConstraint.
See also Type::API::Constraint, etc.
use Types::Standard qw(Int); tie my @list, Int; push @list, 123, 456; # ok push @list, "Hello"; # dies
The following methods exist for Moose/Mouse compatibility, but do not do anything useful.
Previous versions of Type::Tiny would overload the "+" operator to call "plus_coercions" or "plus_fallback_coercions" as appropriate. Support for this was dropped after 0.040.
Otherwise Type::Tiny uses it's own routine to dump data structures. $DD may then be set to a number to limit the lengths of the dumps. (Default limit is 72.)
This is a package variable (rather than get/set class methods) to allow for easy localization.
This should have the effect that "$type->inline_check('$foo')" will return a string of code capable of checking the type on Perl installations that don't have Type::Tiny installed. This is intended to allow Type::Tiny to be used with things like Mite.
The variable works on the honour system. Types need to explicitly check it and decide to generate different code based on its truth value. The bundled types in Types::Standard, Types::Common::Numeric, and Types::Common::String all do. (StrMatch is sometimes unable to, and will issue a warning if it needs to rely on callbacks when asked not to.)
Most normal users can ignore this.
Please report any bugs to <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
The Type::Tiny homepage <https://typetiny.toby.ink/>.
Type::Tiny::Manual, Type::API.
Type::Library, Type::Utils, Types::Standard, Type::Coercion.
Type::Tiny::Class, Type::Tiny::Role, Type::Tiny::Duck, Type::Tiny::Enum, Type::Tiny::Union, Type::Tiny::Intersection.
Moose::Meta::TypeConstraint, Mouse::Meta::TypeConstraint.
Type::Params.
Type::Tiny on GitHub <https://github.com/tobyink/p5-type-tiny>, Type::Tiny on Travis-CI <https://travis-ci.com/tobyink/p5-type-tiny>, Type::Tiny on AppVeyor <https://ci.appveyor.com/project/tobyink/p5-type-tiny>, Type::Tiny on Codecov <https://codecov.io/gh/tobyink/p5-type-tiny>, Type::Tiny on Coveralls <https://coveralls.io/github/tobyink/p5-type-tiny>.
Toby Inkster <tobyink@cpan.org>.
Thanks to Matt S Trout for advice on Moo integration.
This software is copyright (c) 2013-2014, 2017-2020 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.
2020-10-28 | perl v5.34.0 |