Skip to content

Commit 2fc07f2

Browse files
committed
Implemented ASTCompareExpr :)
1 parent 55a2eb6 commit 2fc07f2

3 files changed

Lines changed: 62 additions & 1 deletion

File tree

src/main/java/com/compiler/ExpressionParser.java

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,19 @@ ASTExprNode getShiftExpr() throws Exception {
157157
}
158158

159159
ASTExprNode getCompareExpr() throws Exception {
160-
return getShiftExpr();
160+
ASTExprNode result = getShiftExpr();
161+
while (
162+
m_lexer.lookAhead().m_type == Type.EQUAL ||
163+
m_lexer.lookAhead().m_type == Type.GREATER ||
164+
m_lexer.lookAhead().m_type == Type.LESS
165+
){
166+
Token curToken = m_lexer.lookAhead();
167+
m_lexer.advance();
168+
ASTExprNode operand = getShiftExpr();
169+
result = new ASTCompareExprNode(result, operand, curToken.m_type);
170+
}
171+
172+
return result;
161173
}
162174

163175
ASTExprNode getAndExpr() throws Exception {
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.compiler.ast;
2+
3+
import com.compiler.TokenIntf;
4+
5+
import java.io.OutputStreamWriter;
6+
7+
public class ASTCompareExprNode extends ASTExprNode{
8+
9+
ASTExprNode m_operand0;
10+
ASTExprNode m_operand1;
11+
TokenIntf.Type m_operator;
12+
13+
public ASTCompareExprNode(ASTExprNode operand0, ASTExprNode operand1, TokenIntf.Type operator) {
14+
m_operand0 = operand0;
15+
m_operand1 = operand1;
16+
m_operator = operator;
17+
}
18+
19+
public int eval() {
20+
int operand0 = m_operand0.eval();
21+
int operand1 = m_operand1.eval();
22+
23+
24+
return switch (m_operator) {
25+
case GREATER -> operand0 > operand1 ? 1 : 0;
26+
case LESS -> operand0 < operand1 ? 1 : 0;
27+
case EQUAL -> operand0 == operand1 ? 1 : 0;
28+
default -> 0;
29+
};
30+
}
31+
32+
public void print(OutputStreamWriter outStream, String indent) throws Exception {}
33+
}
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.compiler;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.assertEquals;
6+
7+
public class TestCompareExpression extends TestExpressionEvaluatorBase {
8+
9+
@Test
10+
public void testCompareExpAST() throws Exception {
11+
assertEquals(1, evalExpression("2>0"));
12+
assertEquals(1, evalExpression("2>0>-2"));
13+
assertEquals(0, evalExpression("2>0>2"));
14+
}
15+
16+
}

0 commit comments

Comments
 (0)