typecheck.ml 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. (*
  2. * Do a number of checks:
  3. * - A void function must not return a value.
  4. * - A non-void function must return a value of the correct type.
  5. * - Array indices must be of type integer.
  6. * - The number of array indices must match the number of array dimensions.
  7. * - The type on the right-hand side of an assignment must match the type on
  8. * the left-hand side.
  9. * - The number of arguments used for a function call must match the number of
  10. * parameters for that function.
  11. * - The types of the function arguments must match the types of parameters.
  12. * - The operands of a unary or binary operation must have valid types.
  13. * - The predicate expression of an if, while, or do-while statement must be
  14. * a boolean.
  15. * - Only values having a basic type can be type cast.
  16. *)
  17. open Printf
  18. open Types
  19. open Util
  20. open Stringify
  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. let _ = match (op, right) with
  100. | (Div, Const (IntVal 0, _)) -> node_warning right "division by zero"
  101. | _ -> ()
  102. in
  103. Binop (op, left, right, Type (op_result_type (typeof left) op) :: ann)
  104. (* Conditions must be bool, and right-hand type must match left-hand type *)
  105. | Cond (cond, texpr, fexpr, ann) ->
  106. let cond = check_trav Bool cond in
  107. let texpr = typecheck texpr in
  108. let fexpr = check_trav (typeof texpr) fexpr in
  109. Cond (cond, texpr, fexpr, Type (typeof texpr) :: ann)
  110. (* Only basic types can be typecasted *)
  111. | TypeCast (ctype, value, ann) ->
  112. let value = typecheck value in
  113. check_type_op [Bool; Int; Float] "typecast" value;
  114. TypeCast (ctype, value, Type (ctype) :: ann)
  115. (* Array allocation dimensions must have type int *)
  116. | Allocate (dec, dims, ann) ->
  117. Allocate (dec, List.map (check_trav Int) dims, ann)
  118. (* Array dimensions are always integers *)
  119. | Dim (name, ann) ->
  120. Dim (name, Type Int :: ann)
  121. (* Functions and parameters must be traversed to give types to Dim nodes *)
  122. (*
  123. | FunDec (ret_type, name, params, ann) ->
  124. FunDec (ret_type, name, List.map typecheck params, ann)
  125. | Param (ArrayDims (ctype, dims), name, ann) ->
  126. Param (ArrayDims (ctype, List.map typecheck dims), name, ann)
  127. *)
  128. (* Void functions may have no return statement, other functions must have a
  129. * return statement of valid type *)
  130. | FunDef (export, ret_type, name, params, body, ann) ->
  131. let params = List.map typecheck params in
  132. let body = typecheck body in
  133. let rec find_return = function
  134. | [] -> None
  135. | [Return (value, _) as ret] -> Some (ret, typeof value)
  136. | hd :: tl -> find_return tl
  137. in (
  138. match (ret_type, find_return (block_body body)) with
  139. | (Void, Some (ret, _)) ->
  140. raise (NodeError (ret, "void function should not have a return value"))
  141. | ((Bool | Int | Float), None) ->
  142. let msg = sprintf
  143. "expected return value of type %s for function \"%s\""
  144. (type2str ret_type) name
  145. in
  146. raise (NodeError (node, msg))
  147. | ((Bool | Int | Float), Some (ret, t)) when t != ret_type ->
  148. let msg = sprintf
  149. "function \"%s\" has return type %s, got %s"
  150. name (type2str ret_type) (type2str t)
  151. in
  152. raise (NodeError (ret, msg))
  153. | _ -> FunDef (export, ret_type, name, params, body, ann)
  154. )
  155. (* Conditions in must have type bool *)
  156. | If (cond, body, ann) ->
  157. If (check_trav Bool cond, typecheck body, ann)
  158. | IfElse (cond, tbody, fbody, ann) ->
  159. IfElse (check_trav Bool cond, typecheck tbody, typecheck fbody, ann)
  160. | While (cond, body, ann) ->
  161. While (check_trav Bool cond, typecheck body, ann)
  162. | DoWhile (cond, body, ann) ->
  163. DoWhile (check_trav Bool cond, typecheck body, ann)
  164. (* Constants *)
  165. | Const (BoolVal value, ann) ->
  166. Const (BoolVal value, Type Bool :: ann)
  167. | Const (IntVal value, ann) ->
  168. (* Do a bound check on integers (use Nativeint because default ints in
  169. * ocaml are 31- or 64-bit *)
  170. let cmpval = Nativeint.of_int value in
  171. if cmpval < Nativeint.min_int || cmpval > Nativeint.max_int then (
  172. raise (NodeError (node, "integer value out of range"))
  173. );
  174. Const (IntVal value, Type Int :: ann)
  175. | Const (FloatVal value, ann) ->
  176. Const (FloatVal value, Type Float :: ann)
  177. (* Variables inherit the type of their declaration *)
  178. | VarUse (dec, None, ann) ->
  179. VarUse (dec, None, Type (typeof dec) :: ann)
  180. | VarUse (dec, Some dims, ann) ->
  181. let dims = List.map typecheck dims in
  182. List.iter (check_type Int) dims;
  183. check_dims_match dims (typeof dec) node;
  184. VarUse (dec, Some dims, Type (basetypeof dec) :: ann)
  185. (* Array pointers cannot be re-assigned, because array dimension reduction
  186. * makes assumptions about dimensions of an array *)
  187. | VarLet (dec, None, _, _) when is_array dec ->
  188. raise (NodeError (node, "cannot re-assign array pointer"))
  189. (* Assigned values must match variable declaration *)
  190. | VarLet (dec, None, value, ann) ->
  191. VarLet (dec, None, check_trav (typeof dec) value, ann)
  192. | VarLet (dec, Some dims, value, ann) ->
  193. (* Number of assigned indices must match array definition *)
  194. check_dims_match dims (typeof dec) node;
  195. (* Array indices must be ints *)
  196. let dims = List.map typecheck dims in
  197. List.iter (check_type Int) dims;
  198. (* Assigned value must match array base type *)
  199. let value = typecheck value in
  200. check_type (basetypeof dec) value;
  201. VarLet (dec, Some dims, value, ann)
  202. | _ -> transform_children typecheck node
  203. let phase = function
  204. | Ast node -> Ast (typecheck node)
  205. | _ -> raise (InvalidInput "typecheck")