more docs and clarifications
[gitmo/MooseX-Dependent.git] / lib / MooseX / Dependent / Types.pm
index 5b3f273..b23e750 100644 (file)
-package MooseX::Types::Dependent;
-
-use 5.008;
+package MooseX::Dependent::Types;
 
 use Moose::Util::TypeConstraints;
-use MooseX::Meta::TypeConstraint::Dependent;
-use MooseX::Types -declare => [qw(Depending)];
-
-our $VERSION = '0.01';
-our $AUTHORITY = 'cpan:JJNAPIORK';
+use MooseX::Dependent::Meta::TypeConstraint::Dependent;
+use MooseX::Types -declare => [qw(Dependent)];
 
 =head1 NAME
 
-MooseX::Types::Dependent - L<MooseX::Types> constraints that depend on values.
+MooseX::Dependent::Types - L<MooseX::Types> constraints that depend on values.
 
 =head1 SYNOPSIS
 
-    subtype UniqueInt,
-      as Depending[
-        Int,
-        sub {
-          shift->exists(shift) ? 0:1;
-        },
-        Set,
-      ];
-
-    subtype UniqueInt,
-      as Depending {
-        shift->exists(shift) ? 0:1;        
-      } [Int, Set];
-
-Please see the test cases for more examples.
-
-=head1 DEFINITIONS
-
-The following is a list of terms used in this documentation.
+Within your L<MooseX::Types> declared library module:
 
-=head2 Dependent Type Constraint
-
-=head2 Check Value
-
-=head2 Constraining Type Constraint
-
-=head2 Constraining Value
+    use MooseX::Dependent::Types qw(Dependent);
+       
+       subtype Set,
+               as class_type("Set::Scalar");
 
+    subtype UniqueInt,
+        as Dependent[Int, Set],
+        where {
+            my ($int, $set) = @_;
+            return !$set->has($int);
+        };
+               
+       subtype PositiveSet,
+               as Set,
+               where {
+                       my ($set) = @_;
+                       return !grep {$_ <0 } $set->members;
+               };
+               
+    subtype PositiveUniqueInt,
+        as UniqueInt[PositiveSet];
+       
+       my $set = Set::Scalar->new(1,2,3);
+
+       UniqueInt([$set])->check(100);  ## Okay, 100 isn't in (1,2,3)
+       UniqueInt([$set])->check(-99);  ## Okay, -99 isn't in (1,2,3)
+       UniqueInt([$set])->check(2);  ## Not OK, 2 is in (1,2,3)
+       
+       PositiveUniqueInt([$set])->check(100);  ## Okay, 100 isn't in (1,2,3)
+       PositiveUniqueInt([$set])->check(-99);  ## Not OK, -99 not Positive Int
+       PositiveUniqueInt([$set])->check(2);  ## Not OK, 2 is in (1,2,3)
+       
+       my $negative_set = Set::Scalar->new(-1,-2,-3);
+       
+       UniqueInt([$negative_set])->check(100);  ## Throws exception
+               
 =head1 DESCRIPTION
 
