typecheck.ml 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 Globals
  21. open Stringify
  22. let array_depth = function
  23. | ArrayDims (_, dims) -> List.length dims
  24. | _ -> raise InvalidNode
  25. let spec = function
  26. | ArrayDims (ctype, dims) -> (ctype, List.length dims)
  27. | ctype -> (ctype, 0)
  28. let check_type ?(msg="") expected node =
  29. let got = typeof node in
  30. if (spec got) <> (spec expected) then begin
  31. let msg = match msg with
  32. | "" -> sprintf "type mismatch: expected type %s, got %s"
  33. (type2str expected) (type2str got)
  34. (*(type2str (spec expected)) (type2str (spec got))*)
  35. | _ -> msg
  36. in raise (NodeError (node, msg))
  37. end
  38. let op_types = function
  39. | Not | And | Or -> [Bool]
  40. | Mod -> [Int]
  41. | Neg | Sub | Div | Lt | Le | Gt | Ge -> [Int; Float]
  42. | Add | Mul | Eq | Ne -> [Bool; Int; Float]
  43. let op_result_type opnd_type = function
  44. | Not | And | Or | Eq | Ne | Lt | Le | Gt | Ge -> Bool
  45. | Neg | Add | Sub | Mul | Div | Mod -> opnd_type
  46. (* Check if the given operator can be applied to the given type *)
  47. let check_type_op allowed_types desc node =
  48. let got = typeof node in
  49. if not (List.mem got allowed_types) then (
  50. let msg = sprintf
  51. "%s cannot be applied to type %s, only to %s"
  52. desc (type2str got) (types2str allowed_types)
  53. in
  54. raise (NodeError (node, msg))
  55. ); ()
  56. let check_dims_match dims dec_type errnode =
  57. match (List.length dims, array_depth dec_type) with
  58. | (got, expected) when got != expected ->
  59. let msg = sprintf
  60. "dimension mismatch: expected %d indices, got %d" expected got
  61. in
  62. raise (NodeError (errnode, msg))
  63. | _ -> ()
  64. let rec typecheck node =
  65. let check_trav ctype node =
  66. let node = typecheck node in
  67. check_type ctype node;
  68. node
  69. in
  70. match node with
  71. | FunUse ((FunDec (ret_type, name, params, _) as dec), args, ann)
  72. | FunUse ((FunDef (_, ret_type, name, params, _, _) as dec), args, ann) ->
  73. begin
  74. match (List.length args, List.length params) with
  75. | (nargs, nparams) when nargs != nparams ->
  76. let msg = sprintf
  77. "function \"%s\" expects %d arguments, got %d"
  78. name nparams nargs
  79. in
  80. raise (NodeError (node, msg))
  81. | _ ->
  82. let args = List.map typecheck args in
  83. let check_arg_type arg param =
  84. check_type (typeof param) arg;
  85. in
  86. List.iter2 check_arg_type args params;
  87. FunUse (dec, args, Type ret_type :: ann)
  88. end
  89. (* Operators match operand types and get a new type based on the operator *)
  90. | Monop (op, opnd, ann) ->
  91. let opnd = typecheck opnd in
  92. let desc = sprintf "unary operator \"%s\"" (op2str op) in
  93. check_type_op (op_types op) desc opnd;
  94. Monop (op, opnd, Type (op_result_type (typeof opnd) op) :: ann)
  95. | Binop (op, left, right, ann) ->
  96. let left = typecheck left in
  97. let right = typecheck right in
  98. let desc = sprintf "binary operator \"%s\"" (op2str op) in
  99. check_type_op (op_types op) desc left;
  100. check_type (typeof left) right;
  101. (* Check for division by zero *)
  102. begin
  103. match (op, right) with
  104. | (Div, Const (IntVal 0, _)) -> node_warning right "division by zero"
  105. | _ -> ()
  106. end;
  107. Binop (op, left, right, Type (op_result_type (typeof left) op) :: ann)
  108. (* Conditions must be bool, and right-hand type must match left-hand type *)
  109. | Cond (cond, texpr, fexpr, ann) ->
  110. let cond = check_trav Bool cond in
  111. let texpr = typecheck texpr in
  112. let fexpr = check_trav (typeof texpr) fexpr in
  113. Cond (cond, texpr, fexpr, Type (typeof texpr) :: ann)
  114. (* Only basic types can be typecasted *)
  115. | TypeCast (ctype, value, ann) ->
  116. let value = typecheck value in
  117. check_type_op [Bool; Int; Float] "typecast" value;
  118. TypeCast (ctype, value, Type (ctype) :: ann)
  119. (* Array allocation dimensions must have type int *)
  120. | Allocate (dec, dims, ann) ->
  121. Allocate (dec, List.map (check_trav Int) dims, ann)
  122. (* Array dimensions are always integers *)
  123. | Dim (name, ann) ->
  124. Dim (name, Type Int :: ann)
  125. (* Functions and parameters must be traversed to give types to Dim nodes *)
  126. (*
  127. | FunDec (ret_type, name, params, ann) ->
  128. FunDec (ret_type, name, List.map typecheck params, ann)
  129. | Param (ArrayDims (ctype, dims), name, ann) ->
  130. Param (ArrayDims (ctype, List.map typecheck dims), name, ann)
  131. *)
  132. (* Void functions may have no return statement, other functions must have a
  133. * return statement of valid type *)
  134. | FunDef (export, ret_type, name, params, body, ann) ->
  135. let params = List.map typecheck params in
  136. let body = typecheck body in
  137. let rec find_return = function
  138. | [] -> None
  139. | [Return (value, _) as ret] -> Some (ret, typeof value)
  140. | hd :: tl -> find_return tl
  141. in
  142. begin
  143. match (ret_type, find_return (block_body body)) with
  144. | (Void, Some (ret, _)) ->
  145. raise (NodeError (ret, "void function should not have a return value"))
  146. | ((Bool | Int | Float), None) ->
  147. let msg = sprintf
  148. "expected return value of type %s for function \"%s\""
  149. (type2str ret_type) name
  150. in
  151. raise (NodeError (node, msg))
  152. | ((Bool | Int | Float), Some (ret, t)) when t != ret_type ->
  153. let msg = sprintf
  154. "function \"%s\" has return type %s, got %s"
  155. name (type2str ret_type) (type2str t)
  156. in
  157. raise (NodeError (ret, msg))
  158. | _ -> FunDef (export, ret_type, name, params, body, ann)
  159. end
  160. (* Conditions in must have type bool *)
  161. | If (cond, body, ann) ->
  162. If (check_trav Bool cond, typecheck body, ann)
  163. | IfElse (cond, tbody, fbody, ann) ->
  164. IfElse (check_trav Bool cond, typecheck tbody, typecheck fbody, ann)
  165. | While (cond, body, ann) ->
  166. While (check_trav Bool cond, typecheck body, ann)
  167. | DoWhile (cond, body, ann) ->
  168. DoWhile (check_trav Bool cond, typecheck body, ann)
  169. (* Constants *)
  170. | Const (BoolVal value, ann) ->
  171. Const (BoolVal value, Type Bool :: ann)
  172. | Const (IntVal value, ann) ->
  173. (* Do a bound check on integers (use Int32 because default ints in ocaml
  174. * are 31- or 63-bit *)
  175. let cmpval = Nativeint.of_int value in
  176. let min = Nativeint.of_int32 Int32.min_int in
  177. let max = Nativeint.of_int32 Int32.max_int in
  178. if cmpval < min || cmpval > max then (
  179. raise (NodeError (node, "integer value out of range (signed 32-bit)"))
  180. );
  181. Const (IntVal value, Type Int :: ann)
  182. | Const (FloatVal value, ann) ->
  183. Const (FloatVal value, Type Float :: ann)
  184. (* Variables inherit the type of their declaration *)
  185. | VarUse (dec, None, ann) ->
  186. VarUse (dec, None, Type (typeof dec) :: ann)
  187. | VarUse (dec, Some dims, ann) ->
  188. let dims = List.map typecheck dims in
  189. List.iter (check_type Int) dims;
  190. check_dims_match dims (typeof dec) node;
  191. VarUse (dec, Some dims, Type (basetypeof dec) :: ann)
  192. (* Array pointers cannot be re-assigned, because array dimension reduction
  193. * makes assumptions about dimensions of an array *)
  194. | VarLet (dec, None, _, _) when is_array dec ->
  195. raise (NodeError (node, "cannot assign value to array pointer after \
  196. initialisation"))
  197. (* Assigned values must match variable declaration *)
  198. | VarLet (dec, None, value, ann) ->
  199. VarLet (dec, None, check_trav (typeof dec) value, ann)
  200. | VarLet (dec, Some dims, value, ann) ->
  201. (* Number of assigned indices must match array definition *)
  202. check_dims_match dims (typeof dec) node;
  203. (* Array indices must be ints *)
  204. let dims = List.map typecheck dims in
  205. List.iter (check_type Int) dims;
  206. (* Assigned value must match array base type *)
  207. let value = typecheck value in
  208. check_type (basetypeof dec) value;
  209. VarLet (dec, Some dims, value, ann)
  210. (* ArrayConst initialisations are transformed during desugaring, so any
  211. * occurrences that are left are illegal *)
  212. | ArrayConst _ ->
  213. raise (NodeError (node, "array constants can only be used in array \
  214. initialisation"))
  215. | _ -> transform_children typecheck node
  216. let phase = function
  217. | Ast node -> Ast (typecheck node)
  218. | _ -> raise (InvalidInput "typecheck")