8000 Typing: add check type of Pre/Post operation in expression · compiler-experts/miniJava@34949ac · GitHub
[go: up one dir, main page]

Skip to content

Commit 34949ac

Browse files
committed
Typing: add check type of Pre/Post operation in expression
1 parent 94f8475 commit 34949ac

File tree

3 files changed

+32
-2
lines changed

3 files changed

+32
-2
lines changed

phase2/Typing/TypeError.ml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,3 +17,5 @@ exception InvalidMethodDeclaration of string
1717
exception ArgumentTypeNotMatch of string
1818
exception UnknownMethod of string
1919
exception UnknowActualType of string
20+
exception WrongTypePrefixOperation of string * string
21+
exception WrongTypePostfixOperation of string

phase2/Typing/Typing.ml

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,31 @@ let rec verify_expression env current_env e =
185185
verify_expression env current_env e2;
186186
verify_assignop_type e1.etype e2.etype;
187187
e.etype <- e1.etype
188-
| Post (e,op) -> () (*TODO*)
189-
| Pre (op,e) -> () (*TODO*)
188+
| Post (e1,op) ->
189+
verify_expression env current_env e1;
190+
(match op with
191+
| Incr ->
192+
if (e1.etype <> Some(Primitive(Int)) && e1.etype <> Some(Primitive(Float))) then
193+
raise(WrongTypePostfixOperation(string_of_expression(e1)^"++"))
194+
| Decr ->
195+
if (e1.etype <> Some(Primitive(Int)) && e1.etype <> Some(Primitive(Float))) then
196+
raise(WrongTypePostfixOperation(string_of_expression(e1)^"--"))
197+
);
198+
e.etype <- e1.etype;
199+
| Pre (op,e1) ->
200+
verify_expression env current_env e1;
201+
(match op with
202+
| Op_not ->
203+
if e1.etype <> Some(Primitive(Boolean)) then
204+
raise(WrongTypePrefixOperation(string_of_prefix_op(op), string_of_expression(e1)))
205+
| Op_bnot ->
206+
if e1.etype <> Some(Primitive(Int)) then
207+
raise(WrongTypePrefixOperation(string_of_prefix_op(op), string_of_expression(e1)))
208+
| Op_neg | Op_incr | Op_decr | Op_plus ->
209+
if (e1.etype <> Some(Primitive(Int)) && e1.etype <> Some(Primitive(Float))) then
210+
raise(WrongTypePrefixOperation(string_of_prefix_op(op), string_of_expression(e1)))
211+
);
212+
e.etype <- e1.etype;
190213
| Op (e1,op,e2) ->
191214
verify_expression env current_env e1;
192215
verify_expression env current_env e2;

phase2/tests/test.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,14 @@ public I(int e) {
1212
I my = new I(i);
1313
String mystring1 = I.func1(j);
1414
String mystring2 = func1(i);
15+
boolean f = !a;
16+
int g = ~5;
17+
float h = (-8.5f);
1518
private String func1 (int a) {
1619
int b = 1;
1720
b += (5+4);
21+
++b;
22+
b--;
1823
return "YES";
1924
}
2025

0 commit comments

Comments
 (0)
0