1Type::Tiny(3)         User Contributed Perl Documentation        Type::Tiny(3)
2
3
4

NAME

6       Type::Tiny - tiny, yet Moo(se)-compatible type constraint
7

SYNOPSIS

9          use Scalar::Util qw(looks_like_number);
10          use Type::Tiny;
11
12          my $NUM = "Type::Tiny"->new(
13             name       => "Number",
14             constraint => sub { looks_like_number($_) },
15             message    => sub { "$_ ain't a number" },
16          );
17
18          package Ermintrude {
19             use Moo;
20             has favourite_number => (is => "ro", isa => $NUM);
21          }
22
23          package Bullwinkle {
24             use Moose;
25             has favourite_number => (is => "ro", isa => $NUM);
26          }
27
28          package Maisy {
29             use Mouse;
30             has favourite_number => (is => "ro", isa => $NUM);
31          }
32

STATUS

34       This module is covered by the Type-Tiny stability policy.
35

DESCRIPTION

37       Type::Tiny is a tiny class for creating Moose-like type constraint
38       objects which are compatible with Moo, Moose and Mouse.
39
40       Maybe now we won't need to have separate MooseX, MouseX and MooX
41       versions of everything? We can but hope...
42
43       This documents the internals of Type::Tiny. Type::Tiny::Manual is a
44       better starting place if you're new.
45
46   Constructor
47       "new(%attributes)"
48           Moose-style constructor function.
49
50   Attributes
51       Attributes are named values that may be passed to the constructor. For
52       each attribute, there is a corresponding reader method. For example:
53
54          my $type = Type::Tiny->new( name => "Foo" );
55          print $type->name, "\n";   # says "Foo"
56
57       Important attributes
58
59       These are the attributes you are likely to be most interested in
60       providing when creating your own type constraints, and most interested
61       in reading when dealing with type constraint objects.
62
63       "constraint"
64           Coderef to validate a value ($_) against the type constraint.  The
65           coderef will not be called unless the value is known to pass any
66           parent type constraint (see "parent" below).
67
68           Alternatively, a string of Perl code checking $_ can be passed as a
69           parameter to the constructor, and will be converted to a coderef.
70
71           Defaults to "sub { 1 }" - i.e. a coderef that passes all values.
72
73       "parent"
74           Optional attribute; parent type constraint. For example, an
75           "Integer" type constraint might have a parent "Number".
76
77           If provided, must be a Type::Tiny object.
78
79       "inlined"
80           A coderef which returns a string of Perl code suitable for inlining
81           this type. Optional.
82
83           If "constraint" (above) is a coderef generated via Sub::Quote, then
84           Type::Tiny may be able to automatically generate "inlined" for you.
85           If "constraint" (above) is a string, it will be able to.
86
87       "name"
88           The name of the type constraint. These need to conform to certain
89           naming rules (they must begin with an uppercase letter and continue
90           using only letters, digits 0-9 and underscores).
91
92           Optional; if not supplied will be an anonymous type constraint.
93
94       "display_name"
95           A name to display for the type constraint when stringified. These
96           don't have to conform to any naming rules. Optional; a default name
97           will be calculated from the "name".
98
99       "library"
100           The package name of the type library this type is associated with.
101           Optional. Informational only: setting this attribute does not
102           install the type into the package.
103
104       "deprecated"
105           Optional boolean indicating whether a type constraint is
106           deprecated.  Type::Library will issue a warning if you attempt to
107           import a deprecated type constraint, but otherwise the type will
108           continue to function as normal.  There will not be deprecation
109           warnings every time you validate a value, for instance. If omitted,
110           defaults to the parent's deprecation status (or false if there's no
111           parent).
112
113       "message"
114           Coderef that returns an error message when $_ does not validate
115           against the type constraint. Optional (there's a vaguely sensible
116           default.)
117
118       "coercion"
119           A Type::Coercion object associated with this type.
120
121           Generally speaking this attribute should not be passed to the
122           constructor; you should rely on the default lazily-built coercion
123           object.
124
125           You may pass "coercion => 1" to the constructor to inherit
126           coercions from the constraint's parent. (This requires the parent
127           constraint to have a coercion.)
128
129       "my_methods"
130           Experimenal hashref of additional methods that can be called on the
131           type constraint object.
132
133       Attributes related to parameterizable and parameterized types
134
135       The following additional attributes are used for parameterizable (e.g.
136       "ArrayRef") and parameterized (e.g. "ArrayRef[Int]") type constraints.
137       Unlike Moose, these aren't handled by separate subclasses.
138
139       "constraint_generator"
140           Coderef that is called when a type constraint is parameterized.
141           When called, it is passed the list of parameters, though any
142           parameter which looks like a foreign type constraint (Moose type
143           constraints, Mouse type constraints, etc, and coderefs(!!!)) is
144           first coerced to a native Type::Tiny object.
145
146           Note that for compatibility with the Moose API, the base type is
147           not passed to the constraint generator, but can be found in the
148           package variable $Type::Tiny::parameterize_type. The first
149           parameter is also available as $_.
150
151           Types can be parameterized with an empty parameter list. For
152           example, in Types::Standard, "Tuple" is just an alias for
153           "ArrayRef" but "Tuple[]" will only allow zero-length arrayrefs to
154           pass the constraint.  If you wish "YourType" and "YourType[]" to
155           mean the same thing, then do:
156
157            return $Type::Tiny::parameterize_type unless @_;
158
159           The constraint generator should generate and return a new
160           constraint coderef based on the parameters. Alternatively, the
161           constraint generator can return a fully-formed Type::Tiny object,
162           in which case the "name_generator", "inline_generator", and
163           "coercion_generator" attributes documented below are ignored.
164
165           Optional; providing a generator makes this type into a
166           parameterizable type constraint. If there is no generator,
167           attempting to parameterize the type constraint will throw an
168           exception.
169
170       "name_generator"
171           A coderef which generates a new display_name based on parameters.
172           Called with the same parameters and package variables as the
173           "constraint_generator".  Expected to return a string.
174
175           Optional; the default is reasonable.
176
177       "inline_generator"
178           A coderef which generates a new inlining coderef based on
179           parameters. Called with the same parameters and package variables
180           as the "constraint_generator".  Expected to return a coderef.
181
182           Optional.
183
184       "coercion_generator"
185           A coderef which generates a new Type::Coercion object based on
186           parameters.  Called with the same parameters and package variables
187           as the "constraint_generator". Expected to return a blessed object.
188
189           Optional.
190
191       "deep_explanation"
192           This API is not finalized. Coderef used by
193           Error::TypeTiny::Assertion to peek inside parameterized types and
194           figure out why a value doesn't pass the constraint.
195
196       "parameters"
197           In parameterized types, returns an arrayref of the parameters.
198
199       Lazy generated attributes
200
201       The following attributes should not be usually passed to the
202       constructor; unless you're doing something especially unusual, you
203       should rely on the default lazily-built return values.
204
205       "compiled_check"
206           Coderef to validate a value ($_[0]) against the type constraint.
207           This coderef is expected to also handle all validation for the
208           parent type constraints.
209
210       "complementary_type"
211           A complementary type for this type. For example, the complementary
212           type for an integer type would be all things that are not integers,
213           including floating point numbers, but also alphabetic strings,
214           arrayrefs, filehandles, etc.
215
216       "moose_type", "mouse_type"
217           Objects equivalent to this type constraint, but as a
218           Moose::Meta::TypeConstraint or Mouse::Meta::TypeConstraint.
219
220           It should rarely be necessary to obtain a
221           Moose::Meta::TypeConstraint object from Type::Tiny because the
222           Type::Tiny object itself should be usable pretty much anywhere a
223           Moose::Meta::TypeConstraint is expected.
224
225   Methods
226       Predicate methods
227
228       These methods return booleans indicating information about the type
229       constraint. They are each tightly associated with a particular
230       attribute.  (See "Attributes".)
231
232       "has_parent", "has_library", "has_inlined", "has_constraint_generator",
233       "has_inline_generator", "has_coercion_generator", "has_parameters",
234       "has_message", "has_deep_explanation"
235           Simple Moose-style predicate methods indicating the presence or
236           absence of an attribute.
237
238       "has_coercion"
239           Predicate method with a little extra DWIM. Returns false if the
240           coercion is a no-op.
241
242       "is_anon"
243           Returns true iff the type constraint does not have a "name".
244
245       "is_parameterized", "is_parameterizable"
246           Indicates whether a type has been parameterized (e.g.
247           "ArrayRef[Int]") or could potentially be (e.g. "ArrayRef").
248
249       Validation and coercion
250
251       The following methods are used for coercing and validating values
252       against a type constraint:
253
254       "check($value)"
255           Returns true iff the value passes the type constraint.
256
257       "validate($value)"
258           Returns the error message for the value; returns an explicit undef
259           if the value passes the type constraint.
260
261       "assert_valid($value)"
262           Like "check($value)" but dies if the value does not pass the type
263           constraint.
264
265           Yes, that's three very similar methods. Blame
266           Moose::Meta::TypeConstraint whose API I'm attempting to emulate.
267           :-)
268
269       "assert_return($value)"
270           Like "assert_valid($value)" but returns the value if it passes the
271           type constraint.
272
273           This seems a more useful behaviour than "assert_valid($value)". I
274           would have just changed "assert_valid($value)" to do this, except
275           that there are edge cases where it could break Moose compatibility.
276
277       "get_message($value)"
278           Returns the error message for the value; even if the value passes
279           the type constraint.
280
281       "validate_explain($value, $varname)"
282           Like "validate" but instead of a string error message, returns an
283           arrayref of strings explaining the reasoning why the value does not
284           meet the type constraint, examining parent types, etc.
285
286           The $varname is an optional string like '$foo' indicating the name
287           of the variable being checked.
288
289       "coerce($value)"
290           Attempt to coerce $value to this type.
291
292       "assert_coerce($value)"
293           Attempt to coerce $value to this type. Throws an exception if this
294           is not possible.
295
296       Child type constraint creation and parameterization
297
298       These methods generate new type constraint objects that inherit from
299       the constraint they are called upon:
300
301       "create_child_type(%attributes)"
302           Construct a new Type::Tiny object with this object as its parent.
303
304       "where($coderef)"
305           Shortcut for creating an anonymous child type constraint. Use it
306           like "HashRef->where(sub { exists($_->{name}) })". That said, you
307           can get a similar result using overloaded "&":
308
309              HashRef & sub { exists($_->{name}) }
310
311           Like the "constraint" attribute, this will accept a string of Perl
312           code:
313
314              HashRef->where('exists($_->{name})')
315
316       "child_type_class"
317           The class that create_child_type will construct by default.
318
319       "parameterize(@parameters)"
320           Creates a new parameterized type; throws an exception if called on
321           a non-parameterizable type.
322
323       "of(@parameters)"
324           A cute alias for "parameterize". Use it like "ArrayRef->of(Int)".
325
326       "plus_coercions($type1, $code1, ...)"
327           Shorthand for creating a new child type constraint with the same
328           coercions as this one, but then adding some extra coercions (at a
329           higher priority than the existing ones).
330
331       "plus_fallback_coercions($type1, $code1, ...)"
332           Like "plus_coercions", but added at a lower priority.
333
334       "minus_coercions($type1, ...)"
335           Shorthand for creating a new child type constraint with fewer type
336           coercions.
337
338       "no_coercions"
339           Shorthand for creating a new child type constraint with no
340           coercions at all.
341
342       Type relationship introspection methods
343
344       These methods allow you to determine a type constraint's relationship
345       to other type constraints in an organised hierarchy:
346
347       "equals($other)", "is_subtype_of($other)", "is_supertype_of($other)",
348       "is_a_type_of($other)"
349           Compare two types. See Moose::Meta::TypeConstraint for what these
350           all mean.  (OK, Moose doesn't define "is_supertype_of", but you get
351           the idea, right?)
352
353           Note that these have a slightly DWIM side to them. If you create
354           two Type::Tiny::Class objects which test the same class, they're
355           considered equal. And:
356
357              my $subtype_of_Num = Types::Standard::Num->create_child_type;
358              my $subtype_of_Int = Types::Standard::Int->create_child_type;
359              $subtype_of_Int->is_subtype_of( $subtype_of_Num );  # true
360
361       "strictly_equals($other)", "is_strictly_subtype_of($other)",
362       "is_strictly_supertype_of($other)", "is_strictly_a_type_of($other)"
363           Stricter versions of the type comparison functions. These only care
364           about explicit inheritance via "parent".
365
366              my $subtype_of_Num = Types::Standard::Num->create_child_type;
367              my $subtype_of_Int = Types::Standard::Int->create_child_type;
368              $subtype_of_Int->is_strictly_subtype_of( $subtype_of_Num );  # false
369
370       "parents"
371           Returns a list of all this type constraint's ancestor constraints.
372           For example, if called on the "Str" type constraint would return
373           the list "(Value, Defined, Item, Any)".
374
375           Due to a historical misunderstanding, this differs from the Moose
376           implementation of the "parents" method. In Moose, "parents" only
377           returns the immediate parent type constraints, and because type
378           constraints only have one immediate parent, this is effectively an
379           alias for "parent". The extension module
380           MooseX::Meta::TypeConstraint::Intersection is the only place where
381           multiple type constraints are returned; and they are returned as an
382           arrayref in violation of the base class' documentation. I'm keeping
383           my behaviour as it seems more useful.
384
385       "find_parent($coderef)"
386           Loops through the parent type constraints including the invocant
387           itself and returns the nearest ancestor type constraint where the
388           coderef evaluates to true. Within the coderef the ancestor
389           currently being checked is $_. Returns undef if there is no match.
390
391           In list context also returns the number of type constraints which
392           had been looped through before the matching constraint was found.
393
394       "coercibles"
395           Return a type constraint which is the union of type constraints
396           that can be coerced to this one (including this one). If this type
397           constraint has no coercions, returns itself.
398
399       "type_parameter"
400           In parameterized type constraints, returns the first item on the
401           list of parameters; otherwise returns undef. For example:
402
403              ( ArrayRef[Int] )->type_parameter;    # returns Int
404              ( ArrayRef[Int] )->parent;            # returns ArrayRef
405
406           Note that parameterizable type constraints can perfectly
407           legitimately take multiple parameters (several off the
408           parameterizable type constraints in Types::Standard do). This
409           method only returns the first such parameter.  "Attributes related
410           to parameterizable and parameterized types" documents the
411           "parameters" attribute, which returns an arrayref of all the
412           parameters.
413
414       Inlining methods
415
416       The following methods are used to generate strings of Perl code which
417       may be pasted into stringy "eval"uated subs to perform type checks:
418
419       "can_be_inlined"
420           Returns boolean indicating if this type can be inlined.
421
422       "inline_check($varname)"
423           Creates a type constraint check for a particular variable as a
424           string of Perl code. For example:
425
426              print( Types::Standard::Num->inline_check('$foo') );
427
428           prints the following output:
429
430              (!ref($foo) && Scalar::Util::looks_like_number($foo))
431
432           For Moose-compat, there is an alias "_inline_check" for this
433           method.
434
435       "inline_assert($varname)"
436           Much like "inline_check" but outputs a statement of the form:
437
438              die ... unless ...;
439
440           Note that if this type has a custom error message, the inlined code
441           will ignore this custom message!!
442
443       Other methods
444
445       "qualified_name"
446           For non-anonymous type constraints that have a library, returns a
447           qualified "MyLib::MyType" sort of name. Otherwise, returns the same
448           as "name".
449
450       "isa($class)", "can($method)", "AUTOLOAD(@args)"
451           If Moose is loaded, then the combination of these methods is used
452           to mock a Moose::Meta::TypeConstraint.
453
454           If Mouse is loaded, then "isa" mocks Mouse::Meta::TypeConstraint.
455
456       "DOES($role)"
457           Overridden to advertise support for various roles.
458
459           See also Type::API::Constraint, etc.
460
461       "TIESCALAR", "TIEARRAY", "TIEHASH"
462           These are provided as hooks that wrap Type::Tie. (Type::Tie is
463           distributed separately, and can be used with non-Type::Tiny type
464           constraints too.) They allow the following to work:
465
466              use Types::Standard qw(Int);
467              tie my @list, Int;
468              push @list, 123, 456;   # ok
469              push @list, "Hello";    # dies
470
471       The following methods exist for Moose/Mouse compatibility, but do not
472       do anything useful.
473
474       "compile_type_constraint"
475       "hand_optimized_type_constraint"
476       "has_hand_optimized_type_constraint"
477       "inline_environment"
478       "meta"
479
480   Overloading
481       ·   Stringification is overloaded to return the qualified name.
482
483       ·   Boolification is overloaded to always return true.
484
485       ·   Coderefification is overloaded to call "assert_return".
486
487       ·   On Perl 5.10.1 and above, smart match is overloaded to call
488           "check".
489
490       ·   The "==" operator is overloaded to call "equals".
491
492       ·   The "<" and ">" operators are overloaded to call "is_subtype_of"
493           and "is_supertype_of".
494
495       ·   The "~" operator is overloaded to call "complementary_type".
496
497       ·   The "|" operator is overloaded to build a union of two type
498           constraints.  See Type::Tiny::Union.
499
500       ·   The "&" operator is overloaded to build the intersection of two
501           type constraints. See Type::Tiny::Intersection.
502
503       Previous versions of Type::Tiny would overload the "+" operator to call
504       "plus_coercions" or "plus_fallback_coercions" as appropriate.  Support
505       for this was dropped after 0.040.
506
507   Constants
508       "Type::Tiny::SUPPORT_SMARTMATCH"
509           Indicates whether the smart match overload is supported on your
510           version of Perl.
511
512   Package Variables
513       $Type::Tiny::DD
514           This undef by default but may be set to a coderef that Type::Tiny
515           and related modules will use to dump data structures in things like
516           error messages.
517
518           Otherwise Type::Tiny uses it's own routine to dump data structures.
519           $DD may then be set to a number to limit the lengths of the dumps.
520           (Default limit is 72.)
521
522           This is a package variable (rather than get/set class methods) to
523           allow for easy localization.
524
525   Environment
526       "PERL_TYPE_TINY_XS"
527           Currently this has more effect on Types::Standard than Type::Tiny.
528           In future it may be used to trigger or suppress the loading XS
529           implementations of parts of Type::Tiny.
530

BUGS

532       Please report any bugs to
533       <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
534

SUPPORT

536       IRC: support is available through in the #moops channel on irc.perl.org
537       <http://www.irc.perl.org/channels.html>.
538

SEE ALSO

540       Type::Tiny::Manual, Type::API.
541
542       Type::Library, Type::Utils, Types::Standard, Type::Coercion.
543
544       Type::Tiny::Class, Type::Tiny::Role, Type::Tiny::Duck,
545       Type::Tiny::Enum, Type::Tiny::Union, Type::Tiny::Intersection.
546
547       Moose::Meta::TypeConstraint, Mouse::Meta::TypeConstraint.
548
549       Type::Params.
550

AUTHOR

552       Toby Inkster <tobyink@cpan.org>.
553

THANKS

555       Thanks to Matt S Trout for advice on Moo integration.
556
558       This software is copyright (c) 2013-2014, 2017-2019 by Toby Inkster.
559
560       This is free software; you can redistribute it and/or modify it under
561       the same terms as the Perl 5 programming language system itself.
562

DISCLAIMER OF WARRANTIES

564       THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
565       WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
566       MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
567
568
569
570perl v5.28.1                      2019-01-08                     Type::Tiny(3)
Impressum