-A dependent type is a type constraint whose validity is dependent on a second
-value.  You defined the dependent type constraint with a primary type constraint
-(such as 'Int') a 'constraining' value type constraint (such as a Set object)
-and a coderef which will compare the incoming value to be checked with a value
-that conforms to the constraining type constraint.  Typically there should be a
-comparision operator between the check value and the constraining value
-
-=head2 Subtyping a Dependent type constraints
-
-TDB: Need discussion and examples.
-
+A L<MooseX::Types> library for creating dependent types.  A dependent type
+constraint for all intents and uses is a subclass of a parent type, but adds a
+secondary type parameter which is available to constraint callbacks (such as
+inside the 'where' clause) or in the coercions.
+
+This allows you to create a type that has additional runtime advice, such as a
+set of numbers within which another number must be unique, or allowable ranges
+for a integer, such as in:
+
+       subtype Range,
+               as Dict[max=>Int, min=>Int],
+               where {
+                       my ($range) = @_;
+                       return $range->{max} > $range->{min};
+               };
+
+       subtype RangedInt,
+               as Dependent[Int, Range],
+               where {
+                       my ($value, $range) = @_;
+                       return ($value >= $range->{min} &&
+                        $value <= $range->{max});
+               };
+               
+       RangedInt([{min=>10,max=>100}])->check(50); ## OK
+       RangedInt([{min=>50, max=>75}])->check(99); ## Not OK, 99 exceeds max
+       
+This throws a hard Moose exception.  You'll need to capture it in an eval or
+related exception catching system (see L<TryCatch>).
+
+       RangedInt([{min=>99, max=>10}])->check(10); ## Not OK, not a valid Range!
+
+If you can't accept a hard exception here, you'll need to test the constraining
+values first, as in:
+
+       my $range = {min=>99, max=>10};
+       if(my $err = Range->validate($range)) {
+               ## Handle #$err
+       } else {
+               RangedInt($range)->check(99);
+       }
+       
+Please note that for ArrayRef or HashRef dependent type constraints, as in the
+example above, as a convenience we automatically ref the incoming type
+parameters, so that the above could also be written as:
+
+       RangedInt([min=>10,max=>100])->check(50); ## OK
+       RangedInt([min=>50, max=>75])->check(99); ## Not OK, 99 exceeds max
+       RangedInt([min=>99, max=>10])->check(10); ## Exception, not a valid Range!
+
+This is the preferred syntax, as it improve readability and adds to the
+conciseness of your type constraint declarations.  An exception wil be thrown if
+your type parameters don't match the required reference type.
+
+Also not that if you 'chain' parameterization results with a method call like:
+
+       TypeConstraint([$ob])->method;
+       
+You need to have the "(...)" around the ArrayRef in the Type Constraint
+parameters.  This seems to have something to do with the precendent level of
+"->".  Patches or thoughts welcomed.  You only need to do this in the above
+case which I imagine is not a very common case.
+
+==head2 Subtyping a Dependent type constraints
+
+When subclassing a dependent type you must be careful to match either the
+required type parameter type constraint, or if re-parameterizing, the new
+type constraints are a subtype of the parent.  For example:
+
+       subtype RangedInt,
+               as Dependent[Int, Range],
+               where {
+                       my ($value, $range) = @_;
+                       return ($value >= $range->{min} &&
+                        $value =< $range->{max});
+               };
+
+Example subtype with additional constraints:
+
+       subtype PositiveRangedInt,
+               as RangedInt,
+               where {
+                       shift >= 0;                     
+               };
+               
+Or you could have done the following instead:
+
+       ## Subtype of Int for positive numbers
+       subtype PositiveInt,
+               as Int,
+               where {
+                       my ($value, $range) = @_;
+                       return $value >= 0;
+               };
+
+       ## subtype Range to re-parameterize Range with subtypes
+       subtype PositiveRange,
+               as Range[max=>PositiveInt, min=>PositiveInt];
+       
+       ## create subtype via reparameterizing
+       subtype PositiveRangedInt,
+               as RangedInt[PositiveRange];
+
+Notice how re-parameterizing the dependent type 'RangedInt' works slightly
+differently from re-parameterizing 'PositiveRange'  Although it initially takes
+two type constraint values to declare a dependent type, should you wish to
+later re-parameterize it, you only use a subtype of the second type parameter
+(the dependent type constraint) since the first type constraint sets the parent
+type for the dependent type.  In other words, given the example above, a type
+constraint of 'RangedInt' would have a parent of 'Int', not 'Dependent' and for
+all intends and uses you could stick it wherever you'd need an Int.
+
+       subtype NameAge,
+               as Tuple[Str, Int];
+       
+       ## re-parameterized subtypes of NameAge containing a Dependent Int      
+       subtype NameBetween18and35Age,
+               as NameAge[
+                       Str,
+                       PositiveRangedInt[min=>18,max=>35],
+               ];
+
+One caveat is that you can't stick an unparameterized dependent type inside a
+structure, such as L<MooseX::Types::Structured> since that would require the
+ability to convert a 'containing' type constraint into a dependent type, which
+is a capacity we current don't have.
+       
 =head2 Coercions
 
