1Type::Tiny(3) User Contributed Perl Documentation Type::Tiny(3)
2
3
4
6 Type::Tiny - tiny, yet Moo(se)-compatible type constraint
7
9 use v5.12;
10 use strict;
11 use warnings;
12
13 package Horse {
14 use Moo;
15 use Types::Standard qw( Str Int Enum ArrayRef Object );
16 use Type::Params qw( compile );
17 use namespace::autoclean;
18
19 has name => (
20 is => 'ro',
21 isa => Str,
22 required => 1,
23 );
24 has gender => (
25 is => 'ro',
26 isa => Enum[qw( f m )],
27 );
28 has age => (
29 is => 'rw',
30 isa => Int->where( '$_ >= 0' ),
31 );
32 has children => (
33 is => 'ro',
34 isa => ArrayRef[Object],
35 default => sub { return [] },
36 );
37
38 sub add_child {
39 state $check = compile( Object, Object ); # method signature
40
41 my ($self, $child) = $check->(@_); # unpack @_
42 push @{ $self->children }, $child;
43
44 return $self;
45 }
46 }
47
48 package main;
49
50 my $boldruler = Horse->new(
51 name => "Bold Ruler",
52 gender => 'm',
53 age => 16,
54 );
55
56 my $secretariat = Horse->new(
57 name => "Secretariat",
58 gender => 'm',
59 age => 0,
60 );
61
62 $boldruler->add_child( $secretariat );
63
65 This module is covered by the Type-Tiny stability policy.
66
68 This documents the internals of the Type::Tiny class.
69 Type::Tiny::Manual is a better starting place if you're new.
70
71 Type::Tiny is a small class for creating Moose-like type constraint
72 objects which are compatible with Moo, Moose and Mouse.
73
74 use Scalar::Util qw(looks_like_number);
75 use Type::Tiny;
76
77 my $NUM = "Type::Tiny"->new(
78 name => "Number",
79 constraint => sub { looks_like_number($_) },
80 message => sub { "$_ ain't a number" },
81 );
82
83 package Ermintrude {
84 use Moo;
85 has favourite_number => (is => "ro", isa => $NUM);
86 }
87
88 package Bullwinkle {
89 use Moose;
90 has favourite_number => (is => "ro", isa => $NUM);
91 }
92
93 package Maisy {
94 use Mouse;
95 has favourite_number => (is => "ro", isa => $NUM);
96 }
97
98 Maybe now we won't need to have separate MooseX, MouseX and MooX
99 versions of everything? We can but hope...
100
101 Constructor
102 "new(%attributes)"
103 Moose-style constructor function.
104
105 Attributes
106 Attributes are named values that may be passed to the constructor. For
107 each attribute, there is a corresponding reader method. For example:
108
109 my $type = Type::Tiny->new( name => "Foo" );
110 print $type->name, "\n"; # says "Foo"
111
112 Important attributes
113
114 These are the attributes you are likely to be most interested in
115 providing when creating your own type constraints, and most interested
116 in reading when dealing with type constraint objects.
117
118 "constraint"
119 Coderef to validate a value ($_) against the type constraint. The
120 coderef will not be called unless the value is known to pass any
121 parent type constraint (see "parent" below).
122
123 Alternatively, a string of Perl code checking $_ can be passed as a
124 parameter to the constructor, and will be converted to a coderef.
125
126 Defaults to "sub { 1 }" - i.e. a coderef that passes all values.
127
128 "parent"
129 Optional attribute; parent type constraint. For example, an
130 "Integer" type constraint might have a parent "Number".
131
132 If provided, must be a Type::Tiny object.
133
134 "inlined"
135 A coderef which returns a string of Perl code suitable for inlining
136 this type. Optional.
137
138 (The coderef will be called in list context and can actually return
139 a list of strings which will be joined with "&&". If the first item
140 on the list is undef, it will be substituted with the type's
141 parent's inline check.)
142
143 If "constraint" (above) is a coderef generated via Sub::Quote, then
144 Type::Tiny may be able to automatically generate "inlined" for you.
145 If "constraint" (above) is a string, it will be able to.
146
147 "name"
148 The name of the type constraint. These need to conform to certain
149 naming rules (they must begin with an uppercase letter and continue
150 using only letters, digits 0-9 and underscores).
151
152 Optional; if not supplied will be an anonymous type constraint.
153
154 "display_name"
155 A name to display for the type constraint when stringified. These
156 don't have to conform to any naming rules. Optional; a default name
157 will be calculated from the "name".
158
159 "library"
160 The package name of the type library this type is associated with.
161 Optional. Informational only: setting this attribute does not
162 install the type into the package.
163
164 "deprecated"
165 Optional boolean indicating whether a type constraint is
166 deprecated. Type::Library will issue a warning if you attempt to
167 import a deprecated type constraint, but otherwise the type will
168 continue to function as normal. There will not be deprecation
169 warnings every time you validate a value, for instance. If omitted,
170 defaults to the parent's deprecation status (or false if there's no
171 parent).
172
173 "message"
174 Coderef that returns an error message when $_ does not validate
175 against the type constraint. Optional (there's a vaguely sensible
176 default.)
177
178 "coercion"
179 A Type::Coercion object associated with this type.
180
181 Generally speaking this attribute should not be passed to the
182 constructor; you should rely on the default lazily-built coercion
183 object.
184
185 You may pass "coercion => 1" to the constructor to inherit
186 coercions from the constraint's parent. (This requires the parent
187 constraint to have a coercion.)
188
189 "my_methods"
190 Experimental hashref of additional methods that can be called on
191 the type constraint object.
192
193 Attributes related to parameterizable and parameterized types
194
195 The following additional attributes are used for parameterizable (e.g.
196 "ArrayRef") and parameterized (e.g. "ArrayRef[Int]") type constraints.
197 Unlike Moose, these aren't handled by separate subclasses.
198
199 "constraint_generator"
200 Coderef that is called when a type constraint is parameterized.
201 When called, it is passed the list of parameters, though any
202 parameter which looks like a foreign type constraint (Moose type
203 constraints, Mouse type constraints, etc, and coderefs(!!!)) is
204 first coerced to a native Type::Tiny object.
205
206 Note that for compatibility with the Moose API, the base type is
207 not passed to the constraint generator, but can be found in the
208 package variable $Type::Tiny::parameterize_type. The first
209 parameter is also available as $_.
210
211 Types can be parameterized with an empty parameter list. For
212 example, in Types::Standard, "Tuple" is just an alias for
213 "ArrayRef" but "Tuple[]" will only allow zero-length arrayrefs to
214 pass the constraint. If you wish "YourType" and "YourType[]" to
215 mean the same thing, then do:
216
217 return $Type::Tiny::parameterize_type unless @_;
218
219 The constraint generator should generate and return a new
220 constraint coderef based on the parameters. Alternatively, the
221 constraint generator can return a fully-formed Type::Tiny object,
222 in which case the "name_generator", "inline_generator", and
223 "coercion_generator" attributes documented below are ignored.
224
225 Optional; providing a generator makes this type into a
226 parameterizable type constraint. If there is no generator,
227 attempting to parameterize the type constraint will throw an
228 exception.
229
230 "name_generator"
231 A coderef which generates a new display_name based on parameters.
232 Called with the same parameters and package variables as the
233 "constraint_generator". Expected to return a string.
234
235 Optional; the default is reasonable.
236
237 "inline_generator"
238 A coderef which generates a new inlining coderef based on
239 parameters. Called with the same parameters and package variables
240 as the "constraint_generator". Expected to return a coderef.
241
242 Optional.
243
244 "coercion_generator"
245 A coderef which generates a new Type::Coercion object based on
246 parameters. Called with the same parameters and package variables
247 as the "constraint_generator". Expected to return a blessed object.
248
249 Optional.
250
251 "deep_explanation"
252 This API is not finalized. Coderef used by
253 Error::TypeTiny::Assertion to peek inside parameterized types and
254 figure out why a value doesn't pass the constraint.
255
256 "parameters"
257 In parameterized types, returns an arrayref of the parameters.
258
259 Lazy generated attributes
260
261 The following attributes should not be usually passed to the
262 constructor; unless you're doing something especially unusual, you
263 should rely on the default lazily-built return values.
264
265 "compiled_check"
266 Coderef to validate a value ($_[0]) against the type constraint.
267 This coderef is expected to also handle all validation for the
268 parent type constraints.
269
270 "complementary_type"
271 A complementary type for this type. For example, the complementary
272 type for an integer type would be all things that are not integers,
273 including floating point numbers, but also alphabetic strings,
274 arrayrefs, filehandles, etc.
275
276 "moose_type", "mouse_type"
277 Objects equivalent to this type constraint, but as a
278 Moose::Meta::TypeConstraint or Mouse::Meta::TypeConstraint.
279
280 It should rarely be necessary to obtain a
281 Moose::Meta::TypeConstraint object from Type::Tiny because the
282 Type::Tiny object itself should be usable pretty much anywhere a
283 Moose::Meta::TypeConstraint is expected.
284
285 Methods
286 Predicate methods
287
288 These methods return booleans indicating information about the type
289 constraint. They are each tightly associated with a particular
290 attribute. (See "Attributes".)
291
292 "has_parent", "has_library", "has_inlined", "has_constraint_generator",
293 "has_inline_generator", "has_coercion_generator", "has_parameters",
294 "has_message", "has_deep_explanation"
295 Simple Moose-style predicate methods indicating the presence or
296 absence of an attribute.
297
298 "has_coercion"
299 Predicate method with a little extra DWIM. Returns false if the
300 coercion is a no-op.
301
302 "is_anon"
303 Returns true iff the type constraint does not have a "name".
304
305 "is_parameterized", "is_parameterizable"
306 Indicates whether a type has been parameterized (e.g.
307 "ArrayRef[Int]") or could potentially be (e.g. "ArrayRef").
308
309 "has_parameterized_from"
310 Useless alias for "is_parameterized".
311
312 Validation and coercion
313
314 The following methods are used for coercing and validating values
315 against a type constraint:
316
317 "check($value)"
318 Returns true iff the value passes the type constraint.
319
320 "validate($value)"
321 Returns the error message for the value; returns an explicit undef
322 if the value passes the type constraint.
323
324 "assert_valid($value)"
325 Like "check($value)" but dies if the value does not pass the type
326 constraint.
327
328 Yes, that's three very similar methods. Blame
329 Moose::Meta::TypeConstraint whose API I'm attempting to emulate.
330 :-)
331
332 "assert_return($value)"
333 Like "assert_valid($value)" but returns the value if it passes the
334 type constraint.
335
336 This seems a more useful behaviour than "assert_valid($value)". I
337 would have just changed "assert_valid($value)" to do this, except
338 that there are edge cases where it could break Moose compatibility.
339
340 "get_message($value)"
341 Returns the error message for the value; even if the value passes
342 the type constraint.
343
344 "validate_explain($value, $varname)"
345 Like "validate" but instead of a string error message, returns an
346 arrayref of strings explaining the reasoning why the value does not
347 meet the type constraint, examining parent types, etc.
348
349 The $varname is an optional string like '$foo' indicating the name
350 of the variable being checked.
351
352 "coerce($value)"
353 Attempt to coerce $value to this type.
354
355 "assert_coerce($value)"
356 Attempt to coerce $value to this type. Throws an exception if this
357 is not possible.
358
359 Child type constraint creation and parameterization
360
361 These methods generate new type constraint objects that inherit from
362 the constraint they are called upon:
363
364 "create_child_type(%attributes)"
365 Construct a new Type::Tiny object with this object as its parent.
366
367 "where($coderef)"
368 Shortcut for creating an anonymous child type constraint. Use it
369 like "HashRef->where(sub { exists($_->{name}) })". That said, you
370 can get a similar result using overloaded "&":
371
372 HashRef & sub { exists($_->{name}) }
373
374 Like the "constraint" attribute, this will accept a string of Perl
375 code:
376
377 HashRef->where('exists($_->{name})')
378
379 "child_type_class"
380 The class that create_child_type will construct by default.
381
382 "parameterize(@parameters)"
383 Creates a new parameterized type; throws an exception if called on
384 a non-parameterizable type.
385
386 "of(@parameters)"
387 A cute alias for "parameterize". Use it like "ArrayRef->of(Int)".
388
389 "plus_coercions($type1, $code1, ...)"
390 Shorthand for creating a new child type constraint with the same
391 coercions as this one, but then adding some extra coercions (at a
392 higher priority than the existing ones).
393
394 "plus_fallback_coercions($type1, $code1, ...)"
395 Like "plus_coercions", but added at a lower priority.
396
397 "minus_coercions($type1, ...)"
398 Shorthand for creating a new child type constraint with fewer type
399 coercions.
400
401 "no_coercions"
402 Shorthand for creating a new child type constraint with no
403 coercions at all.
404
405 Type relationship introspection methods
406
407 These methods allow you to determine a type constraint's relationship
408 to other type constraints in an organised hierarchy:
409
410 "equals($other)", "is_subtype_of($other)", "is_supertype_of($other)",
411 "is_a_type_of($other)"
412 Compare two types. See Moose::Meta::TypeConstraint for what these
413 all mean. (OK, Moose doesn't define "is_supertype_of", but you get
414 the idea, right?)
415
416 Note that these have a slightly DWIM side to them. If you create
417 two Type::Tiny::Class objects which test the same class, they're
418 considered equal. And:
419
420 my $subtype_of_Num = Types::Standard::Num->create_child_type;
421 my $subtype_of_Int = Types::Standard::Int->create_child_type;
422 $subtype_of_Int->is_subtype_of( $subtype_of_Num ); # true
423
424 "strictly_equals($other)", "is_strictly_subtype_of($other)",
425 "is_strictly_supertype_of($other)", "is_strictly_a_type_of($other)"
426 Stricter versions of the type comparison functions. These only care
427 about explicit inheritance via "parent".
428
429 my $subtype_of_Num = Types::Standard::Num->create_child_type;
430 my $subtype_of_Int = Types::Standard::Int->create_child_type;
431 $subtype_of_Int->is_strictly_subtype_of( $subtype_of_Num ); # false
432
433 "parents"
434 Returns a list of all this type constraint's ancestor constraints.
435 For example, if called on the "Str" type constraint would return
436 the list "(Value, Defined, Item, Any)".
437
438 Due to a historical misunderstanding, this differs from the Moose
439 implementation of the "parents" method. In Moose, "parents" only
440 returns the immediate parent type constraints, and because type
441 constraints only have one immediate parent, this is effectively an
442 alias for "parent". The extension module
443 MooseX::Meta::TypeConstraint::Intersection is the only place where
444 multiple type constraints are returned; and they are returned as an
445 arrayref in violation of the base class' documentation. I'm keeping
446 my behaviour as it seems more useful.
447
448 "find_parent($coderef)"
449 Loops through the parent type constraints including the invocant
450 itself and returns the nearest ancestor type constraint where the
451 coderef evaluates to true. Within the coderef the ancestor
452 currently being checked is $_. Returns undef if there is no match.
453
454 In list context also returns the number of type constraints which
455 had been looped through before the matching constraint was found.
456
457 "find_constraining_type"
458 Finds the nearest ancestor type constraint (including the type
459 itself) which has a "constraint" coderef.
460
461 Equivalent to:
462
463 $type->find_parent(sub { not $_->_is_null_constraint })
464
465 "coercibles"
466 Return a type constraint which is the union of type constraints
467 that can be coerced to this one (including this one). If this type
468 constraint has no coercions, returns itself.
469
470 "type_parameter"
471 In parameterized type constraints, returns the first item on the
472 list of parameters; otherwise returns undef. For example:
473
474 ( ArrayRef[Int] )->type_parameter; # returns Int
475 ( ArrayRef[Int] )->parent; # returns ArrayRef
476
477 Note that parameterizable type constraints can perfectly
478 legitimately take multiple parameters (several of the
479 parameterizable type constraints in Types::Standard do). This
480 method only returns the first such parameter. "Attributes related
481 to parameterizable and parameterized types" documents the
482 "parameters" attribute, which returns an arrayref of all the
483 parameters.
484
485 "parameterized_from"
486 Harder to spell alias for "parent" that only works for
487 parameterized types.
488
489 Hint for people subclassing Type::Tiny: Since version 1.006000, the
490 methods for determining subtype, supertype, and type equality should
491 not be overridden in subclasses of Type::Tiny. This is because of the
492 problem of diamond inheritance. If X and Y are both subclasses of
493 Type::Tiny, they both need to be consulted to figure out how type
494 constraints are related; not just one of them should be overriding
495 these methods. See the source code for Type::Tiny::Enum for an example
496 of how subclasses can give hints about type relationships to
497 Type::Tiny. Summary: push a coderef onto @Type::Tiny::CMP. This
498 coderef will be passed two type constraints. It should then return one
499 of the constants Type::Tiny::CMP_SUBTYPE (first type is a subtype of
500 second type), Type::Tiny::CMP_SUPERTYPE (second type is a subtype of
501 first type), Type::Tiny::CMP_EQUAL (the two types are exactly the
502 same), Type::Tiny::CMP_EQUIVALENT (the two types are effectively the
503 same), or Type::Tiny::CMP_UNKNOWN (your coderef couldn't establish any
504 relationship).
505
506 Type relationship introspection function
507
508 "Type::Tiny::cmp($type1, $type2)"
509 The subtype/supertype relationship between types results in a
510 partial ordering of type constraints.
511
512 This function will return one of the constants:
513 Type::Tiny::CMP_SUBTYPE (first type is a subtype of second type),
514 Type::Tiny::CMP_SUPERTYPE (second type is a subtype of first type),
515 Type::Tiny::CMP_EQUAL (the two types are exactly the same),
516 Type::Tiny::CMP_EQUIVALENT (the two types are effectively the
517 same), or Type::Tiny::CMP_UNKNOWN (couldn't establish any
518 relationship). In numeric contexts, these evaluate to -1, 1, 0, 0,
519 and 0, making it potentially usable with "sort" (though you may
520 need to silence warnings about treating the empty string as a
521 numeric value).
522
523 Inlining methods
524
525 The following methods are used to generate strings of Perl code which
526 may be pasted into stringy "eval"uated subs to perform type checks:
527
528 "can_be_inlined"
529 Returns boolean indicating if this type can be inlined.
530
531 "inline_check($varname)"
532 Creates a type constraint check for a particular variable as a
533 string of Perl code. For example:
534
535 print( Types::Standard::Num->inline_check('$foo') );
536
537 prints the following output:
538
539 (!ref($foo) && Scalar::Util::looks_like_number($foo))
540
541 For Moose-compat, there is an alias "_inline_check" for this
542 method.
543
544 "inline_assert($varname)"
545 Much like "inline_check" but outputs a statement of the form:
546
547 ... or die ...;
548
549 Can also be called line "inline_assert($varname, $typevarname,
550 %extras)". In this case, it will generate a string of code that
551 may include $typevarname which is supposed to be the name of a
552 variable holding the type itself. (This is kinda complicated, but
553 it allows a useful string to still be produced if the type is not
554 inlineable.) The %extras are additional options to be passed to
555 Error::TypeTiny::Assertion's constructor and must be key-value
556 pairs of strings only, no references or undefs.
557
558 Other methods
559
560 "qualified_name"
561 For non-anonymous type constraints that have a library, returns a
562 qualified "MyLib::MyType" sort of name. Otherwise, returns the same
563 as "name".
564
565 "isa($class)", "can($method)", "AUTOLOAD(@args)"
566 If Moose is loaded, then the combination of these methods is used
567 to mock a Moose::Meta::TypeConstraint.
568
569 If Mouse is loaded, then "isa" mocks Mouse::Meta::TypeConstraint.
570
571 "DOES($role)"
572 Overridden to advertise support for various roles.
573
574 See also Type::API::Constraint, etc.
575
576 "TIESCALAR", "TIEARRAY", "TIEHASH"
577 These are provided as hooks that wrap Type::Tie. (Type::Tie is
578 distributed separately, and can be used with non-Type::Tiny type
579 constraints too.) They allow the following to work:
580
581 use Types::Standard qw(Int);
582 tie my @list, Int;
583 push @list, 123, 456; # ok
584 push @list, "Hello"; # dies
585
586 The following methods exist for Moose/Mouse compatibility, but do not
587 do anything useful.
588
589 "compile_type_constraint"
590 "hand_optimized_type_constraint"
591 "has_hand_optimized_type_constraint"
592 "inline_environment"
593 "meta"
594
595 Overloading
596 · Stringification is overloaded to return the qualified name.
597
598 · Boolification is overloaded to always return true.
599
600 · Coderefification is overloaded to call "assert_return".
601
602 · On Perl 5.10.1 and above, smart match is overloaded to call
603 "check".
604
605 · The "==" operator is overloaded to call "equals".
606
607 · The "<" and ">" operators are overloaded to call "is_subtype_of"
608 and "is_supertype_of".
609
610 · The "~" operator is overloaded to call "complementary_type".
611
612 · The "|" operator is overloaded to build a union of two type
613 constraints. See Type::Tiny::Union.
614
615 · The "&" operator is overloaded to build the intersection of two
616 type constraints. See Type::Tiny::Intersection.
617
618 Previous versions of Type::Tiny would overload the "+" operator to call
619 "plus_coercions" or "plus_fallback_coercions" as appropriate. Support
620 for this was dropped after 0.040.
621
622 Constants
623 "Type::Tiny::SUPPORT_SMARTMATCH"
624 Indicates whether the smart match overload is supported on your
625 version of Perl.
626
627 Package Variables
628 $Type::Tiny::DD
629 This undef by default but may be set to a coderef that Type::Tiny
630 and related modules will use to dump data structures in things like
631 error messages.
632
633 Otherwise Type::Tiny uses it's own routine to dump data structures.
634 $DD may then be set to a number to limit the lengths of the dumps.
635 (Default limit is 72.)
636
637 This is a package variable (rather than get/set class methods) to
638 allow for easy localization.
639
640 $Type::Tiny::AvoidCallbacks
641 If this variable is set to true (you should usually do it in a
642 "local" scope), it acts as a hint for type constraints, when
643 generating inlined code, to avoid making any callbacks to variables
644 and functions defined outside the inlined code itself.
645
646 This should have the effect that "$type->inline_check('$foo')" will
647 return a string of code capable of checking the type on Perl
648 installations that don't have Type::Tiny installed. This is
649 intended to allow Type::Tiny to be used with things like Mite.
650
651 The variable works on the honour system. Types need to explicitly
652 check it and decide to generate different code based on its truth
653 value. The bundled types in Types::Standard,
654 Types::Common::Numeric, and Types::Common::String all do.
655 (StrMatch is sometimes unable to, and will issue a warning if it
656 needs to rely on callbacks when asked not to.)
657
658 Most normal users can ignore this.
659
660 Environment
661 "PERL_TYPE_TINY_XS"
662 Currently this has more effect on Types::Standard than Type::Tiny.
663 In future it may be used to trigger or suppress the loading XS
664 implementations of parts of Type::Tiny.
665
667 Please report any bugs to
668 <http://rt.cpan.org/Dist/Display.html?Queue=Type-Tiny>.
669
671 The Type::Tiny homepage <https://typetiny.toby.ink/>.
672
673 Type::Tiny::Manual, Type::API.
674
675 Type::Library, Type::Utils, Types::Standard, Type::Coercion.
676
677 Type::Tiny::Class, Type::Tiny::Role, Type::Tiny::Duck,
678 Type::Tiny::Enum, Type::Tiny::Union, Type::Tiny::Intersection.
679
680 Moose::Meta::TypeConstraint, Mouse::Meta::TypeConstraint.
681
682 Type::Params.
683
684 Type::Tiny on GitHub <https://github.com/tobyink/p5-type-tiny>,
685 Type::Tiny on Travis-CI <https://travis-ci.org/tobyink/p5-type-tiny>,
686 Type::Tiny on AppVeyor
687 <https://ci.appveyor.com/project/tobyink/p5-type-tiny>, Type::Tiny on
688 Codecov <https://codecov.io/gh/tobyink/p5-type-tiny>, Type::Tiny on
689 Coveralls <https://coveralls.io/github/tobyink/p5-type-tiny>.
690
692 Toby Inkster <tobyink@cpan.org>.
693
695 Thanks to Matt S Trout for advice on Moo integration.
696
698 This software is copyright (c) 2013-2014, 2017-2020 by Toby Inkster.
699
700 This is free software; you can redistribute it and/or modify it under
701 the same terms as the Perl 5 programming language system itself.
702
704 THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED
705 WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
706 MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
707
708
709
710perl v5.32.0 2020-09-17 Type::Tiny(3)