Appendix

Type Inference

Type Inference

This section formally defines the rules for how the compiler performs type inference on lists, maps, and the ternary operator:

// list of expressions
[v1, v2, ...]  =>
  V = common(v1, v2, ...)

// map of expressions
[k1:v1, k2:v2, ...] =>
  K = common(k1, k2, ...)
  V = common(v1, v2, ...)

// ternary operator
cond ? t1 : t2  =>
  common(t1, t2)

Type inference of collections is based on a function we call common which is used to find the most common base class among a list of types. The following algorithm is used to compute the common type:

  1. if the list of types is empty return Obj?
  2. if the list of types has only one item, return that type
  3. if any one type is nullable, then the result is nullable
  4. if none of the types is a parameterized generic, then find the most common class which all the types share; we take only classes into account, mixins are ignored
  5. if any one of the types is a parameterized generic then:
    1. if all the types are parameterized Lists, then compute the common V type
    2. if all the tyeps are parameterized Maps then:
      1. if all have the exact same signature, then use that type
      2. use sys::Map
    3. if all the types are parameterized Funcs then:
      1. if all have the exact same signature, then use that type
      2. use sys::Func
    4. if none of the above holds true, then use Obj