let rec term_replace alpha x exp t =
let frec = term_replace alpha x exp in
match t with
| Tconst _ -> t
| Tvar x0 -> if Var.equal x0 x then exp else t
| Tapp (f, ts) -> e_app f (List.map (frec) ts)
| Tif (a, b, c) -> e_if (frec a) (frec b) (frec c)
| Tgetfield(f,r) -> e_getfield f (frec r)
| Tsetfield(f,r,v) -> e_setfield f (frec r) (frec v)
| Taccess(t,i) -> e_access (frec t) (frec i)
| Tupdate(t,i,v) -> e_update (frec t) (frec i) (frec v)
| Tlet (x0, a, b) ->
if e_has_var [x0] exp then
match alpha x with
| None -> Tlet(x,exp,t)
| Some y ->
let by = term_replace alpha x0 (Tvar y) b in
Tlet(y,frec a,frec by)
else
let b' = if Var.equal x0 x then b else frec b in
Tlet(x0,frec a,b')