Jelajahi Sumber

Added warning and constant propagation check for division by zero

Taddeus Kroes 12 tahun lalu
induk
melakukan
7462e88b3d
4 mengubah file dengan 11 tambahan dan 1 penghapusan
  1. 1 1
      phases/constant_propagation.ml
  2. 5 0
      phases/typecheck.ml
  3. 3 0
      util.ml
  4. 2 0
      util.mli

+ 1 - 1
phases/constant_propagation.ml

@@ -41,7 +41,7 @@ let eval_binop = function
     | (Mul, Const (FloatVal left, _), Const (FloatVal right, _), ann) ->
         Const (FloatVal (left *. right), ann)
 
-    | (Div, Const (IntVal left, _), Const (IntVal right, _), ann) ->
+    | (Div, Const (IntVal left, _), Const (IntVal right, _), ann) when right != 0 ->
         Const (IntVal (left / right), ann)
     | (Div, Const (FloatVal left, _), Const (FloatVal right, _), ann) ->
         Const (FloatVal (left /. right), ann)

+ 5 - 0
phases/typecheck.ml

@@ -109,6 +109,11 @@ let rec typecheck node =
         let desc = sprintf "binary operator \"%s\"" (op2str op) in
         check_type_op (op_types op) desc left;
         check_type (typeof left) right;
+
+        let _ = match (op, right) with
+            | (Div, Const (IntVal 0, _)) -> node_warning right "division by zero"
+            | _ -> ()
+        in
         Binop (op, left, right, Type (op_result_type (typeof left) op) :: ann)
 
     (* Conditions must be bool, and right-hand type must match left-hand type *)

+ 3 - 0
util.ml

@@ -418,3 +418,6 @@ let is_immediate_const const =
 let is_array node = match typeof node with
     | ArrayDims _ | Array _ -> true
     | _ -> false
+
+let node_warning node msg =
+    prerr_loc_msg (locof node) ("Warning: " ^ msg)

+ 2 - 0
util.mli

@@ -63,3 +63,5 @@ val mapi : (int -> 'a -> 'b) -> 'a list -> 'b list
 val is_immediate_const : Types.const -> bool
 
 val is_array : Types.node -> bool
+
+val node_warning : Types.node -> string -> unit