76 lines
2.3 KiB
Java
76 lines
2.3 KiB
Java
package frontend.ast.exp;
|
|
|
|
import frontend.ast.Node;
|
|
import frontend.ast.SyntaxType;
|
|
import frontend.lexer.TokenStream;
|
|
import frontend.lexer.TokenType;
|
|
import frontend.ast.token.TokenNode;
|
|
import frontend.ast.NodeStack;
|
|
import midend.symbol.SymbolManager;
|
|
import error.Errors;
|
|
|
|
public class MulExp extends Node {
|
|
public MulExp(TokenStream ts) {
|
|
super(SyntaxType.MUL_EXP, ts);
|
|
}
|
|
|
|
public void parse(Errors errors) {
|
|
NodeStack stack = new NodeStack();
|
|
while (true) {
|
|
UnaryExp uep = new UnaryExp(this.ts);
|
|
uep.parse(errors);
|
|
stack.push(uep);
|
|
if (isMulOp()) {
|
|
stack.push(new TokenNode(ts)); // mulop
|
|
} else {
|
|
break;
|
|
}
|
|
}
|
|
if (stack.size() == 1) {
|
|
addChild((UnaryExp)stack.pop());
|
|
} else {
|
|
MulExp temp = this;
|
|
while (stack.size() > 1) {
|
|
MulExp mep = new MulExp(this.ts);
|
|
UnaryExp uep = (UnaryExp) stack.pop();
|
|
TokenNode mulop = (TokenNode) stack.pop();
|
|
temp.addChild(mep);
|
|
temp.addChild(mulop);
|
|
temp.addChild(uep);
|
|
temp = mep;
|
|
}
|
|
temp.addChild((UnaryExp)stack.pop());
|
|
}
|
|
}
|
|
|
|
public boolean isMulOp() {
|
|
TokenType t = getCurrToken().getType();
|
|
return t == TokenType.MULT || t == TokenType.DIV || t == TokenType.MOD;
|
|
}
|
|
|
|
public int getType() {
|
|
if (getChildren().size() == 1) {
|
|
return ((UnaryExp) getChild(0)).getType();
|
|
} else {
|
|
return ((MulExp) getChild(0)).getType()
|
|
| ((UnaryExp) getChild(2)).getType();
|
|
}
|
|
}
|
|
|
|
public int getValue() {
|
|
if (getChild(0) instanceof UnaryExp) {
|
|
return ((UnaryExp) getChild(0)).getValue();
|
|
} else {
|
|
int left = ((MulExp) getChild(0)).getValue();
|
|
int right = ((UnaryExp) getChild(2)).getValue();
|
|
if (((TokenNode) getChild(1)).getType() == TokenType.MULT) {
|
|
return left * right;
|
|
} else if (((TokenNode) getChild(1)).getType() == TokenType.DIV) {
|
|
return left / right;
|
|
} else {
|
|
return left % right;
|
|
}
|
|
}
|
|
}
|
|
}
|