{
    "content": [
        {
            "type": "text",
            "text": "# Moose::Util::TypeConstraints (perldoc)\n\n## NAME\n\nMoose::Util::TypeConstraints - Type constraint system for Moose\n\n## SYNOPSIS\n\nuse Moose::Util::TypeConstraints;\nsubtype 'Natural',\nas 'Int',\nwhere { $ > 0 };\nsubtype 'NaturalLessThanTen',\nas 'Natural',\nwhere { $ < 10 },\nmessage { \"This number ($) is not less than ten!\" };\ncoerce 'Num',\nfrom 'Str',\nvia { 0+$ };\nclasstype 'DateTimeClass', { class => 'DateTime' };\nroletype 'Barks', { role => 'Some::Library::Role::Barks' };\nenum 'RGBColors', [qw(red green blue)];\nunion 'StringOrArray', [qw( String ArrayRef )];\nno Moose::Util::TypeConstraints;\n\n## DESCRIPTION\n\nThis module provides Moose with the ability to create custom type constraints to be used in\nattribute definition.\n\n## Sections\n\n- **NAME**\n- **VERSION**\n- **SYNOPSIS**\n- **DESCRIPTION** (6 subsections)\n- **FUNCTIONS** (4 subsections)\n- **BUGS**\n- **AUTHORS**\n- **COPYRIGHT AND LICENSE**\n\nUse structuredContent.sections for detailed options, examples, and full documentation.\n"
        }
    ],
    "structuredContent": {
        "command": "Moose::Util::TypeConstraints",
        "section": "",
        "mode": "perldoc",
        "summary": "Moose::Util::TypeConstraints - Type constraint system for Moose",
        "synopsis": "use Moose::Util::TypeConstraints;\nsubtype 'Natural',\nas 'Int',\nwhere { $ > 0 };\nsubtype 'NaturalLessThanTen',\nas 'Natural',\nwhere { $ < 10 },\nmessage { \"This number ($) is not less than ten!\" };\ncoerce 'Num',\nfrom 'Str',\nvia { 0+$ };\nclasstype 'DateTimeClass', { class => 'DateTime' };\nroletype 'Barks', { role => 'Some::Library::Role::Barks' };\nenum 'RGBColors', [qw(red green blue)];\nunion 'StringOrArray', [qw( String ArrayRef )];\nno Moose::Util::TypeConstraints;",
        "tldr_summary": null,
        "tldr_examples": [],
        "tldr_source": null,
        "flags": [],
        "examples": [],
        "see_also": [],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "VERSION",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 25,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 3,
                "subsections": [
                    {
                        "name": "Important Caveat",
                        "lines": 7
                    },
                    {
                        "name": "Slightly Less Important Caveat",
                        "lines": 20
                    },
                    {
                        "name": "Default Type Constraints",
                        "lines": 47
                    },
                    {
                        "name": "Type Constraint Naming",
                        "lines": 7
                    },
                    {
                        "name": "Use with Other Constraint Modules",
                        "lines": 31
                    },
                    {
                        "name": "Error messages",
                        "lines": 13
                    }
                ]
            },
            {
                "name": "FUNCTIONS",
                "lines": 1,
                "subsections": [
                    {
                        "name": "Type Constraint Constructors",
                        "lines": 160
                    },
                    {
                        "name": "Type Constraint Utilities",
                        "lines": 63
                    },
                    {
                        "name": "Type Coercion Constructors",
                        "lines": 29
                    },
                    {
                        "name": "Creating and Finding Type Constraints",
                        "lines": 90
                    }
                ]
            },
            {
                "name": "BUGS",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "AUTHORS",
                "lines": 20,
                "subsections": []
            },
            {
                "name": "COPYRIGHT AND LICENSE",
                "lines": 5,
                "subsections": []
            }
        ],
        "sections": {
            "NAME": {
                "content": "Moose::Util::TypeConstraints - Type constraint system for Moose\n",
                "subsections": []
            },
            "VERSION": {
                "content": "version 2.2200\n",
                "subsections": []
            },
            "SYNOPSIS": {
                "content": "use Moose::Util::TypeConstraints;\n\nsubtype 'Natural',\nas 'Int',\nwhere { $ > 0 };\n\nsubtype 'NaturalLessThanTen',\nas 'Natural',\nwhere { $ < 10 },\nmessage { \"This number ($) is not less than ten!\" };\n\ncoerce 'Num',\nfrom 'Str',\nvia { 0+$ };\n\nclasstype 'DateTimeClass', { class => 'DateTime' };\n\nroletype 'Barks', { role => 'Some::Library::Role::Barks' };\n\nenum 'RGBColors', [qw(red green blue)];\n\nunion 'StringOrArray', [qw( String ArrayRef )];\n\nno Moose::Util::TypeConstraints;\n",
                "subsections": []
            },
            "DESCRIPTION": {
                "content": "This module provides Moose with the ability to create custom type constraints to be used in\nattribute definition.\n",
                "subsections": [
                    {
                        "name": "Important Caveat",
                        "content": "This is NOT a type system for Perl 5. These are type constraints, and they are not used by Moose\nunless you tell it to. No type inference is performed, expressions are not typed, etc. etc. etc.\n\nA type constraint is at heart a small \"check if a value is valid\" function. A constraint can be\nassociated with an attribute. This simplifies parameter validation, and makes your code clearer\nto read, because you can refer to constraints by name.\n"
                    },
                    {
                        "name": "Slightly Less Important Caveat",
                        "content": "It is always a good idea to quote your type names.\n\nThis prevents Perl from trying to execute the call as an indirect object call. This can be an\nissue when you have a subtype with the same name as a valid class.\n\nFor instance:\n\nsubtype DateTime => as Object => where { $->isa('DateTime') };\n\nwill *just work*, while this:\n\nuse DateTime;\nsubtype DateTime => as Object => where { $->isa('DateTime') };\n\nwill fail silently and cause many headaches. The simple way to solve this, as well as future\nproof your subtypes from classes which have yet to have been created, is to quote the type name:\n\nuse DateTime;\nsubtype 'DateTime', as 'Object', where { $->isa('DateTime') };\n"
                    },
                    {
                        "name": "Default Type Constraints",
                        "content": "This module also provides a simple hierarchy for Perl 5 types, here is that hierarchy\nrepresented visually.\n\nAny\nItem\nBool\nMaybe[`a]\nUndef\nDefined\nValue\nStr\nNum\nInt\nClassName\nRoleName\nRef\nScalarRef[`a]\nArrayRef[`a]\nHashRef[`a]\nCodeRef\nRegexpRef\nGlobRef\nFileHandle\nObject\n\nNOTE: Any type followed by a type parameter \"[`a]\" can be parameterized, this means you can say:\n\nArrayRef[Int]    # an array of integers\nHashRef[CodeRef] # a hash of str to CODE ref mappings\nScalarRef[Int]   # a reference to an integer\nMaybe[Str]       # value may be a string, may be undefined\n\nIf Moose finds a name in brackets that it does not recognize as an existing type, it assumes\nthat this is a class name, for example \"ArrayRef[DateTime]\".\n\nNOTE: Unless you parameterize a type, then it is invalid to include the square brackets. I.e.\n\"ArrayRef[]\" will be treated as a new type name, *not* as a parameterization of \"ArrayRef\".\n\nNOTE: The \"Undef\" type constraint for the most part works correctly now, but edge cases may\nstill exist, please use it sparingly.\n\nNOTE: The \"ClassName\" type constraint does a complex package existence check. This means that\nyour class must be loaded for this type constraint to pass.\n\nNOTE: The \"RoleName\" constraint checks a string is a *package name* which is a role, like\n'MyApp::Role::Comparable'.\n"
                    },
                    {
                        "name": "Type Constraint Naming",
                        "content": "Type names declared via this module can only contain alphanumeric characters, colons (:), and\nperiods (.).\n\nSince the types created by this module are global, it is suggested that you namespace your types\njust as you would namespace your modules. So instead of creating a *Color* type for your\nMy::Graphics module, you would call the type *My::Graphics::Types::Color* instead.\n"
                    },
                    {
                        "name": "Use with Other Constraint Modules",
                        "content": "This module can play nicely with other constraint modules with some slight tweaking. The \"where\"\nclause in types is expected to be a \"CODE\" reference which checks its first argument and returns\na boolean. Since most constraint modules work in a similar way, it should be simple to adapt\nthem to work with Moose.\n\nFor instance, this is how you could use it with Declare::Constraints::Simple to declare a\ncompletely new type.\n\ntype 'HashOfArrayOfObjects',\nwhere {\nIsHashRef(\n-keys   => HasLength,\n-values => IsArrayRef(IsObject)\n)->(@);\n};\n\nFor more examples see the t/examples/examplewDCS.t test file.\n\nHere is an example of using Test::Deep and its non-test related \"eqdeeply\" function.\n\ntype 'ArrayOfHashOfBarsAndRandomNumbers',\nwhere {\neqdeeply($,\narrayeach(subhashof({\nbar           => isa('Bar'),\nrandomnumber => ignore()\n})))\n};\n\nFor a complete example see the t/examples/examplewTestDeep.t test file.\n"
                    },
                    {
                        "name": "Error messages",
                        "content": "Type constraints can also specify custom error messages, for when they fail to validate. This is\nprovided as just another coderef, which receives the invalid value in $, as in:\n\nsubtype 'PositiveInt',\nas 'Int',\nwhere { $ > 0 },\nmessage { \"$ is not a positive integer!\" };\n\nIf no message is specified, a default message will be used, which indicates which type\nconstraint was being used and what value failed. If Devel::PartialDump (version 0.14 or higher)\nis installed, it will be used to display the invalid value, otherwise it will just be printed as\nis.\n"
                    }
                ]
            },
            "FUNCTIONS": {
                "content": "",
                "subsections": [
                    {
                        "name": "Type Constraint Constructors",
                        "content": "The following functions are used to create type constraints. They will also register the type\nconstraints your create in a global registry that is used to look types up by name.\n\nSee the \"SYNOPSIS\" for an example of how to use these.\n\nsubtype 'Name', as 'Parent', where { } ...\nThis creates a named subtype.\n\nIf you provide a parent that Moose does not recognize, it will automatically create a new class\ntype constraint for this name.\n\nWhen creating a named type, the \"subtype\" function should either be called with the sugar\nhelpers (\"where\", \"message\", etc), or with a name and a hashref of parameters:\n\nsubtype( 'Foo', { where => ..., message => ... } );\n\nThe valid hashref keys are \"as\" (the parent), \"where\", \"message\", and \"inlineas\".\n\nsubtype as 'Parent', where { } ...\nThis creates an unnamed subtype and will return the type constraint meta-object, which will be\nan instance of Moose::Meta::TypeConstraint.\n\nWhen creating an anonymous type, the \"subtype\" function should either be called with the sugar\nhelpers (\"where\", \"message\", etc), or with just a hashref of parameters:\n\nsubtype( { where => ..., message => ... } );\n\nclasstype ($class, ?$options)\nCreates a new subtype of \"Object\" with the name $class and the metaclass\nMoose::Meta::TypeConstraint::Class.\n\n# Create a type called 'Box' which tests for objects which ->isa('Box')\nclasstype 'Box';\n\nBy default, the name of the type and the name of the class are the same, but you can specify\nboth separately.\n\n# Create a type called 'Box' which tests for objects which ->isa('ObjectLibrary::Box');\nclasstype 'Box', { class => 'ObjectLibrary::Box' };\n\nroletype ($role, ?$options)\nCreates a \"Role\" type constraint with the name $role and the metaclass\nMoose::Meta::TypeConstraint::Role.\n\n# Create a type called 'Walks' which tests for objects which ->does('Walks')\nroletype 'Walks';\n\nBy default, the name of the type and the name of the role are the same, but you can specify both\nseparately.\n\n# Create a type called 'Walks' which tests for objects which ->does('MooseX::Role::Walks');\nroletype 'Walks', { role => 'MooseX::Role::Walks' };\n\nmaybetype ($type)\nCreates a type constraint for either \"undef\" or something of the given type.\n\nducktype ($name, \\@methods)\nThis will create a subtype of Object and test to make sure the value \"can()\" do the methods in\n\"\\@methods\".\n\nThis is intended as an easy way to accept non-Moose objects that provide a certain interface. If\nyou're using Moose classes, we recommend that you use a \"requires\"-only Role instead.\n\nducktype (\\@methods)\nIf passed an ARRAY reference as the only parameter instead of the $name, \"\\@methods\" pair, this\nwill create an unnamed duck type. This can be used in an attribute definition like so:\n\nhas 'cache' => (\nis  => 'ro',\nisa => ducktype( [qw( getset )] ),\n);\n\nenum ($name, \\@values)\nThis will create a basic subtype for a given set of strings. The resulting constraint will be a\nsubtype of \"Str\" and will match any of the items in \"\\@values\". It is case sensitive. See the\n\"SYNOPSIS\" for a simple example.\n\nNOTE: This is not a true proper enum type, it is simply a convenient constraint builder.\n\nenum (\\@values)\nIf passed an ARRAY reference as the only parameter instead of the $name, \"\\@values\" pair, this\nwill create an unnamed enum. This can then be used in an attribute definition like so:\n\nhas 'sortorder' => (\nis  => 'ro',\nisa => enum([qw[ ascending descending ]]),\n);\n\nunion ($name, \\@constraints)\nThis will create a basic subtype where any of the provided constraints may match in order to\nsatisfy this constraint.\n\nunion (\\@constraints)\nIf passed an ARRAY reference as the only parameter instead of the $name, \"\\@constraints\" pair,\nthis will create an unnamed union. This can then be used in an attribute definition like so:\n\nhas 'items' => (\nis => 'ro',\nisa => union([qw[ Str ArrayRef ]]),\n);\n\nThis is similar to the existing string union:\n\nisa => 'Str|ArrayRef'\n\nexcept that it supports anonymous elements as child constraints:\n\nhas 'color' => (\nisa => 'ro',\nisa => union([ 'Int',  enum([qw[ red green blue ]]) ]),\n);\n\nas 'Parent'\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a single argument, which is the name of a parent type.\n\nwhere { ... }\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a subroutine reference as an argument. When the type constraint is tested, the\nreference is run with the value to be tested in $. This reference should return true or false\nto indicate whether or not the constraint check passed.\n\nmessage { ... }\nThis is just sugar for the type constraint construction syntax.\n\nIt takes a subroutine reference as an argument. When the type constraint fails, then the code\nblock is run with the value provided in $. This reference should return a string, which will be\nused in the text of the exception thrown.\n\ninlineas { ... }\nThis can be used to define a \"hand optimized\" inlinable version of your type constraint.\n\nYou provide a subroutine which will be called *as a method* on a Moose::Meta::TypeConstraint\nobject. It will receive a single parameter, the name of the variable to check, typically\nsomething like \"$\" or \"$[0]\".\n\nThe subroutine should return a code string suitable for inlining. You can assume that the check\nwill be wrapped in parentheses when it is inlined.\n\nThe inlined code should include any checks that your type's parent types do. If your parent type\nconstraint defines its own inlining, you can simply use that to avoid repeating code. For\nexample, here is the inlining code for the \"Value\" type, which is a subtype of \"Defined\":\n\nsub {\n$[0]->parent()->inlinecheck($[1])\n. ' && !ref(' . $[1] . ')'\n}\n\ntype 'Name', where { } ...\nThis creates a base type, which has no parent.\n\nThe \"type\" function should either be called with the sugar helpers (\"where\", \"message\", etc), or\nwith a name and a hashref of parameters:\n\ntype( 'Foo', { where => ..., message => ... } );\n\nThe valid hashref keys are \"where\", \"message\", and \"inlinedas\".\n"
                    },
                    {
                        "name": "Type Constraint Utilities",
                        "content": "matchontype $value => ( $type => \\&action, ... ?\\&default )\nThis is a utility function for doing simple type based dispatching similar to match/case in\nOCaml and case/of in Haskell. It is not as featureful as those languages, nor does not it\nsupport any kind of automatic destructuring bind. Here is a simple Perl pretty printer\ndispatching over the core Moose types.\n\nsub ppprint {\nmy $x = shift;\nmatchontype $x => (\nHashRef => sub {\nmy $hash = shift;\n'{ '\n. (\njoin \", \" => map { $ . ' => ' . ppprint( $hash->{$} ) }\nsort keys %$hash\n) . ' }';\n},\nArrayRef => sub {\nmy $array = shift;\n'[ ' . ( join \", \" => map { ppprint($) } @$array ) . ' ]';\n},\nCodeRef   => sub {'sub { ... }'},\nRegexpRef => sub { 'qr/' . $ . '/' },\nGlobRef   => sub { '*' . B::svref2object($)->NAME },\nObject    => sub { $->can('tostring') ? $->tostring : $ },\nScalarRef => sub { '\\\\' . ppprint( ${$} ) },\nNum       => sub {$},\nStr       => sub { '\"' . $ . '\"' },\nUndef     => sub {'undef'},\n=> sub { die \"I don't know what $ is\" }\n);\n}\n\nOr a simple JSON serializer:\n\nsub tojson {\nmy $x = shift;\nmatchontype $x => (\nHashRef => sub {\nmy $hash = shift;\n'{ '\n. (\njoin \", \" =>\nmap { '\"' . $ . '\" : ' . tojson( $hash->{$} ) }\nsort keys %$hash\n) . ' }';\n},\nArrayRef => sub {\nmy $array = shift;\n'[ ' . ( join \", \" => map { tojson($) } @$array ) . ' ]';\n},\nNum   => sub {$},\nStr   => sub { '\"' . $ . '\"' },\nUndef => sub {'null'},\n=> sub { die \"$ is not acceptable json type\" }\n);\n}\n\nThe matcher is done by mapping a $type to an \"\\&action\". The $type can be either a string type\nor a Moose::Meta::TypeConstraint object, and \"\\&action\" is a subroutine reference. This function\nwill dispatch on the first match for $value. It is possible to have a catch-all by providing an\nadditional subroutine reference as the final argument to \"matchontype\".\n"
                    },
                    {
                        "name": "Type Coercion Constructors",
                        "content": "You can define coercions for type constraints, which allow you to automatically transform values\nto something valid for the type constraint. If you ask your accessor to coerce by adding the\noption \"coerce => 1\", then Moose will run the type-coercion code first, followed by the type\nconstraint check. This feature should be used carefully as it is very powerful and could easily\ntake off a limb if you are not careful.\n\nSee the \"SYNOPSIS\" for an example of how to use these.\n\ncoerce 'Name', from 'OtherName', via { ... }\nThis defines a coercion from one type to another. The \"Name\" argument is the type you are\ncoercing *to*.\n\nTo define multiple coercions, supply more sets of from/via pairs:\n\ncoerce 'Name',\nfrom 'OtherName', via { ... },\nfrom 'ThirdName', via { ... };\n\nfrom 'OtherName'\nThis is just sugar for the type coercion construction syntax.\n\nIt takes a single type name (or type object), which is the type being coerced *from*.\n\nvia { ... }\nThis is just sugar for the type coercion construction syntax.\n\nIt takes a subroutine reference. This reference will be called with the value to be coerced in\n$. It is expected to return a new value of the proper type for the coercion.\n"
                    },
                    {
                        "name": "Creating and Finding Type Constraints",
                        "content": "These are additional functions for creating and finding type constraints. Most of these\nfunctions are not available for importing. The ones that are importable as specified.\n\nfindtypeconstraint($typename)\nThis function can be used to locate the Moose::Meta::TypeConstraint object for a named type.\n\nThis function is importable.\n\nregistertypeconstraint($typeobject)\nThis function will register a Moose::Meta::TypeConstraint with the global type registry.\n\nThis function is importable.\n\nnormalizetypeconstraintname($typeconstraintname)\nThis method takes a type constraint name and returns the normalized form. This removes any\nwhitespace in the string.\n\ncreatetypeconstraintunion($pipeseparatedtypes | @typeconstraintnames)\ncreatenamedtypeconstraintunion($name, $pipeseparatedtypes | @typeconstraintnames)\nThis can take a union type specification like 'Int|ArrayRef[Int]', or a list of names. It\nreturns a new Moose::Meta::TypeConstraint::Union object.\n\ncreateparameterizedtypeconstraint($typename)\nGiven a $typename in the form of 'BaseType[ContainerType]', this will create a new\nMoose::Meta::TypeConstraint::Parameterized object. The \"BaseType\" must already exist as a\nparameterizable type.\n\ncreateclasstypeconstraint($class, $options)\nGiven a class name this function will create a new Moose::Meta::TypeConstraint::Class object for\nthat class name.\n\nThe $options is a hash reference that will be passed to the Moose::Meta::TypeConstraint::Class\nconstructor (as a hash).\n\ncreateroletypeconstraint($role, $options)\nGiven a role name this function will create a new Moose::Meta::TypeConstraint::Role object for\nthat role name.\n\nThe $options is a hash reference that will be passed to the Moose::Meta::TypeConstraint::Role\nconstructor (as a hash).\n\ncreateenumtypeconstraint($name, $values)\nGiven a enum name this function will create a new Moose::Meta::TypeConstraint::Enum object for\nthat enum name.\n\ncreateducktypeconstraint($name, $methods)\nGiven a duck type name this function will create a new Moose::Meta::TypeConstraint::DuckType\nobject for that enum name.\n\nfindorparsetypeconstraint($typename)\nGiven a type name, this first attempts to find a matching constraint in the global registry.\n\nIf the type name is a union or parameterized type, it will create a new object of the\nappropriate, but if given a \"regular\" type that does not yet exist, it simply returns false.\n\nWhen given a union or parameterized type, the member or base type must already exist.\n\nIf it creates a new union or parameterized type, it will add it to the global registry.\n\nfindorcreateisatypeconstraint($typename)\nfindorcreatedoestypeconstraint($typename)\nThese functions will first call \"findorparsetypeconstraint\". If that function does not\nreturn a type, a new type object will be created.\n\nThe \"isa\" variant will use \"createclasstypeconstraint\" and the \"does\" variant will use\n\"createroletypeconstraint\".\n\ngettypeconstraintregistry\nReturns the Moose::Meta::TypeConstraint::Registry object which keeps track of all type\nconstraints.\n\nlistalltypeconstraints\nThis will return a list of type constraint names in the global registry. You can then fetch the\nactual type object using \"findtypeconstraint($typename)\".\n\nlistallbuiltintypeconstraints\nThis will return a list of builtin type constraints, meaning those which are defined in this\nmodule. See the \"Default Type Constraints\" section for a complete list.\n\nexporttypeconstraintsasfunctions\nThis will export all the current type constraints as functions into the caller's namespace\n(\"Int()\", \"Str()\", etc). Right now, this is mostly used for testing, but it might prove useful\nto others.\n\ngetallparameterizabletypes\nThis returns all the parameterizable types that have been registered, as a list of type objects.\n\naddparameterizabletype($type)\nAdds $type to the list of parameterizable types\n"
                    }
                ]
            },
            "BUGS": {
                "content": "See \"BUGS\" in Moose for details on reporting bugs.\n",
                "subsections": []
            },
            "AUTHORS": {
                "content": "*   Stevan Little <stevan@cpan.org>\n\n*   Dave Rolsky <autarch@urth.org>\n\n*   Jesse Luehrs <doy@cpan.org>\n\n*   Shawn M Moore <sartak@cpan.org>\n\n*   יובל קוג'מן (Yuval Kogman) <nothingmuch@woobling.org>\n\n*   Karen Etheridge <ether@cpan.org>\n\n*   Florian Ragwitz <rafl@debian.org>\n\n*   Hans Dieter Pearcey <hdp@cpan.org>\n\n*   Chris Prather <chris@prather.org>\n\n*   Matt S Trout <mstrout@cpan.org>\n",
                "subsections": []
            },
            "COPYRIGHT AND LICENSE": {
                "content": "This software is copyright (c) 2006 by Infinity Interactive, Inc.\n\nThis is free software; you can redistribute it and/or modify it under the same terms as the Perl\n5 programming language system itself.\n",
                "subsections": []
            }
        }
    }
}