1Moose::Util::TypeConstrUasienrtsC(o3n)tributed Perl DocuMmoeonstea:t:iUotnil::TypeConstraints(3)
2
3
4
6 Moose::Util::TypeConstraints - Type constraint system for Moose
7
9 version 2.2012
10
12 use Moose::Util::TypeConstraints;
13
14 subtype 'Natural',
15 as 'Int',
16 where { $_ > 0 };
17
18 subtype 'NaturalLessThanTen',
19 as 'Natural',
20 where { $_ < 10 },
21 message { "This number ($_) is not less than ten!" };
22
23 coerce 'Num',
24 from 'Str',
25 via { 0+$_ };
26
27 class_type 'DateTimeClass', { class => 'DateTime' };
28
29 role_type 'Barks', { role => 'Some::Library::Role::Barks' };
30
31 enum 'RGBColors', [qw(red green blue)];
32
33 union 'StringOrArray', [qw( String ArrayRef )];
34
35 no Moose::Util::TypeConstraints;
36
38 This module provides Moose with the ability to create custom type
39 constraints to be used in attribute definition.
40
41 Important Caveat
42 This is NOT a type system for Perl 5. These are type constraints, and
43 they are not used by Moose unless you tell it to. No type inference is
44 performed, expressions are not typed, etc. etc. etc.
45
46 A type constraint is at heart a small "check if a value is valid"
47 function. A constraint can be associated with an attribute. This
48 simplifies parameter validation, and makes your code clearer to read,
49 because you can refer to constraints by name.
50
51 Slightly Less Important Caveat
52 It is always a good idea to quote your type names.
53
54 This prevents Perl from trying to execute the call as an indirect
55 object call. This can be an issue when you have a subtype with the same
56 name as a valid class.
57
58 For instance:
59
60 subtype DateTime => as Object => where { $_->isa('DateTime') };
61
62 will just work, while this:
63
64 use DateTime;
65 subtype DateTime => as Object => where { $_->isa('DateTime') };
66
67 will fail silently and cause many headaches. The simple way to solve
68 this, as well as future proof your subtypes from classes which have yet
69 to have been created, is to quote the type name:
70
71 use DateTime;
72 subtype 'DateTime', as 'Object', where { $_->isa('DateTime') };
73
74 Default Type Constraints
75 This module also provides a simple hierarchy for Perl 5 types, here is
76 that hierarchy represented visually.
77
78 Any
79 Item
80 Bool
81 Maybe[`a]
82 Undef
83 Defined
84 Value
85 Str
86 Num
87 Int
88 ClassName
89 RoleName
90 Ref
91 ScalarRef[`a]
92 ArrayRef[`a]
93 HashRef[`a]
94 CodeRef
95 RegexpRef
96 GlobRef
97 FileHandle
98 Object
99
100 NOTE: Any type followed by a type parameter "[`a]" can be
101 parameterized, this means you can say:
102
103 ArrayRef[Int] # an array of integers
104 HashRef[CodeRef] # a hash of str to CODE ref mappings
105 ScalarRef[Int] # a reference to an integer
106 Maybe[Str] # value may be a string, may be undefined
107
108 If Moose finds a name in brackets that it does not recognize as an
109 existing type, it assumes that this is a class name, for example
110 "ArrayRef[DateTime]".
111
112 NOTE: Unless you parameterize a type, then it is invalid to include the
113 square brackets. I.e. "ArrayRef[]" will be treated as a new type name,
114 not as a parameterization of "ArrayRef".
115
116 NOTE: The "Undef" type constraint for the most part works correctly
117 now, but edge cases may still exist, please use it sparingly.
118
119 NOTE: The "ClassName" type constraint does a complex package existence
120 check. This means that your class must be loaded for this type
121 constraint to pass.
122
123 NOTE: The "RoleName" constraint checks a string is a package name which
124 is a role, like 'MyApp::Role::Comparable'.
125
126 Type Constraint Naming
127 Type names declared via this module can only contain alphanumeric
128 characters, colons (:), and periods (.).
129
130 Since the types created by this module are global, it is suggested that
131 you namespace your types just as you would namespace your modules. So
132 instead of creating a Color type for your My::Graphics module, you
133 would call the type My::Graphics::Types::Color instead.
134
135 Use with Other Constraint Modules
136 This module can play nicely with other constraint modules with some
137 slight tweaking. The "where" clause in types is expected to be a "CODE"
138 reference which checks its first argument and returns a boolean. Since
139 most constraint modules work in a similar way, it should be simple to
140 adapt them to work with Moose.
141
142 For instance, this is how you could use it with
143 Declare::Constraints::Simple to declare a completely new type.
144
145 type 'HashOfArrayOfObjects',
146 where {
147 IsHashRef(
148 -keys => HasLength,
149 -values => IsArrayRef(IsObject)
150 )->(@_);
151 };
152
153 For more examples see the t/examples/example_w_DCS.t test file.
154
155 Here is an example of using Test::Deep and its non-test related
156 "eq_deeply" function.
157
158 type 'ArrayOfHashOfBarsAndRandomNumbers',
159 where {
160 eq_deeply($_,
161 array_each(subhashof({
162 bar => isa('Bar'),
163 random_number => ignore()
164 })))
165 };
166
167 For a complete example see the t/examples/example_w_TestDeep.t test
168 file.
169
170 Error messages
171 Type constraints can also specify custom error messages, for when they
172 fail to validate. This is provided as just another coderef, which
173 receives the invalid value in $_, as in:
174
175 subtype 'PositiveInt',
176 as 'Int',
177 where { $_ > 0 },
178 message { "$_ is not a positive integer!" };
179
180 If no message is specified, a default message will be used, which
181 indicates which type constraint was being used and what value failed.
182 If Devel::PartialDump (version 0.14 or higher) is installed, it will be
183 used to display the invalid value, otherwise it will just be printed as
184 is.
185
187 Type Constraint Constructors
188 The following functions are used to create type constraints. They will
189 also register the type constraints your create in a global registry
190 that is used to look types up by name.
191
192 See the "SYNOPSIS" for an example of how to use these.
193
194 subtype 'Name', as 'Parent', where { } ...
195
196 This creates a named subtype.
197
198 If you provide a parent that Moose does not recognize, it will
199 automatically create a new class type constraint for this name.
200
201 When creating a named type, the "subtype" function should either be
202 called with the sugar helpers ("where", "message", etc), or with a name
203 and a hashref of parameters:
204
205 subtype( 'Foo', { where => ..., message => ... } );
206
207 The valid hashref keys are "as" (the parent), "where", "message", and
208 "inline_as".
209
210 subtype as 'Parent', where { } ...
211
212 This creates an unnamed subtype and will return the type constraint
213 meta-object, which will be an instance of Moose::Meta::TypeConstraint.
214
215 When creating an anonymous type, the "subtype" function should either
216 be called with the sugar helpers ("where", "message", etc), or with
217 just a hashref of parameters:
218
219 subtype( { where => ..., message => ... } );
220
221 class_type ($class, ?$options)
222
223 Creates a new subtype of "Object" with the name $class and the
224 metaclass Moose::Meta::TypeConstraint::Class.
225
226 # Create a type called 'Box' which tests for objects which ->isa('Box')
227 class_type 'Box';
228
229 By default, the name of the type and the name of the class are the
230 same, but you can specify both separately.
231
232 # Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');
233 class_type 'Box', { class => 'ObjectLibrary::Box' };
234
235 role_type ($role, ?$options)
236
237 Creates a "Role" type constraint with the name $role and the metaclass
238 Moose::Meta::TypeConstraint::Role.
239
240 # Create a type called 'Walks' which tests for objects which ->does('Walks')
241 role_type 'Walks';
242
243 By default, the name of the type and the name of the role are the same,
244 but you can specify both separately.
245
246 # Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');
247 role_type 'Walks', { role => 'MooseX::Role::Walks' };
248
249 maybe_type ($type)
250
251 Creates a type constraint for either "undef" or something of the given
252 type.
253
254 duck_type ($name, \@methods)
255
256 This will create a subtype of Object and test to make sure the value
257 "can()" do the methods in "\@methods".
258
259 This is intended as an easy way to accept non-Moose objects that
260 provide a certain interface. If you're using Moose classes, we
261 recommend that you use a "requires"-only Role instead.
262
263 duck_type (\@methods)
264
265 If passed an ARRAY reference as the only parameter instead of the
266 $name, "\@methods" pair, this will create an unnamed duck type. This
267 can be used in an attribute definition like so:
268
269 has 'cache' => (
270 is => 'ro',
271 isa => duck_type( [qw( get_set )] ),
272 );
273
274 enum ($name, \@values)
275
276 This will create a basic subtype for a given set of strings. The
277 resulting constraint will be a subtype of "Str" and will match any of
278 the items in "\@values". It is case sensitive. See the "SYNOPSIS" for
279 a simple example.
280
281 NOTE: This is not a true proper enum type, it is simply a convenient
282 constraint builder.
283
284 enum (\@values)
285
286 If passed an ARRAY reference as the only parameter instead of the
287 $name, "\@values" pair, this will create an unnamed enum. This can then
288 be used in an attribute definition like so:
289
290 has 'sort_order' => (
291 is => 'ro',
292 isa => enum([qw[ ascending descending ]]),
293 );
294
295 union ($name, \@constraints)
296
297 This will create a basic subtype where any of the provided constraints
298 may match in order to satisfy this constraint.
299
300 union (\@constraints)
301
302 If passed an ARRAY reference as the only parameter instead of the
303 $name, "\@constraints" pair, this will create an unnamed union. This
304 can then be used in an attribute definition like so:
305
306 has 'items' => (
307 is => 'ro',
308 isa => union([qw[ Str ArrayRef ]]),
309 );
310
311 This is similar to the existing string union:
312
313 isa => 'Str|ArrayRef'
314
315 except that it supports anonymous elements as child constraints:
316
317 has 'color' => (
318 isa => 'ro',
319 isa => union([ 'Int', enum([qw[ red green blue ]]) ]),
320 );
321
322 as 'Parent'
323
324 This is just sugar for the type constraint construction syntax.
325
326 It takes a single argument, which is the name of a parent type.
327
328 where { ... }
329
330 This is just sugar for the type constraint construction syntax.
331
332 It takes a subroutine reference as an argument. When the type
333 constraint is tested, the reference is run with the value to be tested
334 in $_. This reference should return true or false to indicate whether
335 or not the constraint check passed.
336
337 message { ... }
338
339 This is just sugar for the type constraint construction syntax.
340
341 It takes a subroutine reference as an argument. When the type
342 constraint fails, then the code block is run with the value provided in
343 $_. This reference should return a string, which will be used in the
344 text of the exception thrown.
345
346 inline_as { ... }
347
348 This can be used to define a "hand optimized" inlinable version of your
349 type constraint.
350
351 You provide a subroutine which will be called as a method on a
352 Moose::Meta::TypeConstraint object. It will receive a single parameter,
353 the name of the variable to check, typically something like "$_" or
354 "$_[0]".
355
356 The subroutine should return a code string suitable for inlining. You
357 can assume that the check will be wrapped in parentheses when it is
358 inlined.
359
360 The inlined code should include any checks that your type's parent
361 types do. If your parent type constraint defines its own inlining, you
362 can simply use that to avoid repeating code. For example, here is the
363 inlining code for the "Value" type, which is a subtype of "Defined":
364
365 sub {
366 $_[0]->parent()->_inline_check($_[1])
367 . ' && !ref(' . $_[1] . ')'
368 }
369
370 type 'Name', where { } ...
371
372 This creates a base type, which has no parent.
373
374 The "type" function should either be called with the sugar helpers
375 ("where", "message", etc), or with a name and a hashref of parameters:
376
377 type( 'Foo', { where => ..., message => ... } );
378
379 The valid hashref keys are "where", "message", and "inlined_as".
380
381 Type Constraint Utilities
382 match_on_type $value => ( $type => \&action, ... ?\&default )
383
384 This is a utility function for doing simple type based dispatching
385 similar to match/case in OCaml and case/of in Haskell. It is not as
386 featureful as those languages, nor does not it support any kind of
387 automatic destructuring bind. Here is a simple Perl pretty printer
388 dispatching over the core Moose types.
389
390 sub ppprint {
391 my $x = shift;
392 match_on_type $x => (
393 HashRef => sub {
394 my $hash = shift;
395 '{ '
396 . (
397 join ", " => map { $_ . ' => ' . ppprint( $hash->{$_} ) }
398 sort keys %$hash
399 ) . ' }';
400 },
401 ArrayRef => sub {
402 my $array = shift;
403 '[ ' . ( join ", " => map { ppprint($_) } @$array ) . ' ]';
404 },
405 CodeRef => sub {'sub { ... }'},
406 RegexpRef => sub { 'qr/' . $_ . '/' },
407 GlobRef => sub { '*' . B::svref_2object($_)->NAME },
408 Object => sub { $_->can('to_string') ? $_->to_string : $_ },
409 ScalarRef => sub { '\\' . ppprint( ${$_} ) },
410 Num => sub {$_},
411 Str => sub { '"' . $_ . '"' },
412 Undef => sub {'undef'},
413 => sub { die "I don't know what $_ is" }
414 );
415 }
416
417 Or a simple JSON serializer:
418
419 sub to_json {
420 my $x = shift;
421 match_on_type $x => (
422 HashRef => sub {
423 my $hash = shift;
424 '{ '
425 . (
426 join ", " =>
427 map { '"' . $_ . '" : ' . to_json( $hash->{$_} ) }
428 sort keys %$hash
429 ) . ' }';
430 },
431 ArrayRef => sub {
432 my $array = shift;
433 '[ ' . ( join ", " => map { to_json($_) } @$array ) . ' ]';
434 },
435 Num => sub {$_},
436 Str => sub { '"' . $_ . '"' },
437 Undef => sub {'null'},
438 => sub { die "$_ is not acceptable json type" }
439 );
440 }
441
442 The matcher is done by mapping a $type to an "\&action". The $type can
443 be either a string type or a Moose::Meta::TypeConstraint object, and
444 "\&action" is a subroutine reference. This function will dispatch on
445 the first match for $value. It is possible to have a catch-all by
446 providing an additional subroutine reference as the final argument to
447 "match_on_type".
448
449 Type Coercion Constructors
450 You can define coercions for type constraints, which allow you to
451 automatically transform values to something valid for the type
452 constraint. If you ask your accessor to coerce by adding the option
453 "coerce => 1", then Moose will run the type-coercion code first,
454 followed by the type constraint check. This feature should be used
455 carefully as it is very powerful and could easily take off a limb if
456 you are not careful.
457
458 See the "SYNOPSIS" for an example of how to use these.
459
460 coerce 'Name', from 'OtherName', via { ... }
461
462 This defines a coercion from one type to another. The "Name" argument
463 is the type you are coercing to.
464
465 To define multiple coercions, supply more sets of from/via pairs:
466
467 coerce 'Name',
468 from 'OtherName', via { ... },
469 from 'ThirdName', via { ... };
470
471 from 'OtherName'
472
473 This is just sugar for the type coercion construction syntax.
474
475 It takes a single type name (or type object), which is the type being
476 coerced from.
477
478 via { ... }
479
480 This is just sugar for the type coercion construction syntax.
481
482 It takes a subroutine reference. This reference will be called with the
483 value to be coerced in $_. It is expected to return a new value of the
484 proper type for the coercion.
485
486 Creating and Finding Type Constraints
487 These are additional functions for creating and finding type
488 constraints. Most of these functions are not available for importing.
489 The ones that are importable as specified.
490
491 find_type_constraint($type_name)
492
493 This function can be used to locate the Moose::Meta::TypeConstraint
494 object for a named type.
495
496 This function is importable.
497
498 register_type_constraint($type_object)
499
500 This function will register a Moose::Meta::TypeConstraint with the
501 global type registry.
502
503 This function is importable.
504
505 normalize_type_constraint_name($type_constraint_name)
506
507 This method takes a type constraint name and returns the normalized
508 form. This removes any whitespace in the string.
509
510 create_type_constraint_union($pipe_separated_types |
511 @type_constraint_names)
512
513 create_named_type_constraint_union($name, $pipe_separated_types |
514 @type_constraint_names)
515
516 This can take a union type specification like 'Int|ArrayRef[Int]', or a
517 list of names. It returns a new Moose::Meta::TypeConstraint::Union
518 object.
519
520 create_parameterized_type_constraint($type_name)
521
522 Given a $type_name in the form of 'BaseType[ContainerType]', this will
523 create a new Moose::Meta::TypeConstraint::Parameterized object. The
524 "BaseType" must already exist as a parameterizable type.
525
526 create_class_type_constraint($class, $options)
527
528 Given a class name this function will create a new
529 Moose::Meta::TypeConstraint::Class object for that class name.
530
531 The $options is a hash reference that will be passed to the
532 Moose::Meta::TypeConstraint::Class constructor (as a hash).
533
534 create_role_type_constraint($role, $options)
535
536 Given a role name this function will create a new
537 Moose::Meta::TypeConstraint::Role object for that role name.
538
539 The $options is a hash reference that will be passed to the
540 Moose::Meta::TypeConstraint::Role constructor (as a hash).
541
542 create_enum_type_constraint($name, $values)
543
544 Given a enum name this function will create a new
545 Moose::Meta::TypeConstraint::Enum object for that enum name.
546
547 create_duck_type_constraint($name, $methods)
548
549 Given a duck type name this function will create a new
550 Moose::Meta::TypeConstraint::DuckType object for that enum name.
551
552 find_or_parse_type_constraint($type_name)
553
554 Given a type name, this first attempts to find a matching constraint in
555 the global registry.
556
557 If the type name is a union or parameterized type, it will create a new
558 object of the appropriate, but if given a "regular" type that does not
559 yet exist, it simply returns false.
560
561 When given a union or parameterized type, the member or base type must
562 already exist.
563
564 If it creates a new union or parameterized type, it will add it to the
565 global registry.
566
567 find_or_create_isa_type_constraint($type_name)
568
569 find_or_create_does_type_constraint($type_name)
570
571 These functions will first call "find_or_parse_type_constraint". If
572 that function does not return a type, a new type object will be
573 created.
574
575 The "isa" variant will use "create_class_type_constraint" and the
576 "does" variant will use "create_role_type_constraint".
577
578 get_type_constraint_registry
579
580 Returns the Moose::Meta::TypeConstraint::Registry object which keeps
581 track of all type constraints.
582
583 list_all_type_constraints
584
585 This will return a list of type constraint names in the global
586 registry. You can then fetch the actual type object using
587 "find_type_constraint($type_name)".
588
589 list_all_builtin_type_constraints
590
591 This will return a list of builtin type constraints, meaning those
592 which are defined in this module. See the "Default Type Constraints"
593 section for a complete list.
594
595 export_type_constraints_as_functions
596
597 This will export all the current type constraints as functions into the
598 caller's namespace ("Int()", "Str()", etc). Right now, this is mostly
599 used for testing, but it might prove useful to others.
600
601 get_all_parameterizable_types
602
603 This returns all the parameterizable types that have been registered,
604 as a list of type objects.
605
606 add_parameterizable_type($type)
607
608 Adds $type to the list of parameterizable types
609
611 See "BUGS" in Moose for details on reporting bugs.
612
614 · Stevan Little <stevan.little@iinteractive.com>
615
616 · Dave Rolsky <autarch@urth.org>
617
618 · Jesse Luehrs <doy@tozt.net>
619
620 · Shawn M Moore <code@sartak.org>
621
622 · יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>
623
624 · Karen Etheridge <ether@cpan.org>
625
626 · Florian Ragwitz <rafl@debian.org>
627
628 · Hans Dieter Pearcey <hdp@weftsoar.net>
629
630 · Chris Prather <chris@prather.org>
631
632 · Matt S Trout <mst@shadowcat.co.uk>
633
635 This software is copyright (c) 2006 by Infinity Interactive, Inc.
636
637 This is free software; you can redistribute it and/or modify it under
638 the same terms as the Perl 5 programming language system itself.
639
640
641
642perl v5.30.1 2020-01-30 Moose::Util::TypeConstraints(3)