§ The Gradual Guarantees



§ statically correct programm



# Inferred f : Int -> Any
def f(x : Int): return x

# Inferred g: Int -> Any
def g(y): return y

a = 42 # Inferred a : Int
b = f(a) # Inferred b : Any
b' = upcast b Int # Inferred b' : Int
c = g(b') # Inferred c : Any

§ statically incorrect programm



# Inferred f : Bool -> Any
def f(x : Bool): return x

# Inferred g: Any -> Any
def g(y): return y

a = 42 # Inferred a : Int
b = f(a) # Type error, f : Bool -> Any mismatch argument a : Int
c = g(b) # See that this is type-correct, (b : Any), (g : Any -> Any)

§ dynamically incorrect programm



# Inferred f : Any -> Any
def f(x): return x

# Inferred g: Bool -> Any
def g(y : Bool): return y

a = 42 # Inferred a : Int
b = f(a) # Inferred b : Any
b' = upcast b Bool # dynamic error at upcast, since at runtime, (b := 42)
c = g(b)

§ What have we learnt?



§ Gradual guarantees



§ Why are the gradual guarantees useful?



level 1 gradual typing does not provide run-time support for catching broken
invariants, such as deriv's expectation that its arguments have type string.
Thus, a TypeScript programmer that really wants to enforce such an invariant
would need to add code to check the type of the argument, a common practice
today in JavaScript.

Level 2 gradual typing ensures that the value stored in a variable is
consistent with the variable's static type and it provides the run-time
checking to catch when this invariant is about to be broken. Thus, level 2
gradual typing removes the need for hand-written type tests. Also, level 2
gradual typing opens up the possibility of compiling statically-typed regions
of a program in a more efficient, type-specific manner. (This is an active
area of my current research.) The disadvantages of level 2 gradual typing are
the run-time overhead from cast checking and the increased implementation
complexity.

Level 3 gradual typing improves on level 2 by adding blame tracking, thereby
improving the diagnostic errors reported when a cast fails. The extra cost of
blame tracking is not very significant, so I would always suggest level 3
over level 2.

§ References