Repository navigation
Expand file tree
/
Copy pathDynamicTyping.java
More file actions
79 lines (73 loc) · 3.04 KB
/
Copy pathDynamicTyping.java
File metadata and controls
79 lines (73 loc) · 3.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
// Following is the semantics class
// for a dynamically typed language.
// The meaning M of a Statement is a State.
// The meaning M of a Expression is a Value.
public class DynamicTyping extends Semantics {
State M (Program p) {
return M (p.body, new State( ));
}
Value applyBinary (Operator op, Value v1, Value v2) {
StaticTypeCheck.check( v1.type( ) == v2.type( ),
"mismatched types");
if (op.ArithmeticOp( )) {
if (v1.type( ) == Type.INT) {
if (op.val.equals(Operator.PLUS))
return new IntValue(v1.intValue( ) + v2.intValue( ));
if (op.val.equals(Operator.MINUS))
return new IntValue(v1.intValue( ) - v2.intValue( ));
if (op.val.equals(Operator.TIMES))
return new IntValue(v1.intValue( ) * v2.intValue( ));
if (op.val.equals(Operator.DIV))
return new IntValue(v1.intValue( ) / v2.intValue( ));
}
// student exercise
}
// student exercise
throw new IllegalArgumentException("should never reach here");
}
Value applyUnary (Operator op, Value v) {
if (op.val.equals(Operator.NOT))
return new BoolValue(!v.boolValue( ));
else if (op.val.equals(Operator.NEG))
return new IntValue(-v.intValue( ));
else if (op.val.equals(Operator.NEG))
return new FloatValue(-v.floatValue( ));
else if (op.val.equals(Operator.FLOAT))
return new FloatValue((float)(v.intValue( )));
else if (op.val.equals(Operator.INT))
return new IntValue((int)(v.floatValue( )));
else if (op.val.equals(Operator.INT))
return new IntValue((int)(v.charValue( )));
else if (op.val.equals(Operator.CHAR))
return new CharValue((char)(v.intValue( )));
throw new IllegalArgumentException("should never reach here");
}
Value M (Expression e, State sigma) {
if (e instanceof Value)
return (Value)e;
if (e instanceof Variable) {
StaticTypeCheck.check( sigma.containsKey(e),
"reference to undefined variable");
return (Value)(sigma.get(e));
}
if (e instanceof Binary) {
Binary b = (Binary)e;
return applyBinary (b.op,
M(b.term1, sigma), M(b.term2, sigma));
}
if (e instanceof Unary) {
Unary u = (Unary)e;
return applyUnary(u.op, M(u.term, sigma));
}
throw new IllegalArgumentException("should never reach here");
}
public static void main(String args[]) {
Parser parser = new Parser(new Lexer(args[0]));
Program prog = parser.program();
// prog.display(); // student exercise
DynamicTyping dynamic = new DynamicTyping( );
State state = dynamic.M(prog);
System.out.println("Final State");
// state.display( ); // student exercise
}
}