Start with this code. It contains a type-checker and interpreter like the one from lecture, except with ref and setref forms:
ref(x) - creates a reference to the variable x.
setref(e1, e2) - installs the value of e2 into the value of e1. The value of e1 must be a reference. The result is always 1.
Examples:
let x = 0 in ref(x) => a reference, prints as _(a-ref 0 #(0))_
let x = 0 in setref(ref(x), 5) => 1
let x = 0 in let d = setref(ref(x), 5) in x => 5
A program using reference values can go wrong in two ways:
Using setref on a non-reference:
setref(0, 1) => crash: 0 is a not a reference
let x = 0 in setref(x, 1) => crash: 0 is not a reference
Putting the wrong type of value into a reference:
let x = 0 in let d = setref(ref(x), false) in +(x,1) => should crash: addition shouldn't work on booleans
Note that, in the second case above, we blame the setref expression for changing the kind of value in x, not the addition expression for using a boolean. To check programs using references, we must extend the grammar of
type expressions:
where (refto texp) means a reference containing a value of type texp.Examples:
let x = 0 in ref(x) : (refto int)
let x = false in let d = setref(ref(x), true) in x : bool because
x : bool
implies ref(x) : (refto bool)
which with true : bool
allows setref(ref(x), true) : int
let f = proc((refto int) r)setref(r, 1) in let x = 0 in let d = (f ref(x)) in x : int because
f : ((refto int) -> int)
and ref(x) : (refto int)
Ill-formed expressions:
setref(0, 1) no type: int is not (refto int)
let x = 0 in setref(x, 1) no type: int is not (refto int)
let x = 0 in setref(ref(x), false) no type: bool is not int
let f = proc(int x)x in setref(ref(f), false) no type: bool is not (int -> int)
let f = proc(int x)x in setref(ref(f), proc(bool y)y) no type: (bool -> bool) is not (int -> int)
let f = proc((refto int) x)setref(x, 1) in (f 0) no type: int is not (refto int)
However, the initial type-checker does not handle ref and setref properly. It always assigns the type int to a ref expression (never correct), and always assigns the type int to a setref expression (correct only if the subexpression types are appropriate).Your task: Modify type-of-expression to correctly type-check ref and setref expressions. The places to modify the code are marked with FIXME! comments. Test your changes using the type-check function.Hand in your revised hw9.scm.
Last update: Monday, October 30th, 2000mflatt@cs.utah.edu