.\" -*- mode: troff; coding: utf-8 -*- .\" Automatically generated by Pod::Man 5.0102 (Pod::Simple 3.45) .\" .\" Standard preamble: .\" ======================================================================== .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" \*(C` and \*(C' are quotes in nroff, nothing in troff, for use with C<>. .ie n \{\ . ds C` "" . ds C' "" 'br\} .el\{\ . ds C` . ds C' 'br\} .\" .\" Escape single quotes in literal strings from groff's Unicode transform. .ie \n(.g .ds Aq \(aq .el .ds Aq ' .\" .\" If the F register is >0, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.SS), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .\" .\" Avoid warning from groff about undefined register 'F'. .de IX .. .nr rF 0 .if \n(.g .if rF .nr rF 1 .if (\n(rF:(\n(.g==0)) \{\ . if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . if !\nF==2 \{\ . nr % 0 . nr F 2 . \} . \} .\} .rr rF .\" ======================================================================== .\" .IX Title "Type::Tiny::Manual::Coercions 3" .TH Type::Tiny::Manual::Coercions 3 2024-09-01 "perl v5.40.0" "User Contributed Perl Documentation" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .if n .ad l .nh .SH NAME Type::Tiny::Manual::Coercions \- advanced information on coercions .SH MANUAL .IX Header "MANUAL" This section of the manual assumes you've already read Type::Tiny::Manual::UsingWithMoo. .PP Type::Tiny takes a slightly different approach to type constraints from Moose. In Moose, there is a single flat namespace for type constraints. Moose defines a type constraint called \fBStr\fR for strings and a type constraint called \&\fBArrayRef\fR for arrayrefs. If you want to define strings differently (maybe you think that the empty string doesn't really count as a string, or maybe you think objects overloading \f(CW\*(C`q[""]\*(C'\fR should count as strings) then you can't call it \fBStr\fR; you need to choose a different name. .PP With Type::Tiny, two type libraries can each offer a string type constraint with their own definitions for what counts as a string, and you can choose which one to import, or import them both with different names: .PP .Vb 2 \& use Some::Types qw( Str ); \& use Other::Types "Str" => { \-as => "Str2" }; .Ve .PP This might seem to be a small advantage of Type::Tiny, but where this global-versus-local philosophy really makes a difference is coercions. .PP Let's imagine for a part of your application that deals with reading username and password data you need to have a "username:password" string. You may wish to accept a \f(CW\*(C`[$username, $password]\*(C'\fR arrayref and coerce it to a string using \f(CW\*(C`join ":", @$arrayref\*(C'\fR. But another part of your application deals with slurping log files, and wants to coerce a string from an arrayref using \f(CW\*(C`join "\en", @$arrayref\*(C'\fR. These are both perfectly sensible ways to coerce an arrayref. In Moose, a typical way to do this would be: .PP .Vb 3 \& package My::UserManager { \& use Moose; \& use Moose::Util::TypeConstraints; \& \& coerce \*(AqStr\*(Aq, \& from \*(AqArrayRef\*(Aq, via { join ":", @$_ }; \& \& ...; \& } \& \& package My::LogReader { \& use Moose; \& use Moose::Util::TypeConstraints; \& \& coerce \*(AqStr\*(Aq, \& from \*(AqArrayRef\*(Aq, via { join "\en", @$_ }; \& \& ...; \& } .Ve .PP However, because in Moose all types and coercions are global, if both these classes are loaded, only one of them will work. One class will overrule the other's coercion. Which one "wins" will depend on load order. .PP It is possible to solve this with Moose native types, but it requires extra work. (The solution is for My::UserManager and My::LogReader to each create a subtype of \fBStr\fR and define the coercion on that subtype instead of on \&\fBStr\fR directly.) .PP Type::Tiny solves this in two ways: .IP 1. 4 Type::Tiny makes it possible for type libraries to "protect" their type constraints to prevent external code from adding new coercions to them. .Sp .Vb 1 \& $type\->coercion\->freeze(); .Ve .Sp You can freeze coercions for your entire type library using: .Sp .Vb 1 \& _\|_PACKAGE_\|_\->make_immutable; .Ve .Sp If you try to add coercions to a type constraint that has frozen coercions, it will throw an error. .Sp .Vb 1 \& use Types::Standard qw( Str ArrayRef ); \& \& Str\->coercion\->add_type_coercions( \& ArrayRef, sub { join "\en", @$_ }, \& ); .Ve .IP 2. 4 Type::Tiny makes the above-mentioned pattern of adding coercions to a subtype much easier. .Sp .Vb 1 \& use Types::Standard ( Str ArrayRef ); \& \& my $subtype = Str\->plus_coercions( \& ArrayRef, sub { join "\en", @$_ }, \& ); .Ve .Sp The \f(CW\*(C`plus_coercions\*(C'\fR method creates a new child type, adds new coercions to it, copies any existing coercions from the parent type, and then freezes coercions for the new child type. .Sp The end result is you now have a "copy" of \fBStr\fR that can coerce from \&\fBArrayRef\fR but other copies of \fBStr\fR won't be affected by your coercion. .SS "Defining Coercions within Type Libraries" .IX Subsection "Defining Coercions within Type Libraries" Some coercions like joining an arrayref to make a string are not going to be coercions that everybody will agree on. Join with a line break in between them as above? Or with a colon, a tab, a space, some other chanaracter? It depends a lot on your application. .PP Others, like coercing a Path::Tiny object from a string, are likely to be very obvious. It is this kind of coercion that it makes sense to define within the library itself so it's available to any packages that use the library. .PP .Vb 6 \& my $pt = _\|_PACKAGE_\|_\->add_type( \& Type::Tiny::Class\->new( \& name => \*(AqPath\*(Aq, \& class => \*(AqPath::Tiny\*(Aq, \& ), \& ); \& \& $pt\->coercion\->add_type_coercions( \& Str, q{ Path::Tiny::path($_) }, \& ); \& \& $pt\->coercion\->freeze; .Ve .SS "Tweak Coercions Outside Type Libraries" .IX Subsection "Tweak Coercions Outside Type Libraries" The \f(CW\*(C`plus_coercions\*(C'\fR method creates a new type constraint with additional coercions. If the original type already had coercions, the new coercions have a higher priority. .PP There's also a \f(CW\*(C`plus_fallback_coercions\*(C'\fR method which does the same as \&\f(CW\*(C`plus_coercions\*(C'\fR but adds the new coercions with a lower priority than any existing ones. .PP Type::Tiny::Class provides a \f(CW\*(C`plus_constructors\*(C'\fR method as a shortcut for coercing via a constructor method. The following two are the same: .PP .Vb 1 \& Path\->plus_constructors( Str, "new" ) \& \& Path\->plus_coercions( Str, q{ Path::Tiny\->new($_) } ) .Ve .PP To create a type constraint without particular existing coercions, you can use \f(CW\*(C`minus_coercions\*(C'\fR. The following uses the \fBDatetime\fR type defined in Type::Tiny::Manual::Libraries, removing the coercion from \&\fBInt\fR but keeping the coercions from \fBUndef\fR and \fBDict\fR. .PP .Vb 2 \& use Types::Standard qw( Int ); \& use Example::Types qw( Datetime ); \& \& has start_date => ( \& is => \*(Aqro\*(Aq, \& isa => Datetime\->minus_coercions( Int ), \& coerce => 1, \& ); .Ve .PP There's also a \f(CW\*(C`no_coercions\*(C'\fR method that creates a subtype with no coercions at all. This is most useful either to create a "blank slate" for \&\f(CW\*(C`plus_coercions\*(C'\fR: .PP .Vb 1 \& my $Path = Path\->no_coercions\->plus_coercions( Str, sub { ... } ); .Ve .PP Or to disable coercions for Type::Params. Type::Params will always automatically coerce a parameter if there is a coercion for that type. .PP .Vb 3 \& use Types::Standard qw( Object ); \& use Types::Common::String qw( UpperCaseStr ); \& use Type::Params; \& \& sub set_account_name { \& state $check = signature( \& method => Object, \& positional => [ UpperCaseStr\->no_coercions ], \& ); \& my ( $self, $name ) = $check\->( @_ ); \& $self\->_account_name( $name ); \& $self\->db\->update( $self ); \& return $self; \& } \& \& # This will die instead of coercing from lowercase \& $robert\->set_account_name( \*(Aqbob\*(Aq ); .Ve .SS "Named Coercions" .IX Subsection "Named Coercions" A compromise between defining a coercion in the type library or defining them in the package that uses the type library is for a type library to define a named collection of coercions which can be optionally added to a type constraint. .PP .Vb 4 \& { \& package MyApp::Types; \& use Type::Library \& \-extends => [ \*(AqTypes::Standard\*(Aq ]; \& \& _\|_PACKAGE_\|_\->add_coercion( \& name => "FromLines", \& type_constraint => ArrayRef, \& type_coercion_map => [ \& Str, q{ [split /\en/] }, \& Undef, q{ [] }, \& ], \& ); \& } .Ve .PP This set of coercions has a name and can be imported and used: .PP .Vb 1 \& use MyApp::Types qw( ArrayRef FromLines ); \& \& has lines => ( \& is => \*(Aqro\*(Aq, \& isa => ArrayRef\->plus_coercions( FromLines ), \& coerce => 1, \& ); .Ve .PP Types::Standard defines a named coercion \fBMkOpt\fR designed to be used for \fBOptList\fR. .PP .Vb 2 \& use Types::Standard qw( OptList MkOpt ); \& my $OptList = OptList\->plus_coercions( MkOpt ); .Ve .SS "Parameterized Coercions" .IX Subsection "Parameterized Coercions" Named coercions can also be parameterizable. .PP .Vb 1 \& my $ArrayOfLines = ArrayRef\->plus_coercions( Split[ qr{\en} ] ); .Ve .PP Types::Standard defines \fBSplit\fR and \fBJoin\fR parameterizable coercions. .PP Viewing the source code for Types::Standard should give you hints as to how they are implemented. .SS """Deep"" Coercions" .IX Subsection """Deep"" Coercions" Certain parameterized type constraints can automatically acquire coercions if their parameters have coercions. For example: .PP .Vb 1 \& ArrayRef[ Int\->plus_coercions( Num, q{int($_)} ) ] .Ve .PP \&... does what you mean! .PP The parameterized type constraints that do this magic include the following ones from Types::Standard: .IP \(bu 4 \&\fBScalarRef\fR .IP \(bu 4 \&\fBArrayRef\fR .IP \(bu 4 \&\fBHashRef\fR .IP \(bu 4 \&\fBMap\fR .IP \(bu 4 \&\fBTuple\fR .IP \(bu 4 \&\fBCycleTuple\fR .IP \(bu 4 \&\fBDict\fR .IP \(bu 4 \&\fBOptional\fR .IP \(bu 4 \&\fBMaybe\fR .PP Imagine we're defining a type \fBPaths\fR in a type library: .PP .Vb 4 \& _\|_PACKAGE_\|_\->add_type( \& name => \*(AqPaths\*(Aq, \& parent => ArrayRef[Path], \& ); .Ve .PP The \fBPath\fR type has a coercion from \fBStr\fR, so \fBPaths\fR should be able to coerce from an arrayref of strings, right? .PP \&\fIWrong!\fR Although \fBArrayRef[Path]\fR could coerce from an arrayref of strings, \fBPaths\fR is a separate type constraint which, although it inherits from \fBArrayRef[Path]\fR has its own (currently empty) set of coercions. .PP Because that is often not what you want, Type::Tiny provides a shortcut when declaring a subtype to copy the parent type constraint's coercions: .PP .Vb 5 \& _\|_PACKAGE_\|_\->add_type( \& name => \*(AqPaths\*(Aq, \& parent => ArrayRef[Path], \& coercion => 1, # inherit \& ); .Ve .PP Now \fBPaths\fR can coerce from an arrayref of strings. .PP \fIDeep Caveat\fR .IX Subsection "Deep Caveat" .PP Currently there exists ill-defined behaviour resulting from mixing deep coercions and mutable (non-frozen) coercions. Consider the following: .PP .Vb 3 \& class_type Path, { class => "Path::Tiny" }; \& coerce Path, \& from Str, via { "Path::Tiny"\->new($_) }; \& \& declare Paths, as ArrayRef[Path], coercion => 1; \& \& coerce Path, \& from InstanceOf["My::File"], via { $_\->get_path }; .Ve .PP An arrayref of strings can now be coerced to an arrayref of Path::Tiny objects, but is it also now possible to coerce an arrayref of My::File objects to an arrayref of Path::Tiny objects? .PP Currently the answer is "no", but this is mostly down to implementation details. It's not clear what the best way to behave in this situation is, and it could start working at some point in the future. .PP This is why you should freeze coercions. .SS "Chained Coercions" .IX Subsection "Chained Coercions" Consider the following type library: .PP .Vb 9 \& package Types::Geometric { \& use Type::Library \-base, \-declare => qw( \& VectorArray \& VectorArray3D \& Point \& Point3D \& ); \& use Type::Utils; \& use Types::Standard qw( Num Tuple InstanceOf ); \& \& declare VectorArray, \& as Tuple[Num, Num]; \& \& declare VectorArray3D, \& as Tuple[Num, Num, Num]; \& \& coerce VectorArray3D, \& from VectorArray, via { \& [ @$_, 0 ]; \& }; \& \& class_type Point, { class => "Point" }; \& \& coerce Point, \& from VectorArray, via { \& Point\->new(x => $_\->[0], y => $_\->[1]); \& }; \& \& class_type Point3D, { class => "Point3D" }; \& \& coerce Point3D, \& from VectorArray3D, via { \& Point3D\->new(x => $_\->[0], y => $_\->[1], z => $_\->[2]); \& }, \& from Point, via { \& Point3D\->new(x => $_\->x, y => $_\->y, z => 0); \& }; \& } .Ve .PP Given an arrayref \f(CW\*(C`[1, 1]\*(C'\fR you might reasonably expect it to be coercible to a \fBPoint3D\fR object; it matches the type constraint \&\fBVectorArray\fR so can be coerced to \fBVectorArray3D\fR and thus to \&\fBPoint3D\fR. .PP However, Type::Coercion does not automatically chain coercions like this. Firstly, it would be incompatible with Moose's type coercion system which does not chain coercions. Secondly, it's ambiguous; in our example, the arrayref could be coerced along two different paths (via \&\fBVectorArray3D\fR or via \fBPoint\fR); in this case the end result would be the same, but in other cases it might not. Thirdly, it runs the risk of accidentally creating loops. .PP Doing the chaining manually though is pretty simple. Firstly, we'll take note of the \f(CW\*(C`coercibles\*(C'\fR method in Type::Tiny. This method called as \f(CW\*(C`VectorArray3D\->coercibles\*(C'\fR returns a type constraint meaning "anything that can be coerced to a \fBVectorArray3D\fR". .PP So we can define the coercions for \fBPoint3D\fR as: .PP .Vb 8 \& coerce Point3D, \& from VectorArray3D\->coercibles, via { \& my $tmp = to_VectorArray3D($_); \& Point3D\->new(x => $tmp\->[0], y => $tmp\->[1], z => $tmp\->[2]); \& }, \& from Point, via { \& Point3D\->new(x => $_\->x, y => $_\->y, z => 0); \& }; .Ve .PP \&... and now coercing from \f(CW\*(C`[1, 1]\*(C'\fR will work. .SH "SEE ALSO" .IX Header "SEE ALSO" Moose::Manual::BestPractices, , MooseX::Types::MoreUtils. .SH "NEXT STEPS" .IX Header "NEXT STEPS" After that last example, probably have a little lie down. Once you're recovered, here's your next step: .IP \(bu 4 Type::Tiny::Manual::AllTypes .Sp An alphabetical list of all type constraints bundled with Type::Tiny. .SH AUTHOR .IX Header "AUTHOR" Toby Inkster . .SH "COPYRIGHT AND LICENCE" .IX Header "COPYRIGHT AND LICENCE" This software is copyright (c) 2013\-2014, 2017\-2023 by Toby Inkster. .PP This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself. .SH "DISCLAIMER OF WARRANTIES" .IX Header "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.