-TBD: Need discussion and example of coercions working for both the
-constrainted and dependent type constraint.
+Dependent types have some limited support for coercions.  Several things must
+be kept in mind.  The first is that the coercion targets the type constraint
+which is being made dependent, Not the dependent type.  So for example if you
+create a Dependent type like:
+
+       subtype RequiredAgeInYears,
+         as Int;
+
+       subtype PersonOverAge,
+         as Dependent[Person, RequiredAgeInYears]
+         where {
+               my ($person, $required_years_old) = @_;
+               return $person->years_old > $required_years_old;
+         }
+
+This would validate the following:
+       
+       my $person = Person->new(age=>35);
+       PersonOverAge([18])->check($person);
+       
+You can then apply the following coercion
+
+       coerce PersonOverAge,
+         from Dict[age=>int],
+         via {Person->new(%$_)},
+         from Int,
+         via {Person->new(age=>$_)};
+         
+This coercion would then apply to all the following:
+
+       PersonOverAge([18])->check(30); ## via the Int coercion
+       PersonOverAge([18])->check({age=>50}); ## via the Dict coercion
+
+However, you are not allowed to place coercions on dependent types that have
+had their constraining value filled, nor subtypes of such.  For example:
+
+       coerce PersonOverAge[18],
+         from DateTime,
+         via {$_->years};
+         
+That would generate a hard exception.  This is a limitation for now until I can
+devise a smarter way to cache the generated type constraints.  However, I doubt
+it will be a significant limitation, since the general use case is supported.
+
+Lastly, the constraining value is available in the coercion in much the same way
+it is available to the constraint.
+
+       ## Create a type constraint where a Person must be in the set
+       subtype PersonInSet,
+               as Dependent[Person, PersonSet],
+               where {
+                       my ($person, $person_set) = @_;
+                       $person_set->find($person);
+               }
+
+       coerce PersonInSet,
+               from HashRef,
+               via {
+                       my ($hashref, $person_set) = @_;
+                       return $person_set->create($hash_ref);
+               };
 
 =head2 Recursion
 
-Newer versions of L<MooseX::Types> support recursive type constraints.  That is
-you can include a type constraint as a contained type constraint of itself.
-Recursion is support in both the dependent and constraining type constraint. For
-example:
+       TBD
 
 =head1 TYPE CONSTRAINTS
 
 This type library defines the following constraints.
 
-=head2 Depending[$dependent_tc, $codref, $constraining_tc]
+=head2 Dependent[ParentTypeConstraint, DependentValueTypeConstraint]
 
-Create a subtype of $dependent_tc that is constrainted by a value that is a
-valid $constraining_tc using $coderef.  For example:
+Create a subtype of ParentTypeConstraint with a dependency on a value that can
+pass the DependentValueTypeConstraint. If DependentValueTypeConstraint is empty
+we default to the 'Any' type constraint (see L<Moose::Util::TypeConstraints>).
 
-    subtype GreaterThanInt,
-      as Depending[
-        Int,
-        sub {
-          my($constraining_value, $check_value) = @_;
-          return $constraining_value > $check_value ? 1:0;
-        },
-        Int,
-      ];
-
-Note that the coderef is passed the constraining value and the check value as an
-Array NOT an ArrayRef.
-
-This would create a type constraint that takes an integer and checks it against
-a second integer, requiring that the check value is greater.  For example:
-
-    GreaterThanInt->check([5,10]);  ## Fails, 5 is less than 10
-    GreaterThanInt->check(['a',10]); ## Fails, 'a' is not an Int.
-    GreaterThanInt->check([5,'b']); ## Fails, 'b' is not an Int either.
-    GreaterThanInt->check([10,5]); ## Success, 10 is greater than 5.
-
-=head1 EXAMPLES
-
-Here are some additional example usage for structured types.  All examples can
-be found also in the 't/examples.t' test.  Your contributions are also welcomed.
-
-TBD
+This creates a type constraint which must be further parameterized at later time
+before it can be used to ->check or ->validate a value.  Attempting to do so
+will cause an exception.
 
 =cut
 
 Moose::Util::TypeConstraints::get_type_constraint_registry->add_type_constraint(
-    MooseX::Meta::TypeConstraint::Dependent->new(
-        name => "MooseX::Types::Dependent::Depending" ,
-        parent => find_type_constraint('ArrayRef'),
-        constraint_generator=> sub { 
-                       my ($dependent_val, $callback, $constraining_val) = @_;
-                       return $callback->($dependent_val, $constraining_val);
-        },
+    MooseX::Dependent::Meta::TypeConstraint::Dependent->new(
+        name => 'MooseX::Dependent::Types::Dependent',
+        parent => find_type_constraint('Any'),
+               constraint => sub {1},
     )
 );
 
-=head1 SEE ALSO
-
-The following modules or resources may be of interest.
-
-L<Moose>, L<MooseX::Types>, L<Moose::Meta::TypeConstraint>,
-L<MooseX::Meta::TypeConstraint::Dependent>
-
-=head1 TODO
-
-Here's a list of stuff I would be happy to get volunteers helping with:
-
-=over 4
-
-=item Examples
-
-Examples of useful code with both POD and ideally a test case to show it
-working.
-
-=back
-
 =head1 AUTHOR
 
 John Napiorkowski, C<< <jjnapiork@cpan.org> >>