Skip to content

Commit 027e684

Browse files
committed
Typing: add check the type of ConditionOperation in expression
1 parent 9b0ab8f commit 027e684

File tree

3 files changed

+15
-1
lines changed

3 files changed

+15
-1
lines changed

phase2/Typing/TypeError.ml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ exception ConstructorAlreadyExists of string
1010
exception DuplicateLocalVariable of string
1111
exception IncompatibleTypes of string
1212
exception InvalidMethodDeclaration of string
13+
exception InvalidTypeCondOperation of Type.t * Type.t
1314
exception MethodAlreadyExists of string
1415
exception UnknownAttribute of string * string
1516
exception UnknownVariable of string
@@ -20,4 +21,5 @@ exception WrongTypePrefixOperation of string * string
2021
exception WrongTypePostfixOperation of string
2122
exception WrongInvokedArgumentsLength of string
2223
exception WrongTypesAssignOperation of Type.t option * Type.t option
24+
exception WrongTypeCondOperation of Type.t option
2325
exception WrongTypesOperation of Type.t option * Type.t option

phase2/Typing/Typing.ml

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -237,7 +237,18 @@ let rec verify_expression env current_env e =
237237
(match op with
238238
| Op_cor | Op_cand | Op_eq | Op_ne | Op_gt | Op_lt | Op_ge | Op_le -> e.etype <- Some(Primitive(Boolean))
239239
| Op_or | Op_and | Op_xor | Op_shl | Op_shr | Op_shrr | Op_add | Op_sub | Op_mul | Op_div | Op_mod -> e.etype <- e1.etype)
240-
| CondOp (e1,e2,e3) -> () (*TODO*)
240+
| CondOp (e1,e2,e3) ->
241+
verify_expression env current_env e1;
242+
verify_expression env current_env e2;
243+
verify_expression env current_env e3;
244+
(* check if e1.etype is boolean and e2.etype equals e3.etype *)
245+
if e1.etype <> Some(Primitive(Boolean))
246+
then raise(WrongTypeCondOperation(e1.etype))
247+
(match e2.etype, e3.etype with
248+
| Some(_), None -> ()
249+
| None, Some(_) -> ()
250+
| Some(t1), Some(t2) -> if t1 <> t2 then raise(InvalidTypeCondOperation(t1, t2)));
251+
if e2.etype <> None then e.etype <- e2.etype else e.etype <- e3.etype
241252
| Cast (t,e1) ->
242253
verify_expression env current_env e1;
243254
e.etype <- Some(t)

phase2/tests/test.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ public I(int e) {
1919
int sr = 5;
2020
long l = (long) sr;
2121
boolean test = my instanceof I;
22+
int condop = (1 == 2) ? 1 : 5;
2223
private String func1 (int a) {
2324
int b = 1;
2425
b += (5+4);

0 commit comments

Comments
 (0)