typecheck.ml 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. open Printf
  2. open Types
  3. open Util
  4. open Stringify
  5. (*
  6. * Do a number of checks:
  7. * - A void function must not return a value.
  8. * - A non-void function must return a value of the correct type.
  9. * - Array indices must be of type integer.
  10. * - The number of array indices must match the number of array dimensions.
  11. * - The type on the right-hand side of an assignment must match the type on
  12. * the left-hand side.
  13. * - The number of arguments used for a function call must match the number of
  14. * parameters for that function.
  15. * - The types of the function arguments must match the types of parameters.
  16. * - The operands of a unary or binary operation must have valid types.
  17. * - The predicate expression of an if, while, or do-while statement must be
  18. * a boolean.
  19. * - Only values having a basic type can be type cast.
  20. *)
  21. let array_depth = function
  22. | ArrayDims (_, dims) -> List.length dims
  23. | _ -> raise InvalidNode
  24. let spec = function
  25. | ArrayDims (ctype, dims) -> (ctype, List.length dims)
  26. | ctype -> (ctype, 0)
  27. let check_type ?(msg="") expected node =
  28. let got = typeof node in
  29. if (spec got) <> (spec expected) then (
  30. let msg = match msg with
  31. | "" -> sprintf "type mismatch: expected type %s, got %s"
  32. (type2str expected) (type2str got)
  33. (*(type2str (spec expected)) (type2str (spec got))*)
  34. | _ -> msg
  35. in raise (NodeError (node, msg))
  36. ); ()
  37. let op_types = function
  38. | Not | And | Or -> [Bool]
  39. | Mod -> [Int]
  40. | Neg | Sub | Div | Lt | Le | Gt | Ge -> [Int; Float]
  41. | Add | Mul | Eq | Ne -> [Bool; Int; Float]
  42. let op_result_type opnd_type = function
  43. | Not | And | Or | Eq | Ne | Lt | Le | Gt | Ge -> Bool
  44. | Neg | Add | Sub | Mul | Div | Mod -> opnd_type
  45. (* Check if the given operator can be applied to the given type *)
  46. let check_type_op allowed_types desc node =
  47. let got = typeof node in
  48. if not (List.mem got allowed_types) then (
  49. let msg = sprintf
  50. "%s cannot be applied to type %s, only to %s"
  51. desc (type2str got) (types2str allowed_types)
  52. in
  53. raise (NodeError (node, msg))
  54. ); ()
  55. let check_dims_match dims dec_type errnode =
  56. match (List.length dims, array_depth dec_type) with
  57. | (got, expected) when got != expected ->
  58. let msg = sprintf
  59. "dimension mismatch: expected %d indices, got %d" expected got
  60. in
  61. raise (NodeError (errnode, msg))
  62. | _ -> ()
  63. let rec typecheck node =
  64. let check_trav ctype node =
  65. let node = typecheck node in
  66. check_type ctype node;
  67. node
  68. in
  69. match node with
  70. | FunUse ((FunDec (ret_type, name, params, _) as dec), args, ann)
  71. | FunUse ((FunDef (_, ret_type, name, params, _, _) as dec), args, ann) ->
  72. (match (List.length args, List.length params) with
  73. | (nargs, nparams) when nargs != nparams ->
  74. let msg = sprintf
  75. "function \"%s\" expects %d arguments, got %d"
  76. name nparams nargs
  77. in
  78. raise (NodeError (node, msg))
  79. | _ ->
  80. let args = List.map typecheck args in
  81. let check_arg_type arg param =
  82. check_type (typeof param) arg;
  83. in
  84. List.iter2 check_arg_type args params;
  85. FunUse (dec, args, Type ret_type :: ann)
  86. )
  87. (* Operators match operand types and get a new type based on the operator *)
  88. | Monop (op, opnd, ann) ->
  89. let opnd = typecheck opnd in
  90. let desc = sprintf "unary operator \"%s\"" (op2str op) in
  91. check_type_op (op_types op) desc opnd;
  92. Monop (op, opnd, Type (op_result_type (typeof opnd) op) :: ann)
  93. | Binop (op, left, right, ann) ->
  94. let left = typecheck left in
  95. let right = typecheck right in
  96. let desc = sprintf "binary operator \"%s\"" (op2str op) in
  97. check_type_op (op_types op) desc left;
  98. check_type (typeof left) right;
  99. Binop (op, left, right, Type (op_result_type (typeof left) op) :: ann)
  100. (* Conditions must be bool, and right-hand type must match left-hand type *)
  101. | Cond (cond, texpr, fexpr, ann) ->
  102. let cond = check_trav Bool cond in
  103. let texpr = typecheck texpr in
  104. let fexpr = check_trav (typeof texpr) fexpr in
  105. Cond (cond, texpr, fexpr, Type (typeof texpr) :: ann)
  106. (* Only basic types can be typecasted *)
  107. | TypeCast (ctype, value, ann) ->
  108. let value = typecheck value in
  109. check_type_op [Bool; Int; Float] "typecast" value;
  110. TypeCast (ctype, value, Type (ctype) :: ann)
  111. (* Array allocation dimensions must have type int *)
  112. | Allocate (dec, dims, ann) ->
  113. Allocate (dec, List.map (check_trav Int) dims, ann)
  114. (* Array dimensions are always integers *)
  115. | Dim (name, ann) ->
  116. Dim (name, Type Int :: ann)
  117. (* Functions and parameters must be traversed to give types to Dim nodes *)
  118. (*
  119. | FunDec (ret_type, name, params, ann) ->
  120. FunDec (ret_type, name, List.map typecheck params, ann)
  121. | Param (ArrayDims (ctype, dims), name, ann) ->
  122. Param (ArrayDims (ctype, List.map typecheck dims), name, ann)
  123. *)
  124. (* Void functions may have no return statement, other functions must have a
  125. * return statement of valid type *)
  126. | FunDef (export, ret_type, name, params, body, ann) ->
  127. let params = List.map typecheck params in
  128. let body = typecheck body in
  129. let rec find_return = function
  130. | [] -> None
  131. | [Return (value, _) as ret] -> Some (ret, typeof value)
  132. | hd :: tl -> find_return tl
  133. in (
  134. match (ret_type, find_return (block_body body)) with
  135. | (Void, Some (ret, _)) ->
  136. raise (NodeError (ret, "void function should not have a return value"))
  137. | ((Bool | Int | Float), None) ->
  138. let msg = sprintf
  139. "expected return value of type %s for function \"%s\""
  140. (type2str ret_type) name
  141. in
  142. raise (NodeError (node, msg))
  143. | ((Bool | Int | Float), Some (ret, t)) when t != ret_type ->
  144. let msg = sprintf
  145. "function \"%s\" has return type %s, got %s"
  146. name (type2str ret_type) (type2str t)
  147. in
  148. raise (NodeError (ret, msg))
  149. | _ -> FunDef (export, ret_type, name, params, body, ann)
  150. )
  151. (* Conditions in must have type bool *)
  152. | If (cond, body, ann) ->
  153. If (check_trav Bool cond, typecheck body, ann)
  154. | IfElse (cond, tbody, fbody, ann) ->
  155. IfElse (check_trav Bool cond, typecheck tbody, typecheck fbody, ann)
  156. | While (cond, body, ann) ->
  157. While (check_trav Bool cond, typecheck body, ann)
  158. | DoWhile (cond, body, ann) ->
  159. DoWhile (check_trav Bool cond, typecheck body, ann)
  160. (* Constants *)
  161. | Const (BoolVal value, ann) -> Const (BoolVal value, Type Bool :: ann)
  162. | Const (IntVal value, ann) -> Const (IntVal value, Type Int :: ann)
  163. | Const (FloatVal value, ann) -> Const (FloatVal value, Type Float :: ann)
  164. (* Variables inherit the type of their declaration *)
  165. | VarUse (dec, None, ann) ->
  166. VarUse (dec, None, Type (typeof dec) :: ann)
  167. | VarUse (dec, Some dims, ann) ->
  168. let dims = List.map typecheck dims in
  169. List.iter (check_type Int) dims;
  170. check_dims_match dims (typeof dec) node;
  171. VarUse (dec, Some dims, Type (basetypeof dec) :: ann)
  172. (* Array pointers cannot be re-assigned, because array dimension reduction
  173. * makes assumptions about dimensions of an array *)
  174. | VarLet (dec, None, _, _) when is_array dec ->
  175. raise (NodeError (node, "cannot re-assign array pointer"))
  176. (* Assigned values must match variable declaration *)
  177. | VarLet (dec, None, value, ann) ->
  178. VarLet (dec, None, check_trav (typeof dec) value, ann)
  179. | VarLet (dec, Some dims, value, ann) ->
  180. (* Number of assigned indices must match array definition *)
  181. check_dims_match dims (typeof dec) node;
  182. (* Array indices must be ints *)
  183. let dims = List.map typecheck dims in
  184. List.iter (check_type Int) dims;
  185. (* Assigned value must match array base type *)
  186. let value = typecheck value in
  187. check_type (basetypeof dec) value;
  188. VarLet (dec, Some dims, value, ann)
  189. | _ -> transform_children typecheck node
  190. let phase = function
  191. | Ast node -> Ast (typecheck node)
  192. | _ -> raise (InvalidInput "typecheck")