2024-03-28 19:20:37 +01:00
|
|
|
(** Infer the type of a given term and, if exists, returns the type of the term *)
|
2024-03-14 22:24:38 +01:00
|
|
|
let rec typeof = function
|
2024-04-11 11:48:47 +02:00
|
|
|
| Term.Var id ->
|
|
|
|
(match Unification.unify (Type.Var id) Type.Int with
|
|
|
|
| Some _ -> Some Type.Int
|
|
|
|
| None -> Some (Type.Var id))
|
2024-03-14 22:24:38 +01:00
|
|
|
| Term.IntConst _ -> Some Type.Int
|
|
|
|
| Term.Binop (t1, _, t2) ->
|
2024-04-11 11:48:47 +02:00
|
|
|
(* Both operands must have type Int *)
|
2024-03-14 22:24:38 +01:00
|
|
|
(match typeof t1, typeof t2 with
|
2024-04-11 11:48:47 +02:00
|
|
|
| Some ty1, Some ty2 ->
|
|
|
|
(match Unification.unify ty1 Type.Int, Unification.unify ty2 Type.Int with
|
|
|
|
| Some _, Some _ -> Some Type.Int
|
|
|
|
| _ -> None)
|
|
|
|
| _, _ -> None)
|
2024-03-14 22:24:38 +01:00
|
|
|
| Term.Pair (t1, t2) ->
|
|
|
|
(match typeof t1, typeof t2 with
|
|
|
|
| Some ty1, Some ty2 -> Some (Type.Product (ty1, ty2))
|
2024-03-28 19:20:37 +01:00
|
|
|
| _, _ -> None)
|
2024-04-11 11:48:47 +02:00
|
|
|
| Term.Proj (proj, t) ->
|
|
|
|
(* Check if the term is a pair *)
|
2024-03-28 19:20:37 +01:00
|
|
|
(match typeof t with
|
2024-04-11 11:48:47 +02:00
|
|
|
| Some (Type.Product (ty1, ty2)) ->
|
|
|
|
(match proj with
|
|
|
|
| Term.First -> Some ty1
|
|
|
|
| Term.Second -> Some ty2)
|
|
|
|
| _ -> None)
|
|
|
|
| Term.Fun (id, body) ->
|
|
|
|
(match typeof body with
|
|
|
|
| Some ty_body ->
|
|
|
|
(match typeof (Term.Var id) with
|
|
|
|
| Some tt -> Some (Type.Arrow (tt, ty_body))
|
|
|
|
| None -> Some (Type.Arrow (Type.Var id, ty_body)))
|
|
|
|
| _ -> None)
|
2024-03-28 19:20:37 +01:00
|
|
|
| Term.App (t1, t2) ->
|
2024-04-11 11:48:47 +02:00
|
|
|
(* Check if the function type matches the arguments *)
|
2024-03-28 19:20:37 +01:00
|
|
|
(match typeof t1, typeof t2 with
|
2024-04-11 11:48:47 +02:00
|
|
|
| Some (Type.Arrow (ty_param, ty_fn)), Some ty_args ->
|
|
|
|
(match Unification.unify ty_param ty_args with
|
|
|
|
| Some _ -> Some ty_fn
|
2024-03-28 19:20:37 +01:00
|
|
|
| None -> None)
|
2024-04-11 11:48:47 +02:00
|
|
|
| _, _ -> None)
|
2024-03-14 22:24:38 +01:00
|
|
|
;;
|