jsigbiz / spec

JavaScript signature notation
131 stars 6 forks source link

Expressing constraints on functions. #51

Open Raynos opened 9 years ago

Raynos commented 9 years ago

To implement support for the + operator in the type checker I want to express that a function (operators are modeled as functions internally) can have constraints on it's types.

see the following definitions for + named sum1, sum2, sum3

sum1 : (String | Number, String | Number) => String | Number
sum2 : (
    ((String, String) => String) &
    ((Number, Number) => Number)
)
sum3 : (A <: String | Number) :: (A, A) => A

In this example sum3 and sum2 are equivelant. Internally in the type checker I am converting sum2 into sum3 as intersections of functions are hard to work with but a function whose arguments are constrained are easier to work with.

I also have examples of the indexAt x[s] operator

index1 : (Array<T> | Object<String, T>, Number | String) => T
index2 : (
    ((Array<T>, Number) => T) &
    ((Object<String, T>, String) => T)
)
index3 : (
    (X <: Array<T> & S <: Number) |
    (X <: Object<String, T> & S <: String)
) :: (X, S) => T

I would like to have a syntax for constraints. my current proposal is:

<constrainedFunction> := ( <constraintish> ) :: <function>
<constrainish> :=
  <constraint> OR
  <constraintish> & <constraintish> OR
  <constraintish> | <constraintish>
<constraint> := <typeLiteral> <: <typeExpression>

Semantically a <constraint> means that the named type is a sub type of the typeExpression. Semantically a <constraintish> is a way of combining multiple constraint expression using boolean logic operations to define a full constraint expression for a function Semantically a <constrainedFunction> is a "generic" function but instead of saying the function is generic over some set of parameters we are saying that the type literals in the function definition must satisfy the constraints

See the following artical for more talk about constraints and "ambigious" types ( https://noamlewis.wordpress.com/2015/02/19/ad-hoc-polymorphism-type-families-ambiguous-types-and-javascript/ ).

I don't think I need syntax in jsig for this since the intersection syntax is already valid; however I will model this information in the AST data structures and it would be nice to have syntax that we can serialize the AST into or have syntax that we can express it in directly rather then indirectly expressing it through function intersection.

cc @jden